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

/*---------------------------------------------------------------------------*
 * 
 * Timer management scheme on IOP
 * 
 *---------------------------------------------------------------------------*/

#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>
#include <priority.h>
#include <dolphin/os.h>
#include <dolphin/ip/IFQueue.h>

typedef struct NETAlarm {
    u32 alarmId;
    OSAlarm *alarm;
    struct NETAlarm *next;
} NETAlarm;

static char __alarmStack[NET_ALARM_STACK_SIZE] ATTRIBUTE_ALIGN(4);
static IOSMessage __msgQ[NET_ALARM_MSGQ_SIZE];
static IOSMessageQueueId __qid;
static OSMutex __mutex;
static NETAlarm *__head;     /* Active alarm list */

extern void osInitTime(void);

/*
 * Must lock __mutex before calling this function
 */
static u32
addToActiveList(OSAlarm *alarm)
{
    static u32 alarmId = 1;
    NETAlarm *netAlarm;

    /* Allocate a new net alarm */
    netAlarm = (NETAlarm *) OSAlloc(sizeof (NETAlarm));
    ASSERT(netAlarm != NULL);

    /* Initialize and insert at the head */
    netAlarm->alarmId = alarmId++;
    netAlarm->alarm = alarm;
    netAlarm->next = __head;
    __head = netAlarm;

    return (netAlarm->alarmId);
}

/*
 * Must lock __mutex before calling this function
 */
static NETAlarm *
findInActiveList(u32 alarmId, OSAlarm *alarm, u32 remove)
{
    NETAlarm *ptr, *prev;

    prev = NULL;
    ptr = __head;
    while (ptr != NULL) {
        if (((alarmId != 0) && (alarmId == ptr->alarmId)) ||
                ((alarm != NULL) && (alarm == ptr->alarm))) {
            if (!remove) {
                goto done;
            }

            if (prev != NULL) {
                prev->next = ptr->next;
            } else {    /* Removing from the head */
                __head = ptr->next;
            }

            /* Free the net alarm */
            OSFree(ptr);
            ptr = NULL;
            goto done;
        }

        prev = ptr;
        ptr = ptr->next;
    }

done:

    return (ptr);
}

static void
alarmHandler(u32 arg)
{
    IOSMessage  msg;
    NETAlarm    *netAlarm;
    OSAlarm     *alarm;
    BOOL         enabled;
    volatile OSAlarmHandler handler;

    OSReport("*** Alarm Thread Started ***\n");

    /* Sit in a loop processing requests */
    while(1) {
        IOS_ReceiveMessage(__qid, &msg, IOS_MESSAGE_BLOCK);

        OSLockMutex(&__mutex);

        /* Retrieve the net alarm, don't remove it since it may be periodic */
        netAlarm = findInActiveList((u32) msg, NULL, 0);
        if (netAlarm == NULL) {
            /* The alarm may have been cancelled already */
            OSUnlockMutex(&__mutex);
            continue;
        }
        alarm = netAlarm->alarm;

        // destroy the timer immediately after it goes off. the handler may set 
        // another timer.
        handler = alarm->handler;
        if (alarm->period == 0)
        {
            IOS_DestroyTimer(alarm->timerId);
            alarm->timerId = -1;
            alarm->handler = NULL;

            /* Remove non-periodic timer from active list */
            (void) findInActiveList((u32) msg, NULL, 1);
        }

        OSUnlockMutex(&__mutex);

        /* Emulate external interrupt condition */
        enabled = OSDisableInterrupts();
        OSDisableScheduler();
        handler(alarm, NULL);
        OSEnableScheduler();
        OSRestoreInterrupts(enabled);
    }

    IOS_DestroyMessageQueue(__qid);
    return;
}

void
OSInitAlarm( void )
{
    IOSThreadId threadId;

    OSInitMutex(&__mutex);

    /*
     * Initialize the active alarm list. Each element in the list
     * is assigned a unique alarm ID. The purpose of this list is
     * to detect cancelled and re-used alarms. Imagine a scenario
     * where an alarm is cancelled and then the OSAlarm structure
     * is re-used. The alarm may have already expired before the
     * cancellation and a message may be sitting in the queue. We
     * can distinguish between the old and new alarms because the
     * would be different
     */
    __head = NULL;

    /* Create a message queue for timer management */
    if ( (__qid = IOS_CreateMessageQueue(__msgQ, NET_ALARM_MSGQ_SIZE)) < 0 ) {
        OSReport("%s: Creating message queue failed\n", __FUNCTION__);
        return;
    }

    /* Create the timer management thread */
    threadId = IOS_CreateThread(alarmHandler, NULL, __alarmStack + sizeof(__alarmStack),
        sizeof(__alarmStack), IOS_PRIORITY_NET, IOS_THREAD_CREATE_DETACHED);
    
    if (threadId < 0) {
        OSReport("%s: could not create the timer thread - exiting\n", __FUNCTION__);
        return;
    }
    IOS_SetThreadPriority(threadId, NET_ALARM_PRIORITY);
    OSInitThread(threadId, NET_ALARM_PRIORITY);

    if (IOS_StartThread(threadId) != IOS_ERROR_OK) {
        OSReport("%s: could not start the timer thread\n", __FUNCTION__);
        return;
    }

    osInitTime();

    return;
}

