//
// 
//	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
// 
//	This program is free software; you can redistribute it 
//	and/or modify it under the terms of the GLOBALBASE 
//	Library General Public License (G-LGPL) as published by 
//
//	http://www.globalbase.org/
// 
//	This program is distributed in the hope that it will be 
//	useful, but WITHOUT ANY WARRANTY; without even the 
//	implied warranty of MERCHANTABILITY or FITNESS FOR A 
//	PARTICULAR PURPOSE.
//
//

extern "C" {

#include	"task.h"
#include	"save_global.h"

void er_panic(char*);

THREAD_BLOCK	tb[THREAD_BLOCK_SIZE];
THREAD_BLOCK *	tb_free_list;

SEM	block_lock;

void
init_thread_block()
{
int i;
	block_lock = new_lock(0);
	lock_task(block_lock);
	tb_free_list = NULL;
	for ( i = 0 ; i < THREAD_BLOCK_SIZE ; i ++ ) {
		tb[i].next = tb_free_list;
		tb_free_list = &tb[i];
	}
	unlock_task(block_lock,"init_thread_block");
	
	SG_TITLE;
	sg("SEM",		"block_lock",	&block_lock);
	sg("THREAD_BLOCK*",	"tb_free_list",	&tb_free_list);
	sg("THREAD_BLOCK",	"tb",		&tb);
}

void *
new_block()
{
THREAD_BLOCK * t;
	lock_task(block_lock);
	if ( tb_free_list == 0 )
		er_panic("new_block(1)");
	t = tb_free_list;
	tb_free_list = t->next;
	unlock_task(block_lock,"new_block");
	return (void*)t;
}

void
free_block(void * t)
{
THREAD_BLOCK * tt;
	lock_task(block_lock);
	tt = (THREAD_BLOCK *)t;
	tt->next = tb_free_list;
	tb_free_list = tt;
	unlock_task(block_lock,"free_block");
}

} // extern "C"