/**********************************************************************
 
	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.

**********************************************************************/


#include	<stdlib.h>
#include	"memory_debug.h"
#include	"task.h"
#include	"utils.h"
#include	"lock_level.h"

#define TA_HASH_KEY(ta,tid)	((tid)%(ta)->ent_size)

THREAD_AREA *	ta_head;
int		ta_flag;
SEM		ta_lock;
extern SEM	utils_lock;

void
init_thread_area(THREAD_AREA * ta,THREAD_AREA * ta_param)
{
int i;
	lock_task(utils_lock);
	if ( ta_flag == 0 ) {
		ta_flag = 1;
		ta_lock = new_lock(LL_THREAD_AREA);
	}
	unlock_task(utils_lock,"init_thread_area");
	lock_task(ta_lock);
	if ( ta->ent )
		goto end;
	*ta = *ta_param;
	ta->ent = d_alloc(sizeof(THREAD_AREA_HEADER*)*ta->ent_size);
	for ( i = 0 ; i < ta->ent_size ; i ++ )
		ta->ent[i] = 0;
	ta->next = ta_head;
	ta_head = ta;
end:
	unlock_task(ta_lock,"init_thread_area");
}

void *
get_my_area(THREAD_AREA * ta)
{
unsigned int tid,key;
THREAD_AREA_HEADER * th;
int i;
char * ptr;
	lock_task(ta_lock);
	tid = get_tid();
	key = TA_HASH_KEY(ta,tid);
	for ( th = ta->ent[key] ; th ; th = th->next )
		if ( th->tid == tid ) {
			unlock_task(ta_lock,"get_my_area");
			return (void*)th;
		}
	th = d_alloc(ta->area_size);
	for ( ptr = (char*)th, i = ta->area_size ; i ; i -- )
		*ptr++ = 0;
	th->tid = tid;
	th->next = ta->ent[key];
	ta->ent[key] = th;
	unlock_task(ta_lock,"get_my_area");
	return (void*)th;
}

void
close_thread_area()
{
int tid;
THREAD_AREA * ta;
THREAD_AREA_HEADER ** thp,* th;
int key;
	lock_task(ta_lock);
	tid = get_tid();
	for ( ta = ta_head ; ta ; ta = ta->next ) {
		key = TA_HASH_KEY(ta,tid);
		for ( thp = &ta->ent[key] ; *thp ; thp = &(*thp)->next ) {
			th = *thp;
			if ( th->tid != tid )
				continue;
			*thp = th->next;
			(*ta->close_gc)(th);
			d_f_ree(th);
			break;
		}
	}
	unlock_task(ta_lock,"close_thread_area");
}


int
scan_ta(THREAD_AREA * ta,int (*func)(),void * work)
{
int key;
THREAD_AREA_HEADER * th;
int ret;
	ret = 0;
	lock_task(ta_lock);
	for ( key = 0; key < ta->ent_size ; key ++ )
		for ( th = ta->ent[key] ; th ; th = th->next ) {
			ret = (*func)(th,work);
			if ( ret )
				goto end;
		}
end:
	unlock_task(ta_lock,"scan_ta");
	return ret;
}
