/*
 *               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 <hw.h>
#include <iostypes.h>
#include <ioslibc.h>
#include <boot.h>
#include <fs.h>
#include <arm.h>
#include <sys.h>
#include <priority.h>
#include <lomem.h>
#include <lomem_12M.h>
#include "thread.h"
#include "except.h"
#include "memory.h"
#include "ioslog.h"
#include "elf.h"
#include "dol.h"
#include "addr_map.h"
#include "resource.h"
#include "mmu.h"
#include "message.h"

#if defined (RVL_PROD_PKI)   // Production version
char const __version[] = "$IOSVersion: IOSP: "BUILD_TIME" "MEM_SIZE_ID" $";
#else
char const __version[] = "$IOSVersion: IOS: "BUILD_TIME" "MEM_SIZE_ID" $";
#endif

#define SYSCALL_STACK_SIZE      (1024)
//#define ENABLE_ELF_MERGE 1
//#define ENABLE_GET_USAGE 1
IOSThread __threads[IOS_THREAD_MAX] __attribute__((section(".bss32")));

/* Order must match pid definitions in iostypes.h. */
static u8 __priorities[IOS_PROCESS_MAX] __attribute__((section("ddr"))) = {
    IOS_PRIORITY_MAX, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
    0, 0, 0, 0, 0, 0, 0, 0, 0};

static u32 __iosIpcTid;
IOSThread *__ipcThread = NULL;

IOSThread __iosThreadTail = {
    .priority = -1
};

IOSThread *__iosRunQueue = &__iosThreadTail;
IOSThread *__iosRunningThread[2] = {NULL, NULL};

#define CHECK_THREAD_ID(id) \
    if (((id) < 0) || ((id) >= IOS_THREAD_MAX)) {\
        rv = IOS_ERROR_INVALID; \
        goto end; \
    } else

#define CHECK_PROCESS_ID(id) \
    if (((id) < 0) || ((id) >= IOS_PROCESS_MAX)) {\
        rv = IOS_ERROR_INVALID; \
        goto end; \
    } else if (THIS_THREAD->pid != IOS_KERNEL_PROCESS && \
               THIS_THREAD->pid != IOS_ETICKET_PROCESS) { \
        rv = IOS_ERROR_ACCESS; \
        goto end; \
    } else

#define CHECK_PROCESS(p) \
    if (THIS_THREAD && THIS_THREAD->pid && (p) != THIS_THREAD->pid) { \
        rv = IOS_ERROR_INVALID; \
        goto end; \
    } else

#define CHECK_PRIORITY(pri) \
    if ((pri) > IOS_PRIORITY_MAX) { \
        rv = IOS_ERROR_INVALID; \
        goto end; \
    } else

#define GET_THREAD(t, id) \
    if (id == 0 && THIS_THREAD) { \
        t = THIS_THREAD; \
    } else { \
        CHECK_THREAD_ID(id); \
        t = __threads + id; \
        CHECK_PROCESS(t->pid); \
    }

void
__iosSetPid(IOSThreadId tid, IOSProcessId pid)
{
    __threads[tid].pid = pid;
}

void
__iosDequeueThread(IOSThread **queue, IOSThread *t)
{
    IOSThread **prev = queue;
    IOSThread *next = *prev;

    while (next != NULL) {
        if (next == t) {
            *prev = next->next;
            return;
        }
        prev = &(next->next);
        next = next->next;
    }
}

static void *__cleanupThread;

IOSThreadId
iosCreateThread(IOSEntryProc entry,
               void *arg, 
               void *stack, 
               u32   stackSize,
               u32   priority,
               u32   attribute)
{
    IOSThreadId rv;
    IOSThread *t;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_THREADS();

    /* Check parameters */
    CHECK_PRIORITY(priority);
    if (THIS_THREAD && (priority > THIS_THREAD->initPriority)) {
        rv = IOS_ERROR_INVALID;
        goto end;
    }

    /* Look for a free thread structure */
    for (rv = 0; rv < IOS_THREAD_MAX; ++rv) {
        if (__threads[rv].state == IOS_STATE_FREE) {
            break;
        }
    }
    if (rv == IOS_THREAD_MAX) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Initialize thread structure */
    t = __threads + rv;
    t->pid = THIS_THREAD ? THIS_THREAD->pid : 0;
    t->state = IOS_STATE_STOPPED;
    t->initPriority = t->priority = priority;

    u32 pid2 = t->pid;
    if (((pid2 == IOS_KERNEL_PROCESS) || (pid2 == IOS_ETICKET_PROCESS)) && 
        ((u32)arg < IOS_PROCESS_MAX)) {
        pid2 = (u32)arg;
    }
    if (priority > __priorities[pid2]) {
        __priorities[pid2] = priority;
    }
    t->context.pc = (u32) entry;
    t->context.r[0] = (u32) arg;
    t->context.sp = (u32) stack ? (u32) stack : t->syscallStack;
    t->context.lr = (u32) __cleanupThread;
    t->context.cpsr = ARM_MODE_USR | ((t->context.pc & 0x1) ? ARM_THUMB_STATE : 0);
    t->next = NULL;
    t->queue = NULL;
    t->joinQueue = NULL;
    t->attribute = attribute;

end:
    UNLOCK_THREADS(mask);

    IOS_EXIT();

    return rv;
}

IOSError
iosJoinThread(IOSThreadId id, void **val)
{
    IOSError rv = IOS_ERROR_OK;
    IOSThread *t;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_THREADS();

    CHECK_WRITABLE_BUFFER(val, sizeof(void *), 0x0);

    GET_THREAD(t, id);

    if (t == THIS_THREAD ||
        t->joinQueue != NULL ||
        t->attribute & IOS_THREAD_CREATE_DETACHED) {
        rv = IOS_ERROR_INVALID;
        goto end;
    }

    if (t->state != IOS_STATE_DEAD) {
        THIS_THREAD->state = IOS_STATE_WAITING;
        __iosEnqueueAndYield(&t->joinQueue);
    }

    if (val) {
        *val = t->val;
    }

    if (t->state != IOS_STATE_DEAD) {
        __iosPanic("Thread %d is not dead, but join from %d resumed\n", t - __threads, THIS_THREAD - __threads);
    }

    t->state = IOS_STATE_FREE;

end:
    UNLOCK_THREADS(mask);

    IOS_EXIT();

    return rv;
}

IOSError
iosDestroyThread(IOSThreadId id, void *val)
{
    IOSError rv = IOS_ERROR_OK;
    IOSThread *t;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_THREADS();

    GET_THREAD(t, id);

    if (t->state != IOS_STATE_STOPPED) {
        __iosDequeueThread(t->queue, t);
    }

    t->val = val;
    if (t->attribute & IOS_THREAD_CREATE_DETACHED) {
        t->state = IOS_STATE_FREE;
    } else {
        t->state = IOS_STATE_DEAD;
        if (t->joinQueue) {
            IOSThread *j = __iosPopThread(&(t->joinQueue));
            j->state = IOS_STATE_READY;
            __iosEnqueueThread(&__iosRunQueue, j);
        }
    }

    if (t == THIS_THREAD) {
        __iosDispatchThread();
    } else {
        /* If running thread is no longer the highest priority, then yield */
        if (THIS_THREAD->priority < __iosRunQueue->priority) {
            THIS_THREAD->state = IOS_STATE_READY;
            __iosEnqueueAndYield(&__iosRunQueue);
        }
    }

end:
    UNLOCK_THREADS(mask);

    IOS_EXIT();

    return rv;
}

IOSThreadId
iosGetThreadId(void)
{
    IOSThreadId id;

    IOS_ENTRY();
    id = THIS_THREAD - __threads;
    IOS_EXIT();

    return id;
}

