/*
 *               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 <hw.h>
#include <iostypes.h>
#include <ioslibc.h> /*XXX debug */

#include "thread.h"
#include "except.h"
#include "message.h"
#include "mmu.h"
#include "ioslog.h"

extern void iosFlushDCache(void *ptr, u32 bytes);

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

    /* 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) {
        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->pid;

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;

end:
    UNLOCK_QUEUES(mask);

    IOS_EXIT();

    return rv;
}

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

    /* 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 PID)*/
    wptr = mq->rptr + mq->count;
    if (wptr >= mq->size) wptr -= mq->size;
    mmuSetDACR(mmuDomainAccess[IOS_KERNEL_PROCESS]);
    mq->buffer[wptr] = msg;
    iosFlushDCache(mq->buffer+wptr, sizeof(u32));
    mmuSetDACR(mmuDomainAccess[THIS_THREAD->pid]);
    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
iosJamMessage(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);

    /* 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 PID)*/
    mq->rptr += (mq->size - 1);
    if (mq->rptr >= mq->size) mq->rptr -= mq->size;
    mmuSetDACR(mmuDomainAccess[IOS_KERNEL_PROCESS]);
    mq->buffer[mq->rptr] = msg;
    iosFlushDCache(mq->buffer+mq->rptr, sizeof(u32));
    mmuSetDACR(mmuDomainAccess[THIS_THREAD->pid]);
    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);

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

static u32 __devices[IOS_NUM_EVENTS];

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

    /* XXX horti  No access control for now */
    if ((__devices[event] == 0 ) ) {
        es = __iosEventState + event;
        es->messageQueue = mq;
        es->message = msg;
        es->owner = THIS_THREAD->pid;
    } else {
        rv = IOS_ERROR_ACCESS;
        printf("iosHandleEvent: got EBUSY: event %d\n", event);
        printf("iosHandleEvent: got __devices[event] = %d\n", __devices[event]);
        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->pid == 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(ENABLE_GET_USAGE)
extern char *__processes[];
void
__iosGetQueueUsage(int i)
{
    IOSMessageQueue *mq;
    mq = __iosQueues + i;

    if (mq->size) {
        printf("Queue: %d [%08x] owner: %d (%s)\n", i, mq, mq->owner, __processes[mq->owner]);
        printf("  size: %d, count: %d\n", mq->size, mq->count);
        printf("  emptyQ: %08x, fullQ: %08x\n", mq->emptyQ, mq->fullQ);
    } else {
        printf("Queue: %d [%08x] (unused)\n", i, mq);
    }
}

void
__iosGetQueuesUsage(void)
{
    int i;

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