/****************************************************************************/
/*	Copyright (c) 2009, Bendor Research Pty. Ltd. All rights reserved.		*/
/*	This software is released under the GNU General Public License, version	*/
/*	3, with the exemptions that 1) the header files installed by this 	 	*/
/*	package can be included in closed-source code and 2) the libraries		*/
/*	built by this package can be statically linked into a closed-source 	*/
/*	binary. See the file LICENSE for the details.							*/
/*	This software is provided "AS IS", without any warranty or guarantee.	*/
/*	By using this software you acknowledge that neither Bendor Research nor	*/
/*	any of its personnel or affiliates can be held liable for any damages,	*/
/*	including, but not limited to, loss of business, loss of money, loss of */
/*	life, loss of reputation, arising out of this software being faulty or	*/
/*	not performing as advertised, even if Bendor Research was aware of such	*/
/*	faults in the software. You use this software at your own risk, any and */
/*	all liabilities that arise out of your using this software are strictly	*/
/*	yours.																	*/
/****************************************************************************/

#include "kernel.h"

/****************************************************************************/
/*					Local prototypes										*/
/****************************************************************************/

static void	LockWait( void *par1, void *par2 );
static void LockTimo( void *par1, void *par2 );
static int	LockTest( BX_LOCK *lock, BX_PROC *self );

/****************************************************************************/
/*					Public API functions									*/
/****************************************************************************/

/** @addtogroup bx_lock */
/** @{ */

/**
*	Obtains a lock.
*
*	This function obtains a lock. If the lock is available, then the caller
*	will own the lock. If the lock is not available, then the caller will
*	be suspended and placed on the waiting queue of the lock.
*
*	@param	lock			Pointer to the lock to get
*
*	@param	timeout			Timeout value. If it is 0xffffffff, that is, -1
*							cast to unsigned, then there is not time limit
*							in waiting for the lock. If it is any other value,
*							then it is the timeout in microseconds. If the
*							caller can not get the lock within that time, then
*							the call will return and indicate timeout. If the
*							timeout is 0, then the caller will not be suspended
*							and the function returns immediately if the lock
*							is not available.
*
*	@retval	>0				The lock was obtained by the caller
*	@retval 0				Timeout, the lock was not taken
*	@retval	BX_ERR_ISOWNER	The lock was already owned by the caller
*	@retval	BX_ERR_CONTEXT	The function was called from an ISR context
*	@retval BX_ERR_OBJECT	The passed object is not a lock or it was not
*							initialised.
*	@retval BX_ERR_SUSPEND	The caller should be suspended but can not because
*							its protection levels is higher than BX_PROT_COOP.
*
*	@note
*		Although the timeout value is specified in microseconds, the actual
*		resolution depends on the frequency of calls to the BX_TimerTick()
*		function.
*
*	@attention
*		This function should not be called from an ISR or delayed ISR.
*		This function can suspend the caller.
*/

int		BX_LockObtain( BX_LOCK *lock, unsigned timeout )
{
int		cpsr;
int		retv;
BX_PROC	*self;

	if ( ! ( self = BX_ProcSelf() ) ) {

		// Not a call from userland

		return( BX_ERR_CONTEXT );
	}

	// Do as much of the timer preparation as we can
	// without disabling the interrupt

	if ( timeout && timeout != (unsigned) -1 ) {

		BX_TimerAction( &self->timo, LockTimo, lock, self );
	}

	// Disable the interrupt and see if we can get the lock immediately

	cpsr = _bx_IrqDis();
	retv = LockTest( lock, self );

	if ( ! retv && timeout ) {

		// We have to wait

		if ( self->prot > BX_PROT_COOP ) {

			// We can't wait

			retv = BX_ERR_SUSPEND;
		}
		else {

			if ( timeout != (unsigned) -1 ) {

				// We have to set up a timeout, start the timer

				_bx_TimerStart( &self->timo, timeout, 0, 0 );
			}

			_bx_QueueEvent( cpsr, LockWait, lock, self );
			retv = self->ramt;
		}
	}

	_bx_IrqEnaUsr( cpsr );
	return( retv );
}

/** @} */

/****************************************************************************/
/*					Local functions											*/
/****************************************************************************/

/*
*	Suspends the calling process and queues it on the lock
*	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

static void	LockWait( void *par1, void *par2 )
{
BX_LOCK	*lock = par1;
BX_PROC	*proc = par2;
int		retv;

	retv = LockTest( lock, proc );

	if ( retv != 0 ) {

		// We don't have to wait

		if ( proc->timo.stat != TIMER_CANCEL &&
			 proc->timo.stat != TIMER_UNUSED ) {

			proc->timo.stat = TIMER_CANCEL;
			_bx_TimerProcess( &proc->timo, (void *) 1 );
		}

		proc->ramt = retv;
	}
	else {

		// We really have to wait

		_bx_ProcSuspend( proc, NULL );
		(*lock->pmut.wait.ftab->ins)( &lock->pmut.wait, proc );
	}
}

/*
*	Timeout waiting on the lock
*	~~~~~~~~~~~~~~~~~~~~~~~~~~~
*	This function is always called by the timer subsystem,
*	thus we know that it executes in system context.
*/

static void LockTimo( void *par1, void *par2 )
{
BX_LOCK	*lock = par1;
BX_PROC	*proc = par2;

	if ( lock->pmut.proc == proc ) {

		// This is a stray timeout. The process got the lock, but the
		// timer subsystem queued this call before the transfer of the
		// lock was completed. We should just ignore this event.

		return;
	}

	// Remove the process from the lock's queue

	(*lock->pmut.wait.ftab->del)( &lock->pmut.wait, proc );

	// Wake up the process

	_bx_ProcRestart( proc, NULL );

	// Set the return value to indicate timeout

	proc->ramt = 0;
}

/*
*	Tests if the given lock can be obtained by the given process
*	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*	Returns +1 if yes (and takes it), 0 if not and a negative error
*	code in case of error.
*/

static int	LockTest( BX_LOCK *lock, BX_PROC *self )
{
	if ( lock->pmut.wait.type != BX_TYPE_LOCK ) {

		// Not a lock

		return( BX_ERR_OBJECT );
	}

	if ( lock->pmut.proc == self ) {

		// We already own this lock

		return( BX_ERR_ISOWNER );
	}

	if ( ! lock->pmut.proc ) {

		// Noone owns the lock, we can get it immediately. So we grab it.

		if ( lock->pmut.wait.ftab->add ) {

			// We must take the lock the hard way.

			_bx_QueueEvent( _bx_CpsrGet(), lock->pmut.wait.ftab->add,
						    lock, self );
		}
		else {

			// No administration, just get the lock.
			// We still have to add the lock to our list of owned objects.

			lock->pmut.proc = self;
			_bx_PmutAddTail( self, &lock->pmut );
		}

		// Indicate that we've succeeded

		return( +1 );
	}
	else {

		// The lock is already owned by a process.
		// Indicate that we failed

		return( 0 );
	}
}

