/*
 *               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 <types.h>
#include <iop.h>
#include <ioslibc.h>
#include <sys.h>

#include <stdarg.h>

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

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

static IOSMessageQueueId    __mqid;     // use this for global mutex
static IOSMessage           __mq;

static OSThread __threads[NET_THREAD_MAX];

/*
 * Internally, the stack is always keeping GameCube (GC) ticks. The bus clock in os.h
 * is GC bus clock
 */
#define IOS_TICKS_TO_US(x)              ((x) / 1.772705078125)
#define IOS_TICKS_TO_GC_TICKS(x)       OSMicrosecondsToTicks(((x) / 1.772705078125))
#define SYSTEM_TO_TIME                  0x1b9251ad

#define SYSTEM_TIME_UPDATE              60 /* in seconds */
static OSTick  __ticks;
static OSTime  __systemTime;
static OSAlarm __systemTimeAlarm;

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

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;
    IOSError rv;

    /* Gain the permission to access the mutex */
    rv = IOS_ReceiveMessage(__mqid, &msg, IOS_MESSAGE_BLOCK);
    ASSERT(rv >= 0);
}

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

    rv = IOS_SendMessage(__mqid, msg, 0);
    ASSERT(rv >= 0);
}

/* This handler periodically update the internal "clock" */
static void SystemTimeUpdateHandler(OSAlarm* alarm, OSContext* context)
{
    OSTime currentTicks;
    OSTime passedTicks;

    TCPIP_UNUSED(alarm);
    TCPIP_UNUSED(context);

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

    __ticks = busRd32(SYS_TIMER_REG);
    __systemTime += IOS_TICKS_TO_GC_TICKS(passedTicks);
}

#ifdef NET_TEST_TIME
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 = busRd32(SYS_TIMER_REG);
        return;
    }

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

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

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

    __ticks = busRd32(SYS_TIMER_REG);
    __systemTime = 0;
}
 
/*---------------------------------------------------------------------------*
  Name:         __OSGetSystemTime

  Description:  Gets system time, which indicates how long it past after
                system reset

  Arguments:    None.

  Returns:      System time
 *---------------------------------------------------------------------------*/
OSTime
__OSGetSystemTime(void)
{
    OSTime currentTicks;
    OSTime passedTicks;

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

    return (__systemTime + IOS_TICKS_TO_GC_TICKS(passedTicks));
}

/*---------------------------------------------------------------------------*
  Name:         __OSTimeToSystemTime

  Description:  Converts time to system time, which indicates how long it
                past after system reset

  Arguments:    time        time base

  Returns:      System time
 *---------------------------------------------------------------------------*/
OSTime
__OSTimeToSystemTime(OSTime time)
{
    OSTime result = time - SYSTEM_TO_TIME;

    return result;
}

OSTick
OSGetTick(void)
{
    OSTick ticks = busRd32(SYS_TIMER_REG);

    return IOS_TICKS_TO_GC_TICKS(ticks);
}

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

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

/*
 * 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 <= 0) {
            __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);
}

/*
 * There is no interrupt disable/enable routines in IOS. It is emulated by
 * using thread priorities and a global mutex
 */
void
NetInitInterrupts(void)
{
    IOSMessage msg = 0;

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

    if ((IOS_SendMessage(__mqid, msg, 0)) < 0) {
        ASSERT(0);
    }
}

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

#ifndef IOP_OS
s32
EXIGetType ( s32 chan, u32 dev, u32* type )
{
    *type = EXI_ETHER;
    return EXI_ETHER;
}
#endif // IOP_OS
