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