/****************************************************************************/
/*	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	Sleep( void *par1, void *par2 );

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

/** @addtogroup bx_time */
/** @{ */

/**
*	Suspends the caller for a given time.
*
*/

int		BX_TimerSleep( unsigned usec )
{
BX_PROC	*self;

	if ( ! usec ) return( 1 );

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

		// We're not in user mode

		return( BX_ERR_CONTEXT );
	}

	if ( self->prot > BX_PROT_COOP ) {

		// We are not suspendable

		return( BX_ERR_SUSPEND );
	}

	self->timo.type = BX_TYPE_TIME;
	self->timo.load = usec;
	self->timo.peri = 0;
	self->timo.runs = 0;
	self->timo.stat = TIMER_RELOAD;
	self->timo.func = _bx_ProcRestart;
	self->timo.par1 = self;

	_bx_QueueEvent( _bx_IrqDis(), Sleep, self, &self->timo );
	return( 1 );
}

/** @} */

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

/*
*	Helper function for sleep
*	~~~~~~~~~~~~~~~~~~~~~~~~~
*	Suspends the process identified by par1 and activates the timer
*	identified by par2. In turn, the timer will wake the process up.
*/

static	void	Sleep( void *par1, void *par2 )
{
	_bx_ProcSuspend( par1, NULL );
	_bx_TimerProcess( par2, (void *) 1 );
}

