/*
 *               Copyright (C) 2006, 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: boot1_dev.c,v 1.6 2008/06/04 20:10:31 cnguyen Exp $
 */

/*
 * Boot1 is stored in block 0 of the flash, and it is loaded from
 * there into sram by boot0.  After some hardware initialization
 * steps, it will load whatever lives in block 1 of the flash into
 * Napa. Block 1, upwards, and last block, downwards of the SYS
 * area of flash may contain the boot2 program, or it may contain 
 * diagnotic tests.
 *
 * In the comments below, we break the steps in the execution of
 * boot1 into hardware-related operations, and system-design related
 * operations.
 *
 * Here are the hardware-related steps in execution of boot1:
 *
 *  1. Initialize HW (assuming enhanced mode)
 *      - PLLs
 *      - Memory (Napa/DDR)
 *
 *  2. Run POST
 *      - Memory test (Napa/DDR)
 *      - Others?
 *
 *  3. Copy boot2 from flash into Napa
 *
 *  4. Turn on cache (I/D) & TLB for Napa
 *
 *  5. Rewrite exception table in SRAM & flip address bit
 *
 *  6. Jump to Napa
 *
 *  
 * Step #3, #4, #6 can be changed if we load Broadway diag
 * program into Napa/DDR. 
 *
 *  3. Copy 2nd block (128 KBytes) from flash into Napa/DDR
 *
 *  4. Rewrite exception table in SRAM & flip address bit
 *
 *  5. Release Broadway from reset
 *  
 * The IOP exception table which begins in Rom as part of Boot0,
 * should permanently reside in SRAM, for performance reasons.
 *  
 * 
 * Here are the system-deign related steps that boot1 has to execute:
 * 
 *  - Read BOOT2 version number from EEPROM.
 * 
 *  - Read block 1 and parse the eTicket. If the server signature is
 *    valid and the version number matches the EEPROM BOOT2 version, then
 *    use this copy of BOOT2.
 * 
 *  - If the above tests fail, then read backwards from the end of SYS
 *    area until a valid block is found (not marked bad in spare area,
 *    ECC and hash check). Parse the eTicket from that block. If the
 *    server signature is valid and the BOOT2 version matches,
 *    proceed. If it doesn't match, then BOOT1 fails. There is no
 *    recovery in the field for this failure.
 * 
 *  - Load the matching BOOT2 from the SYS area by chaining through the
 *    blocks, checking ECC and hash on each one.
 * 
 *  - Decrypt the BOOT2 image and jump to it.
 * 
 *  - BOOT1 requires eTicket functions and associated crypto code,
 *    drivers for eFuse, EEPROM, NAND flash, SHA, AES.
 * 
 *  - BOOT1 does not contain any file system code
 * 
 */


#include <types.h>
#include <ioslibc.h>
#include <fs.h>
#include <es.h>
#include <csl.h>
#include <iosccert.h>
#include <es_int.h>
#include <boot.h>
#include <iop.h>
#include <addr_map.h>
#include <elf.h>
#include <sys.h>
#include <mmu.h>
#include <rvl/ee.h>
#include "boot1_dev.h"


/*
 * Output a value to the LEDs
 */
void
__outputLed(u8 value)
{
    u32 reg;

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

#if defined(ENABLE_DEBUG)
    /* Store LED values to SRAM */
    {
        static u32 ofs=0;
        /* Need to skip the first 6 32-bit words used by init_DDR_Napa()
           and init_lomem() */
        u8 *addr = (u8 *)(getRsvdSRAMStart() + RSVD_SRAM_DDRVID_OFFSET+(6*4));
        /* Just to make sure that error condition won't overflow SRAM. 
           We just store up to 56 bytes (14 32-bit wrods) */
        if (ofs < 56) { 
            *(u8 *)(addr+ofs) = value;
            ofs++;
        }
    }
#endif
}


/*
 * 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.
 */
