/*
 *               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.
 *
 * bootx.c is for short-cutting the simulator. It does not load from flash,
 * rather waits for the BOOT_TRACE flag to be 2, then calls code that has
 * been back-door loaded to DA.
 */

#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	STATUS_BOOT1		2

#define	BOOT_FLAG		IO_READ(BOOT1_BASE+BOOT1_SIZE+SPARE_BUFFER_SIZE)
#define BOOT_TRACE(p)	IO_WRITE(BOOT1_BASE+BOOT1_SIZE+SPARE_BUFFER_SIZE, (p))

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

/*
 * 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)
{
    /* Create writable region to load boot1 and double-buffered spare areas */
	/* spin on boot trace flag, until backdoor says go */

    setAccess(PT_ACCESS_RW, BOOT1_BASE, BOOT1_SIZE + SPARE_BUFFER_SIZE + 16);
    BOOT_TRACE(STATUS_BOOT1);
	while(BOOT_FLAG == STATUS_BOOT1);
    
    /* Mark 1st 256 bytes of boot1 as executable */
    setAccess(PT_ACCESS_EXEC, BOOT1_BASE, 256);

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