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

/*---------------------------------------------------------------------------*
 * 
 * Mutex Functions layer on IOP OS
 * 
 *---------------------------------------------------------------------------*/

#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>

#include <dolphin/os.h>

#include <priority.h>
#include "iop_thread.h"


void 
OSInitMutex ( OSMutex* mutex )
{
    IOSMessage msg = 0;
    BOOL enabled;

    enabled = OSDisableInterrupts();

    mutex->count = 0;
    mutex->owner = -1;

    if ((mutex->mqid = IOS_CreateMessageQueue(mutex->mq, 1)) < 0) {
        OSReport("%s: failed to create message queue\n", __FUNCTION__);
    }

    if ((IOS_SendMessage(mutex->mqid, msg, 0)) < 0) {
        OSReport("%s: failed to send message to %d\n",
                    __FUNCTION__, mutex->mqid);
    }

    OSRestoreInterrupts(enabled);
}

void 
OSCloseMutex ( OSMutex* mutex )
{
    IOSError rc;
    BOOL enabled;

    enabled = OSDisableInterrupts();

    mutex->count = 0;
    mutex->owner = -1;

    if ((rc = IOS_DestroyMessageQueue(mutex->mqid)) != IOS_ERROR_OK) {
        OSReport("%s: failed to destroy message queue (%d)\n",
                    __FUNCTION__, mutex->mqid);
    }

    OSRestoreInterrupts(enabled);
}

void
OSLockMutex ( OSMutex* mutex )
{
    IOSMessage msg;
    BOOL enabled;

    /* Handle nested mutex */
    enabled = OSDisableInterrupts();
    if (mutex->owner == IOS_GetThreadId()) {
        mutex->count++;
        OSRestoreInterrupts(enabled);
        goto done;
    }
    OSRestoreInterrupts(enabled);

    if ((IOS_ReceiveMessage(mutex->mqid, &msg, IOS_MESSAGE_BLOCK)) < 0) {
        OSReport("%s: failed to receive message from %d\n",
                    __FUNCTION__, mutex->mqid);
    }

    enabled = OSDisableInterrupts();
    ++mutex->count;
    mutex->owner = IOS_GetThreadId();
    OSRestoreInterrupts(enabled);

done:

    return;
}

void
OSUnlockMutex ( OSMutex* mutex )
{
    IOSMessage msg = 0;
    BOOL enabled;

    /* The mutex is not locked */
    enabled = OSDisableInterrupts();
    if (mutex->count <= 0) {
        OSRestoreInterrupts(enabled);
        goto done;
    }

    --mutex->count;
    if (mutex->count == 0) {
        mutex->owner = -1;

        if ((IOS_SendMessage(mutex->mqid, msg, 0)) < 0) {
            OSReport("%s: failed to send message to %d\n",
                        __FUNCTION__, mutex->mqid);
        }
    }

    OSRestoreInterrupts(enabled);

done:

    return;
}
