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

/**
*	Closes a port.
*
*	Closes a message port that was opened by BZ_PortOpen().
*	All messages still queued on the port will be discarded and the port
*	will no longer accept new messages. Only the owner of the port can
*	close it.
*
*	@param	port	The ID of the port
*
*
*	@retval	BZ_ILLEGAL_PORT	The specified port ID is not valid
*	@retval	BZ_NOT_OWNER	The caller does not own the port
*	@retval	0				Success
*
*	@attention
*		This function must not be called from an interrupt. It you do
*		that, the system might crash.
*/

int		BZ_PortClose( int port )
{
BZ_STAT	*base = &_bz_stat;
BZ_PORT	*pptr;
int		stat;

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

		return( BZ_ILLEGAL_PORT );

	pptr = base->port + port;

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

		return( BZ_NOT_OWNER );

	stat = BZ_IrqDisable( 1 );

	if ( pptr->head != 255 ) {

		base->pool[ pptr->tail ].link = base->free;
		base->free = pptr->head;
	}

	pptr->pid  = 255;
	pptr->head = 255;
	pptr->tail = 255;

	BZ_IrqDisable( stat );
	return( 0 );
}

/** @} */