IOSProcessId
iosGetProcessId(void)
{
    IOSProcessId id;

    IOS_ENTRY();
    id = THIS_THREAD->pid;
    IOS_EXIT();

    return id;
}

IOSUid __iosUids[IOS_PROCESS_MAX];
IOSGid __iosGids[IOS_PROCESS_MAX];

IOSError
iosSetUid(IOSProcessId id, IOSUid uid)
{
    IOSError rv = IOS_ERROR_OK;
    u32 mask;

    IOS_ENTRY();
    mask = LOCK_THREADS();
    
    CHECK_PROCESS_ID(id);

    __iosUids[id] = uid;

end:
    UNLOCK_THREADS(mask);
    IOS_EXIT();

    return rv;
}

IOSUid
iosGetUid(void)
{
    IOSError rv = IOS_ERROR_OK;

    IOS_ENTRY();
    
    rv = __iosUids[THIS_THREAD->pid];

    IOS_EXIT();

    return rv;
}

IOSError
iosSetGid(IOSProcessId id, IOSGid gid)
{
    IOSError rv = IOS_ERROR_OK;
    u32 mask;

    IOS_ENTRY();
    mask = LOCK_THREADS();
    
    CHECK_PROCESS_ID(id);

    __iosGids[id] = gid;

end:
    UNLOCK_THREADS(mask);
    IOS_EXIT();

    return rv;
}

IOSGid
iosGetGid(void)
{
    IOSError rv = IOS_ERROR_OK;

    IOS_ENTRY();
    
    rv = __iosGids[THIS_THREAD->pid];

    IOS_EXIT();

    return rv;
}

void
__iosRestartThread(IOSThread **queue, IOSError rv)
{
    IOSThread *t = __iosPopThread(queue);
    t->state = IOS_STATE_READY;
    t->context.r[0] = rv;
    __iosEnqueueThread(&__iosRunQueue, t);
    if (THIS_THREAD->priority < __iosRunQueue->priority) {
        THIS_THREAD->state = IOS_STATE_READY;
        __iosEnqueueAndYield(&__iosRunQueue);
    }

}

IOSError
iosStartThread(IOSThreadId id)
{
    IOSError rv = IOS_ERROR_OK;
    IOSThread *t;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_THREADS();
   
    GET_THREAD(t, id);

    if (t->state == IOS_STATE_STOPPED) {
        if ((t->queue == NULL) || (t->queue == &__iosRunQueue)) {
            /* Thread t was just started or pulled out of the run queue */
            t->state = IOS_STATE_READY;
            __iosEnqueueThread(&__iosRunQueue, t);
        } else {
            /* Thread t was pulled out of a message queue */
            t->state = IOS_STATE_WAITING;
            __iosEnqueueThread(t->queue, t);
        }
    } else {
        rv = IOS_ERROR_INVALID;
        goto end;
    }

    if (THIS_THREAD == NULL) {
        __iosDispatchThread();
    } else if (THIS_THREAD->priority < __iosRunQueue->priority) {
        THIS_THREAD->state = IOS_STATE_READY;
        __iosEnqueueAndYield(&__iosRunQueue);
    }

end:
    UNLOCK_THREADS(mask);

    IOS_EXIT();

    return rv;
}

IOSError
iosStopThread(IOSThreadId id)
{
    IOSError rv = IOS_ERROR_OK;
    IOSThread *t;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_THREADS();
   
    GET_THREAD(t, id);

    switch(t->state) {
    case IOS_STATE_RUNNING:
        t->state = IOS_STATE_STOPPED;
        __iosEnqueueAndYield(NULL);
        break;
    case IOS_STATE_READY:
    case IOS_STATE_WAITING:
        t->state = IOS_STATE_STOPPED;
        __iosDequeueThread(t->queue, t);
        break;
    default:
        rv = IOS_ERROR_INVALID;
        goto end;
    }

end:
    UNLOCK_THREADS(mask);

    IOS_EXIT();

    return rv;
}

void
iosYieldThread(void)
{
    u32 mask = LOCK_THREADS();

    IOS_ENTRY();

    THIS_THREAD->state = IOS_STATE_READY;
    __iosEnqueueAndYield(&__iosRunQueue);

    UNLOCK_THREADS(mask);

    IOS_EXIT();
}

s32
iosGetThreadPriority(IOSThreadId id)
{
    IOSThread *t;
    s32 rv;

    IOS_ENTRY();

    GET_THREAD(t, id);

    rv = t->priority;
end:
    IOS_EXIT();

    return rv;
}

IOSError
iosSetThreadPriority(IOSThreadId id, u32 priority)
{
    IOSThread *t;
    IOSError rv = IOS_ERROR_OK;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_THREADS();

    GET_THREAD(t, id);

    CHECK_PRIORITY(priority);
    if (priority > t->initPriority) {
        rv = IOS_ERROR_INVALID;
        goto end;
    }

    /* Update scheduling if priorities changed */
    if (t->priority != priority) {
        t->priority = priority;

        /* Reschedule thread by removing and reinserting into queue */
        if ((t != THIS_THREAD) &&
            (t->state != IOS_STATE_STOPPED)) {
            __iosDequeueThread(t->queue, t);
            __iosEnqueueThread(t->queue, t);
        }

        /* If running thread is no longer the highest priority, then yield */
        if (THIS_THREAD->priority < __iosRunQueue->priority) {
            THIS_THREAD->state = IOS_STATE_READY;
            __iosEnqueueAndYield(&__iosRunQueue);
        }
    }

end:
    UNLOCK_THREADS(mask);

    IOS_EXIT();

    return rv;
}

#ifdef ENABLE_CRYPTO
static u8 cryptoHeap[512] __attribute__((aligned(32)));
IOSHeapId __iosCryptoHeap;
#endif

/* do minimal check on the program header table, returns its length. */

#if defined(ENABLE_GET_USAGE)
extern char *__processes[];

#if defined(ENABLE_THREAD_PROFILE)
static u64 __totalScheduled;
static u64 __totalTimeScheduled;
#endif
void
__iosGetThreadUsage(int i)
{
    char *s;
    IOSThread *t = __threads + i;
    switch (t->state) {
    case IOS_STATE_FREE: return; //s = "free"; break;
    case IOS_STATE_READY: s = "ready"; break;
    case IOS_STATE_RUNNING: s = "running"; break;
    case IOS_STATE_STOPPED: s = "stopped"; break;
    case IOS_STATE_WAITING: s = "waiting"; break;
    case IOS_STATE_DEAD: s = "dead"; break;
    case IOS_STATE_FAULTED: s = "faulted"; break;
    default: s = "unknown"; break;
    }
    printf("Thread %2d [%08x]: (%s)\n", i, t, s);
    switch(t->context.cpsr & ARM_MODE_MASK) {
    case ARM_MODE_USR: s = "USR"; break;
    case ARM_MODE_FIQ: s = "FIQ"; break;
    case ARM_MODE_IRQ: s = "IRQ"; break;
    case ARM_MODE_SVC: s = "SVC"; break;
    case ARM_MODE_ABT: s = "ABT"; break;
    case ARM_MODE_UND: s = "UND"; break;
    case ARM_MODE_SYS: s = "SYS"; break;
    }
    printf("CPSR: %08x, IRQ: %c, FIQ: %c, mode: %s\n", t->context.cpsr, t->context.cpsr & ARM_IRQ ? 'D':'E', t->context.cpsr & ARM_FIQ ? 'D':'E', s);
    printf("Pri: %d, PID: %d (%s)\n", t->priority, t->pid, __processes[t->pid]);
    printf("R00-03: %08x %08x %08x %08x\n", t->context.r[0], t->context.r[1], t->context.r[2], t->context.r[3]);
    printf("R04-07: %08x %08x %08x %08x\n", t->context.r[4], t->context.r[5], t->context.r[6], t->context.r[7]);
    printf("R08-11: %08x %08x %08x %08x\n", t->context.r[8], t->context.r[9], t->context.r[10], t->context.r[11]);
    printf("R12-15: %08x %08x %08x %08x\n", t->context.r[12], t->context.r[13], t->context.r[14], t->context.r[15]);
    u32 *top = (u32 *)(SYSCALL_STACK_START + (i+1) * SYSCALL_STACK_SIZE);
    u32 *bottom = (u32 *)(SYSCALL_STACK_START + i * SYSCALL_STACK_SIZE);
    while (bottom < top) {
        if (*bottom != 0xa5a5a5a5) break;
        ++bottom;
    }
    printf("Syscall stack: %08x (%d/%d used)\n", t->syscallStack, (top-bottom)*sizeof(u32), SYSCALL_STACK_SIZE);
#if defined(ENABLE_THREAD_PROFILE)
    printf("Num scheduled: %u (%d%%)\n", t->numScheduled, 
        (u32)(t->numScheduled*100/__totalScheduled));
    printf("Time scheduled: %u (%d%%), %d/iter\n", t->timeScheduled, 
        (u32)(t->timeScheduled*100/__totalTimeScheduled), 
        t->timeScheduled/t->numScheduled);
#endif
    printf("\n");
}

