/*
 *               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 <sc/sc.h>
#include <ioslibc.h>

#define BOOT1_SIZE  16384
#define BOOT1_BASE  0

#define SPARE_BUFFER_SIZE   256

#define STATUS_INPROGRESS   0
#define STATUS_SUCCESS      1
#define REASON_DBE          -1
#define REASON_HASH         -2
#define REASON_KP           -3
#define BOOT_TRACE(p)       IO_WRITE(BOOT1_BASE+BOOT1_SIZE+SPARE_BUFFER_SIZE, (p))
/*
 * 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.
 *
 */
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 AES device:
 *   - Enable clock
 *   - Take device out of reset
 *   - Program key from boot ROM
 *   - Expand the key
 *   - Copy iv from boot ROM onto stack in DA
 *   - Setup read, write, and iv pointers
 */
static void
setupAes(u32 base, u32 *iv)
{
    u32 *p;
    extern u8 bootKey[];
    extern u32 bootIv[4];
    int i;

    /* Power on AES */
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_CLOCK_ON << PWR_CTRL_AES_SHIFT);
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_DEASSERT_RST << PWR_CTRL_AES_SHIFT);

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

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

    /* Copy iv to the stack (in DA) */
    memcpy(iv, bootIv, sizeof(bootIv));
    IO_WRITE(AES_IVPTR_REG, CPU_TO_BUS_ADDR((u32)iv));

    /* Set memory pointers */
    IO_WRITE(AES_RPTR_REG, CPU_TO_BUS_ADDR(base));
    IO_WRITE(AES_WPTR_REG, CPU_TO_BUS_ADDR(base));
}

/*
 * Setup SHA device:
 *   - Enable clock
 *   - Take device out of reset
 *   - Program initial hash value
 *   - Setup read pointer
 */
static void
setupSha(u32 base)
{
    /* Power on SHA */
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_CLOCK_ON << PWR_CTRL_SHA_SHIFT);
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_DEASSERT_RST << PWR_CTRL_SHA_SHIFT);

    /* Set initial hash value */
    IO_WRITE(SHA_CTRL_REG, 0x10 << 16);
    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);

    /* Set read pointer */
    IO_WRITE(SHA_MPTR_REG, CPU_TO_BUS_ADDR(base));
}

/*
 * Setup Kilopass:
 *   - Take device out of reset
 */
static void
setupKp(void)
{
    /* Take Kilopass out of reset */
    IO_WRITE(KP_CTRL_REG, KP_CTRL_RT | (32 << KP_CTRL_TVAL_SHIFT));
}

/*
 * Setup Flash device:
 *   - Enable clock
 *   - Take device out of reset
 *   - Enable flash device
 *   - Setup memory and flash address pointers
 *   - Reset flash device
 */
static void
setupFlash(u32 base)
{
    /* Power on Flash */
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_CLOCK_ON << PWR_CTRL_FLASH_SHIFT);
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_DEASSERT_RST << PWR_CTRL_FLASH_SHIFT);

    /* Configure device */
    IO_WRITE(FL_CONF_REG, IO_READ(FL_CONF_REG) | FL_CONF_DEV);

    /* Initialize pointers */
    IO_WRITE(FL_MA0_REG, 0);
    IO_WRITE(FL_MA1_REG, 0);
    IO_WRITE(FL_AD0_REG, 0);
    IO_WRITE(FL_AD1_REG, 0);

    /* Issue Reset command */
    IO_WRITE(FL_CTRL_REG, FL_CTRL_EXEC |
                          FL_CTRL_RDY |
                         (0xff << FL_CTRL_CMD_SHIFT));
}

/*
 * 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.  'ptr' is assumed to 
 * be cache-line aligned, and size is an even multiple of the cache-line
 * size.
 */
static void
setAccess(u32 acc, u32 ptr, u32 size)
{
    acc = acc << PT_SC_PROT_SHIFT;
    ptr += DAX_START;
    while (size) {
        IO_WRITE(ptr, acc);
        ptr += 16;
        size -= 16;
    }
}

#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.
 */
