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

/*---------------------------------------------------------------------------*
 * 
 * OS layer on IOP OS
 * 
 *---------------------------------------------------------------------------*/

#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>
#include <priority.h>

#include <stdarg.h>

#include <socket.h>
#include "dolphin/os.h"
#include "private/eth.h"

#define IOS_TICKS_TO_US(x)              ((x) / 1.772705078125)
#define SYSTEM_TO_TIME                  0x1b9251ad

#ifndef _DEBUG
#define NET_THREAD_MAX      (SO_SOCKET_MAX+3)
#else
#define NET_THREAD_MAX      (SO_SOCKET_MAX+3)
#endif // _DEBUG

static OSThread __threads[NET_THREAD_MAX];
static OSMutex  __mutex;

#define SYSTEM_TIME_UPDATE          60
static OSTick __ticks;
static OSTime __systemTime;
static OSAlarm __systemTimeAlarm;

#ifdef _DEBUG
static OSAlarm __testAlarm;
#endif // _DEBUG

void 
OSReport(const char* msg, ...)
{
    va_list marker;

    va_start(marker, msg);
    vprintf(msg, marker);
    va_end(marker);
}

void 
OSPanic(const char* file, int line, const char* msg, ...)
{
    va_list marker;

    OSDisableInterrupts();
    va_start(marker, msg);
    vprintf(msg, marker);
    va_end(marker);
    OSReport(" in \"%s\" on line %d.\n", file, line);

    IOS_DestroyThread(0, NULL);
}

static void SystemTimeUpdateHandler(OSAlarm* alarm, OSContext* context)
{
    OSTime currentTicks;
    OSTime passedTicks;

    TCPIP_UNUSED(alarm);
    TCPIP_UNUSED(context);

    currentTicks = IOS_GetTimer();
    if (currentTicks > __ticks) {
        passedTicks = currentTicks - __ticks;
    } else {
        passedTicks = 0xFFFFFFFF - __ticks + currentTicks;
    }

    // convert IOP ticks to PPC style ticks
    passedTicks = IOS_TICKS_TO_US(passedTicks);
    passedTicks = OSMicrosecondsToTicks(passedTicks);

    __ticks = IOS_GetTimer();
    __systemTime += passedTicks;
}

#ifdef _DEBUG
static void SystemTimeTestHandler(OSAlarm* alarm, OSContext* context)
{
    OSTime time;
    u32 ms;
    u32 s;

    static int count = 0;

    TCPIP_UNUSED(alarm);
    TCPIP_UNUSED(context);

    if (count == 0)
    {
        count++;
        __ticks = IOS_GetTimer();
        return;
    }

    time = __OSGetSystemTime();
    s  = OSTicksToSeconds(time);
    ms = OSTicksToMilliseconds(time);
    // OSReport("%4d.%03d  ", s, (ms % 1000));
}
#endif // _DEBUG

void
osInitTime(void)
{
    OSCreateAlarm(&__systemTimeAlarm);
    OSSetPeriodicAlarm(&__systemTimeAlarm, 0, OSSecondsToTicks(SYSTEM_TIME_UPDATE), 
        SystemTimeUpdateHandler);

#ifdef _DEBUG
    {
        OSCreateAlarm(&__testAlarm);
        OSSetPeriodicAlarm(&__testAlarm, 0, OSSecondsToTicks(1), SystemTimeTestHandler);
    }
#endif // _DEBUG

    __ticks = IOS_GetTimer();
    __systemTime = 0;
}
 
OSTime
__OSGetSystemTime(void)
{
    OSTime currentTicks;
    OSTime passedTicks;

    currentTicks = IOS_GetTimer();
    if (currentTicks > __ticks) {
        passedTicks = currentTicks - __ticks;
    } else {
        passedTicks = 0xFFFFFFFF - __ticks + currentTicks;
    }

    // convert IOP ticks to PPC style ticks
    passedTicks = IOS_TICKS_TO_US(passedTicks);
    passedTicks = OSMicrosecondsToTicks(passedTicks);

    return (__systemTime + passedTicks);
}

OSTime
__OSTimeToSystemTime(OSTime time)
{
    OSTime result = time - SYSTEM_TO_TIME;

    return result;
}

OSTick
OSGetTick(void)
{
    OSTick ticks = IOS_GetTimer();

    ticks = IOS_TICKS_TO_US(ticks);
    ticks = OSMicrosecondsToTicks(ticks);

    return ticks;
}

OSTime
OSGetTime(void)
{
    return (__OSGetSystemTime() + SYSTEM_TO_TIME);
}

void       
OSInitThreadQueue(OSThreadQueue* queue)
{
    queue->head = NULL;
    queue->tail = NULL;
}

/*
 * OSInitThreadPool inits the threading pool structure
 */
void
OSInitThreadPool(void)
{
    u32 i;

    OSInitMutex(&__mutex);

    for (i=0; i<NET_THREAD_MAX; i++) {
        __threads[i].threadId   = -1;
        __threads[i].priority   = 0;
        __threads[i].error      = 0;
        __threads[i].next       = NULL;
        __threads[i].interrupt  = FALSE;
#ifdef _DEBUG
        __threads[i].queue      = NULL;
#endif // _DEBUG
    }
}

/*
 * OSInitThread sets up the thread id inside the threading pool
 *              each thread in threading pool must call this function
 *              once it is being created
 */
void
OSInitThread(IOSThreadId threadId, u32 priority)
{
    u32 i;

    for (i=0; i<NET_THREAD_MAX; i++) {
        if (__threads[i].threadId == -1)
        {
            __threads[i].threadId = threadId;
            __threads[i].priority = priority;
            break;
        }
    }
}

