/*
 *               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 <sc/sc.h>
#include <iostypes.h>
#if defined(GET_USAGE)
#include <ioslibc.h>
#endif

#include "lock.h"
#include "thread.h"
#include "except.h"
#include "message.h"
#include "memory.h"
#include "sklog.h"

#if defined(GET_USAGE)
static int __msgMax = 0;
static int __msgAllocFailed = 0;
#endif

IOSMessageQueue __iosQueues[IOS_MESSAGE_QUEUE_MAX];
IOSEventState __iosEventState[IOS_NUM_EVENTS];

IOSMessageQueueId
iosCreateMessageQueue(IOSMessage *msgarray, u32 size)
{
    IOSMessageQueueId rv;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_QUEUES();

    CHECK_WRITABLE_BUFFER(msgarray, sizeof(IOSMessage) * size, 0xff);

    /* Look for a free mq structure */
    for (rv = 0; rv < IOS_MESSAGE_QUEUE_MAX; ++rv) {
        if (__iosQueues[rv].size == 0) {
            break;
        }
    }
    if (rv == IOS_MESSAGE_QUEUE_MAX) {
#if defined(GET_USAGE)
        __msgAllocFailed++;
#endif
        rv = IOS_ERROR_MAX;
        goto end;
    }

    mq = __iosQueues + rv;
    mq->emptyQ = (IOSThread *)&__iosThreadTail;
    mq->fullQ = (IOSThread *)&__iosThreadTail;
    mq->count = 0;
    mq->rptr = 0;
    mq->size = size;
    mq->buffer = msgarray;
    mq->owner = THIS_THREAD->pidMask;
#if defined(GET_USAGE)
    __msgMax++;
#endif

end:
    UNLOCK_QUEUES(mask);

    IOS_EXIT();

    return rv;
}


IOSError
iosDestroyMessageQueue(IOSMessageQueueId id)
{
    IOSError rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_QUEUES();

    CHECK_MESSAGE_QUEUE_ID(id);

    mq = __iosQueues + id;

    CHECK_MESSAGE_QUEUE_OWNER(mq);

    /* Dispatch any threads blocked on this queue */
    while (mq->fullQ->next != NULL) {
        __iosRestartThread(&mq->fullQ, IOS_ERROR_INTR);
    }
    while (mq->emptyQ->next != NULL) {
        __iosRestartThread(&mq->emptyQ, IOS_ERROR_INTR);
    }

    /* Mark the mq as available */
    mq->size = 0;
#if defined(GET_USAGE)
    __msgMax--;
#endif

end:
    UNLOCK_QUEUES(mask);

    IOS_EXIT();

    return rv;
}

IOSError
__iosSendMessage(IOSMessageQueue *mq, IOSMessage msg, u32 flag)
{
    IOSError rv = IOS_ERROR_OK;
    u32 wptr;
    u32 tid;

    /* While mq is full */
    while (mq->count >= mq->size) {
        if (flag == IOS_MESSAGE_BLOCK) {
            THIS_THREAD->state = IOS_STATE_WAITING;
            if ((rv = __iosEnqueueAndYield(&mq->fullQ)) != IOS_ERROR_OK) {
                goto end;
            }
        } else {
            rv = IOS_ERROR_QFULL;
            goto end;
        }
    }

    /* Compute next available slot and store message (using owner's TID)*/
    wptr = mq->rptr + mq->count;
    if (wptr >= mq->size) wptr -= mq->size;
    tid = SYS_SMP_TID(IO_READ(SYS_SMP_REG));
    IO_WRITE(SYS_SMP_REG, SYS_SMP_SET_TID | (mq->owner << SYS_SMP_TID_SHIFT));
    mq->buffer[wptr] = msg;
    IO_READ(DAX_START); /* Memory barrier */
    IO_WRITE(SYS_SMP_REG, SYS_SMP_SET_TID | (tid << SYS_SMP_TID_SHIFT));
    mq->count++;

    /* If a thread is blocked on this queue, start it */
    if (mq->emptyQ->next != NULL) {
        __iosRestartThread(&mq->emptyQ, IOS_ERROR_OK);
    }
end:
    return rv;
}

