/*
 *               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;
    IOSError rv;

    enabled = OSDisableInterrupts();

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

    mutex->mqid = IOS_CreateMessageQueue(mutex->mq, 1);
    ASSERT(mutex->mqid >= 0);
    
    rv = IOS_SendMessage(mutex->mqid, msg, 0);
    ASSERT(rv == IOS_ERROR_OK);

    OSRestoreInterrupts(enabled);
}

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

    enabled = OSDisableInterrupts();

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

    rv = IOS_DestroyMessageQueue(mutex->mqid);
    ASSERT(rv == IOS_ERROR_OK);

    OSRestoreInterrupts(enabled);
}

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

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

    rv = IOS_ReceiveMessage(mutex->mqid, &msg, IOS_MESSAGE_BLOCK);
    ASSERT(rv == IOS_ERROR_OK);

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

done:
    OSRestoreInterrupts(enabled);
    return;
}

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

    enabled = OSDisableInterrupts();
    ASSERT(mutex->owner == IOS_GetThreadId());  /* The thread is not the owner */
    ASSERT(mutex->count > 0);                   /* The mutex is not locked */

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

        rv = IOS_SendMessage(mutex->mqid, msg, 0);
        ASSERT(rv == IOS_ERROR_OK);
    }

    OSRestoreInterrupts(enabled);
    return;
}
