aboutsummaryrefslogtreecommitdiff
path: root/src/lib9/qlock.c
blob: 7d9d064a069b8c3815c9e681d2f4f4b6e80c2f31 (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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#include <u.h>
#include <libc.h>

/*
 * The function pointers are supplied by the thread
 * library during its initialization.  If there is no thread
 * library, there is no multithreading.
 */

int	(*_lock)(Lock*, int, ulong);
void	(*_unlock)(Lock*, ulong);
int	(*_qlock)(QLock*, int, ulong);	/* do not use */
void	(*_qunlock)(QLock*, ulong);
void	(*_rsleep)(Rendez*, ulong);	/* do not use */
int	(*_rwakeup)(Rendez*, int, ulong);
int	(*_rlock)(RWLock*, int, ulong);	/* do not use */
int	(*_wlock)(RWLock*, int, ulong);
void	(*_runlock)(RWLock*, ulong);
void	(*_wunlock)(RWLock*, ulong);

void
lock(Lock *l)
{
	if(_lock)
		(*_lock)(l, 1, getcallerpc(&l));
	else
		l->held = 1;
}

int
canlock(Lock *l)
{
	if(_lock)
		return (*_lock)(l, 0, getcallerpc(&l));
	else{
		if(l->held)
			return 0;
		l->held = 1;
		return 1;
	}
}

void
unlock(Lock *l)
{
	if(_unlock)
		(*_unlock)(l, getcallerpc(&l));
	else
		l->held = 0;
}

void
qlock(QLock *l)
{
	if(_qlock)
		(*_qlock)(l, 1, getcallerpc(&l));
	else
		l->l.held = 1;
}

int
canqlock(QLock *l)
{
	if(_qlock)
		return (*_qlock)(l, 0, getcallerpc(&l));
	else{
		if(l->l.held)
			return 0;
		l->l.held = 1;
		return 1;
	}
}

void
qunlock(QLock *l)
{
	if(_qunlock)
		(*_qunlock)(l, getcallerpc(&l));
	else
		l->l.held = 0;
}

void
rlock(RWLock *l)
{
	if(_rlock)
		(*_rlock)(l, 1, getcallerpc(&l));
	else
		l->readers++;
}

int
canrlock(RWLock *l)
{
	if(_rlock)
		return (*_rlock)(l, 0, getcallerpc(&l));
	else{
		if(l->writer)
			return 0;
		l->readers++;
		return 1;
	}
}

void
runlock(RWLock *l)
{
	if(_runlock)
		(*_runlock)(l, getcallerpc(&l));
	else
		l->readers--;
}

void
wlock(RWLock *l)
{
	if(_wlock)
		(*_wlock)(l, 1, getcallerpc(&l));
	else
		l->writer = (void*)1;
}

int
canwlock(RWLock *l)
{
	if(_wlock)
		return (*_wlock)(l, 0, getcallerpc(&l));
	else{
		if(l->writer || l->readers)
			return 0;
		l->writer = (void*)1;
		return 1;
	}
}

void
wunlock(RWLock *l)
{
	if(_wunlock)
		(*_wunlock)(l, getcallerpc(&l));
	else
		l->writer = nil;
}

void
rsleep(Rendez *r)
{
	if(_rsleep)
		(*_rsleep)(r, getcallerpc(&r));
}

int
rwakeup(Rendez *r)
{
	if(_rwakeup)
		return (*_rwakeup)(r, 0, getcallerpc(&r));
	return 0;
}

int
rwakeupall(Rendez *r)
{
	if(_rwakeup)
		return (*_rwakeup)(r, 1, getcallerpc(&r));
	return 0;
}