void
__iosGetThreadsUsage(void)
{
    int i;
    
#if defined(ENABLE_THREAD_PROFILE)
    __totalScheduled = 0;
    __totalTimeScheduled = 0;
    /* Thread 0 is used to capture IRQs profiling data */
    for (i = 0; i < IOS_THREAD_MAX; ++i) {
        IOSThread *t = __threads + i;
        __totalScheduled = __totalScheduled + t->numScheduled;
        __totalTimeScheduled = __totalTimeScheduled + t->timeScheduled;
    }
#endif
    for (i = 0; i < IOS_THREAD_MAX; ++i) {
        __iosGetThreadUsage(i);
    }
}

#endif

#if defined(ENABLE_THREAD_PROFILE)
u32 __iosThreadProfileEnable;
u32 __iosLastScheduleTime;
u32 __iosLastScheduleThread;

#define IOS_THREAD_PROFILE_RESET 0
#define IOS_THREAD_PROFILE_START 1
#define IOS_THREAD_PROFILE_STOP  2
#define IOS_THREAD_PROFILE_DUMP  3

static void
__printThreadProfiles()
{
    u32 i;

    for (i = 0; i < IOS_THREAD_MAX; ++i) {
        IOSThread *t = __threads + i;
        /* Only print threads that are active and have been scheduled */
        if ((t->state != IOS_STATE_FREE) &&
            (t->numScheduled > 0 )) {
            printf("* T %2d: S:%1d Pri:%3d PID:%3d (%7s)"
                   " Sched:%7u (%2d%%) Time:%9u (%2d%%), %3d/iter\n",
                   i, t->state, t->priority, t->pid, 
                   __processes[t->pid], t->numScheduled, 
                   (u32)(t->numScheduled/(__totalScheduled/100)),
                   t->timeScheduled, 
                   (u32)(t->timeScheduled/(__totalTimeScheduled/100)),
                   t->timeScheduled/t->numScheduled);
        }  /* if */
    }  /* for */
}

static IOSError
__iosProfIoctlv(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceIoctlv *args = &req->args.ioctlv;
    int i;

    switch (args->cmd) {
    case IOS_THREAD_PROFILE_RESET:
        printf("IOS Profile: RESET(%d)\n", args->cmd);
        for (i = 0; i < IOS_THREAD_MAX; ++i) {
            IOSThread *t = __threads + i;
            t->numScheduled = 0;
            t->timeScheduled = 0;
        }
        break;
    case IOS_THREAD_PROFILE_START:
        printf("IOS Profile: START(%d)\n", args->cmd);
        __iosThreadProfileEnable = 1;
        __iosLastScheduleTime = IO_READ(SYS_TIMER_REG);
        __iosLastScheduleThread = (u32) THIS_THREAD;
        break;
    case IOS_THREAD_PROFILE_STOP:
        printf("IOS Profile: STOP(%d)\n", args->cmd);
        __iosThreadProfileEnable = 0;
        break;
    case IOS_THREAD_PROFILE_DUMP:
        printf("IOS Profile: DUMP(%d)\n", args->cmd);

        __totalScheduled = 0;
        __totalTimeScheduled = 0;
        /* Thread 0 is used to capture IRQs profiling data */
        for (i = 0; i < IOS_THREAD_MAX; ++i) {
            IOSThread *t = __threads + i;
            __totalScheduled = __totalScheduled + t->numScheduled;
            __totalTimeScheduled = __totalTimeScheduled + t->timeScheduled;
        }
        printf("\nTotal Scheduled: 0x%llx, Total Time Scheduled: 0x%llx\n", 
            __totalScheduled, __totalTimeScheduled);

        if (args->writeCount > 0) {
            void *buf = args->vector[0].base;
            u32 size  = args->vector[0].length;

            printf("-> Args: buf: 0x%x size: %d\n", buf, size);

            /* Copy thread profile info to valid user buffer */
            if ((buf != NULL) && 
                (size >= (IOS_THREAD_MAX * sizeof(IOSThreadProfile)))) {
                IOSThreadProfile *p = (IOSThreadProfile *)buf;
                for (i = 0; i < IOS_THREAD_MAX; ++i) {
                    IOSThread *t = __threads + i;
                    p = (IOSThreadProfile *)(buf+(i*sizeof(IOSThreadProfile)));
                    if (t->state != IOS_STATE_FREE) {
                        p->pid          = t->pid;
                        p->priority     = t->priority;
                        p->state        = t->state;
                        p->numScheduled = t->numScheduled;
                        p->timeScheduled = t->timeScheduled;

                    }  /* if */
                }  /* for */
            }  /* if */
        }  /* if */

        __printThreadProfiles();

        break;
    }
    
    return rv;
}
#endif

static void
__idleThread(u32 arg)
{
    iosSetThreadPriority(__iosIpcTid, IOS_PRIORITY_IPC_RUN);
#if defined(ENABLE_THREAD_PROFILE)
    IOSMessage rmArray[8];
    IOSMessage msg;
    IOSMessageQueueId mq;
    IOSError rv;
    /* Create queue and register for profile rm requests */
    if ((mq = iosCreateMessageQueue(rmArray, sizeof(rmArray)/sizeof(rmArray[0]))) < 0) {
        __iosPanic("Unable to create profile rm queue: %d\n", mq);
    }
    if ((rv = iosRegisterResourceManager("/dev/prof", mq)) != IOS_ERROR_OK) {
        __iosPanic("Unable to register profile resource manager: %d\n", rv);
    }
#endif
  while(1) {
#if defined(ENABLE_THREAD_PROFILE)
        if ((rv = iosReceiveMessage(mq, &msg, IOS_MESSAGE_NOBLOCK)) == IOS_ERROR_OK) {
        IOSResourceRequest *req = (IOSResourceRequest *)msg;
        switch (req->cmd) {
        case IOS_OPEN:
            printf("IOS Profile: OPEN\n");
            if (memcmp(req->args.open.path, "/dev/prof", sizeof("/dev/prof"))) {
                rv = IOS_ERROR_NOEXISTS;
            } else {
                rv = 0;
            }
            break;
        case IOS_CLOSE:
            rv = IOS_ERROR_OK;
            break;
        case IOS_IOCTLV:
            rv = __iosProfIoctlv(req);
            break;
        default:
            rv = IOS_ERROR_INVALID;
            break;
        }
        iosResourceReply(req, rv);
    }
#endif
#if defined(ENABLE_GET_USAGE)
        extern void iosGetUsage(u32 usage);
        static volatile u32 __getUsage = 0;
        if (__getUsage) {
            iosGetUsage(__getUsage); 
            __getUsage = 0;
        }
#endif
    }
}

