/*
 *               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 IOSMessageQueueId    __mqid;     // use this for global mutex
static IOSMessage           __mq;

static OSThread __threads[NET_THREAD_MAX];

#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);
}


/* Lock the global mutex */
static void inline
LOCK_SYSTEM()
{
    IOSMessage msg;

    /* Gain the permission to access the mutex */
    if ((IOS_ReceiveMessage(__mqid, &msg, IOS_MESSAGE_BLOCK)) < 0) {
        OSReport("%s: failed to receive message from %d\n",
                    __FUNCTION__, __mqid);
    }
}

/* Unlock the global mutex */
static void inline
UNLOCK_SYSTEM()
{
    IOSMessage msg = 0;

    if ((IOS_SendMessage(__mqid, msg, 0)) < 0) {
        OSReport("%s: failed to send message to %d\n", __FUNCTION__, __mqid);
    }
}


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) P
        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;

    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();

    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

    /* Unlock the global mutex before going into sleep */
    UNLOCK_SYSTEM();
    IOS_StopThread(0);
    LOCK_SYSTEM();

    OSRestoreInterrupts(enabled);
}

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

    enabled = OSDisableInterrupts();

    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;

    OSRestoreInterrupts(enabled);
}


void
OSInitInterrupts(void)
{
    IOSMessage msg = 0;

    /* Init __mqid which will be used for a global mutex */
    __mqid = IOS_CreateMessageQueue(&__mq, 1);

    if (__mqid < 0) {
        OSReport("%s: failed to create message queue\n", __FUNCTION__);
    }

    if ((IOS_SendMessage(__mqid, msg, 0)) < 0) {
        OSReport("%s: failed to send message to %d\n", __FUNCTION__, __mqid);
    }
}

BOOL
OSDisableInterrupts(void)
{
    /*
     * 1) timer thread has priority of (IOS_PRIORITY_NET - 1)
     * 2) transmit and receive thread has a priority of (IOS_PRIORITY_NET - 2)
     * 3) all other threads have priority of (IOS_PRIORITY_NET - 3)
     * 4) 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 + acquiring global mutex
     * - enable interrupts  -> switch priority of current thread back to its
     *                         initial value + releasing global mutex
     */

    BOOL mask;
    u32 priority = IOS_GetThreadPriority(0);

    if (priority == NET_HIGHEST_PRIORITY) {
        mask = FALSE;
    } else {
        /* Lock the global mutex and increase the thread priority */
        LOCK_SYSTEM();
        IOS_SetThreadPriority(0, NET_HIGHEST_PRIORITY);
        mask = TRUE;
    }

    return (mask);
}

BOOL
OSEnableInterrupts(void)
{
    BOOL mask;
    u32 priority = IOS_GetThreadPriority(0);
    
    if (priority == NET_HIGHEST_PRIORITY) {
        /* Reset the thread priority and unlock the global mutex */
        OSThread *thread = OSGetCurrentThread();
        IOS_SetThreadPriority(0, thread->priority);
        UNLOCK_SYSTEM();

        mask = FALSE;
    } else {
        mask = TRUE;
    }

    return (mask);
}

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

s32
OSDisableScheduler(void)
{
    /*
     * This is only used in callbacks, and doesn't really
     * look necessary as long as interrupt is disabled.
     * Leave this as undefined to simplify implementation
     */

    return TRUE;
}

s32
OSEnableScheduler(void)
{
    /*
     * This is only used in callbacks, and doesn't really
     * look necessary as long as interrupt is disabled.
     * Leave this as undefined to simplify implementation
     */

    return TRUE;
}

void
OSYieldThread(void)
{
    /*
     * This is only used in callbacks, and doesn't really
     * look necessary. Leave this as undefined to simplify
     * implementation
     */
}


void
OSRegisterResetFunction(OSResetFunctionInfo* info)
{
    /*
     * The specified reset function is called before the
     * system goes into reset in order to do a clean
     * shut-down. Leave this as undefined
     */
}

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