static void
bootFailure(u32 reason)
{
    while (1) {
        __outputLed (reason);
        busDelay (LED_DELAY);
        __outputLed (~reason);
        busDelay (LED_DELAY);
    }
}


/*
 * Initialize memory
 */
static void
memorySetup(void)
{
    /* Disable prefetch */
    busWrt32(PHYS_TO_PROTECTED(AHM_BASE + AHMPREFC), 0x0);

    /* Parameters: compatFlag, aram emu flag
     *  compat = 1, aram emu = 1 => compat mode with DDR in ARAM emulation
     *  compat = 0, aram emu = X => normal mode
     * init_DDR_Napa() figures out:
     *    - whether yclk is broken, 
     *    - DDR size
     *    - core and yclk values for current mode
     */
    init_DDR_Napa(0, 0);
}


/*
 * Enable the access protection to allow AES, SHA, and Flash to access
 * Sram
 */
static void
setupSron(void)
{
    u32 reg, major, minor;

    reg = ACRSRNPROT_AESEN_MASK | ACRSRNPROT_SHAEN_MASK | \
          ACRSRNPROT_FLAEN_MASK;
    getChipId(&major, &minor);
    if (major == 0) {
        reg |= ACRSRNPROT_IOPDBGEN_MASK;
    }

    busWrt32((u32)(ACRSRNPROT_REG), reg);
}


/*
 * Set up the AES device
 *  - Program and expand the key
 *  - Set up the IV and read/write pointers
 */
void
setupAes(CSLOSAesKey *aesKey, CSLOSAesIv *iv, u32 base)
{
    u32     *ptr32, i;

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

    /* Set up the AES key  */
    ptr32 = (u32 *) aesKey;
    for (i = 0; i < sizeof (CSLOSAesKey) / 4; i++) {
        busWrt32(AES_KEY_REG, *ptr32++);
    }

    /* Set up the AES iv */
    ptr32 = (u32 *) iv;
    for (i = 0; i < sizeof (CSLOSAesIv) / 4; i++) {
        busWrt32(AES_IVPTR_REG, *ptr32++);
    }

    /* Set up the read/write pointers */
    busWrt32(AES_RPTR_REG, base);
    busWrt32(AES_WPTR_REG, base);
}


int
runHashAsync(u32 *ctx, u32 type, u32 base, u32 size, CSLOSSha1Hash *result)
{
    int     rc = 0;
    u32     *hashPtr, partialSize = 0, lastSize, *ptr32, count;
    u8      *padp = (u8 *) NAPA_BUFFER_1;

    if (base & (ALIGN_SZ - 1)) {
        return (REASON_HASH);		/* Bad address alignment */
    }

    switch (type) {
        case (HASH_FIRST):
            /* Stop engine and clear interrupt mask */
            busWrt32(SHA_CTRL_REG, 0);

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

            *ctx = size;
            if (size == 0) {
                /* Initialization only */
                goto runHashAsync_out;
            }

            break;

        case (HASH_MIDDLE):
            *ctx += size;
            break;

        case (HASH_LAST):
            /* Only the last run can have non-aligned size */
            *ctx += size;
            partialSize = size & (ALIGN_SZ - 1);
            break;

        default:
            rc = REASON_HASH;
            goto runHashAsync_out;
    }

    if ((size - partialSize) > 0) {
        /* Hash the data */
        FLUSH(IOD);
        INVAL(SHA);
        busWrt32(SHA_RPTR_REG, base);
        busWrt32(SHA_CTRL_REG, SHA_CTRL_EXEC |
                        ((size - partialSize - 64) >> SHA_BLOCK_SZ_SHIFT));
    }

    /* Return the result for the last run */
    if (type == HASH_LAST) {
        u8 byte[1];

        memset(padp, 0, ALIGN_SZ * 2);

        /* Set 0x80 at the last byte */
        if (partialSize > 0) {
            memcpy(padp, (u8 *) (base + size - partialSize), partialSize);
        }
        byte[0] = 0x80;
        memcpy(&padp[partialSize], byte, 1);

        /* Set the hash size at the last word */
        if (((ALIGN_SZ - partialSize) >= 9) || (partialSize == 0)) {
            ptr32 = (u32 *) (padp + ALIGN_SZ - 4);
            lastSize = ALIGN_SZ;
        } else {
            ptr32 = (u32 *) (padp + (2 * ALIGN_SZ) - 4);
            lastSize = ALIGN_SZ * 2;
        }
        *ptr32 = ntohl(*ctx * 8);

        /* Hash the padding */
        WAIT(SHA);
        FLUSH(IOD);
        INVAL(SHA);
        busWrt32(SHA_RPTR_REG, (u32) padp);
        busWrt32(SHA_CTRL_REG, SHA_CTRL_EXEC |
                            ((lastSize - 64) >> SHA_BLOCK_SZ_SHIFT));
        WAIT(SHA);

        /* Read back the hash result */
        hashPtr = (u32 *) result;
        for (count = 0; count < (sizeof (CSLOSSha1Hash) / 4); count++) {
            hashPtr[count] = busRd32(SHA_BUF0_REG + (count * 4));
        }

        *ctx = 0;
    }

runHashAsync_out:

    return (rc);
}