/* Should the Napa refresh thread be started?.
 * Start if chip version is ES1.1 and Napa version
 * is 1.10.
 */
static IOSError 
napaRefreshNeeded(void)
{
    IOSError rv = IOS_ERROR_INVALID; /* anything but OK */
    u32 strap_value;
    u8 ES11;
    u8 napa1;
    u32 chipid_major;
    u32 chipid_minor;

    /* Do not need to start Napa refresh thread if
     * chip is ES 2.x (chipid_major >= 1).
     */
    getChipId(&chipid_major, &chipid_minor);
    if (0 != chipid_major) { 
        goto done;
    }

    strap_value = DIStraps();
    ES11 = (CONFIG_IS_ES11(strap_value)) ? 1:0;
    napa1 = (CONFIG_IS_NAPA1(strap_value))? 1:0;

    /* If we have ES11 but Napa 1.10, enable refresh thread */
    if ((1 == ES11) && (0 == napa1))
        rv = IOS_ERROR_OK;
done:
    return rv;
}

    
static void
__iosInitKernelThreads(void)
{
    extern void __iosInitTimer(u32);
    extern void __iosInitNapaRefresh(u32);
    extern void __iosIpcThread(u32);
#ifdef ENABLE_CRYPTO
    extern void __iosInitAes(u32);
    extern void __iosInitSha(u32);
    extern void __iosInitCryptoPostThreads();
#endif

    u32 id = iosCreateThread(__iosInitTimer, 0, NULL, 0, IOS_PRIORITY_TIMER, IOS_THREAD_CREATE_DETACHED);
    /* timer handler is a kernel thread */
    __threads[id].context.cpsr &= ~ARM_MODE_MASK;
    __threads[id].context.cpsr |= ARM_MODE_SYS;
    iosStartThread(id);

    /* Start refresh thread _after_ timer */
    if (IOS_ERROR_OK == napaRefreshNeeded()) {
        id = iosCreateThread(__iosInitNapaRefresh, 0, NULL, 0, IOS_PRIORITY_NAPAREF, IOS_THREAD_CREATE_DETACHED);
        __threads[id].context.cpsr &= ~ARM_MODE_MASK;
        __threads[id].context.cpsr |= ARM_MODE_SYS;
        iosStartThread(id);
    }
#ifdef ENABLE_CRYPTO
    id = iosCreateThread(__iosInitAes, 0, NULL, 0, IOS_PRIORITY_AES, IOS_THREAD_CREATE_DETACHED);
    /* timer handler is a kernel thread */
    __threads[id].context.cpsr &= ~ARM_MODE_MASK;
    __threads[id].context.cpsr |= ARM_MODE_SYS;
    iosStartThread(id);

    id = iosCreateThread(__iosInitSha, 0, NULL, 0, IOS_PRIORITY_SHA, IOS_THREAD_CREATE_DETACHED);
    /* timer handler is a kernel thread */
    __threads[id].context.cpsr &= ~ARM_MODE_MASK;
    __threads[id].context.cpsr |= ARM_MODE_SYS;
    iosStartThread(id);

     /* Do initialization for crypto that has to happen post thread creation */
    __iosInitCryptoPostThreads();
#endif

    __iosIpcTid = id = iosCreateThread(__iosIpcThread, 0, NULL, 
                    0, IOS_PRIORITY_IPC_RUN, 
                    IOS_THREAD_CREATE_DETACHED);
    __threads[id].context.cpsr &= ~ARM_MODE_MASK;
    __threads[id].context.cpsr |= ARM_MODE_SYS;
    __ipcThread = &__threads[id];
    iosStartThread(id);
}

#ifdef ENABLE_ELF_MERGE
/* do minimal check on the program header table, returns its length. */
static u32
__checkProgramHeaders(const Elf32_Phdr* phdr)
{
    if (phdr->p_type != PT_PHDR ||
        (u32)phdr != phdr->p_vaddr ||
        phdr->p_vaddr != phdr->p_paddr ||
        (phdr->p_memsz/sizeof(Elf32_Phdr)) < 2) {
        return 0;
    }

    u32 n = phdr->p_memsz / sizeof(Elf32_Phdr);
    int i;

    /* minimal consistency check */
    for (i = 1; i < n; ++i) {
        if (phdr[i].p_type == PT_LOAD || phdr[i].p_type == PT_NOTE) {
            if (/*phdr[i].p_vaddr != phdr[i].p_paddr ||*/
                phdr[i].p_memsz < phdr[i].p_filesz ||
                (phdr[i].p_vaddr & (phdr[i].p_align - 1))) {
                return 0;
            }
        }
    }
    return n;
} /* __checkProgramHeaders */

static const Elf32_auxv_t*
__getEntryPoints(const Elf32_Phdr* phdr, u32* num_entries)
{
    *num_entries = 0;

    /* The PT_NOTE (4) segment, if present, must be the second entry. */
    ++phdr;
    if (phdr->p_type != PT_NOTE || (phdr->p_vaddr & 0x3)) {
        return NULL;
    }

    /*
     * See The Elf spec for the definition of the note section.  In short,
     * word #1: name size (which we ignore)
     * word #2: descriptor size in bytes
     * word #3: note type
     * word #4- : name string padded to word boundary
     * after the name string is the entry point vector.
     */

    u32* note_desc = (u32*) phdr->p_vaddr;
    if (note_desc[2] != NT_AUXV)
        return NULL;
    *num_entries = note_desc[1] / sizeof(Elf32_auxv_t);

    return (const Elf32_auxv_t*)
        (note_desc + 3 + ((note_desc[0] + 3) / sizeof(u32)));
    
} /* __getEntryPoints */
static void
__iosInitOSThreads(void)
{
    const Elf32_Phdr* phdr = (const Elf32_Phdr*) SHARED_SP_START;
    u32 segLen = __checkProgramHeaders(phdr);
    int i;

    /* set up all memory segments */
    for (i = 1; i < segLen; ++i) {
        if (phdr[i].p_type != PT_LOAD) {
            continue;
        }

        /* skip kernel segment */
        if ((phdr[i].p_flags & PF_MASKOS) == 0) {
            continue;
        }

        /* skip shared heap region */
        if (phdr[i].p_vaddr == SHARED_SP_START) {
            continue;
        }

        u32 mask = PF_MEM_MASK(phdr[i].p_flags);

        IOSMemoryRegion region;
        
        region.paddr = phdr[i].p_paddr;
        region.vaddr = phdr[i].p_vaddr;
        region.len = (phdr[i].p_memsz+4095)&~4095;
        region.domain = mask;
        region.ap = ((phdr[i].p_flags & PF_X) ? PT_AP_RO :
              (phdr[i].p_flags & PF_W) ? PT_AP_RW :
              (phdr[i].p_flags & PF_R) ? PT_AP_RO :
              PT_AP_NA);
        region.cached = 1;
        if (mmuMapRegion(&region) != IOS_ERROR_OK) {
            __iosPanic("Unable to map region %08x [%d bytes]\n", region.vaddr, region.len);
        }

        /* Create uncached window into the same region */
        region.vaddr |= 0x80000000;
        region.cached = 0;
        if (mmuMapRegion(&region) != IOS_ERROR_OK) {
            __iosPanic("Unable to map region %08x [%d bytes]\n", region.vaddr, region.len);
        }

printf("load segment @ [%08x, %08x] (%d bytes)\n", phdr[i].p_vaddr, phdr[i].p_vaddr+phdr[i].p_memsz, phdr[i].p_memsz);

        if (phdr[i].p_memsz > phdr[i].p_filesz) {
            memset((void*) (phdr[i].p_vaddr + phdr[i].p_filesz),
                   0,
                   phdr[i].p_memsz - phdr[i].p_filesz);
        }
    }
    /* Look for the entry point vector, if present */
    u32 ev_size;
    const Elf32_auxv_t* ev =
        __getEntryPoints((const Elf32_Phdr*) SHARED_SP_START, &ev_size);

    for (i = 0; i < ev_size; i += 5) {
        if (i + 1 >= ev_size) {
            break;
        }

        u32 pid = ev[i].a_un.a_val & 0xff;
        void* entry = (void *)((u32)(ev[i+1].a_un.a_ptr));
        u32 priority = ev[i+2].a_un.a_val; 
        u32 stackSize = ev[i+3].a_un.a_val; 
        void *stackPtr = (void *)ev[i+4].a_un.a_ptr; 
printf("priority = %d, stackSize = %d, stackPtr = %08x\n", priority, stackSize, stackPtr);
        /* Create thread */
        printf("starting thread entry: 0x%08x\n", entry);
        u32 id = iosCreateThread((IOSEntryProc) entry, (void*)pid, stackPtr, stackSize, priority, IOS_THREAD_CREATE_DETACHED);
        __threads[id].pid = pid;
        iosStartThread(id);
    }
}
#endif /* ENABLE_ELF_MERGE */


