pthread_mutex.c revision 1.51.22.1 1 /* $NetBSD: pthread_mutex.c,v 1.51.22.1 2013/04/29 01:50:18 riz Exp $ */
2
3 /*-
4 * Copyright (c) 2001, 2003, 2006, 2007, 2008 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 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * To track threads waiting for mutexes to be released, we use lockless
34 * lists built on atomic operations and memory barriers.
35 *
36 * A simple spinlock would be faster and make the code easier to
37 * follow, but spinlocks are problematic in userspace. If a thread is
38 * preempted by the kernel while holding a spinlock, any other thread
39 * attempting to acquire that spinlock will needlessly busy wait.
40 *
41 * There is no good way to know that the holding thread is no longer
42 * running, nor to request a wake-up once it has begun running again.
43 * Of more concern, threads in the SCHED_FIFO class do not have a
44 * limited time quantum and so could spin forever, preventing the
45 * thread holding the spinlock from getting CPU time: it would never
46 * be released.
47 */
48
49 #include <sys/cdefs.h>
50 __RCSID("$NetBSD: pthread_mutex.c,v 1.51.22.1 2013/04/29 01:50:18 riz Exp $");
51
52 #include <sys/types.h>
53 #include <sys/lwpctl.h>
54 #include <sys/lock.h>
55
56 #include <errno.h>
57 #include <limits.h>
58 #include <stdlib.h>
59 #include <time.h>
60 #include <string.h>
61 #include <stdio.h>
62
63 #include "pthread.h"
64 #include "pthread_int.h"
65 #include "reentrant.h"
66
67 #define MUTEX_WAITERS_BIT ((uintptr_t)0x01)
68 #define MUTEX_RECURSIVE_BIT ((uintptr_t)0x02)
69 #define MUTEX_DEFERRED_BIT ((uintptr_t)0x04)
70 #define MUTEX_THREAD ((uintptr_t)-16L)
71
72 #define MUTEX_HAS_WAITERS(x) ((uintptr_t)(x) & MUTEX_WAITERS_BIT)
73 #define MUTEX_RECURSIVE(x) ((uintptr_t)(x) & MUTEX_RECURSIVE_BIT)
74 #define MUTEX_OWNER(x) ((uintptr_t)(x) & MUTEX_THREAD)
75
76 #if __GNUC_PREREQ__(3, 0)
77 #define NOINLINE __attribute ((noinline))
78 #else
79 #define NOINLINE /* nothing */
80 #endif
81
82 static void pthread__mutex_wakeup(pthread_t, pthread_mutex_t *);
83 static int pthread__mutex_lock_slow(pthread_mutex_t *);
84 static int pthread__mutex_unlock_slow(pthread_mutex_t *);
85 static void pthread__mutex_pause(void);
86
87 int _pthread_mutex_held_np(pthread_mutex_t *);
88 pthread_t _pthread_mutex_owner_np(pthread_mutex_t *);
89
90 __weak_alias(pthread_mutex_held_np,_pthread_mutex_held_np)
91 __weak_alias(pthread_mutex_owner_np,_pthread_mutex_owner_np)
92
93 __strong_alias(__libc_mutex_init,pthread_mutex_init)
94 __strong_alias(__libc_mutex_lock,pthread_mutex_lock)
95 __strong_alias(__libc_mutex_trylock,pthread_mutex_trylock)
96 __strong_alias(__libc_mutex_unlock,pthread_mutex_unlock)
97 __strong_alias(__libc_mutex_destroy,pthread_mutex_destroy)
98
99 __strong_alias(__libc_mutexattr_init,pthread_mutexattr_init)
100 __strong_alias(__libc_mutexattr_destroy,pthread_mutexattr_destroy)
101 __strong_alias(__libc_mutexattr_settype,pthread_mutexattr_settype)
102
103 __strong_alias(__libc_thr_once,pthread_once)
104
105 int
106 pthread_mutex_init(pthread_mutex_t *ptm, const pthread_mutexattr_t *attr)
107 {
108 intptr_t type;
109
110 if (__predict_false(__uselibcstub))
111 return __libc_mutex_init_stub(ptm, attr);
112
113 if (attr == NULL)
114 type = PTHREAD_MUTEX_NORMAL;
115 else
116 type = (intptr_t)attr->ptma_private;
117
118 switch (type) {
119 case PTHREAD_MUTEX_ERRORCHECK:
120 __cpu_simple_lock_set(&ptm->ptm_errorcheck);
121 ptm->ptm_owner = NULL;
122 break;
123 case PTHREAD_MUTEX_RECURSIVE:
124 __cpu_simple_lock_clear(&ptm->ptm_errorcheck);
125 ptm->ptm_owner = (void *)MUTEX_RECURSIVE_BIT;
126 break;
127 default:
128 __cpu_simple_lock_clear(&ptm->ptm_errorcheck);
129 ptm->ptm_owner = NULL;
130 break;
131 }
132
133 ptm->ptm_magic = _PT_MUTEX_MAGIC;
134 ptm->ptm_waiters = NULL;
135 ptm->ptm_recursed = 0;
136
137 return 0;
138 }
139
140
141 int
142 pthread_mutex_destroy(pthread_mutex_t *ptm)
143 {
144
145 if (__predict_false(__uselibcstub))
146 return __libc_mutex_destroy_stub(ptm);
147
148 pthread__error(EINVAL, "Invalid mutex",
149 ptm->ptm_magic == _PT_MUTEX_MAGIC);
150 pthread__error(EBUSY, "Destroying locked mutex",
151 MUTEX_OWNER(ptm->ptm_owner) == 0);
152
153 ptm->ptm_magic = _PT_MUTEX_DEAD;
154 return 0;
155 }
156
157 int
158 pthread_mutex_lock(pthread_mutex_t *ptm)
159 {
160 pthread_t self;
161 void *val;
162
163 if (__predict_false(__uselibcstub))
164 return __libc_mutex_lock_stub(ptm);
165
166 self = pthread__self();
167 val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
168 if (__predict_true(val == NULL)) {
169 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
170 membar_enter();
171 #endif
172 return 0;
173 }
174 return pthread__mutex_lock_slow(ptm);
175 }
176
177 /* We want function call overhead. */
178 NOINLINE static void
179 pthread__mutex_pause(void)
180 {
181
182 pthread__smt_pause();
183 }
184
185 /*
186 * Spin while the holder is running. 'lwpctl' gives us the true
187 * status of the thread. pt_blocking is set by libpthread in order
188 * to cut out system call and kernel spinlock overhead on remote CPUs
189 * (could represent many thousands of clock cycles). pt_blocking also
190 * makes this thread yield if the target is calling sched_yield().
191 */
192 NOINLINE static void *
193 pthread__mutex_spin(pthread_mutex_t *ptm, pthread_t owner)
194 {
195 pthread_t thread;
196 unsigned int count, i;
197
198 for (count = 2;; owner = ptm->ptm_owner) {
199 thread = (pthread_t)MUTEX_OWNER(owner);
200 if (thread == NULL)
201 break;
202 if (thread->pt_lwpctl->lc_curcpu == LWPCTL_CPU_NONE ||
203 thread->pt_blocking)
204 break;
205 if (count < 128)
206 count += count;
207 for (i = count; i != 0; i--)
208 pthread__mutex_pause();
209 }
210
211 return owner;
212 }
213
214 NOINLINE static int
215 pthread__mutex_lock_slow(pthread_mutex_t *ptm)
216 {
217 void *waiters, *new, *owner, *next;
218 pthread_t self;
219
220 pthread__error(EINVAL, "Invalid mutex",
221 ptm->ptm_magic == _PT_MUTEX_MAGIC);
222
223 owner = ptm->ptm_owner;
224 self = pthread__self();
225
226 /* Recursive or errorcheck? */
227 if (MUTEX_OWNER(owner) == (uintptr_t)self) {
228 if (MUTEX_RECURSIVE(owner)) {
229 if (ptm->ptm_recursed == INT_MAX)
230 return EAGAIN;
231 ptm->ptm_recursed++;
232 return 0;
233 }
234 if (__SIMPLELOCK_LOCKED_P(&ptm->ptm_errorcheck))
235 return EDEADLK;
236 }
237
238 for (;; owner = ptm->ptm_owner) {
239 /* Spin while the owner is running. */
240 owner = pthread__mutex_spin(ptm, owner);
241
242 /* If it has become free, try to acquire it again. */
243 if (MUTEX_OWNER(owner) == 0) {
244 do {
245 new = (void *)
246 ((uintptr_t)self | (uintptr_t)owner);
247 next = atomic_cas_ptr(&ptm->ptm_owner, owner,
248 new);
249 if (next == owner) {
250 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
251 membar_enter();
252 #endif
253 return 0;
254 }
255 owner = next;
256 } while (MUTEX_OWNER(owner) == 0);
257 /*
258 * We have lost the race to acquire the mutex.
259 * The new owner could be running on another
260 * CPU, in which case we should spin and avoid
261 * the overhead of blocking.
262 */
263 continue;
264 }
265
266 /*
267 * Nope, still held. Add thread to the list of waiters.
268 * Issue a memory barrier to ensure mutexwait/mutexnext
269 * are visible before we enter the waiters list.
270 */
271 self->pt_mutexwait = 1;
272 for (waiters = ptm->ptm_waiters;; waiters = next) {
273 self->pt_mutexnext = waiters;
274 membar_producer();
275 next = atomic_cas_ptr(&ptm->ptm_waiters, waiters, self);
276 if (next == waiters)
277 break;
278 }
279
280 /*
281 * Set the waiters bit and block.
282 *
283 * Note that the mutex can become unlocked before we set
284 * the waiters bit. If that happens it's not safe to sleep
285 * as we may never be awoken: we must remove the current
286 * thread from the waiters list and try again.
287 *
288 * Because we are doing this atomically, we can't remove
289 * one waiter: we must remove all waiters and awken them,
290 * then sleep in _lwp_park() until we have been awoken.
291 *
292 * Issue a memory barrier to ensure that we are reading
293 * the value of ptm_owner/pt_mutexwait after we have entered
294 * the waiters list (the CAS itself must be atomic).
295 */
296 membar_consumer();
297 for (owner = ptm->ptm_owner;; owner = next) {
298 if (MUTEX_HAS_WAITERS(owner))
299 break;
300 if (MUTEX_OWNER(owner) == 0) {
301 pthread__mutex_wakeup(self, ptm);
302 break;
303 }
304 new = (void *)((uintptr_t)owner | MUTEX_WAITERS_BIT);
305 next = atomic_cas_ptr(&ptm->ptm_owner, owner, new);
306 if (next == owner) {
307 /*
308 * pthread_mutex_unlock() can do a
309 * non-interlocked CAS. We cannot
310 * know if our attempt to set the
311 * waiters bit has succeeded while
312 * the holding thread is running.
313 * There are many assumptions; see
314 * sys/kern/kern_mutex.c for details.
315 * In short, we must spin if we see
316 * that the holder is running again.
317 */
318 membar_sync();
319 next = pthread__mutex_spin(ptm, owner);
320 }
321 }
322
323 /*
324 * We may have been awoken by the current thread above,
325 * or will be awoken by the current holder of the mutex.
326 * The key requirement is that we must not proceed until
327 * told that we are no longer waiting (via pt_mutexwait
328 * being set to zero). Otherwise it is unsafe to re-enter
329 * the thread onto the waiters list.
330 */
331 while (self->pt_mutexwait) {
332 self->pt_blocking++;
333 (void)_lwp_park(NULL, self->pt_unpark,
334 __UNVOLATILE(&ptm->ptm_waiters),
335 __UNVOLATILE(&ptm->ptm_waiters));
336 self->pt_unpark = 0;
337 self->pt_blocking--;
338 membar_sync();
339 }
340 }
341 }
342
343 int
344 pthread_mutex_trylock(pthread_mutex_t *ptm)
345 {
346 pthread_t self;
347 void *val, *new, *next;
348
349 if (__predict_false(__uselibcstub))
350 return __libc_mutex_trylock_stub(ptm);
351
352 self = pthread__self();
353 val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
354 if (__predict_true(val == NULL)) {
355 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
356 membar_enter();
357 #endif
358 return 0;
359 }
360
361 if (MUTEX_RECURSIVE(val)) {
362 if (MUTEX_OWNER(val) == 0) {
363 new = (void *)((uintptr_t)self | (uintptr_t)val);
364 next = atomic_cas_ptr(&ptm->ptm_owner, val, new);
365 if (__predict_true(next == val)) {
366 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
367 membar_enter();
368 #endif
369 return 0;
370 }
371 }
372 if (MUTEX_OWNER(val) == (uintptr_t)self) {
373 if (ptm->ptm_recursed == INT_MAX)
374 return EAGAIN;
375 ptm->ptm_recursed++;
376 return 0;
377 }
378 }
379
380 return EBUSY;
381 }
382
383 int
384 pthread_mutex_unlock(pthread_mutex_t *ptm)
385 {
386 pthread_t self;
387 void *value;
388
389 if (__predict_false(__uselibcstub))
390 return __libc_mutex_unlock_stub(ptm);
391
392 /*
393 * Note this may be a non-interlocked CAS. See lock_slow()
394 * above and sys/kern/kern_mutex.c for details.
395 */
396 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
397 membar_exit();
398 #endif
399 self = pthread__self();
400 value = atomic_cas_ptr_ni(&ptm->ptm_owner, self, NULL);
401 if (__predict_true(value == self))
402 return 0;
403 return pthread__mutex_unlock_slow(ptm);
404 }
405
406 NOINLINE static int
407 pthread__mutex_unlock_slow(pthread_mutex_t *ptm)
408 {
409 pthread_t self, owner, new;
410 int weown, error, deferred;
411
412 pthread__error(EINVAL, "Invalid mutex",
413 ptm->ptm_magic == _PT_MUTEX_MAGIC);
414
415 self = pthread__self();
416 owner = ptm->ptm_owner;
417 weown = (MUTEX_OWNER(owner) == (uintptr_t)self);
418 deferred = (int)((uintptr_t)owner & MUTEX_DEFERRED_BIT);
419 error = 0;
420
421 if (__SIMPLELOCK_LOCKED_P(&ptm->ptm_errorcheck)) {
422 if (!weown) {
423 error = EPERM;
424 new = owner;
425 } else {
426 new = NULL;
427 }
428 } else if (MUTEX_RECURSIVE(owner)) {
429 if (!weown) {
430 error = EPERM;
431 new = owner;
432 } else if (ptm->ptm_recursed) {
433 ptm->ptm_recursed--;
434 new = owner;
435 } else {
436 new = (pthread_t)MUTEX_RECURSIVE_BIT;
437 }
438 } else {
439 pthread__error(EPERM,
440 "Unlocking unlocked mutex", (owner != NULL));
441 pthread__error(EPERM,
442 "Unlocking mutex owned by another thread", weown);
443 new = NULL;
444 }
445
446 /*
447 * Release the mutex. If there appear to be waiters, then
448 * wake them up.
449 */
450 if (new != owner) {
451 owner = atomic_swap_ptr(&ptm->ptm_owner, new);
452 if (MUTEX_HAS_WAITERS(owner) != 0) {
453 pthread__mutex_wakeup(self, ptm);
454 return 0;
455 }
456 }
457
458 /*
459 * There were no waiters, but we may have deferred waking
460 * other threads until mutex unlock - we must wake them now.
461 */
462 if (!deferred)
463 return error;
464
465 if (self->pt_nwaiters == 1) {
466 /*
467 * If the calling thread is about to block, defer
468 * unparking the target until _lwp_park() is called.
469 */
470 if (self->pt_willpark && self->pt_unpark == 0) {
471 self->pt_unpark = self->pt_waiters[0];
472 } else {
473 (void)_lwp_unpark(self->pt_waiters[0],
474 __UNVOLATILE(&ptm->ptm_waiters));
475 }
476 } else {
477 (void)_lwp_unpark_all(self->pt_waiters, self->pt_nwaiters,
478 __UNVOLATILE(&ptm->ptm_waiters));
479 }
480 self->pt_nwaiters = 0;
481
482 return error;
483 }
484
485 static void
486 pthread__mutex_wakeup(pthread_t self, pthread_mutex_t *ptm)
487 {
488 pthread_t thread, next;
489 ssize_t n, rv;
490
491 /*
492 * Take ownership of the current set of waiters. No
493 * need for a memory barrier following this, all loads
494 * are dependent upon 'thread'.
495 */
496 thread = atomic_swap_ptr(&ptm->ptm_waiters, NULL);
497
498 for (;;) {
499 /*
500 * Pull waiters from the queue and add to our list.
501 * Use a memory barrier to ensure that we safely
502 * read the value of pt_mutexnext before 'thread'
503 * sees pt_mutexwait being cleared.
504 */
505 for (n = self->pt_nwaiters, self->pt_nwaiters = 0;
506 n < pthread__unpark_max && thread != NULL;
507 thread = next) {
508 next = thread->pt_mutexnext;
509 if (thread != self) {
510 self->pt_waiters[n++] = thread->pt_lid;
511 membar_sync();
512 }
513 thread->pt_mutexwait = 0;
514 /* No longer safe to touch 'thread' */
515 }
516
517 switch (n) {
518 case 0:
519 return;
520 case 1:
521 /*
522 * If the calling thread is about to block,
523 * defer unparking the target until _lwp_park()
524 * is called.
525 */
526 if (self->pt_willpark && self->pt_unpark == 0) {
527 self->pt_unpark = self->pt_waiters[0];
528 return;
529 }
530 rv = (ssize_t)_lwp_unpark(self->pt_waiters[0],
531 __UNVOLATILE(&ptm->ptm_waiters));
532 if (rv != 0 && errno != EALREADY && errno != EINTR &&
533 errno != ESRCH) {
534 pthread__errorfunc(__FILE__, __LINE__,
535 __func__, "_lwp_unpark failed");
536 }
537 return;
538 default:
539 rv = _lwp_unpark_all(self->pt_waiters, (size_t)n,
540 __UNVOLATILE(&ptm->ptm_waiters));
541 if (rv != 0 && errno != EINTR) {
542 pthread__errorfunc(__FILE__, __LINE__,
543 __func__, "_lwp_unpark_all failed");
544 }
545 break;
546 }
547 }
548 }
549 int
550 pthread_mutexattr_init(pthread_mutexattr_t *attr)
551 {
552 if (__predict_false(__uselibcstub))
553 return __libc_mutexattr_init_stub(attr);
554
555 attr->ptma_magic = _PT_MUTEXATTR_MAGIC;
556 attr->ptma_private = (void *)PTHREAD_MUTEX_DEFAULT;
557 return 0;
558 }
559
560 int
561 pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
562 {
563 if (__predict_false(__uselibcstub))
564 return __libc_mutexattr_destroy_stub(attr);
565
566 pthread__error(EINVAL, "Invalid mutex attribute",
567 attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
568
569 return 0;
570 }
571
572
573 int
574 pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *typep)
575 {
576 pthread__error(EINVAL, "Invalid mutex attribute",
577 attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
578
579 *typep = (int)(intptr_t)attr->ptma_private;
580 return 0;
581 }
582
583
584 int
585 pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
586 {
587 if (__predict_false(__uselibcstub))
588 return __libc_mutexattr_settype_stub(attr, type);
589
590 pthread__error(EINVAL, "Invalid mutex attribute",
591 attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
592
593 switch (type) {
594 case PTHREAD_MUTEX_NORMAL:
595 case PTHREAD_MUTEX_ERRORCHECK:
596 case PTHREAD_MUTEX_RECURSIVE:
597 attr->ptma_private = (void *)(intptr_t)type;
598 return 0;
599 default:
600 return EINVAL;
601 }
602 }
603
604
605 static void
606 once_cleanup(void *closure)
607 {
608
609 pthread_mutex_unlock((pthread_mutex_t *)closure);
610 }
611
612
613 int
614 pthread_once(pthread_once_t *once_control, void (*routine)(void))
615 {
616 if (__predict_false(__uselibcstub))
617 return __libc_thr_once_stub(once_control, routine);
618
619 if (once_control->pto_done == 0) {
620 pthread_mutex_lock(&once_control->pto_mutex);
621 pthread_cleanup_push(&once_cleanup, &once_control->pto_mutex);
622 if (once_control->pto_done == 0) {
623 routine();
624 once_control->pto_done = 1;
625 }
626 pthread_cleanup_pop(1);
627 }
628
629 return 0;
630 }
631
632 void
633 pthread__mutex_deferwake(pthread_t self, pthread_mutex_t *ptm)
634 {
635
636 if (__predict_false(ptm == NULL ||
637 MUTEX_OWNER(ptm->ptm_owner) != (uintptr_t)self)) {
638 (void)_lwp_unpark_all(self->pt_waiters, self->pt_nwaiters,
639 __UNVOLATILE(&ptm->ptm_waiters));
640 self->pt_nwaiters = 0;
641 } else {
642 atomic_or_ulong((volatile unsigned long *)
643 (uintptr_t)&ptm->ptm_owner,
644 (unsigned long)MUTEX_DEFERRED_BIT);
645 }
646 }
647
648 int
649 _pthread_mutex_held_np(pthread_mutex_t *ptm)
650 {
651
652 return MUTEX_OWNER(ptm->ptm_owner) == (uintptr_t)pthread__self();
653 }
654
655 pthread_t
656 _pthread_mutex_owner_np(pthread_mutex_t *ptm)
657 {
658
659 return (pthread_t)MUTEX_OWNER(ptm->ptm_owner);
660 }
661