IOSError
iosSendMessage(IOSMessageQueueId id, IOSMessage msg, u32 flag)
{
    IOSError rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_QUEUES();

    CHECK_MESSAGE_QUEUE_ID(id);
    CHECK_MESSAGE_QUEUE_FLAGS(flag);

    mq = __iosQueues + id;

    CHECK_MESSAGE_QUEUE_OWNER(mq);

    rv = __iosSendMessage(mq, msg, flag);

end:
    UNLOCK_QUEUES(mask);

    IOS_EXIT();

    return rv;
}

IOSError
iosSendMessageInt(IOSMessageQueueId id, IOSMessage msg, u32 flag)
{
    IOSError rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_QUEUES();

    CHECK_MESSAGE_QUEUE_ID(id);
    CHECK_MESSAGE_QUEUE_FLAGS(flag);

    mq = __iosQueues + id;

    rv = __iosSendMessage(mq, msg, flag);

end:
    UNLOCK_QUEUES(mask);

    IOS_EXIT();

    return rv;
}


IOSError
iosJamMessage(IOSMessageQueueId id, IOSMessage msg, u32 flag)
{
    IOSError rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;
    u32 tid;

    IOS_ENTRY();

    mask = LOCK_QUEUES();

    CHECK_MESSAGE_QUEUE_ID(id);
    CHECK_MESSAGE_QUEUE_FLAGS(flag);

    mq = __iosQueues + id;

    CHECK_MESSAGE_QUEUE_OWNER(mq);

    /* While mq is full */
    while (mq->count >= mq->size) {
        if (flag == IOS_MESSAGE_BLOCK) {
            THIS_THREAD->state = IOS_STATE_WAITING;
            if ((rv = __iosEnqueueAndYield(&mq->fullQ)) != IOS_ERROR_OK) {
                goto end;
            }
        } else {
            rv = IOS_ERROR_QFULL;
            goto end;
        }
    }

    /* Decrement for next available slot and store message (using owner's TID)*/
    mq->rptr += (mq->size - 1);
    if (mq->rptr >= mq->size) mq->rptr -= mq->size;
    tid = SYS_SMP_TID(IO_READ(SYS_SMP_REG));
    IO_WRITE(SYS_SMP_REG, SYS_SMP_SET_TID | (mq->owner << SYS_SMP_TID_SHIFT));
    mq->buffer[mq->rptr] = msg;
    IO_WRITE(SYS_SMP_REG, SYS_SMP_SET_TID | (tid << SYS_SMP_TID_SHIFT));
    mq->count++;

    /* If a thread is blocked on this queue, start it */
    if (mq->emptyQ->next != NULL) {
        __iosRestartThread(&mq->emptyQ, IOS_ERROR_OK);
    }

end:
    UNLOCK_QUEUES(mask);

    IOS_EXIT();

    return rv;
}

IOSError
__iosReceiveMessage(IOSMessageQueue *mq, IOSMessage *msg, u32 flag)
{
    IOSError rv = IOS_ERROR_OK;

    /* While mq is empty */
    while (mq->count == 0) {
        if (flag == IOS_MESSAGE_BLOCK) {
            THIS_THREAD->state = IOS_STATE_WAITING;
            if ((rv = __iosEnqueueAndYield(&mq->emptyQ)) != IOS_ERROR_OK) {
                goto end;
            }
        } else {
            rv = IOS_ERROR_QEMPTY;
            goto end;
        }
    }

    /* Copy out message and remove it from queue */
    if (msg != NULL) {
        *msg = mq->buffer[mq->rptr];
    }
    mq->rptr += 1;
    if (mq->rptr >= mq->size) mq->rptr -= mq->size;
    mq->count--;

    /* If a thread is blocked on this queue, start it */
    if (mq->fullQ->next != NULL) {
        __iosRestartThread(&mq->fullQ, IOS_ERROR_OK);
    }

end:
    return rv;
}

IOSError
iosReceiveMessage(IOSMessageQueueId id, IOSMessage *msg, u32 flag)
{
    IOSError rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_QUEUES();

    /* Check arguments */
    CHECK_MESSAGE_QUEUE_ID(id);
    CHECK_MESSAGE_QUEUE_FLAGS(flag);
    CHECK_WRITABLE_BUFFER(msg, sizeof(IOSMessage), 0xff);

    mq = __iosQueues + id;

    /* Only allow threads in the creator's process to receive messages */
    CHECK_MESSAGE_QUEUE_OWNER(mq);

    rv = __iosReceiveMessage(mq, msg, flag);

end:
    UNLOCK_QUEUES(mask);

    IOS_EXIT();

    return rv;
}