#ifndef ENABLE_ELF_MERGE
/* Starts iossh, which allows users to start their own programs.
 */

/* XXX horti: This facility should only be in the development version */
#define IOSSHSTACK_SIZE 8
#define IOSSHSTACK 0x10000007
#define IOSSH 0x10000008
extern u8 iosshStack[2048];

static void
__iosCreateAndStartTest(IOSEntryProc iossh, u32 priority)
{
//    u32 thrId = iosCreateThread(iossh, 0, (u8 *) IOSSHSTACK, IOSSHSTACK_SIZE, priority, IOS_THREAD_CREATE_DETACHED);
    u32 thrId = iosCreateThread(iossh, 0, iosshStack + sizeof(iosshStack), sizeof(iosshStack), priority, IOS_THREAD_CREATE_DETACHED);
    __threads[thrId].context.cpsr &= ~ARM_MODE_MASK;
    __threads[thrId].context.cpsr |= ARM_MODE_SYS;
    iosStartThread(thrId);
}
#endif /* !ENABLE_ELF_MERGE */

static void
__iosInitSystemThreads(u32 arg)
{
    extern void iossh(u32);
    __iosInitKernelThreads();
#ifdef ENABLE_ELF_MERGE
    __iosInitOSThreads();
    iosCreateHeap((void *) SHARED_SP_START, SHARED_SP_SIZE);
#else
    iosCreateHeap((void *) SHARED_SP_START, SHARED_SP_SIZE);
    __iosCreateAndStartTest(iossh, IOS_PRIORITY_MAX);
#endif
#ifdef ENABLE_CRYPTO
    __iosCryptoHeap = iosCreateHeap(cryptoHeap, sizeof(cryptoHeap));
#endif
    printf("%s\n", __version);

    /* Now that real threads are started, lower our priority to let them run */
    iosSetThreadPriority(0, 0);
    __idleThread(0);
}

extern u32 __iosKernelDataEnd;

void
__iosInitThreads(void)
{
    /* Move __iosCleanupThread to someplace that is readable by the world */
    __iosKernelDataEnd -= 16;
    __cleanupThread = (void *)__iosKernelDataEnd;
    memcpy(__cleanupThread, __iosCleanupThread, 16);

    /* Initialize uid/gid */
    IOSProcessId pid;
    for (pid = 0; pid < IOS_PROCESS_MAX; ++pid) {
        __iosUids[pid] = pid;
        __iosGids[pid] = pid;
    }

    int i;
    memset((void *)SYSCALL_STACK_START, 0xa5, SYSCALL_STACK_END-SYSCALL_STACK_START);
    for (i = 0; i < IOS_THREAD_MAX; ++i) {
        __threads[i].syscallStack = SYSCALL_STACK_START + (i+1) * SYSCALL_STACK_SIZE;
    }
    if ((SYSCALL_STACK_START + i * SYSCALL_STACK_SIZE) > SYSCALL_STACK_END) {
        __iosPanic("Syscall stacks are too large: start=%08x, end=%08x\n", SYSCALL_STACK_START, SYSCALL_STACK_END);
    }

#if defined(ENABLE_THREAD_PROFILE)
    __threads[0].state = IOS_STATE_STOPPED;
    printf("IOS Profile: Use threads[0] as irq\n");
#endif

    /* Create idle thread */
    u32 id = iosCreateThread(__iosInitSystemThreads, 0, NULL, 0, IOS_PRIORITY_MAX, IOS_THREAD_CREATE_DETACHED);
    /* The idle thread is special, so it should run in kernel mode */
    __threads[id].context.cpsr &= ~ARM_MODE_MASK;
    __threads[id].context.cpsr |= ARM_MODE_SYS;

    iosStartThread(id);
}


extern void __iosFlushDCache();
extern void __iosInvalidateICache();
extern void disableDCache();
extern void disableICache();

#define PPC_TO_IOP_ADDR(x)  ((x) > 0x80000000 ? ((x) - 0x80000000) : (x))

static void
__iosSetupPPC(void)
{
    /* 16 instructions BS0 for PPC */
    u32 __iosPPCBS0[] = {
        0x3c600000, 0x60633400, 0x7c7a03a6, 0x38600000,
        0x7c7b03a6, 0x4c000064, 0x00000000, 0x00000000,
        0x00000000, 0x00000000, 0x00000000, 0x00000000,
        0x00000000, 0x00000000, 0x00000000, 0x00000000
    };

    /* Put PPC into reset */
    stopPPC();

    /*
     * Put BS0 in place. The AHBIOPI bit needs to be enabled before
     * setting up the EXI registers. However, it should be disabled
     * before BS0 is launched by the PPC. After PPC passed the BS0
     * stage, the bit needs to be enabled again
     */
    setAHBIOPI(1);
    setupEXIRegBoot(enhancedmode, __iosPPCBS0,
                    sizeof(__iosPPCBS0) / sizeof(__iosPPCBS0[0]));
    setAHBIOPI(0);

    /* Initialize boot info */
    initLoMemInt();
}

static IOSError
__iosLoadDol(IOSFd fd)
{
    IOSError rv = IOS_ERROR_OK;
    u32 seg, size;
    DolImage *dolHeader = NULL;

    /* Dol format is used only for PPC apps */
    __iosSetupPPC();

    /* Seek to the beginning */
    if ((rv = iosSeek(fd, 0, IOS_SEEK_SET)) != 0) {
        goto end;
    }

    /* Read the Dol header */
    if ((dolHeader = iosAlloc(0, sizeof(DolImage))) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }
    if ((rv = iosRead(fd, dolHeader, sizeof(DolImage))) != sizeof(DolImage)) {
        goto end;
    }

    /* Zero the BSS */
    memset((void *) PPC_TO_IOP_ADDR(dolHeader->bss), 0, dolHeader->bssLen);

    /* Load the text segments */
    for (seg = 0; seg < DOL_MAX_TEXT; seg++) {
        if (dolHeader->textData[seg] == NULL) {
            continue;
        }

        size = (dolHeader->textLen[seg] + 31) & ~31;
        if ((rv = iosSeek(fd, (u32) dolHeader->textData[seg], IOS_SEEK_SET)) < 0) {
            goto end;
        }
        if ((rv = iosRead(fd, (void *) PPC_TO_IOP_ADDR(dolHeader->text[seg]), size)) != size) {
            goto end;
        }
    }

    /* Load the data segments */
    for (seg = 0; seg < DOL_MAX_DATA; seg++) {
        if (dolHeader->dataData[seg] == NULL) {
            continue;
        }

        size = (dolHeader->dataLen[seg] + 31) & ~31;
        if ((rv = iosSeek(fd, (u32) dolHeader->dataData[seg], IOS_SEEK_SET)) < 0) {
            goto end;
        }
        if ((rv = iosRead(fd, (void *) PPC_TO_IOP_ADDR(dolHeader->data[seg]), size)) != size) {
            goto end;
        }
        rv = IOS_ERROR_OK;
    }

end:
    if (dolHeader != NULL) iosFree(0, dolHeader);

    return (rv);
}

