pthread_mutex.c revision 1.9 1 /* $NetBSD: pthread_mutex.c,v 1.9 2003/02/15 00:52:18 nathanw Exp $ */
2
3 /*-
4 * Copyright (c) 2001, 2003 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Nathan J. Williams, and by Jason R. Thorpe.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 #include <sys/cdefs.h>
40 #include <errno.h>
41 #include <limits.h>
42 #include <stdlib.h>
43 #include <string.h>
44
45 #include "pthread.h"
46 #include "pthread_int.h"
47
48 static int pthread_mutex_lock_slow(pthread_mutex_t *);
49
50 __strong_alias(__libc_mutex_init,pthread_mutex_init)
51 __strong_alias(__libc_mutex_lock,pthread_mutex_lock)
52 __strong_alias(__libc_mutex_trylock,pthread_mutex_trylock)
53 __strong_alias(__libc_mutex_unlock,pthread_mutex_unlock)
54 __strong_alias(__libc_mutex_destroy,pthread_mutex_destroy)
55
56 __strong_alias(__libc_mutexattr_init,pthread_mutexattr_init)
57 __strong_alias(__libc_mutexattr_destroy,pthread_mutexattr_destroy)
58 __strong_alias(__libc_mutexattr_settype,pthread_mutexattr_settype)
59
60 __strong_alias(__libc_thr_once,pthread_once)
61
62 struct mutex_private {
63 int type;
64 int recursecount;
65 };
66
67 static const struct mutex_private mutex_private_default = {
68 PTHREAD_MUTEX_DEFAULT,
69 0,
70 };
71
72 struct mutexattr_private {
73 int type;
74 };
75
76 static const struct mutexattr_private mutexattr_private_default = {
77 PTHREAD_MUTEX_DEFAULT,
78 };
79
80 /*
81 * If the mutex does not already have private data (i.e. was statically
82 * initialized), then give it the default.
83 */
84 #define GET_MUTEX_PRIVATE(mutex, mp) \
85 do { \
86 if (__predict_false((mp = (mutex)->ptm_private) == NULL)) { \
87 /* LINTED cast away const */ \
88 mp = ((mutex)->ptm_private = \
89 (void *)&mutex_private_default); \
90 } \
91 } while (/*CONSTCOND*/0)
92
93 int
94 pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
95 {
96 struct mutexattr_private *map;
97 struct mutex_private *mp;
98
99 #ifdef ERRORCHECK
100 if ((mutex == NULL) ||
101 (attr && (attr->ptma_magic != _PT_MUTEXATTR_MAGIC)))
102 return EINVAL;
103 #endif
104
105 if (attr != NULL && (map = attr->ptma_private) != NULL &&
106 memcmp(map, &mutexattr_private_default, sizeof(*map)) != 0) {
107 mp = malloc(sizeof(*mp));
108 if (mp == NULL)
109 return ENOMEM;
110
111 mp->type = map->type;
112 mp->recursecount = 0;
113 } else {
114 /* LINTED cast away const */
115 mp = (struct mutex_private *) &mutex_private_default;
116 }
117
118 mutex->ptm_magic = _PT_MUTEX_MAGIC;
119 mutex->ptm_owner = NULL;
120 pthread_lockinit(&mutex->ptm_lock);
121 pthread_lockinit(&mutex->ptm_interlock);
122 PTQ_INIT(&mutex->ptm_blocked);
123 mutex->ptm_private = mp;
124
125 return 0;
126 }
127
128
129 int
130 pthread_mutex_destroy(pthread_mutex_t *mutex)
131 {
132
133 #ifdef ERRORCHECK
134 if ((mutex == NULL) ||
135 (mutex->ptm_magic != _PT_MUTEX_MAGIC) ||
136 (mutex->ptm_lock != __SIMPLELOCK_UNLOCKED))
137 return EINVAL;
138 #endif
139
140 mutex->ptm_magic = _PT_MUTEX_DEAD;
141 if (mutex->ptm_private != NULL &&
142 mutex->ptm_private != (const void *)&mutex_private_default)
143 free(mutex->ptm_private);
144
145 return 0;
146 }
147
148
149 /*
150 * Note regarding memory visibility: Pthreads has rules about memory
151 * visibility and mutexes. Very roughly: Memory a thread can see when
152 * it unlocks a mutex can be seen by another thread that locks the
153 * same mutex.
154 *
155 * A memory barrier after a lock and before an unlock will provide
156 * this behavior. This code relies on pthread__simple_lock_try() to issue
157 * a barrier after obtaining a lock, and on pthread__simple_unlock() to
158 * issue a barrier before releasing a lock.
159 */
160
161 int
162 pthread_mutex_lock(pthread_mutex_t *mutex)
163 {
164 int error;
165
166 #ifdef ERRORCHECK
167 if ((mutex == NULL) || (mutex->ptm_magic != _PT_MUTEX_MAGIC))
168 return EINVAL;
169 #endif
170
171 PTHREADD_ADD(PTHREADD_MUTEX_LOCK);
172 /*
173 * Note that if we get the lock, we don't have to deal with any
174 * non-default lock type handling.
175 */
176 if (__predict_false(pthread__simple_lock_try(&mutex->ptm_lock) == 0)) {
177 error = pthread_mutex_lock_slow(mutex);
178 if (error)
179 return error;
180 }
181
182 /* We have the lock! */
183 /*
184 * Identifying ourselves may be slow, and this assignment is
185 * only needed for (a) debugging identity of the owning thread
186 * and (b) handling errorcheck and recursive mutexes. It's
187 * better to just stash our stack pointer here and let those
188 * slow exception cases compute the stack->thread mapping.
189 */
190 mutex->ptm_owner = (pthread_t)pthread__sp();
191
192 return 0;
193 }
194
195
196 static int
197 pthread_mutex_lock_slow(pthread_mutex_t *mutex)
198 {
199 pthread_t self;
200
201 self = pthread__self();
202
203 PTHREADD_ADD(PTHREADD_MUTEX_LOCK_SLOW);
204 while (/*CONSTCOND*/1) {
205 if (pthread__simple_lock_try(&mutex->ptm_lock))
206 break; /* got it! */
207
208 /* Okay, didn't look free. Get the interlock... */
209 pthread_spinlock(self, &mutex->ptm_interlock);
210 /*
211 * The mutex_unlock routine will get the interlock
212 * before looking at the list of sleepers, so if the
213 * lock is held we can safely put ourselves on the
214 * sleep queue. If it's not held, we can try taking it
215 * again.
216 */
217 if (mutex->ptm_lock == __SIMPLELOCK_LOCKED) {
218 struct mutex_private *mp;
219
220 GET_MUTEX_PRIVATE(mutex, mp);
221
222 if (pthread__id(mutex->ptm_owner) == self) {
223 switch (mp->type) {
224 case PTHREAD_MUTEX_ERRORCHECK:
225 pthread_spinunlock(self,
226 &mutex->ptm_interlock);
227 return EDEADLK;
228
229 case PTHREAD_MUTEX_RECURSIVE:
230 /*
231 * It's safe to do this without
232 * holding the interlock, because
233 * we only modify it if we know we
234 * own the mutex.
235 */
236 pthread_spinunlock(self,
237 &mutex->ptm_interlock);
238 if (mp->recursecount == INT_MAX)
239 return EAGAIN;
240 mp->recursecount++;
241 return 0;
242 }
243 }
244
245 PTQ_INSERT_TAIL(&mutex->ptm_blocked, self, pt_sleep);
246 /*
247 * Locking a mutex is not a cancellation
248 * point, so we don't need to do the
249 * test-cancellation dance. We may get woken
250 * up spuriously by pthread_cancel or signals,
251 * but it's okay since we're just going to
252 * retry.
253 */
254 pthread_spinlock(self, &self->pt_statelock);
255 self->pt_state = PT_STATE_BLOCKED_QUEUE;
256 self->pt_sleepobj = mutex;
257 self->pt_sleepq = &mutex->ptm_blocked;
258 self->pt_sleeplock = &mutex->ptm_interlock;
259 pthread_spinunlock(self, &self->pt_statelock);
260
261 pthread__block(self, &mutex->ptm_interlock);
262 /* interlock is not held when we return */
263 } else {
264 pthread_spinunlock(self, &mutex->ptm_interlock);
265 }
266 /* Go around for another try. */
267 }
268
269 return 0;
270 }
271
272
273 int
274 pthread_mutex_trylock(pthread_mutex_t *mutex)
275 {
276
277 #ifdef ERRORCHECK
278 if ((mutex == NULL) || (mutex->ptm_magic != _PT_MUTEX_MAGIC))
279 return EINVAL;
280 #endif
281
282 PTHREADD_ADD(PTHREADD_MUTEX_TRYLOCK);
283 if (pthread__simple_lock_try(&mutex->ptm_lock) == 0) {
284 pthread_t self;
285 struct mutex_private *mp;
286
287 GET_MUTEX_PRIVATE(mutex, mp);
288
289 /*
290 * These tests can be performed without holding the
291 * interlock because these fields are only modified
292 * if we know we own the mutex.
293 */
294 self = pthread__self();
295 if (pthread__id(mutex->ptm_owner) == self) {
296 switch (mp->type) {
297 case PTHREAD_MUTEX_ERRORCHECK:
298 return EDEADLK;
299
300 case PTHREAD_MUTEX_RECURSIVE:
301 if (mp->recursecount == INT_MAX)
302 return EAGAIN;
303 mp->recursecount++;
304 return 0;
305 }
306 }
307
308 return EBUSY;
309 }
310
311 /* see comment at the end of pthread_mutex_lock() */
312 mutex->ptm_owner = (pthread_t)pthread__sp();
313
314 return 0;
315 }
316
317
318 int
319 pthread_mutex_unlock(pthread_mutex_t *mutex)
320 {
321 struct mutex_private *mp;
322 pthread_t self, blocked;
323
324 #ifdef ERRORCHECK
325 if ((mutex == NULL) || (mutex->ptm_magic != _PT_MUTEX_MAGIC))
326 return EINVAL;
327
328 if (mutex->ptm_lock != __SIMPLELOCK_LOCKED)
329 return EPERM; /* Not exactly the right error. */
330 #endif
331 PTHREADD_ADD(PTHREADD_MUTEX_UNLOCK);
332
333 GET_MUTEX_PRIVATE(mutex, mp);
334
335 /*
336 * These tests can be performed without holding the
337 * interlock because these fields are only modified
338 * if we know we own the mutex.
339 */
340 switch (mp->type) {
341 case PTHREAD_MUTEX_ERRORCHECK:
342 if (pthread__id(mutex->ptm_owner) != pthread__self())
343 return EPERM;
344 break;
345
346 case PTHREAD_MUTEX_RECURSIVE:
347 if (pthread__id(mutex->ptm_owner) != pthread__self())
348 return EPERM;
349 if (mp->recursecount != 0) {
350 mp->recursecount--;
351 return 0;
352 }
353 break;
354 }
355
356 mutex->ptm_owner = NULL;
357 pthread__simple_unlock(&mutex->ptm_lock);
358 /*
359 * Do a double-checked locking dance to see if there are any
360 * waiters. If we don't see any waiters, we can exit, because
361 * we've already released the lock. If we do see waiters, they
362 * were probably waiting on us... there's a slight chance that
363 * they are waiting on a different thread's ownership of the
364 * lock that happened between the unlock above and this
365 * examination of the queue; if so, no harm is done, as the
366 * waiter will loop and see that the mutex is still locked.
367 */
368 if (!PTQ_EMPTY(&mutex->ptm_blocked)) {
369 self = pthread__self();
370 pthread_spinlock(self, &mutex->ptm_interlock);
371 blocked = PTQ_FIRST(&mutex->ptm_blocked);
372 if (blocked)
373 PTQ_REMOVE(&mutex->ptm_blocked, blocked, pt_sleep);
374 pthread_spinunlock(self, &mutex->ptm_interlock);
375
376 /* Give the head of the blocked queue another try. */
377 if (blocked) {
378 PTHREADD_ADD(PTHREADD_MUTEX_UNLOCK_UNBLOCK);
379 pthread__sched(self, blocked);
380 }
381 }
382 return 0;
383 }
384
385 int
386 pthread_mutexattr_init(pthread_mutexattr_t *attr)
387 {
388 struct mutexattr_private *map;
389
390 #ifdef ERRORCHECK
391 if (attr == NULL)
392 return EINVAL;
393 #endif
394
395 map = malloc(sizeof(*map));
396 if (map == NULL)
397 return ENOMEM;
398
399 *map = mutexattr_private_default;
400
401 attr->ptma_magic = _PT_MUTEXATTR_MAGIC;
402 attr->ptma_private = map;
403
404 return 0;
405 }
406
407
408 int
409 pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
410 {
411
412 #ifdef ERRORCHECK
413 if ((attr == NULL) ||
414 (attr->ptma_magic != _PT_MUTEXATTR_MAGIC))
415 return EINVAL;
416 #endif
417
418 attr->ptma_magic = _PT_MUTEXATTR_DEAD;
419 if (attr->ptma_private != NULL)
420 free(attr->ptma_private);
421
422 return 0;
423 }
424
425
426 int
427 pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *typep)
428 {
429 struct mutexattr_private *map;
430
431 #ifdef ERRORCHECK
432 if ((attr == NULL) ||
433 (attr->ptma_magic != _PT_MUTEXATTR_MAGIC) ||
434 (typep == NULL))
435 return EINVAL;
436 #endif
437
438 map = attr->ptma_private;
439
440 *typep = map->type;
441
442 return 0;
443 }
444
445
446 int
447 pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
448 {
449 struct mutexattr_private *map;
450
451 #ifdef ERRORCHECK
452 if ((attr == NULL) ||
453 (attr->ptma_magic != _PT_MUTEXATTR_MAGIC))
454 return EINVAL;
455 #endif
456 map = attr->ptma_private;
457
458 switch (type) {
459 case PTHREAD_MUTEX_NORMAL:
460 case PTHREAD_MUTEX_ERRORCHECK:
461 case PTHREAD_MUTEX_RECURSIVE:
462 map->type = type;
463 break;
464
465 default:
466 return EINVAL;
467 }
468
469 return 0;
470 }
471
472
473 int
474 pthread_once(pthread_once_t *once_control, void (*routine)(void))
475 {
476
477 if (once_control->pto_done == 0) {
478 pthread_mutex_lock(&once_control->pto_mutex);
479 if (once_control->pto_done == 0) {
480 routine();
481 once_control->pto_done = 1;
482 }
483 pthread_mutex_unlock(&once_control->pto_mutex);
484 }
485
486 return 0;
487 }
488