/****************************************************************************/
/*	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 */
/** @{ */

/**
*	Reads a message from a port.
*
*	The caller must be the owner of the message port. If the port has any
*	messages on it, this function will read the next one. If after reading
*	that message the port will still contain messages, then the nominated
*	event will be delivered to the caller.
*	This call does not suspend the caller.
*
*
*	@param	portid	The ID of the port to open
*
*	@param	message	Pointer to a BZ_MESSAGE structure. The message read
*					from the port will be copied into that structure.
*
*	@retval	BZ_ILLEGAL_PORT	The specified port ID is not valid
*	@retval	BZ_NOT_OWNER	The caller does not own the port
*	@retval	0				The port had no messages on it
*	@retval	1				A message was read into the buffer
*
*	@attention
*		This function must not be called from an interrupt. It you do
*		that, the system will crash.
*/

int		BZ_PortRead( int portid, BZ_MESG *message )
{
BZ_STAT	*base = &_bz_stat;
BZ_PORT	*port;
BZ_MESG	*mesg;
int		stat, head, link;

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

		return( BZ_ILLEGAL_PORT );

	port = base->port + portid;

	if ( port->pid != base->self )

		return( BZ_NOT_OWNER );

	stat = BZ_IrqDisable( 1 );

	if ( ( head = port->head ) == 255 ) {

		BZ_IrqDisable( stat );
		return( 0 );
	}

	mesg = base->pool + head;
	link = mesg->link;

	if ( ( port->head = link ) == 255 ) port->tail = 255;

	message->lpar = mesg->lpar;
	message->spar = mesg->spar;
	message->type = mesg->type;

	mesg->link = base->free;
	base->free = head;

	BZ_IrqDisable( stat );
	if ( link != 255 ) BZ_EventPost( base->self, 1 << port->sig );
	return( 1 );
}

/** @} */