#ifndef BOOT1_DISABLE_EFUSE
/*
 * Read 'size' bytes starting at 'address' into 'buffer'
 */
static void
readEfuse(u32 address, u8 *buffer, u32 size)
{
    u32     data, i;

    memset (buffer, 0, size);
    for (i = 0; i < size; i += sizeof (u32)) {
        /* Physical read */
        busWrt32(EFUSE_ADDR_REG,
             ACREFUSEADDR_EFEN_MASK | (address & ACREFUSEADDR_EFADDR_MASK));
        data = busRd32(EFUSE_DATA_REG);
        *((u32 *)buffer) = data;

        buffer += sizeof (u32);
        address++;
    }
}
#endif


#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. 
 */
int
checkEcc(u8 *buf, u8* spare, u32 pageSize)
{
    int rc = 0, 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, don't bother fixing it... */
            continue;
        }

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

            /*
             * Repair the error. Bits 0 to 2 indicate the bit location,
             * bits 3 to 11 indicate the byte location. Since the
             * correction may happen in NAPA, use memcpy
             */
            dataPtr = ((u8 *)buf) + (eccCount * FL_ECC_UNIT);
            data = dataPtr[(high & 0x00000ff8) >> 3];
            data ^= (1 << (high & 0x7));
            memcpy(&dataPtr[(high & 0x00000ff8) >> 3], &data, 1);
            continue;
        } else {
            /* Multi-bit error */
            rc = REASON_DBE;
            goto checkEcc_out;
        }
    }

checkEcc_out:

    return (rc);
}


/*
 * Read a page into memory asynchronously
 */
void
readPageAsync(u32 page, u8 *dataBuf, u8 *spareBuf)
{
    /* Stop engine and clear interrupt mask */
    busWrt32(FL_CTRL_REG, 0);

    /* Set up page and byte offset */
    busWrt32(FL_AD0_REG, 0);
    busWrt32(FL_AD1_REG, page);

    /* Read setup */
    busWrt32(FL_CTRL_REG, FL_CTRL_EXEC | (FL_ADP_1F << FL_CTRL_ADP_SHIFT) |
                            (FL_READ_SETUP_CMD << FL_CTRL_CMD_SHIFT));
    WAIT(FL);

    /* Read */
    busWrt32(FL_MA0_REG, (u32) dataBuf);
    busWrt32(FL_MA1_REG, (u32) spareBuf);
    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) |
                        (FL_PAGE_SIZE + FL_SPARE_SIZE));
}


/*
 * Read the boot2 block map
 */
