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


#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 <sc/sc.h>
#include <sc/addr_map.h>
#include <sc/elf.h>
#include <sc/nvram.h>
#include <root.h>

#ifdef POST_ENABLE
#include "post/test.h"
#endif


/* Flash capabilities */
typedef struct {
    u32 blockShift;
    u32 pageShift;
    u32 spareSize;
    u32 readSetupCmd;
    u32 readCmd;
    u32 adp;
    u32 statusByte;
} Boot1FlashCap;


/* Size constants */
#define SDRAM_PAGE_SIZE     (16 * 1024)
#define BOOT2_MAX_SIZE      (BOOT2_LOAD_END - BOOT2_LOAD_START -            \
                                SDRAM_PAGE_SIZE)
#define ALIGN_SZ            64

#define BLOCK_WITHIN_SYSAREA(bl)                                            \
    ((bl >= 1) && (bl < (ISFS_SYSAREA_SIZE >> flashCap.blockShift)))
    
#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

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

/* Error codes */
#define STATUS_INPROGRESS   0
#define STATUS_SUCCESS      1
#define REASON_DBE          -1
#define REASON_BADMAP       -2
#define REASON_BADELF       -3
#define REASON_BADBLOCK     -4
#define REASON_BADHEADER    -5
#define REASON_BADCONTENT   -6
#define REASON_HASH         -7
#define REASON_BADSIG       -8
#define REASON_BADNAME      -9
#define REASON_BADVERSION   -10
#define REASON_BADTITLE     -11
#define REASON_BADKEY       -12
#define BOOT_TRACE(p)       IO_WRITE(BOOT2_LOAD_START + BOOT2_MAX_SIZE, (p))

/* Polling */
#define WAIT(dev) while(IO_READ(dev##_CTRL_REG) & dev##_CTRL_EXEC)


static Boot1FlashCap        flashCap;

//#define NITRO_EMULATOR 1 /* Turn this on to work with Nitro Emulator */

/* GBA required header */
static u8 header[] = {
#if defined(NITRO_EMULATOR)
    /*
     * Asada-san says that the Nitro Emulator requires that the cartridge look
     * like a DS option card.  If it does not see 0xff in the header, it will
     * not allow access to the full cartridge address space.
     */
    /* 0x0800_0000 */
    0xfe,0xff,0xff,0xea,
    0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    /* 0x0800_0010 */
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    /* 0x0800_0020 */
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    /* 0x0800_0030 */
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    /* 0x0800_0040 */
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    /* 0x0800_0050 */
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    /* 0x0800_0060 */
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    /* 0x0800_0070 */
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    /* 0x0800_0080 */
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    /* 0x0800_0090 */
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
    0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
#else
    /*
     * Normal GBA cartridge header
     */

    /* Branch to itself */
    0xfe,0xff,0xff,0xea,

    /* Nintendo logo @ 0x0800_0004 */
    0x24,0xff,0xae,0x51,0x69,0x9a,0xa2,0x21,
    0x3d,0x84,0x82,0x0a,0x84,0xe4,0x09,0xad,
    0x11,0x24,0x8b,0x98,0xc0,0x81,0x7f,0x21,
    0xa3,0x52,0xbe,0x19,0x93,0x09,0xce,0x20,

    0x10,0x46,0x4a,0x4a,0xf8,0x27,0x31,0xec,
    0x58,0xc7,0xe8,0x33,0x82,0xe3,0xce,0xbf,
    0x85,0xf4,0xdf,0x94,0xce,0x4b,0x09,0xc1,
    0x94,0x56,0x8a,0xc0,0x13,0x72,0xa7,0xfc,

    0x9f,0x84,0x4d,0x73,0xa3,0xca,0x9a,0x61,
    0x58,0x97,0xa3,0x27,0xfc,0x03,0x98,0x76,
    0x23,0x1d,0xc7,0x61,0x03,0x04,0xae,0x56,
    0xbf,0x38,0x84,0x00,0x40,0xa7,0x0e,0xfd,

    0xff,0x52,0xfe,0x03,0x6f,0x95,0x30,0xf1,
    0x97,0xfb,0xc0,0x85,0x60,0xd6,0x80,0x25,
    0xa9,0x63,0xbe,0x03,0x01,0x4e,0x38,0xe2,
    0xf9,0xa2,0x34,0xff,0xbb,0x3e,0x03,0x44,

    0x78,0x00,0x90,0xcb,0x88,0x11,0x3a,0x94,
    0x65,0xc0,0x7c,0x63,0x87,0xf0,0x3c,0xaf,
    0xd6,0x25,0xe4,0x8b,0x38,0x0a,0xac,0x72,
    0x21,0xd4,0xf8,0x07,
#endif /* !NITRO_EMULATOR */

    /* Software titles @ 0x0800_00a0 */
    0x4E,0x65,0x74,0x43,0x61,0x72,0x64,0x00,
    0x01,0x00,0x00,0x00,

    /* Initial code @ 0x0800_00ac */
    0x00,0x00,0x00,0x00,

    /* Maker code @ 0x0800_00b0 */
    0x30,0x31,

    /* Fixed value @ 0x0800_00b2 */
    0x96,

    /* Main unit code @ 0x0800_00b3 */
    0x00,

    /* Device type @ 0x0800_00b4 */
    0x80,

    /*
     * "Unused" data @ 0x0800_00b5
     *
     * It is unused in the GBA case, but matters when
     * the NetCard is plugged into a DS and used in DS mode.
     * The first three bytes correspond to "NumberID" in the
     * CTRDG_IsNumberID call.  (XXX need better info here)
     */
    0x23,0x23,0x23,0x00,0x00,0x00,0x00,

    /* Software version number @ 0x0800_00bc */
    0x00,

    /*
     * Complement check @ 0x0800_00bd
     * This is the bytewise sum from 0x0800_00a0 to 0x0800_00bc
     * plus 0x19 and then take the two's complement
     */
    0x65,

    /* Check sum @ 0x0800_00be */
    0xff, 0x7f
};

