/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 * $Id: bootc.c,v 1.1 2006/04/19 00:56:51 cnguyen Exp $
 */

#include "iop.h"
#include "iostypes.h"
#include "arm_libc.h"

#define BOOT1_BASE         (SRN_SRAM_BASE)
#ifdef SMALL_BOOT
#define BOOT1_SIZE         (6 * 1024)
#else
#define BOOT1_SIZE         (94 * 1024)
#endif /* SMALL_BOOT */

#define LED_DELAY          1000000
#define FAIL_ECC           0xF1
#define FAIL_HASH          0xF2
#define SUCCESS            0x88

#define byte_swap(x) (((x & 0xff000000) >> 24) \
                      | ((x & 0x00ff0000) >> 8) \
                      | ((x & 0x0000ff00) << 8) \
                      | ((x & 0x000000ff) << 24))

#define busRd32(addr)         (*(volatile u32 *)(addr))
#define busWrt32(addr, val)  (*(volatile u32 *)(addr)) = (val)

/*
 * Constants for flash.
 */
#define FL_PAGE_SHIFT       11
#define FL_PAGE_SIZE        (1 << FL_PAGE_SHIFT)
#define FL_SPARE_SIZE       64
#define FL_READ_SETUP_CMD   0x00
#define FL_READ_CMD         0x30
#define FL_ADP_1F           0x1f
#define FL_ADP_00           0x00

/*
 * Output a value to the LEDs.
 */
void
outputLed(int value)
{
    u32 reg;

    reg = busRd32(GPIIOPOUT_REG);
    reg = (reg & ~GPIIO_PIO_ENABLE) | ((value & 0xff) << GPIIO_PIO_SHIFT);
    busWrt32(GPIIOPOUT_REG, reg);

    return;
}

/*
 * bootFailure
 *
 * This is called from the assembler code if for some reason we don't
 * successfully load and jump to boot1, but instead we return to the
 * initial boot loader code.   If we fail, we flash the LEDs with
 * a reason code alternating with zero.
 */
void
bootFailure(u32 reason)
{
    while (1) {
        outputLed (reason);
        busDelay (LED_DELAY);
        outputLed (0);
        busDelay (LED_DELAY);
    }
}

/*
 * Enable IOP access to the GPIO.
 */
void
enableGpio(void)
{
    u32 reg;

    reg = busRd32(GPIIOPEN_REG);
    GPIIOPEN_SET_EN(reg, GPIIO_PIO_ENABLE);
    busWrt32(GPIIOPEN_REG, reg);

    reg = busRd32(GPIIOPOE_REG);
    GPIIOPEN_SET_EN(reg, GPIIO_PIO_ENABLE);
    busWrt32(GPIIOPOE_REG, reg);

    return;
}

/*
 * setupSron
 *
 * Enable the access protection to allow AES, SHA, and Flash to access
 * Sram.
 */
static void
setupSron(void)
{

    busWrt32((u32)(ACRSRNPROT_REG),
             (ACRSRNPROT_AESEN_MASK 
              | ACRSRNPROT_SHAEN_MASK 
              | ACRSRNPROT_FLAEN_MASK ));

    return;
}

/*
 * setupAes
 *
 * Prepare the AES engine.
 *
 *   + Set up the AES key from embedded value.
 *   + Write the Init Vector to the stack from embedded value.
 *   + Setup read and write pointers.
 */
static void
setupAes(u32 base)
{
    int i;
    u32 *p;
    extern u8 bootKey[];
    extern u32 bootIv[];

    /*
     * Stop engine and clear interrupt mask.
     */
    busWrt32(AES_CTRL_REG, 0);

    /* 
     * Setup AES key 
     */
    p = (u32 *)bootKey;
    for (i = 0; i < 4; ++i) {
        busWrt32(AES_KEY_REG, *p++);
    }

    /*
     * Setup AES iv
     */
    p = (u32 *)bootIv;
    for (i = 0; i < 4; ++i) {
        busWrt32(AES_IVPTR_REG, *p++);
    }

    busWrt32(AES_RPTR_REG, base);
    busWrt32(AES_WPTR_REG, base);

    return;
}

/*
 * setupSha
 *
 * Prepare the SHA engine.
 *
 *    + Program initial hash value.
 *    + Set up the control and data registers, and read pointer.
 */
static void
setupSha(u32 base)
{

    /*
     * Stop engine and clear interrupt mask.
     */
    busWrt32(SHA_CTRL_REG, 0);

    /*
     * Set initial hash value.
     */
    busWrt32(SHA_BUF0_REG, 0x67452301); /* Data is big endian */
    busWrt32(SHA_BUF1_REG, 0xefcdab89);
    busWrt32(SHA_BUF2_REG, 0x98badcfe);
    busWrt32(SHA_BUF3_REG, 0x10325476);
    busWrt32(SHA_BUF4_REG, 0xc3d2e1f0);

    /*
     * Set read pointer.
     */
    busWrt32(SHA_RPTR_REG, base);

    return;
}

