/*
 *               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.
 *
 */
#ifndef BUILD_BOOT2_LOADER
#include <addr_map.h>
#endif 
        .text
        .code 32
        .align 0
        .global _start
_start:
    /* Record the base address */
    mov     r4, pc
    sub     r4, r4, #8

#ifndef BUILD_BOOT2_LOADER
    /* If we are running outside the IOP space,
     * we are already using the new relaunch buffer.
     */
    ldr r5, =IOP_GDDR3_START
    cmp r4, r5
    blt relocate_done

    /* Relocate to new relaunch space and run */
    ldr sp, =(OSLAUNCH_SP_START - 4) 
    ldr r0, =OSLAUNCH_SP_START /* new relaunch buffer */
    mov r1, r4                 /* current loader's address */
    bl relocateImg             /* never returns */
relocate_done:
#endif /* !BUILD_BOOT2_LOADER */

    /* Zero the BSS */
    ldr     r0, =__bss_start
    ldr     r1, =__bss_end
    ldr     r2, =0
    ldr     r3, =4
    bl      word_set

    /* Set up the stack */
    ldr     r2, =_initStackSize
    ldr     r3, =_start
    sub     r2, r2, r3      /* Get offset from start */
    add     r2, r2, r4      /* Add the base address */
    ldr     r2, [r2]
    ldr     sp, =_initStack
    ldr     r3, =_start
    sub     sp, sp, r3      /* Get offset from start */
    add     sp, sp, r4      /* Add the base address */ 
    add     sp, sp, r2

    /* Run the C portion, passing the start address of this loader as input */
    mov     r0, r4
    bl      loadOS

#ifndef BUILD_BOOT2_LOADER
    mov     r0, r4
    bl      runOS /* wipe loader, run new kernel */
#else
    /* Jump to the kernel reset vector */
    ldr     pc, =0xffff0000
#endif
word_set:
    cmp     r0, r1
    bcs     1f
    str     r2, [r0], r3
    b       word_set
1:
    bx      lr
    .end