IOSError
iosReceiveMessageInt(IOSMessageQueueId id, IOSMessage *msg, u32 flag)
{
    IOSError rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    u32 mask;

    IOS_ENTRY();

    mask = LOCK_QUEUES();

    /* Check arguments */
    CHECK_MESSAGE_QUEUE_ID(id);
    CHECK_MESSAGE_QUEUE_FLAGS(flag);

    mq = __iosQueues + id;

    rv = __iosReceiveMessage(mq, msg, flag);

end:
    UNLOCK_QUEUES(mask);

    IOS_EXIT();

    return rv;
}

static u32 __devices[] = {
    AES_ID_REG,         /* IOS_EVENT_AES */
    SHA_ID_REG,         /* IOS_EVENT_SHA */
    USB_ID_REG,         /* IOS_EVENT_USB */
    FL_ID_REG,          /* IOS_EVENT_FLASH */
    AUD_ID_REG,         /* IOS_EVENT_ADC */
    AUD_ID_REG,         /* IOS_EVENT_DAC */
    0/*CIF_ID_REG*/,    /* IOS_EVENT_CIF */
    0/*TIMER_ID_REG*/,  /* IOS_EVENT_TIMER */
};

IOSError
iosHandleEvent(IOSEvent event, IOSMessageQueueId id, IOSMessage msg)
{
    u32 mask;
    IOSError rv = IOS_ERROR_OK;
    IOSMessageQueue *mq;
    IOSEventState *es;

    IOS_ENTRY();

    mask = LOCK_QUEUES();

    CHECK_EVENT(event);
    CHECK_MESSAGE_QUEUE_ID(id);

    mq = __iosQueues + id;

    CHECK_MESSAGE_QUEUE_OWNER(mq);

    if (THIS_THREAD->pid == 0 ||
        (__devices[event] == 0 && THIS_THREAD->pid == IOS_GBA_PROCESS) ||
        (DEVID_RTID(IO_READ(__devices[event])) & THIS_THREAD->pidMask)) {
        es = __iosEventState + event;
        es->messageQueue = mq;
        es->message = msg;
        es->owner = THIS_THREAD->pidMask;
    } else {
        rv = IOS_ERROR_ACCESS;
        goto end;
    }

end:
    UNLOCK_QUEUES(mask);

    IOS_EXIT();

    return rv;
}

IOSError
iosUnhandleEvent(IOSEvent event)
{
    u32 mask;
    IOSError rv = IOS_ERROR_OK;
    IOSEventState *es;

    IOS_ENTRY();

    mask = LOCK_QUEUES();

    CHECK_EVENT(event);

    es = __iosEventState + event;
    if (THIS_THREAD->pidMask == es->owner) {
        es->messageQueue = NULL;
        es->message = 0;
    } else {
        rv = IOS_ERROR_ACCESS;
        goto end;
    }

end:
    UNLOCK_QUEUES(mask);

    IOS_EXIT();

    return rv;
}

#if defined(GET_USAGE)
#if defined(GET_USAGE_MESSAGE_QUEUE)
char *
__iosGetQueueUsage(int i, char *start, char *end)
{
    IOSMessageQueue *mq;
    mq = __iosQueues + i;

    if (mq->size) {
        start += snprintf(start, end-start, "Queue: %d [%08x] (%02x)\n", i, mq, mq->owner);
        start += snprintf(start, end-start, "  size: %d, count: %d\n", mq->size, mq->count);
        start += snprintf(start, end-start, "  emptyQ: %08x, fullQ: %08x\n", mq->emptyQ, mq->fullQ);
    } else {
        start += snprintf(start, end-start, "Queue: %d [%08x] (unused)\n", i, mq);
    }
    return start;
}
#endif

char *
__iosGetQueuesUsage(char *start, char *end)
{
#if defined(GET_USAGE_MESSAGE_QUEUE)
    int i;
    
    for (i = 0; i < IOS_MESSAGE_QUEUE_MAX; ++i) {
        start = __iosGetQueueUsage(i, start, end);
    }
    start += snprintf(start, end-start, "\n");
#endif
    start += snprintf(start, end-start,
                      "Msg Queue Max %d of %d, alloc failed %d\n",
                       __msgMax, IOS_MESSAGE_QUEUE_MAX, __msgAllocFailed);
    return start;
}
#endif
