/*
 *               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.c,v 1.38 2008/07/28 20:50:56 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. See ng/doc/sw/boot_iop.html for some details
 * of the layout.
 *
 * 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 2nd block (128 KBytes) 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 <diag/proto.h>
#include <rvl/nvram.h>
#include <rvl/ee.h>
#include <root.h>


/* Turn on/off support for SS (spread spectrum) feature in Bollywood */
#define ENABLE_SS           1

/* Hardcoded addresses for the start of AHB, AHB protected, SRAM, and Napa */
#define AHB_START           0x0d000000
#define AHB_PROT_START      0x0d800000
#define SRAM_START          0x0d400000
#define SRAM_ALT_START      0xfff00000
#define NAPA_START          0x00000000

/*
 * The maximum boot1 size, anything after this can be used for buffering
 * The size is aligned on 16KB boundary so that the TTB can be placed
 * at this location. The first 32KB of the SRAM is used for boot1 code,
 * the next 16KB is used for the TTB, and the last 16KB is used for the
 * stack. The SRAM beyond that is not used because it may not work in
 * some older version of hardware
 */
#define BOOT1_MAX_SIZE      (BOOT1_MAX_CODEDATA_SIZE + BOOT1_MAX_BSS_SIZE)

/* TTB address and size */
#define BOOT1_TTB_START     (SRAM_START + BOOT1_MAX_SIZE)
#define BOOT1_TTB_ENTRIES   4096

/* Define staging area for loading boot2 */
#ifdef LOAD_TO_NAPA
#define BOOT2_LOAD_START    0x00028000
#define BOOT2_LOAD_END      0x00080000
#endif /* LOAD_TO_NAPA */

#ifdef LOAD_TO_DDR
#define BOOT2_LOAD_START    (RSVD_SP_START - (4 * 1024 * 1024))
#define BOOT2_LOAD_END      (BOOT2_LOAD_START + (1024 * 1024))
#endif

#define BOOT2_MAX_SIZE      (BOOT2_LOAD_END - BOOT2_LOAD_START)

/*
 * Because of a hardware bug, we can't do DMA with from/into the
 * SRAM while running in the SRAM. The workaround here is to use
 * the second safe area inside the Napa for buffering. The area
 * from 0x0000a8000 to 0x00100000 is safe. Divide the area into
 * several 16KB sections for use by the boot1 code
 */
#define NAPA_BUFFER_1       0x000a8000
#define NAPA_BUFFER_2       0x000ac000
#define NAPA_BUFFER_3       0x000b0000
#define NAPA_BUFFER_SIZE    (16*1024)

/* Alignment sizes */
#define AES_BLOCK_SZ_SHIFT  4
#define AES_BLOCK_SZ        (1 << AES_BLOCK_SZ_SHIFT)
#define SHA_BLOCK_SZ_SHIFT  6
#define SHA_BLOCK_SZ        (1 << SHA_BLOCK_SZ_SHIFT)
#define ALIGN_SZ_SHIFT      6
#define ALIGN_SZ            (1 << ALIGN_SZ_SHIFT)

#define OVERLAP(addr1, sz1, addr2, sz2)                                     \
    (((addr1 <= addr2) && ((addr1 + sz1) > addr2)) ||                       \
    ((addr2 <= addr1) && ((addr2 + sz2) > addr1)))

/* Direction to read boot2 */
#define DIR_FORWARD         1
#define DIR_BACKWARD        2

/*
 * String limiting for cert names;
 * each piece is a two-char name followed by 8 digits;
 * we build up ROOT plus up to 3 pieces, for a total of 4;
 * sizeof(IOSCName) is 64, divide by 4 is 16 for each piece;
 */
#define SIZE_LIMCNAME       (sizeof(IOSCName) / 4)

/* Constants for flash */
#define FL_BLOCK_SHIFT      17
#define FL_BLOCK_SIZE       (1 << FL_BLOCK_SHIFT)
#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 FL_STATUS_BYTE      0

#define BLOCK_WITHIN_SYSAREA(bl)                                            \
    ((bl >= 1) && (bl < (ISFS_SYSAREA_SIZE >> FL_BLOCK_SHIFT)))

/* Hash types */
#define HASH_FIRST          1
#define HASH_MIDDLE         2
#define HASH_LAST           3

