/*
 *               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 <types.h>
#include <iop.h>
#include <ioslibc.h>
#include <sys.h>
#include "thread.h"
#include "except.h"
#include "message.h"
#include "ioslog.h"

static u32 __iosTimerBase;

typedef struct IOSTimer {
    IOSTime value;
    IOSTime interval;
    IOSMessageQueue *mq;
    IOSMessage mesg;
    u32 owner;

    struct IOSTimer *prev;
    struct IOSTimer *next;
} IOSTimer;

#define IOS_TIMER_MAX 256
static IOSTimer __timers[IOS_TIMER_MAX]  __attribute__((section(".bss32")));

static IOSTimer __iosSentinelTimer;
static IOSTimer *__iosTimerList = &__iosSentinelTimer;

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

#define CHECK_TIMER_OWNER(t) \
    if ((t)->owner != THIS_THREAD->pid) {\
        rv = IOS_ERROR_ACCESS; \
        goto end; \
    } else

#define LOCK_TIMERS  __iosDisableInt
#define UNLOCK_TIMERS(mask)  __iosRestoreInt((mask))

/* SYS_TIMER_REG == ACR_TMRCNT_REG
 *  SYS_COUNT_REG == ACR_TMRCMP_REG
 */

static void
__iosSetCount(IOSTime value)
{
    if (value < 2) {
        value = 2;
    }
    __iosTimerBase = IO_READ(SYS_TIMER_REG);
    value = __iosTimerBase + value;
    IO_WRITE(SYS_COUNT_REG, value);
}

static void
__iosInsertTimer(IOSTimer *t)
{
    IOSTimer *p = __iosTimerList->next;
    IOSTime value = t->value;

    /* Adjust first timer's value since it was programmed */
    u32 timer = IO_READ(SYS_TIMER_REG);
    u32 elapsed = timer - __iosTimerBase;
    __iosTimerBase = timer;
    if (p != __iosTimerList) {
        if (p->value > elapsed) {
            p->value -= elapsed;
        } else {
            p->value = 0;
        }
    }

    /* Find correct location in ordered list, adjusting value as we go */
    while (p != __iosTimerList && value > p->value) {
        value -= p->value;
        p = p->next;
    }
    t->value = value;

    /* Adjust next timer's value */
    if (p != __iosTimerList) {
        p->value -= value;
    }

    /* Insert timer into list */
    t->next = p;
    t->prev = p->prev;
    p->prev->next = t;
    p->prev = t;

    if (t->prev == __iosTimerList) {
        __iosSetCount(t->value);
    }
}

static void
__iosTimerInterrupt(void)
{
    u32 mask;
    IOSTimer *t;
    u32 timer, elapsed;

    mask = LOCK_TIMERS();

    /* Process all timers on the list */
    while (1) {
        t = __iosTimerList->next;

        /* No timers left */
        if (t == __iosTimerList) {
            __iosTimerBase = 0;
            break;
        }
        /* Compute elapsed time since timer was set */
        timer = IO_READ(SYS_TIMER_REG);
        elapsed = timer - __iosTimerBase;
        __iosTimerBase = timer;

        /* No timers ready yet */
        if (elapsed < t->value) {
            t->value -= elapsed;
            __iosSetCount(t->value);
            break;
        }

        /* Remove head of timer list and process it */
        t->prev->next = t->next;
        t->next->prev = t->prev;
        t->next = NULL;
        t->prev = NULL;

        /* Re-insert timer if periodic */
        if (t->interval) {
            u32 intervalTicks = convertMicrosecondsToTicks(t->interval);
            if (elapsed > (t->value + intervalTicks)) {
                t->value = 1;
            } else {
                t->value = t->value - elapsed + intervalTicks - 1;
            }
            __iosInsertTimer(t);
        }

        /* Send timer's message */
        if (t->mq) {
            __iosSendMessage(t->mq, t->mesg, IOS_MESSAGE_NOBLOCK);
        }
    }
    UNLOCK_TIMERS(mask);
}

void
__iosInitTimer(void)
{
    IOSMessageQueueId mqid;
    IOSMessage array;
    IOSTimer *t = __iosTimerList;
    IOSError rv;

    /* Initialize timer list as a circular doubly-linked list with
       a single sentinel node */
    t->next = t->prev = __iosTimerList;
    t->interval = t->value = 0;
    t->mq = 0;
    t->mesg = 0;

    __iosTimerBase = 0;

    /* Create a message queue and register for timer events */
    if ((mqid = iosCreateMessageQueue(&array, 1)) < 0) {
        __iosPanic("Unable to create timer message queue: %d\n", mqid);
    }
    if ((rv = iosHandleEvent(IOS_EVENT_TIMER, mqid, 0)) != IOS_ERROR_OK) {
        __iosPanic("Unable to register timer event handler: %d\n", rv);
    }

    /* Loop forever while waiting for timer events */
    while (1) {
        if (iosReceiveMessage(mqid, NULL, IOS_MESSAGE_BLOCK) == IOS_ERROR_OK) {
            __iosTimerInterrupt();
        }
    }
}