void
checkEcc(u8 *buf, u8* spare, u32 pageSize)
{
    int eccCount;
    int spareSize = pageSize >> 5;

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

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

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

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

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

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

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

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

    if (SYS_CTRL_BOARD_ID(IO_READ(SYS_CTRL_REG)) & SYS_BOARD_ID_2K_PAGE) {
        pageShift = 11;
        spareSize = 64;
        readSetupCmd = 0x00;
        readCmd = 0x30;
        adp = 0x1f;
    } else {
        pageShift = 9;
        spareSize = 16;
        readSetupCmd = -1;
        readCmd = 0x00;
        adp = 0x1d;
    }
    numPages = size >> pageShift;

    for (i = 0; i < numPages + 2; ++i) {
        /* Load page 'i' from flash */
        WAIT(FL);
        if (i < numPages) {
            IO_WRITE(FL_AD1_REG, i);
            if (readSetupCmd != -1) {
                adp = 0x1f;
                IO_WRITE(FL_CTRL_REG, FL_CTRL_EXEC |
                                     (adp << FL_CTRL_ADP_SHIFT) |
                                     (readSetupCmd << FL_CTRL_CMD_SHIFT));
                WAIT(FL);
                adp = 0;
            }
            IO_WRITE(FL_MA0_REG, CPU_TO_BUS_ADDR(base + (i << pageShift)));
            IO_WRITE(FL_MA1_REG, CPU_TO_BUS_ADDR(base + size + (i & 1) * 128));
            IO_WRITE(FL_CTRL_REG, FL_CTRL_EXEC |
                                  FL_CTRL_RDP |
                                  FL_CTRL_RDY |
                                  FL_CTRL_ECC |
                                  (adp << FL_CTRL_ADP_SHIFT) |
                                  (readCmd << FL_CTRL_CMD_SHIFT) |
                                  ((1 << pageShift)+spareSize) );

        }

        /* Decrypt page 'i-1' */
        WAIT(AES);
        if (i > 0 && i < (numPages + 1)) {
            checkEcc((u8 *)(base + ((i-1) << pageShift)),
                     (u8 *)(base + size + ((i-1)&1)*128),
                     (1 << pageShift));
            IO_WRITE(AES_CTRL_REG, AES_CTRL_EXEC |
                                  (i == 1 ? 0 : AES_CTRL_CHAIN ) |
                                  (AES_DECRYPT_CMD << AES_CTRL_CMD_SHIFT) |
                                  ((1 << pageShift) - 16));
        }

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

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

/*
 * This is the C code portion of the boot ROM.  The reset handler has
 * flipped the address space, and setup a stack prior to calling this
 * routine.
 *
 * This routine first initializes the HW devices (aes, sha, flash, and kp).
 * Next it loads a 16Kb chunk from the first block on the flash device. 
 * The block is decrpyted and hashed.  The hash value is checked against
 * an expected hash value stored in the Kilopass. If the hash check 
 * succeeds, then newly loaded code is executed.
 *
 */
void
bootc(void)
{
    u32 i;
    u32 expHash[5], invHash[5];
    u8 ivBuf[32];
    u32 *iv = (u32 *)(((u32)ivBuf + 15) & ~15); /* cache-line align iv */
    u32 compareHash = 0;

    /* Create writable region to load boot1 and double-buffered spare areas */
    setAccess(PT_ACCESS_RW, BOOT1_BASE, BOOT1_SIZE + SPARE_BUFFER_SIZE + 16);
    BOOT_TRACE(STATUS_INPROGRESS);

    /* Initialize HW */
    setupAes(BOOT1_BASE, iv);
    setupSha(BOOT1_BASE);
    setupFlash(BOOT1_BASE);
    setupKp();

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

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

    /* Check computed hash against expected value from Kilopass */
    if (compareHash) {
        IO_WRITE(SHA_CTRL_REG, 0x10 << 16);
        IO_READ(SHA_DATA_REG);
        for (i = 0; i < sizeof(expHash)/sizeof(expHash[0]); ++i) {
            if (expHash[i] != ~invHash[i]) {
                bootFailure(REASON_KP);
            }
            if (expHash[i] != IO_READ(SHA_DATA_REG)) {
                bootFailure(REASON_HASH);
            }
        }
    }
    
    /* Mark 1st 256 bytes of boot1 as executable */
    setAccess(PT_ACCESS_EXEC, BOOT1_BASE, 256);

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