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


#include <ioslibc.h>
#include <iop.h>
#include <boot.h>
#include <elf.h>
#include <sys.h>


/*
 * The loader can't have a BSS since the BSS doesn't show up in the
 * binary file. There's a check in the makefile for that. If a BSS
 * is really needed in the future, the createOSImage.py script needs
 * to be modified to account for that when calculating the loader
 * size
 */
u8  _initStack[256]     __attribute__ ((section(".data")));
u32 _initStackSize = sizeof (_initStack);


/*
 * This is the C code portion of the boot2 loader. The assembly portion
 * has set up the stack and input arguments
 */
void
loadOS(u32 base)
{
    u32                 reg, count;
    BootOSImageHeader   *hdr;
    Elf32_Ehdr          *ehdr;
    Elf32_Phdr          *phdr;

    /* Flip the SRAM if not already done so */
    reg = IO_READ(ACRSRNPROT_REG);
    if ((reg & ACRSRNPROT_IOUEN_MASK) == 0) {
        reg |= ACRSRNPROT_IOUEN_MASK;
        IO_WRITE(ACRSRNPROT_REG, reg);
    }

    /*
     * Do nothing now if ddrInit is set. In the future, it may be
     * necessary to re-initialize the DDR. The boot sequence would
     * need to be revamped if the re-initialization affects Napa
     * as well, since currently boot1 uses boot2 as the staging
     * area
     */
    hdr = (BootOSImageHeader *) (base - sizeof (BootOSImageHeader));
    if (hdr->ddrInit) {
        /* Do nothing */
    }

    /* TODO: Alignment and overlap check? */

    ehdr = (Elf32_Ehdr *) (base + hdr->loaderSize);
    phdr = (Elf32_Phdr *) (base + hdr->loaderSize + sizeof (Elf32_Ehdr));

    for (count = 0; count < ehdr->e_phnum; count++) {
        if (phdr[count].p_type != PT_LOAD) {
            continue;
        }

        memcpy((u8 *) phdr[count].p_paddr,
            (u8 *) (base + hdr->loaderSize + phdr[count].p_offset),
            phdr[count].p_filesz);

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

    /* For security reason, wipe out the loaded image here */
    memset((u8 *) ehdr, 0, hdr->imageSize);

    /*
     * The assembly section of the code will then jump to the kernel.
     * Since caching is not enabled, there's no need to flush or
     * invalidate the I or D cache here. As for the AHB buffers, the
     * kernel will handle them during initialization since a program
     * has to be in the SRAM in order to flush or invalidate the AHB
     * buffers
     */
}