static void
loadBoot2BlockMap(Boot2BlockMap *blockMap, u32 base)
{
    u32             i, numBlocks, page, numPagesInBlock;
    u8              *dataBuf = (u8 *) base;
    u8              *spareBuf = (u8 *) (base + FL_PAGE_SIZE);
    Boot2BlockMap   *map1, *map2, *map3, *map;
    u8              boot2Magic[BOOT2_MAGIC_SIZE] = BOOT2_MAGIC;

    /* Do not read beyond the SYS area */
    numBlocks = ISFS_SYSAREA_SIZE >> FL_BLOCK_SHIFT;
    numPagesInBlock = 1 << (FL_BLOCK_SHIFT - FL_PAGE_SHIFT);

    /* Load the boot2 block map */
    blockMap->seq = 0;
    for (i = 1; i < numBlocks; i++) {
        /* Read the last page of each block */
        page = ((i + 1) * numPagesInBlock) - 1;

        readPageAsync(page, dataBuf, spareBuf);
        WAIT(FL);
        FLUSH(FLA);
        INVAL(IOD);

        /* Find the latest block map */
        map1 = (Boot2BlockMap *) dataBuf;
        map2 = (Boot2BlockMap *) (dataBuf + sizeof (Boot2BlockMap));
        map3 = (Boot2BlockMap *) (dataBuf + (2 * sizeof (Boot2BlockMap)));

        if (!memcmp(map1->magic, boot2Magic, BOOT2_MAGIC_SIZE) &&
                (!memcmp(map1, map2, sizeof (Boot2BlockMap)) ||
                !memcmp(map1, map3, sizeof (Boot2BlockMap)))) {
            map = map1;
        } else {
            if (!memcmp(map2->magic, boot2Magic, BOOT2_MAGIC_SIZE) &&
                    !memcmp(map2, map3, sizeof (Boot2BlockMap))) {
                map = map2;
            } else {
                continue;
            }
        }

        if (map->seq > blockMap->seq) {
            /* Found a newer block map */
            blockMap->seq = map->seq;
            memcpy(blockMap->map, map->map, BOOT2_MAX_BLOCKS);
        }
    }
}


/*
 * Skip bad blocks
 */
static int
skipBadBlocks(u32 dir, u32 blockOffset, Boot2BlockMap *blockMap, u32 base)
{
    int     rc, next;
    u32     page, i;
    u8      *dataBuf = (u8 *) base;
    u8      *spareBuf = (u8 *) (base + FL_PAGE_SIZE);

    /* Move forward or backward */
    next = (dir == DIR_FORWARD) ? 1 : -1;

    if (blockMap->seq > 1) {
        /* The block map has all the bad block info */
        while (BLOCK_WITHIN_SYSAREA(blockOffset) &&
                (blockMap->map[blockOffset] == BOOT2_BLOCK_BAD)) {
            blockOffset += next;
        }
    } else {
        /* Read in the first two pages and check the status byte */
        while (BLOCK_WITHIN_SYSAREA(blockOffset)) {
            page = blockOffset << (FL_BLOCK_SHIFT - FL_PAGE_SHIFT);

            for (i = 0; i < 2; i++) {
                readPageAsync(page + i, dataBuf, spareBuf);
                WAIT(FL);
                FLUSH(FLA);
                INVAL(IOD);

                if (spareBuf[FL_STATUS_BYTE] != 0xff) {
                    blockOffset += next;
                    break;
                }
            }

            /* Found a good block */
            if (i == 2) {
                break;
            }
        }
    }

    if (!BLOCK_WITHIN_SYSAREA(blockOffset)) {
        rc = REASON_BADBLOCK;
    } else {
        rc = blockOffset;
    }

    return (rc);
}


/*
 * Read the boot2 WAD header
 */