/* Type of certs/tmd/ticket to verify */
#define TYPE_CERT4096       1
#define TYPE_CERT2048       2
#define TYPE_TMD            3
#define TYPE_TICKET         4

/* Delay */
#define LED_DELAY           1000000

/* Error codes */
#define REASON_DBE          -1      // HEX LED = 0xFF
#define REASON_BADMAP       -2      // HEX LED = 0xFE
#define REASON_BADELF       -3      // HEX LED = 0xFD
#define REASON_BADBLOCK     -4      // HEX LED = 0xFC
#define REASON_BADHEADER    -5      // HEX LED = 0xFB
#define REASON_BADCONTENT   -6      // HEX LED = 0xFA
#define REASON_HASH         -7      // HEX LED = 0xF9
#define REASON_BADSIG       -8      // HEX LED = 0xF8
#define REASON_BADNAME      -9      // HEX LED = 0xF7
#define REASON_BADVERSION   -10     // HEX LED = 0xF6
#define REASON_BADTITLE     -11     // HEX LED = 0xF5
#define REASON_EEPROM       -12     // HEX LED = 0xF4

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

/* Device control */
#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)
#define FLUSH_ALL()                                                         \
    do {                                                                    \
        FLUSH(IOD);                                                         \
        FLUSH(FLA);                                                         \
        FLUSH(AES);                                                         \
        FLUSH(SHA);                                                         \
    } while (0)
#define INVAL_ALL()                                                         \
    do {                                                                    \
        INVAL(IOD);                                                         \
        INVAL(FLA);                                                         \
        INVAL(AES);                                                         \
        INVAL(SHA);                                                         \
    } while (0)


#if defined(ENABLE_DEBUG)
#define DEBUG_LED(x)    __outputLed(x)
#else
#define DEBUG_LED(x)    (void)(0)
#endif


/* Root key and exponent */
#if defined (RVL_DEVEL_PKI)
static u8 rootExp[] = RVL_DEVEL_PKI_EXP
static u8 rootKey[] = RVL_DEVEL_PKI_MOD
#elif defined (RVL_PROD_PKI)
static u8 rootExp[] = RVL_PROD_PKI_EXP
static u8 rootKey[] = RVL_PROD_PKI_MOD
#endif

/* Default common key */
#if defined (RVL_DEVEL_PKI)
static u8 commonAesKey[] = {
 0xa1,  0x60,  0x4a,  0x6a,  0x71,  0x23,  0xb5,  0x29,
 0xae,  0x8b,  0xec,  0x32,  0xc8,  0x16,  0xfc,  0xaa
};
#elif defined (RVL_PROD_PKI)
static u8 commonAesKey[] = {
 0xeb,  0xe4,  0x2a,  0x22,  0x5e,  0x85,  0x93,  0xe4,
 0x48,  0xd9,  0xc5,  0x45,  0x73,  0x81,  0xaa,  0xf7
};
#endif


/*
 * Output a value to the LEDs
 */
static 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);
}


#ifndef BOOT1_DISABLE_DCACHE
extern void mmuSetTTB(u32 ttbAddr);
extern void mmuSetDACR(u32 access);
extern void drainWriteBuffer(void);
extern void mmuEnable(void);
extern void mmuDisable(void);
extern void enableDCache(void);
extern void disableDCache(void);
extern void flushDCache(void);

/*
 * Initialize the MMU and D-cache
 */
static void
enableMMUDCache(void)
{
    u32	*ttbAddr = (u32 *) BOOT1_TTB_START;

    /* Initialize the TTB region */
    memset(ttbAddr, 0, BOOT1_TTB_ENTRIES * sizeof (u32));

    /*
     * Set up the MMU regions, one for the SRAM and the other for
     * Napa. The SRAM region is cached and the Napa region is
     * uncached. With this configuration, we can achieve both goals
     * of fast execution (caching SRAM), and less exposure to bugs
     * (not caching the Napa which we use for all device ops). For
     * both SRAM and Napa, we only need to setup the first MB since
     * boot1 doesn't use anything outside of the first MB
     */
    setupSectionEntry(ttbAddr, SRAM_START >> 20, WRITEBACK_SECTION);
    setupSectionEntry(ttbAddr, SRAM_ALT_START >> 20, WRITEBACK_SECTION);
    setupSectionEntry(ttbAddr, NAPA_START >> 20, NONBUFFERED_SECTION);

    /*
     * Other than the actual memory regions, also set up access to
     * the register space at AHB_START and AHB_PROT_START. 1MB is
     * also enough in both cases
     */
    setupSectionEntry(ttbAddr, AHB_START >> 20, NONBUFFERED_SECTION);
    setupSectionEntry(ttbAddr, AHB_PROT_START >> 20, NONBUFFERED_SECTION);

    /* Set the TTB base register */
    mmuSetTTB((u32) ttbAddr);

    /* Set up the domain access */
    mmuSetDACR(DOMAIN_MANAGER_ACCESS);

    /* Enable the MMU */
    mmuEnable();

    /* Enable the D-cache */
    enableDCache();
}