/* Root key and exponent */
#if defined (NC_BETA_PKI)
static u8 rootExp[] = NC_BETA_PKI_EXP
static u8 rootKey[] = NC_BETA_PKI_MOD

/* Default common key */
static u8 commonAesKey[] = {
 0x67,  0x45,  0x8b,  0x6b,  0xc6,  0x23,  0x7b,  0x32,
 0x69,  0x98,  0x3c,  0x64,  0x73,  0x48,  0x33,  0x66
};
#elif defined (NC_PROD_PKI)
static u8 rootExp[] = NC_PROD_PKI_EXP
static u8 rootKey[] = NC_PROD_PKI_MOD

/* Default common key */
static u8 commonAesKey[] = {
 0x83,  0xff,  0x7c,  0x8b,  0xfc,  0x2b,  0xc7,  0x6d,
 0x44,  0xf0,  0xf1,  0x86,  0x48,  0x0e,  0x2a,  0x4d
};
#endif


/*
 * The bootFailure() function is called for fatal errors, such as
 * double-bit errors during flash read, or hash value miscompare.  
 * The link return (lr or r14) register will indicate the source
 * of the error.
 */
static void
bootFailure(u32 reason)
{
    /* Put devices to sleep, just to be safe */
    IO_WRITE(PWR_CTRL_REG, (PWR_CTRL_CLOCK_OFF << PWR_CTRL_AES_SHIFT) |
                           (PWR_CTRL_CLOCK_OFF << PWR_CTRL_SHA_SHIFT) |
                           (PWR_CTRL_CLOCK_OFF << PWR_CTRL_FLASH_SHIFT));

    /* Store failure reason to memory (for test/debug purposes) */
    BOOT_TRACE(reason);
    
    /* Loop forever */
    while (1);
}


/*
 * Setup SDRAM
 */
static void
setupSdram(void)
{
    u32     tap, delay;

    /* Set up a SC space */
    IO_WRITE(SYS_CTRL_REG, (IO_READ(SYS_CTRL_REG) &
        ~(SYS_CTRL_CACHE_CONF_MASK | SYS_CTRL_SOFT_RST)) |
        (SYS_CACHE_CONF_DA_192_CC_64_SC_64 << SYS_CTRL_CACHE_CONF_SHIFT) |
        SYS_CTRL_CFG_EN);

    tap = (12 << MC_CTRL_TAP_SHIFT);    /* Working tap */

    IO_WRITE(MC_CTRL_REG, tap | MC_CTRL_ENA | MC_CTRL_PALL | 0x400);
    delay = 150;
    while (delay--);

    IO_WRITE(MC_CTRL_REG, tap | MC_CTRL_ENA);
    delay = 300;
    while (delay--);

    IO_WRITE(MC_CTRL_REG, tap | MC_CTRL_ENA | MC_CTRL_MRS | 0x2a);
    delay = 150;
    while (delay--);

    IO_WRITE(MC_CTRL_REG, tap | MC_CTRL_ENA);
    delay = 300;
    while (delay--);

    IO_WRITE(MC_CTRL_REG, tap | MC_CTRL_ENA | MC_CTRL_DQM_ENA);
    delay = 150;
    while (delay--);

    IO_WRITE(MC_CTRL_REG, tap | MC_CTRL_ENA | MC_CTRL_DQM_ENA |
        (6 << MC_CTRL_RFINT_SHIFT));
}