IOSTimerId
iosCreateTimer(IOSTime value, IOSTime interval, IOSMessageQueueId mqid, IOSMessage mesg)
{
    u32 i, mask;
    IOSError rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    IOSTimer *t;

    IOS_ENTRY();

    mask = LOCK_TIMERS();

    CHECK_MESSAGE_QUEUE_ID(mqid);

    mq = __iosQueues + mqid;

    CHECK_MESSAGE_QUEUE_OWNER(mq);

    /* Look for unused timer struct */
    for (i = 0; i < sizeof(__timers)/sizeof(__timers[0]); ++i) {
        if (__timers[i].mq == 0) {
            break;
        }
    }

    /* Return error if all timer structs are in use */
    if (i == sizeof(__timers)/sizeof(__timers[0])) {
        IOS_WARN("Unable to allocate timer");
        rv = IOS_ERROR_MAX;
        goto end;
    }

    /* Initialize timer struct */
    rv = i;
    t = __timers + i;
    t->mesg = mesg;
    t->mq = mq;

    t->interval = interval;
    t->value = value ? convertMicrosecondsToTicks(value) : convertMicrosecondsToTicks(interval);
    t->owner = THIS_THREAD->pid;

    /* Add timer to list */
    if (t->value) {
        __iosInsertTimer(t);
    }

end:
    UNLOCK_TIMERS(mask);

    IOS_EXIT();

    return rv;
}

IOSError
iosRestartTimer(IOSTimerId id, IOSTime value, IOSTime interval)
{
    u32 mask;
    IOSError rv = IOS_ERROR_OK;
    IOSTimer *t;

    IOS_ENTRY();

    mask = LOCK_TIMERS();

    CHECK_TIMER_ID(id);

    t = __timers + id;

    CHECK_TIMER_OWNER(t);

    /* Make sure timer is stopped */
    if (t->interval || t->value || t->next || t->prev) {
        rv = IOS_ERROR_INVALID;
        goto end;
    }

    /* Reset timer struct */
    t->interval = interval;
    t->value = value ? convertMicrosecondsToTicks(value) : convertMicrosecondsToTicks(interval);

    /* Add timer to list */
    if (t->value) {
        __iosInsertTimer(t);
    }

end:
    UNLOCK_TIMERS(mask);

    IOS_EXIT();

    return rv;
}

static IOSError
__iosStopTimer(IOSTimerId id, u32 destroy)
{
    IOSError rv = IOS_ERROR_OK;
    u32 mask;
    IOSTimer *t, *next;

    mask = LOCK_TIMERS();

    CHECK_TIMER_ID(id);

    t = __timers + id;

    CHECK_TIMER_OWNER(t);

    if ((next = t->next) != NULL) {
        if (next != __iosTimerList) {
            /* If head of the list */
            if (__iosTimerList->next == t) {
                /* Compute elapsed time since timer was set */
                u32 timer = IO_READ(SYS_TIMER_REG);
                u32 elapsed = timer - __iosTimerBase;
                __iosTimerBase = timer;
                if (elapsed < (next->value + t->value)) {
                    next->value += (t->value - elapsed);
                } else {
                    next->value = 0;
                }
            } else {
                next->value += t->value;
            }
        }
        t->prev->next = t->next;
        t->next->prev = t->prev;
    }
    if (destroy) {
        memset(t, 0, sizeof(IOSTimer));
    } else {
        t->next = t->prev = 0;
        t->value = t->interval = 0;
    }
end:
    UNLOCK_TIMERS(mask);

    IOS_EXIT();

    return rv;
}

IOSError
iosStopTimer(IOSTimerId id)
{
    IOSError rv = IOS_ERROR_OK;

    IOS_ENTRY();

    rv = __iosStopTimer(id, 0);

    IOS_EXIT();

    return rv;
}

IOSError
iosDestroyTimer(IOSTimerId id)
{
    IOSError rv = IOS_ERROR_OK;

    IOS_ENTRY();

    rv = __iosStopTimer(id, 1);

    IOS_EXIT();

    return rv;
}

u32
iosGetTimer(void)
{
    u32 t = busRd32(SYS_TIMER_REG); 
    return t;
}

#if defined(ENABLE_GET_USAGE)
extern char *__processes[];
void
__iosGetTimerUsage(int i)
{
    IOSTimer *t = __timers + i;
    printf("Timer %d [%08x]:\n", i, t);
    if (!t->mq) return;
    printf("  value: %d, interval: %d\n", t->value, t->interval);
    printf("  mesg: %08x, mq: %08x\n", t->mesg, t->mq);
    printf("  prev: %08x, next: %08x\n", t->prev, t->next);
    printf("  owner: %d (%s)\n", t->owner, __processes[t->owner]);
}

void
__iosGetTimersUsage(void)
{
    int i;

    for (i = 0; i < IOS_TIMER_MAX; ++i) {
        __iosGetTimerUsage(i);
    }
    printf("\n");
}
#endif
