aboutsummaryrefslogtreecommitdiff
path: root/src/libthread/OpenBSD.c
blob: 80a5097755f35ccc44afa3d86850778bf175c026 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include "threadimpl.h"
#include "BSD.c"

#include <dlfcn.h>

struct thread_tag {
	struct thread_tag	*next;
	spinlock_t		l;
	volatile int		key;
	void			*data;
};

static spinlock_t mlock;
static spinlock_t dl_lock;
static spinlock_t tag_lock;
static struct thread_tag *thread_tag_store = nil;
static uint nextkey = 0;

void
_thread_malloc_lock(void)
{
	_spinlock(&mlock);
}

void
_thread_malloc_unlock(void)
{
	_spinunlock(&mlock);
}

void
_thread_malloc_init(void)
{
}

/*
 * for ld.so
 */
void
_thread_dl_lock(int t)
{
	if(t)
		_spinunlock(&dl_lock);
	else
		_spinlock(&dl_lock);
}

/*
 * for libc
 */
static void
_thread_tag_init(void **tag)
{
	struct thread_tag *t;

	_spinlock(&tag_lock);
	if(*tag == nil) {
		t = malloc(sizeof (*t));
		if(t != nil) {
			memset(&t->l, 0, sizeof(t->l));
			t->key = nextkey++;
			*tag = t;
		}
	}
	_spinunlock(&tag_lock);
}

void
_thread_tag_lock(void **tag)
{
	struct thread_tag *t;

	if(*tag == nil)
		_thread_tag_init(tag);
	t = *tag;
	_spinlock(&t->l);
}

void
_thread_tag_unlock(void **tag)
{
	struct thread_tag *t;

	if(*tag == nil)
		_thread_tag_init(tag);
	t = *tag;
	_spinunlock(&t->l);
}

static void *
_thread_tag_insert(struct thread_tag *t, void *v)
{
	t->data = v;
	t->next = thread_tag_store;
	thread_tag_store = t;
	return t;
}

static void *
_thread_tag_lookup(struct thread_tag *tag, int size)
{
	struct thread_tag *t;
	void *p;

	_spinlock(&tag->l);
	for(t = thread_tag_store; t != nil; t = t->next)
		if(t->key == tag->key)
			break;
	if(t == nil) {
		p = malloc(size);
		if(p == nil) {
			_spinunlock(&tag->l);
			return nil;
		}
		_thread_tag_insert(tag, p);
	}
	_spinunlock(&tag->l);
	return tag->data;
}

void *
_thread_tag_storage(void **tag, void *storage, size_t n, void *err)
{
	struct thread_tag *t;
	void *r;

	if(*tag == nil)
		_thread_tag_init(tag);
	t = *tag;

	r = _thread_tag_lookup(t, n);
	if(r == nil)
		r = err;
	else
		memcpy(r, storage, n);
	return r;
}

void
_pthreadinit(void)
{
	__isthreaded = 1;
	dlctl(nil, DL_SETTHREADLCK, _thread_dl_lock);
	signal(SIGUSR2, sigusr2handler);
}