/*
 * Disable the D-cache and MMU
 */
static void
disableMMUDCache(void)
{
    /* Flush the D-cache */
    flushDCache();

    /* Disable the D-cache */
    disableDCache();

    /* Drain the write buffer */
    drainWriteBuffer();

    /* Disable the MMU */
    mmuDisable();
}
#endif


/*
 * 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
 */
static 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);
}


static 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. 
 */
static 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
 */
static 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);
}


static u32
getExpSize(CSLOSRsaExponent exponent, u32 maxSize)
{
    int trailingZeros = 0;
    int i;

    /* Find trailing zeros */
    for (i = maxSize - 1; i >= 0; i--) {
        if (exponent[i] != 0x0) {
            break;
        }

        trailingZeros++;
    }

    return (maxSize - trailingZeros);
}


static int
verifySig(u32 base, void *p, IOSCName *issuer, void *pubKey, 
    CSLOSRsaExponent *exp, u32 type, u32 size)
{
    int                 rc = 0;
	void                *bp;
    u32                 hashSize, ctx;
    u8                  *bufp = (u8 *) NAPA_BUFFER_2;
    IOSCRsa4096RsaCert  *cert4096;
    IOSCRsa2048RsaCert  *cert2048;
    ESTitleMeta         *tmd;
    ESTicket            *ticket;
    IOSCName            *issuerName;
    CSLOSSha1Hash       hash;

    /* 
     * Below memcpy() could be abused for attacks if not checked;
     * some of the wad header sizes have been checked to stay within the
     * flash block, but some are combined, so we need to check p again;
     * assert that copied size fits into 32k NAPA_BUFFER_2;
     */
    bp = (void *)base;
    rc = REASON_BADHEADER;
    if (p < bp) {
        goto verifySig_out;			/* obvious violation */
    }
    if (p > (bp + FL_BLOCK_SIZE)) {
        goto verifySig_out;			/* something is outside flash block */
    }
    if (size >= NAPA_BUFFER_SIZE) {
        goto verifySig_out;			/* size to big */
    }

    /* Copy to the aligned buffer */
    memcpy(bufp, p, size);
    cert4096 = (IOSCRsa4096RsaCert *) bufp;
    cert2048 = (IOSCRsa2048RsaCert *) bufp;
    tmd = (ESTitleMeta *) bufp;
    ticket = (ESTicket *) bufp;

    switch (type) {
        case (TYPE_CERT4096):
            issuerName = &(cert4096->sig.issuer);
            base = (u32) cert4096 + sizeof (IOSCSigRsa4096) - sizeof (IOSCName);
            hashSize = size - sizeof (IOSCSigRsa4096) + sizeof (IOSCName);
            break;

        case (TYPE_CERT2048):
            issuerName = &(cert2048->sig.issuer);
            base = (u32) cert2048 + sizeof (IOSCSigRsa2048) - sizeof (IOSCName);
            hashSize = size - sizeof (IOSCSigRsa2048) + sizeof (IOSCName);
            break;

        case (TYPE_TMD):
            issuerName = &(tmd->sig.issuer);
            base = (u32) tmd + sizeof (IOSCSigRsa2048) - sizeof (IOSCName);
            hashSize = size - sizeof (IOSCSigRsa2048) + sizeof (IOSCName);
            break;

        case (TYPE_TICKET):
            issuerName = &(ticket->sig.issuer);
            base = (u32) ticket + sizeof (IOSCSigRsa2048) - sizeof (IOSCName);
            hashSize = size - sizeof (IOSCSigRsa2048) + sizeof (IOSCName);
            break;

        default:
            rc = REASON_BADSIG;
            goto verifySig_out;
    }

    /*
     * hashSize could still be bad if corrupted size is passed in;
     * it is unsigned, so can't be < 0, but roll over;
     */
    if (hashSize >= NAPA_BUFFER_SIZE) {
        goto verifySig_out;
    }

    /* Check the issuer's name */
    if (memcmp(issuerName, issuer, sizeof (IOSCName))) {
        rc = REASON_BADSIG;
        goto verifySig_out;
    }

    /* Calculate the hash */
    rc = runHashAsync(&ctx, HASH_FIRST, base, 0, NULL);
    if (rc < 0) {
        goto verifySig_out;
    }
    rc = runHashAsync(&ctx, HASH_LAST, base, hashSize, &hash);
    if (rc < 0) {
        goto verifySig_out;
    }

    /* Verify the signature */
    switch (type) {
        case (TYPE_CERT4096):
            rc = CSL_VerifyRsaSig4096(hash, pubKey, cert4096->sig.sig,
                            *exp, getExpSize(*exp, sizeof (CSLOSRsaExponent)));
            if (rc != CSL_OK) {
                rc = REASON_BADSIG;
                goto verifySig_out;
            }

            break;

        case (TYPE_CERT2048):
            rc = CSL_VerifyRsaSig2048(hash, pubKey, cert2048->sig.sig,
                            *exp, getExpSize(*exp, sizeof (CSLOSRsaExponent)));
            if (rc != CSL_OK) {
                rc = REASON_BADSIG;
                goto verifySig_out;
            }

            break;

        case (TYPE_TMD):
            rc = CSL_VerifyRsaSig2048(hash, pubKey, tmd->sig.sig,
                            *exp, getExpSize(*exp, sizeof (CSLOSRsaExponent)));
            if (rc != CSL_OK) {
                rc = REASON_BADSIG;
                goto verifySig_out;
            }

            break;

        case (TYPE_TICKET):
            rc = CSL_VerifyRsaSig2048(hash, pubKey, ticket->sig.sig,
                            *exp, getExpSize(*exp, sizeof (CSLOSRsaExponent)));
            if (rc != CSL_OK) {
                rc = REASON_BADSIG;
                goto verifySig_out;
            }

            break;

        default:
            rc = REASON_BADSIG;
            goto verifySig_out;
    }

verifySig_out:

    return (rc);
}