#ifdef _DEBUG
void
OSDumpThread()
{
    u32 i;

    for (i=0; i<NET_THREAD_MAX; i++) {
        if (__threads[i].queue != NULL) {
            OSReport("%02d: id=%2d, pri=%2d, pri2=%2d, next=%x, q=%x, q->thread=%x, thread=%x\n", 
                i, __threads[i].threadId, __threads[i].priority, 
                IOS_GetThreadPriority(__threads[i].threadId), __threads[i].next,
                __threads[i].queue, __threads[i].queue->head, &__threads[i]);
        } else {
            OSReport("%02d: id=%2d, pri=%2d, pri2=%2d, next=%x\n", 
                i, __threads[i].threadId, __threads[i].priority, 
                IOS_GetThreadPriority(__threads[i].threadId), __threads[i].next);
        }
    }
}
#endif // _DEBUG

OSThread*
OSGetCurrentThread(void)
{
    u32 i;
    IOSThreadId threadId = IOS_GetThreadId();

    for (i=0; i<NET_THREAD_MAX; i++) {
        if (__threads[i].threadId == threadId)
            break;
    }

#ifdef _DEBUG
    if (i >= NET_THREAD_MAX) {
        OSReport("%s: current thread id = %d\n", __FUNCTION__, threadId);
        OSDumpThread();
    }
#endif // _DEBUG
    ASSERT(i < NET_THREAD_MAX);

    return &__threads[i];
}

void
OSSleepThread(OSThreadQueue* queue)
{
    BOOL      enabled;
    OSThread* currentThread;

    enabled = OSDisableInterrupts();
    OSLockMutex(&__mutex);

    currentThread = OSGetCurrentThread();

    currentThread->next = NULL;
    if (queue->head == NULL)
    {
        queue->head = currentThread;
    }
    else
    {
        queue->tail->next = currentThread;
    }
    queue->tail = currentThread;
#ifdef _DEBUG
    currentThread->queue = queue;
#endif // _DEBUG
    
    OSUnlockMutex(&__mutex);

    IOS_StopThread(0);

    OSRestoreInterrupts(enabled);
}

void
OSWakeupThread(OSThreadQueue* queue)
{
    BOOL      enabled;
    OSThread* thread;

    enabled = OSDisableInterrupts();
    OSLockMutex(&__mutex);
    while (queue->head)
    {
        thread = queue->head;
        queue->head = thread->next;
        thread->next = NULL;
#ifdef _DEBUG
        thread->queue = NULL;
#endif // _DEBUG
        IOS_StartThread(thread->threadId);
    }
	queue->tail = NULL;
    OSUnlockMutex(&__mutex);
    OSRestoreInterrupts(enabled);
}

BOOL
OSDisableInterrupts(void)
{
    // 1) timer thread has priority of (IOS_PRIORITY_NET - 1)
    // 2) all other threads have priority of (IOS_PRIORITY_NET - 2)
    // 3) disabling interrupts == don't want to get interrupted by any other
    //    threads in net.
    //    disable interrupts -> switch priority of current thread to IOS_PRIORITY_NET
    //    enable interrupts  -> switch priority of current thread back to its initial value

    u32 priority = IOS_GetThreadPriority(0);
    
    if (priority == NET_HIGHEST_PRIORITY) {
        return FALSE;
    } else if (priority == NET_HIGH_PRIORITY) {
        return FALSE;
    } else {
        IOS_SetThreadPriority(0, NET_HIGH_PRIORITY);
        return TRUE;
    }
}

BOOL
OSEnableInterrupts(void)
{
    u32 priority = IOS_GetThreadPriority(0);
    
    if (priority == NET_HIGHEST_PRIORITY) {
        return FALSE;
    } else if (priority == NET_HIGH_PRIORITY) {
        OSThread *thread;
        
        OSLockMutex(&__mutex);
        thread = OSGetCurrentThread();
        OSUnlockMutex(&__mutex);

        IOS_SetThreadPriority(0, thread->priority);
        return FALSE;
    } else {
        return TRUE;
    }
}

BOOL
OSRestoreInterrupts(BOOL level)
{
    if (level == 0)
    {
        // disabled
        return OSDisableInterrupts();
    }
    else
    {
        // enabled
        return OSEnableInterrupts();
    }
}

s32
OSDisableScheduler(void)
{
    u32 priority = IOS_GetThreadPriority(0);
    OSThread *thread;
    
    OSLockMutex(&__mutex);
    thread = OSGetCurrentThread();
    OSUnlockMutex(&__mutex);
    
    if (priority == NET_HIGH_PRIORITY) {
        thread->interrupt = FALSE;
    } else {
        thread->interrupt = TRUE;
    }

    IOS_SetThreadPriority(0, NET_HIGHEST_PRIORITY);

    return TRUE;
}

s32
OSEnableScheduler(void)
{
    OSThread *thread;
    
    OSLockMutex(&__mutex);
    thread = OSGetCurrentThread();
    OSUnlockMutex(&__mutex);

    if (thread->interrupt == FALSE) {
        IOS_SetThreadPriority(0, NET_HIGH_PRIORITY);
    } else {
        IOS_SetThreadPriority(0, thread->priority);
    }

    return TRUE;
}

void
OSYieldThread(void)
{
}

void
OSRegisterResetFunction(OSResetFunctionInfo* info)
{
}

s32
EXIGetType ( s32 chan, u32 dev, u32* type )
{
    *type = EXI_ETHER;
    return EXI_ETHER;
}