static int
loadWadHeader(u32 blockOffset, ESWadHeader *wadHdr, u32 base)
{
    int     rc = 0;
    u32     page;
    u8      *dataBuf = (u8 *) base;
    u8      *spareBuf = (u8 *) (base + FL_PAGE_SIZE);

    /* The WAD header is in the first page */
    page = blockOffset << (FL_BLOCK_SHIFT - FL_PAGE_SHIFT);
    readPageAsync(page, dataBuf, spareBuf);
    WAIT(FL);
    FLUSH(FLA);
    INVAL(IOD);

    rc = checkEcc(dataBuf, spareBuf, FL_PAGE_SIZE);
    if (rc != 0) {
        goto loadWadHeader_out;
    }

    /* Handle the wad header endianness */
    memcpy(wadHdr, dataBuf, sizeof (ESWadHeader));
    wadHdr->hdrSize = ntohl(wadHdr->hdrSize);
    wadHdr->contentOffset = ntohl(wadHdr->contentOffset);
    wadHdr->certSize = ntohl(wadHdr->certSize);
    wadHdr->ticketSize = ntohl(wadHdr->ticketSize);
    wadHdr->tmdSize = ntohl(wadHdr->tmdSize);
    wadHdr->metaSize = ntohl(wadHdr->metaSize);
    wadHdr->metaCid = ntohl(wadHdr->metaCid);

    /*
     * Check the header:
     *
     *  - For simplicity, assert that the header size is smaller
     *    than one page, and that the content offset is smaller
     *    than one flash block
     *  - The offset to the start of content has to be aligned to
     *    64 byte boundary for SHA operations
     *  - Assert that all header values do not point outside the flash block
     */
    if ((wadHdr->hdrSize != sizeof (ESWadHeader)) ||
            (wadHdr->certSize != (sizeof(IOSCRsa4096RsaCert)
                   + (2 * sizeof(IOSCRsa2048RsaCert)))) ||
            (wadHdr->ticketSize != sizeof(ESTicket)) ||
            (wadHdr->tmdSize != (sizeof(IOSCSigRsa2048)
                   + sizeof(ESTitleMetaHeader) + sizeof(ESContentMeta))) ||
            (wadHdr->contentOffset > FL_BLOCK_SIZE) ||
            (wadHdr->contentOffset & (ALIGN_SZ - 1))) {
        rc = REASON_BADHEADER;
        goto loadWadHeader_out;
    }

loadWadHeader_out:

    return (rc);
}


/*
 * Load and verify the content
 */