/*
 * verifyBundle
 *  - Verify the certs, tmd, and ticket
 *  - Output the decryption key, public key, and content hash
 *  - Check to make sure the content can fit into the load area
 */
static int
verifyBundle(u32 blockOffset, ESWadHeader *wadHdr, u32 *contentSize,
    CSLOSAesKey *aesKey, CSLOSAesIv *iv, CSLOSSha1Hash *hash, u32 base)
{
    int                 rc = 0;
    u32                 basePage, lastPage, page, spare;
    IOSCName            issuerName, *entityName, caName;
    CSLOSRsaPublicKey4096   *pubKey4096;
    CSLOSRsaPublicKey2048   *pubKey2048;
    CSLOSRsaExponent        *exp;
    IOSCRsa4096RsaCert  *caCert;
    IOSCRsa2048RsaCert  *cpCert, *xsCert;
    ESTitleMeta         *tmd;
    ESTicket            *ticket;
    ESTitleId           tid;
    s32                 ver;
    u8                  ivBuf[ALIGN_SZ*2];
    CSLOSAesIv          *ivPtr = (CSLOSAesIv *)
                                (((u32)ivBuf+ALIGN_SZ-1) & ~(ALIGN_SZ-1));
    CSLOSAesKey         *keyPtr = (CSLOSAesKey *) NAPA_BUFFER_3;
    CSLOSAesKey         commonKey;
#ifndef BOOT1_DISABLE_EFUSE
    u32                 i;
#endif

    /* Load all the related flash pages */
    basePage = blockOffset << (FL_BLOCK_SHIFT - FL_PAGE_SHIFT);
    lastPage = (wadHdr->contentOffset >> FL_PAGE_SHIFT);
    spare = base + FL_BLOCK_SIZE;
    for (page = 0; page <= (lastPage + 1); page++) {
        WAIT(FL);
        FLUSH(FLA);
        INVAL(IOD);

        if (page <= lastPage) {
            readPageAsync(page + basePage,
                    (u8 *) (base + (page << FL_PAGE_SHIFT)),
                    (u8 *) (spare + ((page & 1) * 128)));
        }

        if (page > 0) {
            rc = checkEcc((u8 *) (base + ((page - 1) << FL_PAGE_SHIFT)),
                        (u8 *) (spare + (((page - 1) & 1) * 128)),
                        FL_PAGE_SIZE);
            if (rc != 0) {
                goto verifyBundle_out;
            }
        }
    }

    DEBUG_LED(0x16);	/* Verify CA cert */

    /* Verify the CA cert */
    caCert = (IOSCRsa4096RsaCert *) (base + wadHdr->hdrSize);
    memset(issuerName, 0, sizeof (IOSCName));
    strncpy(issuerName, ES_ROOT_NAME, SIZE_LIMCNAME);
    pubKey4096 = (CSLOSRsaPublicKey4096 *) rootKey;
    exp = (CSLOSRsaExponent *) rootExp;
    rc = verifySig(base, caCert, &issuerName, pubKey4096, exp, TYPE_CERT4096,
                sizeof (IOSCRsa4096RsaCert));
    if (rc != 0) {
        goto verifyBundle_out;
    }
    if (memcmp(&caCert->head.name, ES_CA_PREFIX, 2) != 0) {
        rc = REASON_BADNAME;
        goto verifyBundle_out;
    }
    entityName = (IOSCName *) &(caCert->head.name);

    DEBUG_LED(0x17);	/* Verify CP cert */

    /* Verify the CP cert */
    cpCert = (IOSCRsa2048RsaCert *)
                (base + wadHdr->hdrSize + sizeof (IOSCRsa4096RsaCert));
    strncat(issuerName, "-", 2);
    strncat(issuerName, *entityName, SIZE_LIMCNAME);
    pubKey2048 = (CSLOSRsaPublicKey2048 *) &(caCert->pubKey);
    exp = (CSLOSRsaExponent *) &(caCert->exponent);
    rc = verifySig(base, cpCert, &issuerName, pubKey2048, exp, TYPE_CERT2048,
                sizeof (IOSCRsa2048RsaCert));
    if (rc != 0) {
        goto verifyBundle_out;
    }
    if (memcmp(&cpCert->head.name, ES_CP_PREFIX, 2) != 0) {
        rc = REASON_BADNAME;
        goto verifyBundle_out;
    }
    entityName = (IOSCName *) &(cpCert->head.name);

    /* Save the CA name for verifying the XS cert later */
    memcpy(caName, issuerName, sizeof(IOSCName));

    DEBUG_LED(0x18);	/* Verify TMD */

    /* Verify the TMD */
    tmd = (ESTitleMeta *)
            (base + wadHdr->hdrSize + wadHdr->certSize + wadHdr->ticketSize);
    strncat(issuerName, "-", 2);
    strncat(issuerName, *entityName, SIZE_LIMCNAME);
    pubKey2048 = (CSLOSRsaPublicKey2048 *) &(cpCert->pubKey);
    exp = (CSLOSRsaExponent *) &(cpCert->exponent);
    rc = verifySig(base, tmd, &issuerName, pubKey2048, exp, TYPE_TMD,
                wadHdr->tmdSize);
    if (rc != 0) {
        goto verifyBundle_out;
    }

    DEBUG_LED(0x19);	/* Verify XS cert */

    /* Verify the XS cert */
    xsCert = (IOSCRsa2048RsaCert *)
                (base + wadHdr->hdrSize + sizeof (IOSCRsa4096RsaCert) +
                    sizeof(IOSCRsa2048RsaCert));
    memset(issuerName, 0, sizeof (IOSCName));
    strncpy(issuerName, caName, sizeof (IOSCName));
    pubKey2048 = (CSLOSRsaPublicKey2048 *) &(caCert->pubKey);
    exp = (CSLOSRsaExponent *) &(caCert->exponent);
    rc = verifySig(base, xsCert, &issuerName, pubKey2048, exp, TYPE_CERT2048,
                sizeof (IOSCRsa2048RsaCert));
    if (rc != 0) {
        goto verifyBundle_out;
    }
    if (memcmp(&xsCert->head.name, ES_XS_PREFIX, 2) != 0) {
        rc = REASON_BADNAME;
        goto verifyBundle_out;
    }
    entityName = (IOSCName *) &(xsCert->head.name);

    DEBUG_LED(0x20);	/* Verify ticket */

    /* Verify the ticket */
    ticket = (ESTicket *) (base + wadHdr->hdrSize + wadHdr->certSize);
    strncat(issuerName, "-", 2);
    strncat(issuerName, *entityName, SIZE_LIMCNAME);
    pubKey2048 = (CSLOSRsaPublicKey2048 *) &(xsCert->pubKey);
    exp = (CSLOSRsaExponent *) &(xsCert->exponent);
    rc = verifySig(base, ticket, &issuerName, pubKey2048, exp, TYPE_TICKET,
                sizeof (ESTicket));
    if (rc != 0) {
        goto verifyBundle_out;
    }

#ifdef BOOT1_DISABLE_EFUSE
    memcpy(commonKey, commonAesKey, sizeof (CSLOSAesKey));
#else
    /* Read the common key from eFuse */
    readEfuse(NV_RVL_COMMON_AES_KEY_OFF / sizeof (u32), (u8 *) commonKey,
            NV_RVL_COMMON_AES_KEY_SIZE);

    /* If the common key is not programmed, use the default key */
    for (i = 0; i < NV_RVL_COMMON_AES_KEY_SIZE; i++) {
        if (commonKey[i] != 0) {
            break;
        }
    }
    if (i == NV_RVL_COMMON_AES_KEY_SIZE) {
        memcpy(commonKey, commonAesKey, sizeof (CSLOSAesKey));
    }
#endif

    /* Decrypt the title key */
    memcpy(keyPtr, &(ticket->titleKey), sizeof (CSLOSAesKey));
    memset(ivPtr, 0, sizeof (CSLOSAesIv));
    memcpy(ivPtr, (u8 *) &(tmd->head.titleId), sizeof (ESTitleId));
    setupAes(&commonKey, ivPtr, (u32) keyPtr);

    FLUSH(IOD);
    INVAL(AES);
    busWrt32(AES_CTRL_REG, AES_CTRL_EXEC |
                        (AES_DECRYPT_CMD << AES_CTRL_CMD_SHIFT));
    WAIT(AES);
    FLUSH(AES);
    INVAL(IOD);
    memcpy(aesKey, keyPtr, sizeof (CSLOSAesKey));

    /* Zero out the title key in Napa for security */
    memset(keyPtr, 0, sizeof (CSLOSAesKey));

    /* Check the title ID */
    tid = ntohll(tmd->head.titleId);
    if (tid != ES_TITLE_ID_BOOT_64) {
        rc = REASON_BADTITLE;
        goto verifyBundle_out;
    }

    /* Check the boot2 version number in EEPROM */
#ifdef BOOT1_DISABLE_EEPROM
    ver = 0;
#else
    ver = EE_GetOsVersion();
#endif

    /* Only the lowest 8-bit in the version matter */
    if ((ver < 0) || (ver > (u8) ntohll(tmd->head.sysVersion))) {
        rc = REASON_BADVERSION;
        goto verifyBundle_out;
    }

    /* Set the IV for decrypting content */
    memset(iv, 0, sizeof (CSLOSAesIv));
    memcpy(iv, (u8 *) &(tmd->contents[0].index), sizeof (u16));

    /* Set the content size */
    *contentSize = (u32) ntohll(tmd->contents[0].size);

    /* Set the content hash */
    memcpy(hash, &(tmd->contents[0].hash), sizeof (IOSCSha1Hash));

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

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

    /* Spread spectrum (SS) feature is only supported in Bollywood */
#if 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();

#ifndef BOOT1_DISABLE_DCACHE
    /* Enable the MMU and D-cache */
    enableMMUDCache();
#endif

    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;

#ifndef BOOT1_DISABLE_DCACHE
    /* Disable the MMU and D-cache */
    disableMMUDCache();
#endif

    __outputLed(0x22);

    return (imgStart + hdr->hdrSize);
}

/* eof */
