/**********************************************************************
 
	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	<sys/wait.h>
#include	<sys/time.h>
#include	<sys/types.h>
#include	<unistd.h>
#include	<stdlib.h>
#include	<stdio.h>
#include	<signal.h>
#include	<errno.h>
#include	"init.h"
#include	"task.h"
#include	"memory_debug.h"
#include	"utils.h"

void sigalarm_handler();
void sigpipe_handler();
void sigint_handler();
void siglwp_handler();

extern int task_flags;
int pri_table[PRI_MAX] = {0,10,20,30,40,50};


sem_t*
new_semaphore()
{
sem_t * s;
char name[16];
static int sem_num;
int i = 0;
	do {
		sprintf(name, "%d-%04i", getpid(), ++sem_num);
		s = sem_open(name, O_CREAT | O_EXCL, 0600, 0);
		i++;
	} while ( s == (sem_t*)SEM_FAILED && i < 10 );
	if ( i == 10 ) {
		perror("new_semaphore");
		printf("name : %s\n", name);
		er_panic("new_semaphore");
	}
	sem_unlink(name);
	sem_trywait(s);
	for ( ; sem_post(s); );
	return s;
}


void
_lock_task(D_SEM s,char * file,int line)
{
retry:
	errno = 0;
	if ( cmp_htid(s->tid,_get_tid()) == 0 && s->value <= 0 )
		er_panic("double lock?");
	if ( sem_wait(s->s) ) {
		if ( errno == EINTR )
			goto retry;
	}
	s->tid = _get_tid();
	s->value--;
	s->lock_file = file;
	s->lock_line = line;
}

void
_unlock_task(D_SEM s,char *str,char * file,int line)
{
	s->tid = invalid_htid();
	s->value++;
	s->unlock_file = file;
	s->unlock_line = line;
	for ( ; sem_post(s->s); );
}

void xx_close_lock(D_SEM s)
{
	sem_destroy(s->s);
	free_block(s);
}

D_SEM
xx_new_lock(int level,char * file,int line)
{
D_SEM s;
	s = new_block();
	s->s = new_semaphore();
	s->value = 1;
	return s;
}

int
_sem_getvalue(D_SEM s,int * value)
{
	*value = 0;
	return 0;
}


 
int
ss_do(void (*func)(void*),void * arg)
{
	(*func)(arg);
	return 0;
}