void
OSSetAlarm ( OSAlarm* alarm, OSTime tick, OSAlarmHandler handler )
{
    OSTime duration = OSTicksToMicroseconds(tick);
    u32 alarmId;

    // timer w/ 0 value will never goes off
    if (duration <= 0)
        duration = 1;

    OSLockMutex(&__mutex);

    // this will prevent two timers get created on the same structure, 
    // w/o the previous expired or canceled.
    if (alarm->timerId >= 0) {
        OSCancelAlarm(alarm);
    }

    /* Add alarm to active list */
    alarmId = addToActiveList(alarm);

    /* Create the alarm */
	alarm->handler  = handler;
	alarm->fire     = __OSGetSystemTime() + tick;
    alarm->period   = 0;
	alarm->timerId  = IOS_CreateTimer(duration, 0, __qid, (IOSMessage) alarmId);

    if (alarm->timerId < 0) {
        OSReport("%s: create alarm error\n", __FUNCTION__);

        /* Remove from active list if alarm could not be created */
        (void) findInActiveList(alarmId, NULL, 1);
    }

    OSUnlockMutex(&__mutex);
}

void
OSSetAbsAlarm ( OSAlarm* alarm, OSTime time, OSAlarmHandler handler )
{
    OSTime duration = __OSTimeToSystemTime(time) - __OSGetSystemTime();
    u32 alarmId;

    duration = OSTicksToMicroseconds(duration);
    // timer w/ 0 value will never goes off
    if (duration <= 0)
        duration = 1;

    OSLockMutex(&__mutex);

    // this will prevent two timers get created on the same structure, 
    // w/o the previous expired or canceled.
    if (alarm->timerId >= 0)
        OSCancelAlarm(alarm);

    /* Add alarm to active list */
    alarmId = addToActiveList(alarm);

    /* Create the alarm */
	alarm->handler  = handler;
	alarm->fire     = __OSTimeToSystemTime(time);
    alarm->period   = 0;
	alarm->timerId  = IOS_CreateTimer(duration, 0, __qid, (IOSMessage) alarmId);

    if (alarm->timerId < 0) {
        OSReport("%s: create alarm error\n", __FUNCTION__);

        /* Remove from active list if alarm could not be created */
        (void) findInActiveList(alarmId, NULL, 1);
    }

    OSUnlockMutex(&__mutex);
}

void
OSSetPeriodicAlarm ( OSAlarm* alarm, OSTime start, OSTime period,
                          OSAlarmHandler handler )
{
    OSTime fire;
    OSTime time = OSTicksToMicroseconds(period);
    u32 alarmId;

    // timer w/ 0 value will never goes off
    if (time <= 0)
        time = 1;

    OSLockMutex(&__mutex);

    /* Add alarm to active list */
    alarmId = addToActiveList(alarm);

    /* Create the alarm */
	alarm->handler  = handler;
    alarm->start  = __OSTimeToSystemTime(start);
	alarm->period   = period;

    // Calculate next fire for periodic alarm
    fire = __OSGetSystemTime();

    alarm->fire = alarm->start;
    if (alarm->start < fire)
    {
        alarm->fire += alarm->period *
            ((fire - alarm->start) / alarm->period + 1);
    }

	alarm->timerId  = IOS_CreateTimer(0, (IOSTime)time, __qid, (IOSMessage) alarmId);

    if (alarm->timerId < 0) {
        OSReport("%s: create alarm error\n", __FUNCTION__);

        /* Remove from active list if alarm could not be created */
        (void) findInActiveList(alarmId, NULL, 1);
    }

    OSUnlockMutex(&__mutex);
}

void
OSCreateAlarm ( OSAlarm* alarm )
{
    OSLockMutex(&__mutex);

    alarm->timerId  = -1;
	alarm->handler  = NULL;
	alarm->fire     = 0;
	alarm->period   = 0;
	alarm->start    = 0;
    alarm->state    = ALARM_INITIALIZED;

    OSUnlockMutex(&__mutex);
}

void
OSCancelAlarm ( OSAlarm* alarm )
{
    OSLockMutex(&__mutex);

    // this prevents to destroy a valid timer which is create by another owner
    if (alarm->state != ALARM_INITIALIZED) {
        OSCreateAlarm(alarm);
        goto done;
    }

    if (alarm->timerId == -1)
        goto done;

    IOS_DestroyTimer(alarm->timerId);
	alarm->timerId = -1;
    alarm->handler = NULL;

    /* Remove from active list */
    (void) findInActiveList(0, alarm, 1);

done:
    OSUnlockMutex(&__mutex);
}