static int
loadAndVerifyContent(u32 dir, u32 blockOffset, Boot2BlockMap *blockMap,
    u32 contentOffset, u32 contentSize, u32 base, CSLOSSha1Hash *hash)
{
    int             rc = 0;
    u32             numBlocks, numPagesInBlock, pageSize, next, page;
    u32             firstPageOffset, spare, numPages, pageInMem, i, j;
    u32             startPageForCurBlock, startPageForFirstBlock;
    u32             numPagesInCurBlock, numPagesInLastBlock;
    u32             firstPageSize, lastPageSize, count, hashCtx;
    u32             *hashInTicket, *hashComputed, padSize;
    CSLOSSha1Hash   hashResult;

    /* Content size is the raw size, the true size is padded to 16 bytes */
    padSize = (contentSize + 15) & ~15;

    pageSize = FL_PAGE_SIZE;
    numPages = (padSize + contentOffset + pageSize - 1) >>
                    FL_PAGE_SHIFT;
    numPagesInBlock = (1 << (FL_BLOCK_SHIFT - FL_PAGE_SHIFT));
    numBlocks = (numPages + numPagesInBlock - 1) >>
                    (FL_BLOCK_SHIFT - FL_PAGE_SHIFT);

    /* Read only part of the first and last blocks */
    startPageForFirstBlock = contentOffset >> FL_PAGE_SHIFT;
    numPagesInLastBlock = numPages & (numPagesInBlock - 1);
    if (numPagesInLastBlock == 0) {
        numPagesInLastBlock = numPagesInBlock;
    }

    /* Decrypt/hash only part of the first and last pages */
    firstPageOffset = contentOffset & (pageSize - 1);
    firstPageSize = pageSize - firstPageOffset;
    lastPageSize = (padSize + firstPageOffset) & (pageSize - 1);
    if (lastPageSize == 0) {
        lastPageSize = pageSize;
    }

    /* Spare buffer */
    spare = (base + padSize + firstPageOffset + pageSize + 127) & ~127;
    if ((spare + 256) >= (BOOT2_LOAD_START + BOOT2_MAX_SIZE)) {
        /* Content too large */
        rc = REASON_BADCONTENT;
        goto loadAndVerifyContent_out;
    }

    /* Move forward or backward */
    next = (dir == DIR_FORWARD) ? 1 : -1;

    i = 0;
    while (i < numBlocks) {
        /* Skip bad blocks not marked by manufacturing */
        if (blockMap->seq > 1) {
            while (BLOCK_WITHIN_SYSAREA(blockOffset) &&
                    (blockMap->map[blockOffset] == BOOT2_BLOCK_BAD)) {
                blockOffset += next;
            }
        }

        if (!BLOCK_WITHIN_SYSAREA(blockOffset)) {
            rc = REASON_BADCONTENT;
            goto loadAndVerifyContent_out;
        }

        /* The first block may not start at page 0 */
        if (i == 0) {
            startPageForCurBlock = startPageForFirstBlock;
        } else {
            startPageForCurBlock = 0;
        }

        /*
         * The last page to read is a bit tricky since it may not go
         * all the way to the end for the last block, but it still
         * needs to read at least the first two pages to make sure
         * the block is not marked as invalid. The trick here is to
         * change the value of numPagesInCurBlock after j reaches 2
         * inside the loop. The following loop should still handle
         * the case of having only one valid page in the block
         * correctly
         */
        numPagesInCurBlock = numPagesInBlock;

        for (j = startPageForCurBlock; j < (numPagesInCurBlock + 2); j++) {
            /*
             * For the last flash block, read only until the last page
             * that contains valid data, but read at least the first
             * two pages
             */
            if ((j == 2) && (i == (numBlocks - 1))) {
                numPagesInCurBlock = numPagesInLastBlock;
            }

            page = (blockOffset * numPagesInBlock) + j;
            pageInMem = (i * numPagesInBlock) + j - startPageForFirstBlock;

            /* Load page from flash */
            WAIT(FL);
            FLUSH(FLA);
            INVAL(IOD);
            if (j < numPagesInCurBlock) {
                readPageAsync(page,
                        (u8 *) (base + (pageInMem << FL_PAGE_SHIFT)),
                        (u8 *) (spare + ((j & 1) * 128)));
            }

            /* Check the status byte in the first two pages of a block */
            if ((j == 0) || (j == 1)) {
                u8      *spareBuf;

                /* Check the status byte in the spare area for bad blocks */
                WAIT(FL);
                FLUSH(FLA);
                INVAL(IOD);
                spareBuf = (u8 *) (spare + ((j & 1) * 128));
                if (spareBuf[FL_STATUS_BYTE] != 0xff) {
                    /* Skip the current block if it's bad */
                    break;
                }

                if (j == 0) {
                    /* Go to the next page */
                    continue;
                }
            }

            /* Check ECC and decrypt for page 'j-1' */
            WAIT(AES);
            FLUSH(AES);
            INVAL(IOD);
            if ((j > startPageForCurBlock) && (j < (numPagesInCurBlock + 1))) {
                u32     aesSize;

                rc = checkEcc(
                        (u8 *) (base + ((pageInMem - 1) << FL_PAGE_SHIFT)),
                        (u8 *) (spare + ((j - 1) & 1) * 128), pageSize);
                if (rc < 0) {
                    goto loadAndVerifyContent_out;
                }

                /* Only decrypt the necessary size */
                if ((i == 0) && (j == (startPageForFirstBlock + 1))) {
                    aesSize = firstPageSize;
                } else if ((i == (numBlocks - 1)) &&
                        (j == numPagesInCurBlock)) {
                    aesSize = lastPageSize;
                } else {
                    aesSize = pageSize;
                }

                FLUSH(IOD);
                INVAL(AES);
                busWrt32(AES_CTRL_REG, AES_CTRL_EXEC |
                    (((i == 0) && (j == (startPageForCurBlock + 1))) ?
                        0 : AES_CTRL_CHAIN) |
                    (AES_DECRYPT_CMD << AES_CTRL_CMD_SHIFT) |
                    ((aesSize - 16) >> AES_BLOCK_SZ_SHIFT));
            }

            /* Hash page 'j-2' */
            WAIT(SHA);
            if (j > (startPageForCurBlock + 1)) {
                u32     shaStart, shaSize, type;

                /* Only hash the necessary size */
                if ((i == 0) && (j == (startPageForFirstBlock + 2))) {
                    shaStart = base + firstPageOffset;
                    shaSize = firstPageSize;
                    type = HASH_FIRST;
                } else if ((i == (numBlocks - 1)) &&
                        (j == (numPagesInCurBlock + 1))) {
                    shaStart = base + ((pageInMem - 2) << FL_PAGE_SHIFT);
                    shaSize = lastPageSize + contentSize - padSize;
                    type = HASH_LAST;
                } else {
                    shaStart = base + ((pageInMem - 2) << FL_PAGE_SHIFT);
                    shaSize = pageSize;
                    type = HASH_MIDDLE;
                }

                rc = runHashAsync(&hashCtx, type, shaStart, shaSize,
                                &hashResult);
                if (rc < 0) {
                    goto loadAndVerifyContent_out;
                }
            }
        }

        if (j == (numPagesInCurBlock + 2)) {
            i++;
        }
        blockOffset += next;
    }

    /* Verify the hash value */
    hashInTicket = (u32 *) hash;
    hashComputed = (u32 *) hashResult;
    for (count = 0; count < (sizeof (CSLOSSha1Hash) / 4); count++) {
        if (hashInTicket[count] != hashComputed[count]) {
            rc = REASON_HASH;
            goto loadAndVerifyContent_out;
        }
    }

loadAndVerifyContent_out:

    return (rc);
}


