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

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

int		_bx_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 );
	}
}