/*
 * setupFlash
 *
 * Set up the flash memory.
 *
 *    + Enable flash device.
 *    + Configure the device.
 *    + Initialise the pointers
 *    + Reset flash device
 */
static void
setupFlash(u32 base)
{

    /*
     * Enable flash device.
     */
    busWrt32(FL_CONF_REG, busRd32(FL_CONF_REG)|FL_CONF_DEV);

    /*
     * Initialise pointers.
     */
    busWrt32(FL_MA0_REG, 0);
    busWrt32(FL_MA1_REG, 0);
    busWrt32(FL_AD0_REG, 0);
    busWrt32(FL_AD1_REG, 0);

    /*
     * Issue reset command.
     */
    busWrt32(FL_CTRL_REG, FL_CTRL_EXEC | FL_CTRL_RDY |
             (0xff << FL_CTRL_CMD_SHIFT));

    return;
}

/*
 * setupEfuse*
 */
static void
setupEfuse (void)
{

    /*
     * Enable IOP access to Efuse.
     */
    busWrt32(EFUSE_ADDR_REG, ACREFUSEADDR_EFEN_MASK | 0);

    return;
}

/*
 * readEfuse
 *
 * Read 'size' bytes starting at 'address' into 'buffer'.
 */
static void
readEfuse(u32 address, u8 *buffer, int size)
{
    int i;
    unsigned int data;

    memset (buffer, 0, size);
    for (i = 0; i < size; i += sizeof (unsigned int)) {

        /*
         * Physical read.
         */
        busWrt32(EFUSE_ADDR_REG, 
                 ACREFUSEADDR_EFEN_MASK | (address & ACREFUSEADDR_EFADDR_MASK));
        data = busRd32(EFUSE_DATA_REG);
        *((int *)buffer) = data;   /* XXX check endianness */
        buffer += sizeof(unsigned int);
        address++;
    }

    return;
}

#define FL_ECC_UNIT 512
#define FL_ECC_SIZE 4
#define FL_SPARE_ECC_OFFSET 64

/*
 * checkEcc
 *
 * This function checks the computed ECC syndrome(s) with the ECC value(s)     
 * stored on flash for a single flash page. If a single-bit error is           
 * discovered, it is repaired.  A double-bit error causes the boot process     
 * to fail. 'buf' points to 'pageSize' bytes of flash page data, 'spare'       
 * points to a 128-byte buffer that contains the stored ECC values in the      
 * lower 64 bytes and the computed ECC values in the upper 64 bytes. 
 */
static void
checkEcc(u8 *buf, u8* spare, u32 pageSize)
{
    int eccCount;
    int spareSize = pageSize >> 5;

    for (eccCount = 0; eccCount < pageSize / FL_ECC_UNIT; ++eccCount) {
        int eccOffset;
        u32 eccStored, eccComputed;
        u32 eccResult;
        u16 high, low;

        eccOffset = eccCount * FL_ECC_SIZE;
        eccComputed = *(u32 *) &spare[FL_SPARE_ECC_OFFSET + eccOffset];
        eccStored = *(u32 *) &spare[spareSize - (spareSize >> 2) + eccOffset];

        /* Check for bit errors */
        if (eccStored == eccComputed) {
            continue;
        }

        /*
         * The ECC hardware returns its computed ECC in little-endian
         * order, and we store also store the pre-calculated ECC in 
         * the flash image in little-endian order.    For the straight 
         * comparison above, this doesn't matter, but now we have to 
         * get both calculated and pre-loaded ECC values into big-
         * endian order for the following computation to work correctly.
         */
        eccStored = byte_swap(eccStored);
        eccComputed = byte_swap(eccComputed);

        /* Result is XOR'ed together */
        eccResult = eccStored ^ eccComputed;
        if ((eccResult & (eccResult - 1)) == 0) {
            /* Single-bit error in the ecc code itself, don't bother fixing it... */
            continue;
        } 

        high = eccResult >> 16;
        low = (eccResult & 0x00000fff);
        if ((high ^ low) == 0x00000fff) {
            /* Single-bit error in the data region, fix the error and continue... */
            u8 *dataPtr;

            /*
             * Repair the error. Bits 0 to 2 indicate the bit location,
             * bits 3 to 11 indicate the byte location
             */
            dataPtr = ((u8 *)buf) + (eccCount * FL_ECC_UNIT);
            dataPtr[(high & 0x00000ff8) >> 3] ^= (1 << (high & 0x7));
            continue;
        } else {
            /* Multi-bit error */
            bootFailure(FAIL_ECC);
        }
    }

    return;
}