/*
 * Load the next stage of the boot process
 */
static int
loadBoot2(u32 dir, u32 base, u32 maxSize)
{
    int                     rc = 0, blockOffset;
    u32                     numBlocks, contentSize, skipBytes;
    Boot2BlockMap           blockMap;
    ESWadHeader             wadHdr;
    CSLOSAesKey             aesKey;
    u8                      ivBuf[ALIGN_SZ*2];
    CSLOSAesIv              *ivPtr = (CSLOSAesIv *)
                                    (((u32)ivBuf+ALIGN_SZ-1) & ~(ALIGN_SZ-1));
    CSLOSSha1Hash           hash;


    DEBUG_LED(0x12);	/* Enter loadBoot2 */

    /* Load the block map */
    loadBoot2BlockMap(&blockMap, base);

    /* Find the starting block based on the direction */
    numBlocks = ISFS_SYSAREA_SIZE >> FL_BLOCK_SHIFT;
    if (dir == DIR_FORWARD) {
        blockOffset = 1;
    } else {
        blockOffset = numBlocks - 1;
    }

    DEBUG_LED(0x13);	/* Before skip bad blocks */

    /* Skip bad blocks */
    blockOffset = skipBadBlocks(dir, blockOffset, &blockMap, base);
    if (blockOffset < 0) {
        rc = blockOffset;
        goto loadBoot2_out;
    }

    DEBUG_LED(0x14);	/* Before load wad header */

    /* Read the WAD header */
    rc = loadWadHeader(blockOffset, &wadHdr, base);
    if (rc < 0) {
        goto loadBoot2_out;
    }

    DEBUG_LED(0x15);	/* Before verify certs, tmd, and ticket */

    /* If debug is enabled, verifyBundle() can output 0x16 - 0x20 to LED */
    /* Verify certs, tmd, and ticket */
    rc = verifyBundle(blockOffset, &wadHdr, &contentSize,
                    &aesKey, ivPtr, &hash, base);
    if (rc < 0) {
        goto loadBoot2_out;
    }

    DEBUG_LED(0x21);	/* Before load and verify content */

    /* Skip a certain number of bytes when doing AES/SHA for the first page */
    skipBytes = wadHdr.contentOffset & (FL_PAGE_SIZE - 1);
    setupAes(&aesKey, ivPtr, base + skipBytes);

    /* Load and verify the content */
    rc = loadAndVerifyContent(dir, blockOffset, &blockMap,
                            wadHdr.contentOffset, contentSize, base, &hash);
    if (rc < 0) {
        goto loadBoot2_out;
    }
    rc = base + skipBytes;

loadBoot2_out:

    return (rc);
}


