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