/****************************************************************************/
/*	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 "coop.h"

/** @addtogroup coop_port */
/** @{ */

/**
*	Opens a port.
*
*	The caller opens the nominated message port for reading. After the
*	successful execution of this function the nominated port will accept
*	messages and will deliver the nominated event to the caller as long
*	as there are unread messages queued on the port.
*	This call does not suspend the caller.
*
*	@param	portid	The ID of the port to open
*
*	@param	signal	The bitmap of the event to be delivered to the process.
*					It must not be 0 and must not contain events from the
*					kernel range, that is, an bit with an index larger
*					than BZ_MAX_EVENT. Only one bit should be set, if more
*					than one is specified, then the lowest number bit will
*					be used to signal message availability.
*
*	@retval	BZ_ILLEGAL_PORT	The specified port ID is not valid
*	@retval	BZ_IN_USE		The specified port is already open
*	@retval	BZ_SIGNAL_MASK	The specified signal mask is not valid
*	@retval	0				Success
*
*	@attention
*		This function must not be called from an interrupt. It you do
*		that, the system might crash.
*/

int		BZ_PortOpen( int portid, int signal )
{
BZ_STAT	*base = &_bz_stat;
BZ_PORT	*port;

	if ( (unsigned) portid >= base->pnum )

		return( BZ_ILLEGAL_PORT );

	port = base->port + portid;

	if ( port->pid != 255 )

		return( BZ_IN_USE );

	if ( ! ( signal &= ( 1 << BZ_EVENT_MAX ) - 1 ) )

		return( BZ_SIGNAL );

	for ( portid = 0 ; ! ( signal & 1 ) ; portid++, signal >>= 1 );
	port->sig = portid;
	port->pid = base->self;
	return( 0 );
}

/** @} */

