pthread_mutex.c revision 1.28.2.1 1 /* $NetBSD: pthread_mutex.c,v 1.28.2.1 2007/07/18 13:36:19 skrll Exp $ */
2
3 /*-
4 * Copyright (c) 2001, 2003, 2006, 2007 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, by Jason R. Thorpe, and by Andrew Doran.
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 __RCSID("$NetBSD: pthread_mutex.c,v 1.28.2.1 2007/07/18 13:36:19 skrll Exp $");
41
42 #include <errno.h>
43 #include <limits.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include <sys/types.h>
48 #include <sys/lock.h>
49
50 #include "pthread.h"
51 #include "pthread_int.h"
52
53 static int pthread_mutex_lock_slow(pthread_t, pthread_mutex_t *);
54
55 __strong_alias(__libc_mutex_init,pthread_mutex_init)
56 __strong_alias(__libc_mutex_lock,pthread_mutex_lock)
57 __strong_alias(__libc_mutex_trylock,pthread_mutex_trylock)
58 __strong_alias(__libc_mutex_unlock,pthread_mutex_unlock)
59 __strong_alias(__libc_mutex_destroy,pthread_mutex_destroy)
60
61 __strong_alias(__libc_mutexattr_init,pthread_mutexattr_init)
62 __strong_alias(__libc_mutexattr_destroy,pthread_mutexattr_destroy)
63 __strong_alias(__libc_mutexattr_settype,pthread_mutexattr_settype)
64
65 __strong_alias(__libc_thr_once,pthread_once)
66
67 struct mutex_private {
68 int type;
69 int recursecount;
70 };
71
72 static const struct mutex_private mutex_private_default = {
73 PTHREAD_MUTEX_DEFAULT,
74 0,
75 };
76
77 struct mutexattr_private {
78 int type;
79 };
80
81 static const struct mutexattr_private mutexattr_private_default = {
82 PTHREAD_MUTEX_DEFAULT,
83 };
84
85 /*
86 * If the mutex does not already have private data (i.e. was statically
87 * initialized), then give it the default.
88 */
89 #define GET_MUTEX_PRIVATE(mutex, mp) \
90 do { \
91 if (__predict_false((mp = (mutex)->ptm_private) == NULL)) { \
92 /* LINTED cast away const */ \
93 mp = ((mutex)->ptm_private = \
94 (void *)&mutex_private_default); \
95 } \
96 } while (/*CONSTCOND*/0)
97
98 int
99 pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
100 {
101 struct mutexattr_private *map;
102 struct mutex_private *mp;
103
104 pthread__error(EINVAL, "Invalid mutex attribute",
105 (attr == NULL) || (attr->ptma_magic == _PT_MUTEXATTR_MAGIC));
106
107 if (attr != NULL && (map = attr->ptma_private) != NULL &&
108 memcmp(map, &mutexattr_private_default, sizeof(*map)) != 0) {
109 mp = malloc(sizeof(*mp));
110 if (mp == NULL)
111 return ENOMEM;
112
113 mp->type = map->type;
114 mp->recursecount = 0;
115 } else {
116 /* LINTED cast away const */
117 mp = (struct mutex_private *) &mutex_private_default;
118 }
119
120 mutex->ptm_magic = _PT_MUTEX_MAGIC;
121 mutex->ptm_owner = NULL;
122 pthread_lockinit(&mutex->ptm_lock);
123 pthread_lockinit(&mutex->ptm_interlock);
124 PTQ_INIT(&mutex->ptm_blocked);
125 mutex->ptm_private = mp;
126
127 return 0;
128 }
129
130
131 int
132 pthread_mutex_destroy(pthread_mutex_t *mutex)
133 {
134
135 pthread__error(EINVAL, "Invalid mutex",
136 mutex->ptm_magic == _PT_MUTEX_MAGIC);
137 pthread__error(EBUSY, "Destroying locked mutex",
138 __SIMPLELOCK_UNLOCKED_P(&mutex->ptm_lock));
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 pthread_t self;
165 int error;
166
167 self = pthread__self();
168
169 PTHREADD_ADD(PTHREADD_MUTEX_LOCK);
170
171 /*
172 * Note that if we get the lock, we don't have to deal with any
173 * non-default lock type handling.
174 */
175 if (__predict_false(pthread__simple_lock_try(&mutex->ptm_lock) == 0)) {
176 error = pthread_mutex_lock_slow(self, mutex);
177 if (error)
178 return error;
179 }
180
181 /*
182 * We have the lock!
183 */
184 self->pt_mutexhint = mutex;
185 mutex->ptm_owner = self;
186
187 return 0;
188 }
189
190
191 static int
192 pthread_mutex_lock_slow(pthread_t self, pthread_mutex_t *mutex)
193 {
194 extern int pthread__started;
195
196 pthread__error(EINVAL, "Invalid mutex",
197 mutex->ptm_magic == _PT_MUTEX_MAGIC);
198
199 PTHREADD_ADD(PTHREADD_MUTEX_LOCK_SLOW);
200 while (/*CONSTCOND*/1) {
201 if (pthread__simple_lock_try(&mutex->ptm_lock))
202 break; /* got it! */
203
204 /* Okay, didn't look free. Get the interlock... */
205 pthread_spinlock(self, &mutex->ptm_interlock);
206
207 /*
208 * The mutex_unlock routine will get the interlock
209 * before looking at the list of sleepers, so if the
210 * lock is held we can safely put ourselves on the
211 * sleep queue. If it's not held, we can try taking it
212 * again.
213 */
214 PTQ_INSERT_HEAD(&mutex->ptm_blocked, self, pt_sleep);
215 if (__SIMPLELOCK_LOCKED_P(&mutex->ptm_lock)) {
216 struct mutex_private *mp;
217
218 GET_MUTEX_PRIVATE(mutex, mp);
219
220 if (mutex->ptm_owner == self) {
221 switch (mp->type) {
222 case PTHREAD_MUTEX_ERRORCHECK:
223 PTQ_REMOVE(&mutex->ptm_blocked, self,
224 pt_sleep);
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 PTQ_REMOVE(&mutex->ptm_blocked, self,
237 pt_sleep);
238 pthread_spinunlock(self,
239 &mutex->ptm_interlock);
240 if (mp->recursecount == INT_MAX)
241 return EAGAIN;
242 mp->recursecount++;
243 return 0;
244 }
245 }
246
247 if (pthread__started == 0) {
248 sigset_t ss;
249
250 /*
251 * The spec says we must deadlock, so...
252 */
253 pthread__assert(mp->type ==
254 PTHREAD_MUTEX_NORMAL);
255 (void) sigprocmask(SIG_SETMASK, NULL, &ss);
256 for (;;) {
257 sigsuspend(&ss);
258 }
259 /*NOTREACHED*/
260 }
261
262 /*
263 * Locking a mutex is not a cancellation
264 * point, so we don't need to do the
265 * test-cancellation dance. We may get woken
266 * up spuriously by pthread_cancel or signals,
267 * but it's okay since we're just going to
268 * retry.
269 */
270 self->pt_sleeponq = 1;
271 self->pt_sleepobj = &mutex->ptm_blocked;
272 (void)pthread__park(self, &mutex->ptm_interlock,
273 &mutex->ptm_blocked, NULL, 0, &mutex->ptm_blocked);
274 pthread_spinunlock(self, &mutex->ptm_interlock);
275 } else {
276 PTQ_REMOVE(&mutex->ptm_blocked, self, pt_sleep);
277 pthread_spinunlock(self, &mutex->ptm_interlock);
278 }
279 /* Go around for another try. */
280 }
281
282 return 0;
283 }
284
285
286 int
287 pthread_mutex_trylock(pthread_mutex_t *mutex)
288 {
289 struct mutex_private *mp;
290 pthread_t self;
291
292 pthread__error(EINVAL, "Invalid mutex",
293 mutex->ptm_magic == _PT_MUTEX_MAGIC);
294
295 self = pthread__self();
296
297 PTHREADD_ADD(PTHREADD_MUTEX_TRYLOCK);
298 if (pthread__simple_lock_try(&mutex->ptm_lock) == 0) {
299 /*
300 * These tests can be performed without holding the
301 * interlock because these fields are only modified
302 * if we know we own the mutex.
303 */
304 GET_MUTEX_PRIVATE(mutex, mp);
305 if (mp->type == PTHREAD_MUTEX_RECURSIVE &&
306 mutex->ptm_owner == self) {
307 if (mp->recursecount == INT_MAX)
308 return EAGAIN;
309 mp->recursecount++;
310 return 0;
311 }
312
313 return EBUSY;
314 }
315
316 mutex->ptm_owner = self;
317 self->pt_mutexhint = mutex;
318
319 return 0;
320 }
321
322
323 int
324 pthread_mutex_unlock(pthread_mutex_t *mutex)
325 {
326 struct mutex_private *mp;
327 pthread_t self;
328 int weown;
329
330 pthread__error(EINVAL, "Invalid mutex",
331 mutex->ptm_magic == _PT_MUTEX_MAGIC);
332
333 PTHREADD_ADD(PTHREADD_MUTEX_UNLOCK);
334
335 GET_MUTEX_PRIVATE(mutex, mp);
336
337 self = pthread_self();
338 /*
339 * These tests can be performed without holding the
340 * interlock because these fields are only modified
341 * if we know we own the mutex.
342 */
343 weown = (mutex->ptm_owner == self);
344 switch (mp->type) {
345 case PTHREAD_MUTEX_RECURSIVE:
346 if (!weown)
347 return EPERM;
348 if (mp->recursecount != 0) {
349 mp->recursecount--;
350 return 0;
351 }
352 break;
353 case PTHREAD_MUTEX_ERRORCHECK:
354 if (!weown)
355 return EPERM;
356 /*FALLTHROUGH*/
357 default:
358 if (__predict_false(!weown)) {
359 pthread__error(EPERM, "Unlocking unlocked mutex",
360 (mutex->ptm_owner != 0));
361 pthread__error(EPERM,
362 "Unlocking mutex owned by another thread", weown);
363 }
364 break;
365 }
366
367 mutex->ptm_owner = NULL;
368 pthread__simple_unlock(&mutex->ptm_lock);
369
370 /*
371 * Do a double-checked locking dance to see if there are any
372 * waiters. If we don't see any waiters, we can exit, because
373 * we've already released the lock. If we do see waiters, they
374 * were probably waiting on us... there's a slight chance that
375 * they are waiting on a different thread's ownership of the
376 * lock that happened between the unlock above and this
377 * examination of the queue; if so, no harm is done, as the
378 * waiter will loop and see that the mutex is still locked.
379 *
380 * Note that waiters may have been transferred here from a
381 * condition variable.
382 */
383 if (self->pt_mutexhint == mutex)
384 self->pt_mutexhint = NULL;
385
386 pthread_spinlock(self, &mutex->ptm_interlock);
387 pthread__unpark_all(self, &mutex->ptm_interlock, &mutex->ptm_blocked);
388
389 return 0;
390 }
391
392 int
393 pthread_mutexattr_init(pthread_mutexattr_t *attr)
394 {
395 struct mutexattr_private *map;
396
397 map = malloc(sizeof(*map));
398 if (map == NULL)
399 return ENOMEM;
400
401 *map = mutexattr_private_default;
402
403 attr->ptma_magic = _PT_MUTEXATTR_MAGIC;
404 attr->ptma_private = map;
405
406 return 0;
407 }
408
409
410 int
411 pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
412 {
413
414 pthread__error(EINVAL, "Invalid mutex attribute",
415 attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
416
417 attr->ptma_magic = _PT_MUTEXATTR_DEAD;
418 if (attr->ptma_private != NULL)
419 free(attr->ptma_private);
420
421 return 0;
422 }
423
424
425 int
426 pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *typep)
427 {
428 struct mutexattr_private *map;
429
430 pthread__error(EINVAL, "Invalid mutex attribute",
431 attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
432
433 map = attr->ptma_private;
434
435 *typep = map->type;
436
437 return 0;
438 }
439
440
441 int
442 pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
443 {
444 struct mutexattr_private *map;
445
446 pthread__error(EINVAL, "Invalid mutex attribute",
447 attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
448
449 map = attr->ptma_private;
450
451 switch (type) {
452 case PTHREAD_MUTEX_NORMAL:
453 case PTHREAD_MUTEX_ERRORCHECK:
454 case PTHREAD_MUTEX_RECURSIVE:
455 map->type = type;
456 break;
457
458 default:
459 return EINVAL;
460 }
461
462 return 0;
463 }
464
465
466 static void
467 once_cleanup(void *closure)
468 {
469
470 pthread_mutex_unlock((pthread_mutex_t *)closure);
471 }
472
473
474 int
475 pthread_once(pthread_once_t *once_control, void (*routine)(void))
476 {
477
478 if (once_control->pto_done == 0) {
479 pthread_mutex_lock(&once_control->pto_mutex);
480 pthread_cleanup_push(&once_cleanup, &once_control->pto_mutex);
481 if (once_control->pto_done == 0) {
482 routine();
483 once_control->pto_done = 1;
484 }
485 pthread_cleanup_pop(1);
486 }
487
488 return 0;
489 }
490