/*
 * This is the C code portion of boot1. The assembler portion of the code
 * has setup a stack prior to calling this routine
 */
u32
bootc(void)
{
    int                 rc = 0, imgStart;
    u32                 dir;
    BootOSImageHeader   *hdr;

    __outputLed(0x11);

    /* Set up the EEPROM */
    EE_GPIOSetup();

#if defined(ENABLE_SS)

#define EEPROM_BWD_SS_OFS       66      /* Half-word location for SS */

    u32 chipid_major, chipid_minor;
    getChipId( &chipid_major, &chipid_minor);

    if (chipid_major >= 2) {  /* Check for SS only in Bollywood */
        u32 ssVal;

        DEBUG_LED(0x51);

        /* Check EEPROM half-word location 66 for SS setting */
        rc = EE_RdCmd(EEPROM_BWD_SS_OFS, &ssVal);
        if (rc != IOS_ERROR_OK) {
            bootFailure(REASON_EEPROM);
        }
        DEBUG_LED(ssVal);

        if (isSSConfigValid(ssVal)) {

            /* Check SSEN bit in ACRPLLSYSEXT1 to see if Bollywood has been
             * reset or not
             */
            u32 volatile reg = busRd32(PHYS_TO_PROTECTED(ACR_REGS_BASE +
                                   ACRPLLSYSEXT1_OFFSET));

            /* If SS is not set, enable it now */
            if (!(ACRPLLSYSEXT1_GET_SYSPLL_SSEN(reg))) {
                DEBUG_LED(0x52);

                /* Turn on SS feature */
                setSS(ssVal);

                /* Should not reached here since setting SS will also do a
                 * soft reset of Bollywood.
                 */
                DEBUG_LED(0x53);
                while (1) {};
            }
            else {
                DEBUG_LED(0x54);
            }
        }  /* SS is on */
    }  /* Bollywood */
#endif  /* ENABLE_SS */

    /* Initialize access protection and memory */
    setupSron();
    memorySetup();

    for (dir = DIR_FORWARD; dir <= DIR_BACKWARD; dir++) {
        /* The forward direction has failed, clean up the HW states */
        if (dir == DIR_BACKWARD) {
            WAIT(FL);
            WAIT(AES);
            WAIT(SHA);
            
            /* To get a clean start, flush and invalidate all AHB buffers */
            FLUSH_ALL();
            INVAL_ALL();
        }

        /* Load boot2 from flash */
        imgStart = loadBoot2(dir, BOOT2_LOAD_START, BOOT2_MAX_SIZE);
        if (imgStart >= 0) {
            /* Done if successful */
            break;
        }

        /* Try the other copy */
        rc = imgStart;
        DEBUG_LED(rc);
    }

    /* Check for failure */
    if (dir > DIR_BACKWARD) {
        bootFailure(rc);
    }

    /*
     * After the image is loaded, boot1 will jump to the OS loader.
     * The address of the OS loader is indicated in the image header.
     * The assembly code after "bl bootc" will jump to the start of
     * the OS loader
     */
    hdr = (BootOSImageHeader *) imgStart;
    hdr->ddrInit = 1;

    __outputLed(0x22);

    return (imgStart + hdr->hdrSize);
}

/* eof */
