/*
 * This file is part of the UCB release of Plan 9. It is subject to the license
 * terms in the LICENSE file found in the top-level directory of this
 * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
 * part of the UCB release of Plan 9, including this file, may be copied,
 * modified, propagated, or distributed except according to the terms contained
 * in the LICENSE file.
 */

#include <u.h>
#include <libc.h>
#include <thread.h>
#include "threadimpl.h"

int
threadid(void)
{
	return _threadgetproc()->thread->id;
}

int
threadpid(int id)
{
	int pid;
	Proc *p;
	Thread *t;

	if (id < 0)
		return -1;
	if (id == 0)
		return _threadgetproc()->pid;
	jehanne_lock(&_threadpq.lock);
	for (p = _threadpq.head; p; p = p->next){
		jehanne_lock(&p->lock);
		for (t = p->threads.head; t; t = t->nextt)
			if (t->id == id){
				pid = p->pid;
				jehanne_unlock(&p->lock);
				jehanne_unlock(&_threadpq.lock);
				return pid;
			}
		jehanne_unlock(&p->lock);
	}
	jehanne_unlock(&_threadpq.lock);
	return -1;
}

int
threadsetgrp(int ng)
{
	int og;
	Thread *t;

	t = _threadgetproc()->thread;
	og = t->grp;
	t->grp = ng;
	return og;
}

int
threadgetgrp(void)
{
	return _threadgetproc()->thread->grp;
}

void
threadsetname(char *fmt, ...)
{
	int fd;
	char buf[128];
	va_list arg;
	Proc *p;
	Thread *t;

	p = _threadgetproc();
	t = p->thread;
	if (t->cmdname)
		jehanne_free(t->cmdname);
	va_start(arg, fmt);
	t->cmdname = jehanne_vsmprint(fmt, arg);
	va_end(arg);
	if(t->cmdname && p->nthreads == 1){
		jehanne_snprint(buf, sizeof buf, "#p/%lud/args", jehanne_getpid());
		if((fd = open(buf, OWRITE)) >= 0){
			write(fd, t->cmdname, jehanne_strlen(t->cmdname)+1);
			close(fd);
		}
	}
}

char*
threadgetname(void)
{
	Proc *p;

	if((p = _threadgetproc()) && p->thread)
		return p->thread->cmdname;
	return nil;
}

void**
threaddata(void)
{
	return &_threadgetproc()->thread->udata[0];
}

void**
_workerdata(void)
{
	return &_threadgetproc()->wdata;
}

void**
procdata(void)
{
	return &_threadgetproc()->udata;
}

static Lock privlock;
static int privmask = 1;

int
tprivalloc(void)
{
	int i;

	jehanne_lock(&privlock);
	for(i=0; i<NPRIV; i++)
		if(!(privmask&(1<<i))){
			privmask |= 1<<i;
			jehanne_unlock(&privlock);
			return i;
		}
	jehanne_unlock(&privlock);
	return -1;
}

void
tprivfree(int i)
{
	if(i < 0 || i >= NPRIV)
		abort();
	jehanne_lock(&privlock);
	privmask &= ~(1<<i);
}

void**
tprivaddr(int i)
{
	return &_threadgetproc()->thread->udata[i];
}