static IOSError
__iosLoadElf(IOSFd fd, u32 *entry, u32 *resetPPC)
{
    IOSError rv = IOS_ERROR_OK;
    u32 seg, loadIOP = 0, loadPPC = 0;
    Elf32_Ehdr *ehdr = NULL;
    Elf32_Phdr *phdr = NULL;

    /* Seek to the beginning */
    if ((rv = iosSeek(fd, 0, IOS_SEEK_SET)) != 0) {
        goto end;
    }

    /* Read the Elf header */
    if ((ehdr = iosAlloc(0, sizeof(Elf32_Ehdr))) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }
    if ((rv = iosRead(fd, ehdr, sizeof(Elf32_Ehdr))) != sizeof(Elf32_Ehdr)) {
        goto end;
    }

    /* ELF header consistency check */
    if ((*((u32 *) ehdr) != *((u32 *) ELFMAG)) ||
            (ehdr->e_ident[EI_CLASS] != ELFCLASS32) ||
            (ehdr->e_ident[EI_DATA] != ELFDATA2MSB) ||
            (ehdr->e_ident[EI_VERSION] != EV_CURRENT) ||
            (ehdr->e_ident[EI_OSABI] != ELFOSABI_ARM) ||
            /*(ehdr->e_ident[EI_ABIVERSION] != ELFABIVERSION_BCC) ||*/
            (ehdr->e_type != ET_EXEC) || (ehdr->e_machine != EM_ARM) ||
            (ehdr->e_version != EV_CURRENT) ||
            ((ehdr->e_flags & (EF_ARM_RELEXEC | EF_ARM_PIC)) != 0)) {
        rv = IOS_ERROR_INVALID;
        goto end;
    }

    /* Read the program headers */
    if ((phdr = iosAlloc(0, ehdr->e_phnum * sizeof(Elf32_Phdr))) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }
    if ((rv = iosRead(fd, phdr, ehdr->e_phnum * sizeof(Elf32_Phdr))) != (ehdr->e_phnum * sizeof(Elf32_Phdr))) {
        goto end;
    }
    rv = IOS_ERROR_OK;

    /* Load each program segment */
    for (seg = 0; seg < ehdr->e_phnum; seg++) {
        if (phdr[seg].p_type != PT_LOAD) {
            continue;
        }

        if (PF_MEM_MASK(phdr[seg].p_flags) != 0x7f) {
            /* Set the entry point if there is at least one IOP segment */
            loadIOP = 1;
        } else {
            /* Found PPC segment, put PPC in reset first then start it later */
            if (loadPPC == 0) {
                __iosSetupPPC();
                loadPPC = 1;
            }
        }

        if ((rv = iosSeek(fd, phdr[seg].p_offset, IOS_SEEK_SET)) < 0) {
            goto end;
        }
        if ((rv = iosRead(fd, (void *) phdr[seg].p_vaddr, phdr[seg].p_filesz)) != phdr[seg].p_filesz) {
            goto end;
        }
        rv = IOS_ERROR_OK;

        /* Zero the rest of memory */
        if (phdr[seg].p_memsz > phdr[seg].p_filesz) {
            memset((void *) (phdr[seg].p_vaddr + phdr[seg].p_filesz), 0, phdr[seg].p_memsz - phdr[seg].p_filesz);
        }
    }

    if (loadIOP) {
        /* Set the entry point */
        *entry = ehdr->e_entry;
    }
    if (loadPPC) {
        /* Reset the PPC */
        *resetPPC = 1;
    }

end:
    if (phdr != NULL) iosFree(0, phdr);
    if (ehdr != NULL) iosFree(0, ehdr);

    return (rv);
}