/*
 * Setup GBA header
 */
static void
setupGba(void)
{
    IO_WRITE(PT_START, (PT_ACCESS_RW << PT_SC_PROT_SHIFT) << PT_ENTRY_SHIFT);

    /* Copy over the GBA header */
    memcpy((void *) MEM0_START, header, sizeof (header));

    /* Flush cache */
    SCWriteback((void *) MEM0_START, sizeof (header));
    CCInvalidate((void *) MEM0_START, sizeof (header));

    /* Make first SDRAM page readable by GBA */
    IO_WRITE(PT_START, (PT_ACCESS_READ << PT_CC_PROT_SHIFT) << PT_ENTRY_SHIFT);

    /* Enable ROM emulation */
    IO_WRITE(CIF_CTRL_REG, CIF_CTRL_EMU | CIF_CTRL_EMU_ROM);
}


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

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

    /* Expand Key */
    IO_WRITE(AES_CTRL_REG, AES_CTRL_EXEC |
        (AES_KEYEXPAND_CMD << AES_CTRL_CMD_SHIFT));
    while (IO_READ(AES_CTRL_REG) & AES_CTRL_EXEC) {
        /* do nothing */
    }
    IO_WRITE(AES_CTRL_REG, 0);

    /* Set up the IV and read/write pointers */
    IO_WRITE(AES_IVPTR_REG, CPU_TO_BUS_ADDR((u32) iv));
    IO_WRITE(AES_RPTR_REG, CPU_TO_BUS_ADDR(base));
    IO_WRITE(AES_WPTR_REG, CPU_TO_BUS_ADDR(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      pad[ALIGN_SZ * 3];
    u8      *padp = (u8 *) (((u32)pad + ALIGN_SZ - 1) & ~(ALIGN_SZ - 1));

    switch (type) {
        case (HASH_FIRST):
            /* Set up the initial hash value */
            IO_WRITE(SHA_CTRL_REG, 0x10 << SHA_CTRL_BUF_PTR_SHIFT);
            IO_WRITE(SHA_DATA_REG, 0x01234567);
            IO_WRITE(SHA_DATA_REG, 0x89abcdef);
            IO_WRITE(SHA_DATA_REG, 0xfedcba98);
            IO_WRITE(SHA_DATA_REG, 0x76543210);
            IO_WRITE(SHA_DATA_REG, 0xf0e1d2c3);

            *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;
            break;
    }

    if ((size - partialSize) > 0) {
        /* Hash the data */
        IO_WRITE(SHA_MPTR_REG, CPU_TO_BUS_ADDR(base));
        IO_WRITE(SHA_CTRL_REG, SHA_CTRL_EXEC | (size - partialSize - 64));
    }

    /* Return the result for the last run */
    if (type == HASH_LAST) {
        memset(padp, 0, ALIGN_SZ * 2);

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

        /* 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);
        IO_WRITE(SHA_MPTR_REG, CPU_TO_BUS_ADDR(padp));
        IO_WRITE(SHA_CTRL_REG, SHA_CTRL_EXEC | (lastSize - 64));
        WAIT(SHA);

        /* Read back the hash result */
        hashPtr = (u32 *) result;
        IO_WRITE(SHA_CTRL_REG, 0x10 << SHA_CTRL_BUF_PTR_SHIFT);
        IO_READ(SHA_DATA_REG);
        for (count = 0; count < (sizeof (CSLOSSha1Hash) / 4); count++) {
            hashPtr[count] = IO_READ(SHA_DATA_REG);
        }

        *ctx = 0;
    }

runHashAsync_out:

    return (rc);
}


/*
 * Determine the flash capabilities based on the board ID
 */
static void
setupFlash(void)
{
    if (SYS_CTRL_BOARD_ID(IO_READ(SYS_CTRL_REG)) & SYS_BOARD_ID_2K_PAGE) {
        flashCap.blockShift = 17;
        flashCap.pageShift = 11;
        flashCap.spareSize = 64;
        flashCap.readSetupCmd = 0x00;
        flashCap.readCmd = 0x30;
        flashCap.adp = 0x1f;
        flashCap.statusByte = 0;
    } else {
        flashCap.blockShift = 14;
        flashCap.pageShift = 9;
        flashCap.spareSize = 16;
        flashCap.readSetupCmd = -1;
        flashCap.readCmd = 0x00;
        flashCap.adp = 0x1d;
        flashCap.statusByte = 5;
    }
}


/*
 * Read Kilopass device
 * This function reads 'size' bytes from the Kilopass memory, starting
 * at bit 'address'.  The results are stored in 'buffer'.
 */
static void
readKp(u32 address, u8 *buffer, int size)
{
    int i;

    memset(buffer, 0, size);
    for (i = 0; i < (size * 8); ++i) {
        u32 v;

        IO_WRITE(KP_CTRL_REG, KP_CTRL_EXEC | (address + i));
        do {
            v = IO_READ(KP_CTRL_REG);
        } while ((v) & KP_CTRL_EXEC);

        if (v & KP_CTRL_R) {
            buffer[i >> 3] |= (1 << (i & 7));
        }
    }
}


/*
 * Set Memory Access rights
 * This function sets the access rights to 'acc' for the region of memory
 * starting at 'ptr' with a length of 'size' bytes.
 * If the memory region is in DA, 'ptr' is assumed to be cache-line
 * aligned, and size is an even multiple of the cache-line size. If the
 * memory region is in SDRAM, 'ptr' is assumed to be page aligned, and
 * size is an even multiple of the page size.
 */
static void
setAccess(u32 acc, u32 ptr, u32 size)
{
    u32     entryShift, base, alignment, start, end, off, invalStart;

    if (((ptr >= MEM0_START) && ((ptr + size) <= MEM0_END)) ||
            ((ptr >= MEM1_START) && ((ptr + size) <= MEM1_END)) ||
            ((ptr >= MEM2_START) && ((ptr + size) <= MEM2_END)) ||
            ((ptr >= MEM3_START) && ((ptr + size) <= MEM3_END))) {
        /* SDRAM */
        entryShift = PT_ENTRY_SHIFT;
        base = PT_START;
        alignment = SDRAM_PAGE_SIZE;
    } else {
        entryShift = 0;
        base = DAX_START;
        alignment = 16;
    }

    /* Compute the values to be used for L1 invalidation */
    if (size < 4096) {
        start = ptr;
        end = ptr + size;
        invalStart = L1_DH_START;   /* Use hit invalidate */
    } else {
        start = 0;
        end = 4096;
        invalStart = L1_DI_START;   /* Use index invalidate */
    }

    acc = acc << PT_SC_PROT_SHIFT << entryShift;
    ptr += base;

    /* Change permission */
    while (size) {
        IO_WRITE(ptr, acc);
        ptr += alignment;
        size -= alignment;
    }

    /* Invalidate the D-cache */
    for (off = start; off < end; off += 16) {
        IO_WRITE(invalStart + off, 1);
    }
}


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

/*
 * Check ECC
 * 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;
        }

        eccStored = eccStored;
        eccComputed = 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;

            /*
             * 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 */
            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)
{
    u32     adp = flashCap.adp;

    IO_WRITE(FL_AD0_REG, 0);
    IO_WRITE(FL_AD1_REG, page);

    if (flashCap.readSetupCmd != -1) {
        IO_WRITE(FL_CTRL_REG, FL_CTRL_EXEC | (adp << FL_CTRL_ADP_SHIFT) |
                            (flashCap.readSetupCmd << FL_CTRL_CMD_SHIFT));
        WAIT(FL);
        adp = 0;
    }

    IO_WRITE(FL_MA0_REG, CPU_TO_BUS_ADDR((u32) dataBuf));
    IO_WRITE(FL_MA1_REG, CPU_TO_BUS_ADDR((u32) spareBuf));
    IO_WRITE(FL_CTRL_REG, FL_CTRL_EXEC | FL_CTRL_RDP |
                        FL_CTRL_RDY | FL_CTRL_ECC | 
                        (adp << FL_CTRL_ADP_SHIFT) |
                        (flashCap.readCmd << FL_CTRL_CMD_SHIFT) |
                        ((1 << flashCap.pageShift) + flashCap.spareSize) );
}