#define WAIT(dev) while(busRd32(dev##_CTRL_REG) & dev##_CTRL_EXEC)

/*
 * loadBoot1
 *
 * Load the next stage of the boot process
 * This function loads a 94KB "block" from the first block of the flash
 * device a page (2KB) at a time.  Each page is error-corrected, decrypted,
 * and hashed.
 */
static void
loadBoot1(u32 base, u32 size)
{
    u32 i, numPages;

    numPages = size >> FL_PAGE_SHIFT;

    for (i = 0; i < numPages + 2; ++i) {
        /* Load page 'i' from flash */

        outputLed(i);
        outputLed(0x80 | i);

        WAIT(FL);

        if (i < numPages) {
            busWrt32(FL_AD1_REG, i);
            busWrt32(FL_CTRL_REG, FL_CTRL_EXEC |
                                 (FL_ADP_1F << FL_CTRL_ADP_SHIFT) |
                                 (FL_READ_SETUP_CMD << FL_CTRL_CMD_SHIFT));

            WAIT(FL);
            
            busWrt32(FL_MA0_REG, (base + (i << FL_PAGE_SHIFT)));
            busWrt32(FL_MA1_REG, (base + size + (i & 1) * 128));

            busWrt32(FL_CTRL_REG, FL_CTRL_EXEC |
                                  FL_CTRL_RDP |
                                  FL_CTRL_RDY |
                                  FL_CTRL_ECC |
                                  (FL_ADP_00 << FL_CTRL_ADP_SHIFT) |
                                  (FL_READ_CMD << FL_CTRL_CMD_SHIFT) |
                                  ((1 << FL_PAGE_SHIFT)+FL_SPARE_SIZE) );

        }

        /* Decrypt page 'i-1' */
        WAIT(AES);
        if (i > 0 && i < (numPages + 1)) {
            checkEcc((u8 *)(base + ((i-1) << FL_PAGE_SHIFT)),
                     (u8 *)(base + size + ((i-1)&1)*128),
                     (1 << FL_PAGE_SHIFT));

            busWrt32(AES_CTRL_REG, AES_CTRL_EXEC |
                                  (i == 1 ? 0 : AES_CTRL_CHAIN ) |
                                  (AES_DECRYPT_CMD << AES_CTRL_CMD_SHIFT) |
                                  ((FL_PAGE_SIZE/16) - 1));
        }

        /* Hash page 'i-2' */
        WAIT(SHA);
        if (i > 1) {
            busWrt32(SHA_CTRL_REG, SHA_CTRL_EXEC | ((FL_PAGE_SIZE/64) - 1));
        }
    }

    /* Wait for last SHA operation to complete */
    WAIT(SHA);

    return;
}

/*
 * bootc
 *
 * This is the main line of the C language boot0 code.   It calls all
 * the other routines that are needed to read, decrypt and verify the
 * code of boot1 when read from flash.
 *
 * This routine first initializes the HW devices (aes, sha, flash, and
 * eFuse).  Next it loads a 94KB chunk from the first block on the
 * flash device.  The block is decrpyted and hashed.  The hash value
 * is checked against an expected hash value stored in the eFuse. If
 * the hash check succeeds, then newly loaded code is executed.
 */
void
bootc(void)
{
    u32  i;
    u32  expHash[5], newHash[5];
    u32  compareHash = 0;
    u32  badhash = 0;

    /*
     * Initialise hardware
     */
    setupSron();
    setupAes(BOOT1_BASE);
    setupSha(BOOT1_BASE);
    setupFlash(BOOT1_BASE);
    setupEfuse();
    enableGpio();

    /*
     * Read expected hash value from eFuse.
     */
    readEfuse(0, (u8 *)expHash, sizeof(expHash));
    for (i = 0; i < sizeof(expHash)/sizeof(expHash[0]); ++i) {
        if (expHash[i]) {
            compareHash = 1;
            break;
        }
    }

    /*
     * Load boot1 from flash into SRAM.
     */
    loadBoot1(BOOT1_BASE, BOOT1_SIZE);

    /*
     * Check computed hash against expected value from eFuse.
     */
    if (compareHash) {
        for (i = 0; i < 5; i++) {
            newHash[i] = busRd32(SHA_BUF0_REG+(i*4));
        }
        for (i = 0; i < sizeof(expHash)/sizeof(expHash[0]); ++i) {
            if (expHash[i] != newHash[i]) {
                badhash = 1;
            }
        }
    }

    if (badhash)
        bootFailure(FAIL_HASH);

    outputLed(0x0A);
    outputLed(SUCCESS);

    /* Jump to reset vector of boot1 */
    asm("ldr pc, =0xfff00000");
}

/* eof */