IOSError
iosLaunchElf(const char *path)
{
    IOSError rv = IOS_ERROR_OK;
    IOSFd fd = -1;
    u32 entry = 0, id, resetPPC = 0;
    u8 *hdr = NULL;

    IOS_ENTRY();

    if ((hdr = iosAlloc(0, 4)) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Only allow root to launch a new process */
    if (iosGetUid() != IOS_ROOT_ID) {
        rv = IOS_ERROR_ACCESS;
        goto end;
    }

    /* Open the ELF file from the file system */
    if ((fd = iosOpen(path, ISFS_READ_ACCESS)) < 0) {
        rv = fd;
        goto end;
    }

    /*
     * Read the first 4 bytes. If it's "\177ELF", then the file is in
     * ELF format, otherwise it is assumed to be in DOL format. Since
     * "\177ELF" is not 32-byte aligned when expressed as a u32,
     * therefore it can not be the same as dolHeader->textData[0]
     * since all DOL segments are 32-byte aligned
     */
    if ((rv = iosRead(fd, hdr, 4)) != 4) {
        goto end;
    }
    if (memcmp(hdr, ELFMAG, 4)) {   /* DOL */
        resetPPC = 1;
        rv = __iosLoadDol(fd);
    } else {                        /* ELF */
        rv = __iosLoadElf(fd, &entry, &resetPPC);
    }
    if (rv != IOS_ERROR_OK) {
        goto end;
    }

    /*
     * Programs loaded are likely to be large. It would be more
     * efficient to simply flush the whole D-cache and invalidate
     * the whole I-cache once at the end
     */
    __iosFlushDCache();
    __iosInvalidateICache();
    ahbMemFlush(IOS_WB_IOD);
    ahbMemRBInvalidate(IOS_RB_IOI);

    if (entry != 0) {
        /* Launch the program */
        id = iosCreateThread((IOSEntryProc) entry, 0, 0, 0, 10, IOS_THREAD_CREATE_DETACHED);
        iosStartThread(id);
        __threads[id].pid = 0;
    }

    if (resetPPC) {
        /* Take PPC out of reset */
        bootPPC();

        outputLed(0xaa);

        /* Let PPC take ownership of NDEV LED GPIO pins */
        gpioSetOwner(busRd32(GPIIOPPPCOWNER_REG) | GPIO_NDEV_LED);

        /* Enable the AHBIOPI bit after some delay */
        busDelay(8000);
        setAHBIOPI(1);

    }

end:
    if (fd >= 0) iosClose(fd);
    if (hdr) iosFree(0, hdr);

    IOS_EXIT();

    return (rv);
}


/*
 * Launch an OS image in memory (hdr + loader + merged OS)
 */
extern void iosFlushDCache(void *ptr, u32 bytes);
void
__iosLaunchOSFromMemory(u32 addr, u32 version)
{
    BootOSImageHeader *hdr;
    u32 loaderStartAddr;
    u32 oldVersion, oldDiv;

    hdr = (BootOSImageHeader *) addr;

    /* No need to re-initialize DDR */
    hdr->ddrInit = 0;

    /* Disable interrupts */
    __iosDisableInt();
    IO_WRITE(ACR_INTMASK_TRUSTED, 0x0);

    /* Disable the I and D caches */
    __iosFlushDCache();
    disableICache();
    mmuDisableMMU();

    /* Set version number in lomem */
    oldVersion = setLoMemOSVersion(version);
    { 
        /* Update DDR info with 12M map info. If an
         * old OS is launched, this info is correct.
         * If a new OS is launched, this will get overwritten
         * with correct info, because new OSes do that in
         * initc.
         */
        OSLoMem *m = (OSLoMem *) RVL_LOMEM_BASE;
        m->ddrSize = LOMEM_12M_DDR_SIZE;
        m->ddrSimSize = LOMEM_12M_DDR_SIMSIZE;
        m->ddrSecureBoundary = LOMEM_12M_DDR_SECURE_BOUNDARY;
        m->ddrArenaLo = LOMEM_12M_DDR_ARENALO;
        m->ddrArenaHi = LOMEM_12M_DDR_ARENAHI;
        m->ipcArenaLo = LOMEM_12M_IPC_ARENALO;
        m->ipcArenaHi = LOMEM_12M_IPC_ARENAHI;
        m->diBufferLo = LOMEM_12M_DI_BUFFER_LO;
        m->diBufferHi = LOMEM_12M_DI_BUFFER_HI;
        iosFlushDCache(m, sizeof(OSLoMem));
        printf("Updated DDR settings in lomem: 0x%x with 12M settings\n", m);
    }

    /* Set flash DIV register to power-on reset values
     *   Bits 31:2 = 0, 1 (devsel) = 0, 0 (div2) = 1
     */
    oldDiv = IO_READ(FL_DIV_REG);
    IO_WRITE(FL_DIV_REG, 0x1);

    /* Jump to the loader. This will never return */
    loaderStartAddr = addr + hdr->hdrSize;
    __iosExecLoader(loaderStartAddr);

    /* Launch failed. Restore version. */
    setLoMemOSVersion(oldVersion);

    /* Restore previous flash DIV reg value */
    IO_WRITE(FL_DIV_REG, oldDiv);

}

IOSError
iosLaunchOSFromMemory(u32 addr, u32 version)
{
    IOSError rv = IOS_ERROR_UNKNOWN;

    /* Only allow root to launch a new OS */
    if (iosGetUid() != IOS_ROOT_ID) {
        rv = IOS_ERROR_ACCESS;
        goto end;
    }

    /* This should not return */
    __iosLaunchOSFromMemory(addr, version);

end:
    return (rv);
}

/*
 * Load an OS image from the file system and launch it
 */

IOSError
iosLaunchOS(const char *path, int resetPPC, u32 version)
{
    IOSError rv = IOS_ERROR_OK;
    IOSFd fd = -1;
    ISFSFileStats *stats = NULL;
    u8 *mem = (u8 *) OSLAUNCH_SP_START;

    IOS_ENTRY();

    /* Only allow root to launch a new OS */
    if (iosGetUid() != IOS_ROOT_ID) {
        rv = IOS_ERROR_ACCESS;
        goto end;
    }

    /* Stop threads we don't need. XXX Only IPC thread for now. */
    iosStopThread(__iosIpcTid); 
    
    setupDDR_PPCCGBoundary(OSLAUNCH_SP_START, DDR_BASE + (DDR_ADDRSPACE_SIZE - 1));
  
    /* Open the OS image file from the file system */
    if ((fd = iosOpen(path, ISFS_READ_ACCESS)) < 0) {
        rv = fd;
        goto end;
    }

    /* Find out the file size */
    if ((stats = iosAlloc(0, sizeof(ISFSFileStats))) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }
    if ((rv = iosIoctl(fd, ISFS_FSTATS, NULL, 0, stats, sizeof (ISFSFileStats))) != IOS_ERROR_OK) {
        goto end;
    }

    /*
     * Check that the size is within range. Note that the apps
     * space is used for test apps only, so in a real system, the
     * re-launch buffer can overflow into the apps space
     */
    if (stats->size > (OSLAUNCH_SP_END - OSLAUNCH_SP_START)) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    if (resetPPC) {
        stopPPC();
    }

    /* Read the entire file into memory */
    if ((rv = iosRead(fd, mem, stats->size)) != stats->size) {
        goto end;
    }

    /* Reset the NDEV LED GPIO bits so that IOP can own them in next OS */
    gpioSetOwner(busRd32(GPIIOPPPCOWNER_REG) & ~GPIO_NDEV_LED);

    /* Launch the OS, this should not return */
    rv = IOS_ERROR_UNKNOWN;
    __iosLaunchOSFromMemory((u32) mem, version);

end:
    if (stats != NULL) iosFree(0, stats);
    if (fd >= 0) iosClose(fd);

    IOS_EXIT();

    return (rv);
}

IOSError
iosLaunchRM(const char *path)
{
    IOSError rv = IOS_ERROR_OK;
    IOSFd fd = -1;
    Elf32_Ehdr *ehdr = NULL;
    Elf32_Phdr *phdr = NULL;
    u8 *fbuf = NULL;
    u32 seg;
    u32 note_size = 0, note_offset = 0;

    IOS_ENTRY();

    /* Only allow root access to this function */
    if (iosGetUid() != IOS_ROOT_ID) {
        rv = IOS_ERROR_ACCESS;
        goto end;
    }

    /* Allocate header from shared segment */
    if ((ehdr = iosAlloc(0, sizeof(Elf32_Ehdr))) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Open the ELF file from the file system */
    if ((fd = iosOpen(path, ISFS_READ_ACCESS)) < 0) {
        rv = fd;
        goto end;
    }

    /* Read magic word to see if the file is ELF */
    if ((rv = iosRead(fd, ehdr, 4)) != 4) {
        goto end;
    }
    if (memcmp(ehdr, ELFMAG, 4)) {
        /* Not an ELF file */
        rv = IOS_ERROR_OK;
        goto end;
    }

    /* Seek to the beginning */
    if ((rv = iosSeek(fd, 0, IOS_SEEK_SET)) != 0) {
        goto end;
    }

    if ((rv = iosRead(fd, ehdr, sizeof(Elf32_Ehdr))) != sizeof(Elf32_Ehdr)) {
        goto end;
    }

    /* ELF header consistency check */
    if ((*((u32 *) ehdr) != *((u32 *) ELFMAG)) ||
            (ehdr->e_ident[EI_CLASS] != ELFCLASS32) ||
            (ehdr->e_ident[EI_DATA] != ELFDATA2MSB) ||
            (ehdr->e_ident[EI_VERSION] != EV_CURRENT) ||
            (ehdr->e_ident[EI_OSABI] != ELFOSABI_ARM) ||
            /*(ehdr->e_ident[EI_ABIVERSION] != ELFABIVERSION_BCC) ||*/
            (ehdr->e_type != ET_EXEC) || (ehdr->e_machine != EM_ARM) ||
            (ehdr->e_version != EV_CURRENT) ||
            ((ehdr->e_flags & (EF_ARM_RELEXEC | EF_ARM_PIC)) != 0)) {
        rv = IOS_ERROR_INVALID;
        goto end;
    }

    /* Read the program headers */
    if ((phdr = iosAlloc(0, ehdr->e_phnum * sizeof(Elf32_Phdr))) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }
    if ((rv = iosRead(fd, phdr, ehdr->e_phnum * sizeof(Elf32_Phdr))) != (ehdr->e_phnum * sizeof(Elf32_Phdr))) {
        goto end;
    }
    rv = IOS_ERROR_OK;

    if (rv != IOS_ERROR_OK) {
        goto end;
    }

    if ((fbuf = iosAlloc(0, 16384)) == NULL) {
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Load each program segment */
    for (seg = 0; seg < ehdr->e_phnum; seg++) {
        if (phdr[seg].p_type != PT_LOAD || phdr[seg].p_vaddr == 0) {
            if (phdr[seg].p_type == PT_NOTE) {
                note_size = phdr[seg].p_filesz;
                note_offset = phdr[seg].p_offset;
            }
            continue;
        }

        u32 mask = PF_MEM_MASK(phdr[seg].p_flags);

        /* Create an MMU region that is accessible to ES */
        IOSMemoryRegion region;
        region.paddr = phdr[seg].p_paddr;
        region.vaddr = phdr[seg].p_vaddr;
        region.len = (phdr[seg].p_memsz+4095)&~4095;
        region.domain = DOMAIN_SHARED;
        region.ap =  PT_AP_RW; /* Make it writable for now */
        region.cached = 1;
        if (mmuReMapRegion(&region) != IOS_ERROR_OK) {
            __iosPanic("Unable to map region %08x [%d bytes]\n", region.vaddr, region.len);
        }

        /* Read segment from flash into correct location */
        if ((rv = iosSeek(fd, phdr[seg].p_offset, IOS_SEEK_SET)) < 0) {
            goto end;
        }
        if ((rv = iosRead(fd, (void *)phdr[seg].p_vaddr, phdr[seg].p_filesz)) != phdr[seg].p_filesz) {
            goto end;
        }
        rv = IOS_ERROR_OK;

        /* Zero the rest of memory */
        if (phdr[seg].p_memsz > phdr[seg].p_filesz) {
            memset((void *) (phdr[seg].p_vaddr + phdr[seg].p_filesz), 0, phdr[seg].p_memsz - phdr[seg].p_filesz);
        }

        /* Now remap the region to the correct domain */
        region.domain = mask;
        region.ap = ((phdr[seg].p_flags & PF_X) ? PT_AP_RO :
              (phdr[seg].p_flags & PF_W) ? PT_AP_RW :
              (phdr[seg].p_flags & PF_R) ? PT_AP_RO :
              PT_AP_NA);
        if (mmuReMapRegion(&region) != IOS_ERROR_OK) {
            __iosPanic("Unable to map region %08x [%d bytes]\n", region.vaddr, region.len);
        }

        /* Create uncached window into the same region */
        region.vaddr |= 0x80000000;
        region.cached = 0;
        if (mmuMapRegion(&region) != IOS_ERROR_OK) {
            __iosPanic("Unable to map region %08x [%d bytes]\n", region.vaddr, region.len);
        }

    }

    /*
     * Programs loaded are likely to be large. It would be more
     * efficient to simply flush the whole D-cache and invalidate
     * the whole I-cache once at the end
     */
    __iosFlushDCache();
    __iosInvalidateICache();
    ahbMemFlush(IOS_WB_IOD);
    ahbMemRBInvalidate(IOS_RB_IOI);

    if (note_size) {
        if ((rv = iosSeek(fd, note_offset, IOS_SEEK_SET)) < 0) {
            goto end;
        }
        if ((rv = iosRead(fd, fbuf, note_size)) != note_size) {
            goto end;
        }
        rv = IOS_ERROR_OK;
        u32* note_desc = (u32*) fbuf;
        u32 ev_size = note_desc[1] / sizeof(Elf32_auxv_t);

        /* Look for the entry point vector, if present */
        Elf32_auxv_t *ev = (Elf32_auxv_t *)(note_desc + 3 + ((note_desc[0] + 3) / sizeof(u32)));
        u32 i;

        for (i = 0; i < ev_size; i += 5) {
            if (i + 1 >= ev_size) {
                break;
            }

            u32 pid = ev[i].a_un.a_val & 0xff;
            void* entry = (void *)((u32)(ev[i+1].a_un.a_ptr));
            u32 priority = ev[i+2].a_un.a_val; 
            u32 stackSize = ev[i+3].a_un.a_val; 
            void *stackPtr = (void *)ev[i+4].a_un.a_ptr; 
            /* Create thread */
            u32 id = iosCreateThread((IOSEntryProc) entry, (void*)pid, stackPtr, stackSize, priority, IOS_THREAD_CREATE_DETACHED);
            __threads[id].pid = pid;
            u32 oldPid = THIS_THREAD->pid;
            THIS_THREAD->pid = 0;
            iosStartThread(id);
            THIS_THREAD->pid = oldPid;
        }
    }

end:
    if (fd >= 0) iosClose(fd);
    if (phdr != NULL) iosFree(0, phdr);
    if (ehdr != NULL) iosFree(0, ehdr);
    if (fbuf != NULL) iosFree(0, fbuf);

    IOS_EXIT();

    return rv;
}

#define CHECK_VALID_PID(id) \
    if (((id) < 0) || ((id) >= IOS_PROCESS_MAX)) {\
        rv = IOS_ERROR_INVALID; \
        goto end; \
    }

static u8 __forbiddenPids[6] = { 
    IOS_KERNEL_PROCESS,
    IOS_ETICKET_PROCESS,
    IOS_FS_PROCESS,
    IOS_KD_PROCESS,
    IOS_STM_PROCESS,
    IOS_PPCBOOT_PROCESS
};

#define CHECK_ALLOWED_PID(id) \
    if (((id) < 0) || ((id) >= IOS_PROCESS_MAX)) {\
        rv = IOS_ERROR_INVALID; \
        goto end; \
    } \
    for (k = 0; k < sizeof(__forbiddenPids)/sizeof(u8); ++k) {\
        if (id == __forbiddenPids[k]) { \
            rv = IOS_ERROR_ACCESS;\
            goto end; \
        }\
    }

#define CHECK_ALLOWED_PRIORITY(pri) \
    if ((pri) >= (IOS_PRIORITY_MAX-1)) { \
        rv = IOS_ERROR_INVALID; \
        goto end; \
    } else

        
IOSError
iosChangePriorities(IOSPidPriority *pidPriList, u32 size)
{
    IOSError rv;
    u32 mask;
    u32 i, k;
    u8 tmp[IOS_PROCESS_MAX];  /* 20 bytes */
   
    if (THIS_THREAD->pid != IOS_ETICKET_PROCESS) {
        rv = IOS_ERROR_ACCESS;
        goto end;
    }
    CHECK_READABLE_BUFFER((void *)pidPriList, size*sizeof(IOSPidPriority), 
                          THIS_THREAD->pid);
   
    memset(tmp, 0, sizeof(tmp));
    for (i = 0; i < size; ++i) {
        CHECK_ALLOWED_PID(pidPriList[i].pid);
        CHECK_ALLOWED_PRIORITY(pidPriList[i].priority);
        tmp[pidPriList[i].pid] = pidPriList[i].priority;
    }
    mask = LOCK_THREADS();
    for (i = 0; i < IOS_THREAD_MAX; ++i) {
        if ((__threads[i].state == IOS_STATE_FREE) 
               || (0 == tmp[__threads[i].pid])) {
            continue;
        }
        __threads[i].initPriority= __threads[i].priority= tmp[__threads[i].pid]
           - (__priorities[__threads[i].pid] - __threads[i].priority);
    }

    /* Update current max priorities */
    for (i = 0; i < size; ++i) {
        __priorities[pidPriList[i].pid] = pidPriList[i].priority;
    }
    UNLOCK_THREADS(mask);

    rv = IOS_ERROR_OK;
end:
    return rv;
}

IOSError
iosGetMaxPriorities(IOSPidPriority *pidPriList, u32 size)
{
    IOSError rv;
    u32 i;

    if (THIS_THREAD->pid != IOS_ETICKET_PROCESS) {
        rv = IOS_ERROR_ACCESS;
        goto end;
    }
    CHECK_WRITABLE_BUFFER((void *)pidPriList, size*sizeof(IOSPidPriority), 
                          THIS_THREAD->pid);
    CHECK_READABLE_BUFFER((void *)pidPriList, size*sizeof(IOSPidPriority), 
                          THIS_THREAD->pid);

    for (i = 0; i < size; ++i) {
        CHECK_VALID_PID(pidPriList[i].pid);
        pidPriList[i].priority = __priorities[pidPriList[i].pid];
    }
    rv = IOS_ERROR_OK;
end:
    return rv;
}