/*
 * 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 + (1 << flashCap.pageShift));
    Boot2BlockMap   *map1, *map2, *map3, *map;
    u8              boot2Magic[BOOT2_MAGIC_SIZE] = BOOT2_MAGIC;

    /* Do not read beyond the SYS area */
    numBlocks = ISFS_SYSAREA_SIZE >> flashCap.blockShift;
    numPagesInBlock = 1 << (flashCap.blockShift - flashCap.pageShift);

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

        /* 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 + (1 << flashCap.pageShift));

    /* 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 << (flashCap.blockShift - flashCap.pageShift);

            for (i = 0; i < 2; i++) {
                readPageAsync(page + i, dataBuf, spareBuf);
                WAIT(FL);
                if (spareBuf[flashCap.statusByte] != 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 + (1 << flashCap.pageShift));

    /* The WAD header is in the first page */
    page = blockOffset << (flashCap.blockShift - flashCap.pageShift);
    readPageAsync(page, dataBuf, spareBuf);
    WAIT(FL);

    rc = checkEcc(dataBuf, spareBuf, (1 << flashCap.pageShift));
    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
     */
    if ((wadHdr->hdrSize != sizeof (ESWadHeader)) ||
            (wadHdr->hdrSize > (1 << flashCap.pageShift)) ||
            (wadHdr->contentOffset > (1 << flashCap.blockShift)) ||
            (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(void *p, IOSCName *issuer, void *pubKey, CSLOSRsaExponent *exp,
    u32 type, u32 size)
{
    int                 rc = 0;
    u32                 base, hashSize, ctx;
    u8                  buf[2048];
    u8                  *bufp = (u8 *) (((u32)buf+ALIGN_SZ-1) & ~(ALIGN_SZ-1));
    IOSCRsa4096RsaCert  *cert4096;
    IOSCRsa2048RsaCert  *cert2048;
    ESTitleMeta         *tmd;
    ESTicket            *ticket;
    IOSCName            *issuerName;
    CSLOSSha1Hash       hash;

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

    /* 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, i, spare;
    IOSCName            issuerName, *entityName, caName;
    CSLOSRsaPublicKey4096   *pubKey4096;
    CSLOSRsaPublicKey2048   *pubKey2048;
    CSLOSRsaExponent        *exp;
    IOSCRsa4096RsaCert  *caCert;
    IOSCRsa2048RsaCert  *cpCert, *xsCert;
    ESTitleMeta         *tmd;
    ESTicket            *ticket;
    ESTitleId           tid;
    ESSysVersion        ver = 0;
    u8                  ivBuf[ALIGN_SZ*2];
    u8                  boot2Version[NV_NC_OS_VERSION_SIZE/8];
    u8                  keyBuf[ALIGN_SZ*2];
    CSLOSAesIv          *ivPtr = (CSLOSAesIv *)
                                (((u32)ivBuf+ALIGN_SZ-1) & ~(ALIGN_SZ-1));
    CSLOSAesKey         *keyPtr = (CSLOSAesKey *)
                                (((u32)keyBuf+ALIGN_SZ-1) & ~(ALIGN_SZ-1));
    CSLOSAesKey         commonKey, commonKeyC;

    /* Load all the related flash pages */
    basePage = blockOffset << (flashCap.blockShift - flashCap.pageShift);
    lastPage = (wadHdr->contentOffset >> flashCap.pageShift);
    spare = base + (1 << flashCap.blockShift);
    for (page = 0; page <= (lastPage + 1); page++) {
        WAIT(FL);
        if (page <= lastPage) {
            readPageAsync(page + basePage,
                    (u8 *) (base + (page << flashCap.pageShift)),
                    (u8 *) (spare + ((page & 1) * 128)));
        }

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

    /* Verify the CA cert */
    caCert = (IOSCRsa4096RsaCert *) (base + wadHdr->hdrSize);
    memset(issuerName, 0, sizeof (IOSCName));
    strncpy(issuerName, ES_ROOT_NAME, sizeof (IOSCName));
    pubKey4096 = (CSLOSRsaPublicKey4096 *) rootKey;
    exp = (CSLOSRsaExponent *) rootExp;
    rc = verifySig(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);

    /* Verify the CP cert */
    cpCert = (IOSCRsa2048RsaCert *)
                (base + wadHdr->hdrSize + sizeof (IOSCRsa4096RsaCert));
    strncat(issuerName, "-", sizeof (IOSCName));
    strncat(issuerName, *entityName, sizeof (IOSCName));
    pubKey2048 = (CSLOSRsaPublicKey2048 *) &(caCert->pubKey);
    exp = (CSLOSRsaExponent *) &(caCert->exponent);
    rc = verifySig(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));

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

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

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

    /* Read the common key from Kilopass */
    readKp(NV_NC_COMMON_AES_KEY_OFF, (u8 *) commonKey,
        NV_NC_COMMON_AES_KEY_SIZE/8);
    readKp(NV_NC_COMMON_AES_KEYC_OFF, (u8 *) commonKeyC,
        NV_NC_COMMON_AES_KEYC_SIZE/8);

    /* If the common key is not programmed, use the default key */
    for (i = 0; i < sizeof (CSLOSAesKey); i++) {
        if (commonKey[i] != 0) {
            break;
        }
    }
    if (i == sizeof (CSLOSAesKey)) {
        memcpy(commonKey, commonAesKey, sizeof (CSLOSAesKey));
    } else {
        /* Check the key against its complement */
        for (i = 0; i < sizeof (CSLOSAesKey); i++) {
            if (commonKey[i] != (u8) ~commonKeyC[i]) {
                bootFailure(REASON_BADKEY);
            }
        }
    }

    /* 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);
    IO_WRITE(AES_CTRL_REG, AES_CTRL_EXEC |
                        (AES_DECRYPT_CMD << AES_CTRL_CMD_SHIFT));
    WAIT(AES);
    memcpy(aesKey, keyPtr, sizeof (CSLOSAesKey));

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

    /* Check the boot2 version number in Kilopass */
    readKp(NV_NC_OS_VERSION_OFF, boot2Version, NV_NC_OS_VERSION_SIZE/8);
    for (i = 0; i < NV_NC_OS_VERSION_SIZE; i++) {
        if (boot2Version[i >> 3] & (1 << (i & 7))) {
            ver++;
        }
    }

    /* Only the lowest 8-bit in the version matter */
    if (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 = (1 << flashCap.pageShift);
    numPages = (padSize + contentOffset + pageSize - 1) >>
                    flashCap.pageShift;
    numPagesInBlock = (1 << (flashCap.blockShift - flashCap.pageShift));
    numBlocks = (numPages + numPagesInBlock - 1) >>
                    (flashCap.blockShift - flashCap.pageShift);

    /* Read only part of the first and last blocks */
    startPageForFirstBlock = contentOffset >> flashCap.pageShift;
    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);
            if (j < numPagesInCurBlock) {
                readPageAsync(page,
                        (u8 *) (base + (pageInMem << flashCap.pageShift)),
                        (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);
                spareBuf = (u8 *) (spare + ((j & 1) * 128));
                if (spareBuf[flashCap.statusByte] != 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);
            if ((j > startPageForCurBlock) && (j < (numPagesInCurBlock + 1))) {
                u32     aesSize;

                rc = checkEcc(
                        (u8 *) (base + ((pageInMem - 1) << flashCap.pageShift)),
                        (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;
                }

                IO_WRITE(AES_CTRL_REG, AES_CTRL_EXEC |
                    (((i == 0) && (j == (startPageForCurBlock + 1))) ?
                        0 : AES_CTRL_CHAIN) |
                    (AES_DECRYPT_CMD << AES_CTRL_CMD_SHIFT) | (aesSize - 16));
            }

            /* 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) << flashCap.pageShift);
                    shaSize = lastPageSize + contentSize - padSize;
                    type = HASH_LAST;
                } else {
                    shaStart = base + ((pageInMem - 2) << flashCap.pageShift);
                    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;

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

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

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

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

    /* Verify certs, tmd, and ticket */
    rc = verifyBundle(blockOffset, &wadHdr, &contentSize,
                    &aesKey, ivPtr, &hash, base);
    if (rc < 0) {
        goto loadBoot2_out;
    }

    /* Skip a certain number of bytes when doing AES/SHA for the first page */
    skipBytes = wadHdr.contentOffset & ((1 << flashCap.pageShift) - 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);
}


static int
loadElf(u32 base)
{
    int         rc = 0;
    Elf32_Ehdr  *ehdr;
    Elf32_Phdr  *phdr;
    u32         count, size, alignment;

    /* Elf and program headers */
    ehdr = (Elf32_Ehdr *) base;
    phdr = (Elf32_Phdr *) (base + sizeof (Elf32_Ehdr));

    /* Copy the programs one-by-one */
    for (count = 0; count < ehdr->e_phnum; count++) {
        if (phdr[count].p_type != PT_LOAD) {
            continue;
        }

        /* Check that the new segment does not over-write existing segments */
        if (OVERLAP(phdr[count].p_vaddr, phdr[count].p_memsz,
                        BOOT1_SP_START, BOOT1_SP_END - BOOT1_SP_START) ||
                OVERLAP(phdr[count].p_vaddr, phdr[count].p_memsz,
                        BOOT2_LOAD_START, BOOT2_LOAD_END - BOOT2_LOAD_START)) {
            rc = REASON_BADELF;
            goto loadElf_out;
        }

        /* Check alignment */
        size = phdr[count].p_filesz;
        if (((phdr[count].p_vaddr >= MEM0_START) &&
                    (phdr[count].p_vaddr <= MEM0_END)) ||
                ((phdr[count].p_vaddr >= MEM1_START) &&
                    (phdr[count].p_vaddr <= MEM1_END)) ||
                ((phdr[count].p_vaddr >= MEM2_START) &&
                    (phdr[count].p_vaddr <= MEM2_END)) ||
                ((phdr[count].p_vaddr >= MEM3_START) &&
                    (phdr[count].p_vaddr <= MEM3_END))) {
            alignment = SDRAM_PAGE_SIZE;
        } else {
            alignment = 16;
        }

        if ((phdr[count].p_vaddr & (alignment - 1)) != 0) {
            rc = REASON_BADELF;
            goto loadElf_out;
        }
        size = (size + alignment - 1) & ~(alignment - 1);

        /* Give access to the destination memory */
        setAccess(PT_ACCESS_RW, phdr[count].p_vaddr, size);

        /* Copy over the segment */
        memcpy((u8 *) phdr[count].p_vaddr, (u8 *) (base + phdr[count].p_offset),
            phdr[count].p_filesz);

        /* If it is a SDRAM segment, make sure the CC is coherent */
        if (alignment == SDRAM_PAGE_SIZE) {
            SCWriteback((void *) phdr[count].p_vaddr, phdr[count].p_filesz);
            CCInvalidate((void *) phdr[count].p_vaddr, phdr[count].p_filesz);
        }

        /* No need to zero (memsz - filesz) since the kernel will do this */
    }

loadElf_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
 */
void
bootc(void)
{
    int     rc = 0, elfStart;
    u32     off, dir;

    /* Enable the SDRAM */
    setupSdram();

    /* Set up the GBA header */
    setupGba();

#ifdef POST_ENABLE
    /*
     * Run POST: Beware that POST will enable memory access without
     * resetting it at the end
     */
    runPost();
#endif

    /* Set up flash */
    setupFlash();

    /* Create writable region to load boot2 */
    setAccess(PT_ACCESS_RW, BOOT2_LOAD_START,
                BOOT2_LOAD_END - BOOT2_LOAD_START);
    BOOT_TRACE(STATUS_INPROGRESS);

    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);
        }

        /* Load boot2 from flash */
        elfStart = loadBoot2(dir, BOOT2_LOAD_START, BOOT2_MAX_SIZE);
        if (elfStart < 0) {
            rc = elfStart;
            continue;
        }

        /* Load the ELF image to the appropriate memory locations */
        rc = loadElf(elfStart);
        if (rc < 0) {
            continue;
        }

        /* Done if no error is detected */
        break;
    }

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

    /* Store cookie indicating success */
    BOOT_TRACE(STATUS_SUCCESS);

    /* Remove access to the scratch area */
    setAccess(PT_ACCESS_NONE, BOOT2_LOAD_START,
                BOOT2_LOAD_END - BOOT2_LOAD_START);

    /* Mark 1st 256 bytes of kernel as executable */
    setAccess(PT_ACCESS_EXEC, KERNEL_SP_START, 256);

    /* Invalidate the 1st 256 bytes of I-cache */
    for (off = 0; off < 256; off += 16) {
        IO_WRITE(L1_II_START + off, 1);
    }
}
