/*
 *               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.
 *
 */

/*
 * This program is a port of the boot0 program to run from GDDR3 memory. 
 * It verifies the hash of boot1 (block0 of NAND) by reading all the flash
 * pages into SRAM, decrypting them, and generating the hash.
 * The resulting hash can then be compared to the hash (i.e., boot1_prod.sha)
 * generated by the tool "make_sha" when building building boot1.
 */

#include <iop.h>
#include <iostypes.h>
#include <ioslibc.h>
#include <sys.h>
#include <ahb_fdl_defs.h>

#define ENABLE_DECRYPT      1
#define ENABLE_HASH         1

#define BOOT1_BASE         (SRN_SRAM_BASE)
//#define BOOT1_BASE         0x10200000       /* Use GDDR3 for temporary buf */

#define BOOT1_SIZE         (94 * 1024)      /* 94 KB */

#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


#define STACK_SIZE          1024

const u8        _initStack[STACK_SIZE];
const u32       _initStackSize = sizeof(_initStack);
const u32       _initPriority = 120;


extern u32      __armDisableInt(void);


/*
 * Output a value to the LEDs.
 */
static 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)
{
    printf("bootFailure: %x\n", reason);
    while (1) {
        ;
    }
}

/*
 * Initialize memory
 */
static void
memorySetup(u32 base)
{
    
    if (base != SRN_SRAM_BASE) {
        /* Disable prefetch */
        busWrt32(PHYS_TO_PROTECTED(AHM_BASE + AHMPREFC), 0x0);

        init_DDR_Napa(0, 0);
    }
}

/*
 * Enable IOP access to the GPIO.
 */
static 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;

            printf("checkEcc: Fixing 1-bit error in data...\n");

            /*
             * 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)
#define FLUSH(dev)  ahbMemFlush(IOS_WB_##dev)
#define INVAL(dev)  ahbMemRBInvalidate(IOS_RB_##dev)

/*
 * 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;

    printf("Loading Boot1\n");
    for (i = 0; i < numPages + 2; ++i) {
        /* Load page 'i' from flash */

        __outputLed(i);
        __outputLed(0x80 | i);

        printf("  -> Page %2d\n", i);

        WAIT(FL);
        FLUSH(FLA);
        INVAL(IOD);

        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);
            FLUSH(FLA);
            INVAL(IOD);
            
            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' */
#if defined(ENABLE_DECRYPT)
        WAIT(AES);
        FLUSH(AES);
        INVAL(IOD);
#endif
        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));

#if defined(ENABLE_DECRYPT)
            FLUSH(IOD);
            INVAL(AES);
            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));
#endif
        }

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

    /* 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.
 */
int
main(void)
{
    u32  i;
    u32  expHash[5], newHash[5];

    /*
     * Initialize hardware
     */

    __armDisableInt();
    setupSron();
    setupAes(BOOT1_BASE);
    setupSha(BOOT1_BASE);
    setupFlash(BOOT1_BASE);
    setupEfuse();
    enableGpio();
    memorySetup(BOOT1_BASE);

    /*
     * Read expected hash value from eFuse.
     */
    readEfuse(0, (u8 *)expHash, sizeof(expHash));

    printf("\nboot1Hash [" BUILD_TIME "]:\n"); 

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

    printf("\nBoot1 Hash:\n");
    for (i = 0; i < 5; i++) {
        newHash[i] = busRd32(SHA_BUF0_REG+(i*4));
        printf("Hash[%2d] = %08x\n", i, newHash[i]);
    }

    printf("\nComparing new Hash and eFuse Hash:\n");
    for (i = 0; i < sizeof(expHash)/sizeof(expHash[0]); ++i) {
        if (expHash[i] != newHash[i]) {
            printf("Hash[%2d]: New:%08x != Exp:%08x\n", i, newHash[i], 
                expHash[i]);
        }
        else {
            printf("Hash[%2d]: New:%08x == Exp:%08x\n", i, newHash[i], 
                expHash[i]);
        }
    }
    printf("\n");

    return(0);
}

/* eof */
