pthread_mutex.c revision 1.51.22.2 1 /* $NetBSD: pthread_mutex.c,v 1.51.22.2 2014/02/20 13:00:40 sborrill 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.2 2014/02/20 13:00:40 sborrill 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 void
215 pthread__mutex_setwaiters(pthread_t self, pthread_mutex_t *ptm)
216 {
217 void *new, *owner;
218
219 /*
220 * Note that the mutex can become unlocked before we set
221 * the waiters bit. If that happens it's not safe to sleep
222 * as we may never be awoken: we must remove the current
223 * thread from the waiters list and try again.
224 *
225 * Because we are doing this atomically, we can't remove
226 * one waiter: we must remove all waiters and awken them,
227 * then sleep in _lwp_park() until we have been awoken.
228 *
229 * Issue a memory barrier to ensure that we are reading
230 * the value of ptm_owner/pt_mutexwait after we have entered
231 * the waiters list (the CAS itself must be atomic).
232 */
233 again:
234 membar_consumer();
235 owner = ptm->ptm_owner;
236
237 if (MUTEX_OWNER(owner) == 0) {
238 pthread__mutex_wakeup(self, ptm);
239 return;
240 }
241 if (!MUTEX_HAS_WAITERS(owner)) {
242 new = (void *)((uintptr_t)owner | MUTEX_WAITERS_BIT);
243 if (atomic_cas_ptr(&ptm->ptm_owner, owner, new) != owner) {
244 goto again;
245 }
246 }
247
248 /*
249 * Note that pthread_mutex_unlock() can do a non-interlocked CAS.
250 * We cannot know if the presence of the waiters bit is stable
251 * while the holding thread is running. There are many assumptions;
252 * see sys/kern/kern_mutex.c for details. In short, we must spin if
253 * we see that the holder is running again.
254 */
255 membar_sync();
256 pthread__mutex_spin(ptm, owner);
257
258 if (membar_consumer(), !MUTEX_HAS_WAITERS(ptm->ptm_owner)) {
259 goto again;
260 }
261 }
262
263 NOINLINE static int
264 pthread__mutex_lock_slow(pthread_mutex_t *ptm)
265 {
266 void *waiters, *new, *owner, *next;
267 pthread_t self;
268 int serrno;
269
270 pthread__error(EINVAL, "Invalid mutex",
271 ptm->ptm_magic == _PT_MUTEX_MAGIC);
272
273 owner = ptm->ptm_owner;
274 self = pthread__self();
275
276 /* Recursive or errorcheck? */
277 if (MUTEX_OWNER(owner) == (uintptr_t)self) {
278 if (MUTEX_RECURSIVE(owner)) {
279 if (ptm->ptm_recursed == INT_MAX)
280 return EAGAIN;
281 ptm->ptm_recursed++;
282 return 0;
283 }
284 if (__SIMPLELOCK_LOCKED_P(&ptm->ptm_errorcheck))
285 return EDEADLK;
286 }
287
288 serrno = errno;
289 for (;; owner = ptm->ptm_owner) {
290 /* Spin while the owner is running. */
291 owner = pthread__mutex_spin(ptm, owner);
292
293 /* If it has become free, try to acquire it again. */
294 if (MUTEX_OWNER(owner) == 0) {
295 do {
296 new = (void *)
297 ((uintptr_t)self | (uintptr_t)owner);
298 next = atomic_cas_ptr(&ptm->ptm_owner, owner,
299 new);
300 if (next == owner) {
301 errno = serrno;
302 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
303 membar_enter();
304 #endif
305 return 0;
306 }
307 owner = next;
308 } while (MUTEX_OWNER(owner) == 0);
309 /*
310 * We have lost the race to acquire the mutex.
311 * The new owner could be running on another
312 * CPU, in which case we should spin and avoid
313 * the overhead of blocking.
314 */
315 continue;
316 }
317
318 /*
319 * Nope, still held. Add thread to the list of waiters.
320 * Issue a memory barrier to ensure mutexwait/mutexnext
321 * are visible before we enter the waiters list.
322 */
323 self->pt_mutexwait = 1;
324 for (waiters = ptm->ptm_waiters;; waiters = next) {
325 self->pt_mutexnext = waiters;
326 membar_producer();
327 next = atomic_cas_ptr(&ptm->ptm_waiters, waiters, self);
328 if (next == waiters)
329 break;
330 }
331
332 /* Set the waiters bit and block. */
333 pthread__mutex_setwaiters(self, ptm);
334
335 /*
336 * We may have been awoken by the current thread above,
337 * or will be awoken by the current holder of the mutex.
338 * The key requirement is that we must not proceed until
339 * told that we are no longer waiting (via pt_mutexwait
340 * being set to zero). Otherwise it is unsafe to re-enter
341 * the thread onto the waiters list.
342 */
343 while (self->pt_mutexwait) {
344 self->pt_blocking++;
345 (void)_lwp_park(NULL, self->pt_unpark,
346 __UNVOLATILE(&ptm->ptm_waiters),
347 __UNVOLATILE(&ptm->ptm_waiters));
348 self->pt_unpark = 0;
349 self->pt_blocking--;
350 membar_sync();
351 }
352 }
353 }
354
355 int
356 pthread_mutex_trylock(pthread_mutex_t *ptm)
357 {
358 pthread_t self;
359 void *val, *new, *next;
360
361 if (__predict_false(__uselibcstub))
362 return __libc_mutex_trylock_stub(ptm);
363
364 self = pthread__self();
365 val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
366 if (__predict_true(val == NULL)) {
367 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
368 membar_enter();
369 #endif
370 return 0;
371 }
372
373 if (MUTEX_RECURSIVE(val)) {
374 if (MUTEX_OWNER(val) == 0) {
375 new = (void *)((uintptr_t)self | (uintptr_t)val);
376 next = atomic_cas_ptr(&ptm->ptm_owner, val, new);
377 if (__predict_true(next == val)) {
378 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
379 membar_enter();
380 #endif
381 return 0;
382 }
383 }
384 if (MUTEX_OWNER(val) == (uintptr_t)self) {
385 if (ptm->ptm_recursed == INT_MAX)
386 return EAGAIN;
387 ptm->ptm_recursed++;
388 return 0;
389 }
390 }
391
392 return EBUSY;
393 }
394
395 int
396 pthread_mutex_unlock(pthread_mutex_t *ptm)
397 {
398 pthread_t self;
399 void *value;
400
401 if (__predict_false(__uselibcstub))
402 return __libc_mutex_unlock_stub(ptm);
403
404 /*
405 * Note this may be a non-interlocked CAS. See lock_slow()
406 * above and sys/kern/kern_mutex.c for details.
407 */
408 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
409 membar_exit();
410 #endif
411 self = pthread__self();
412 value = atomic_cas_ptr_ni(&ptm->ptm_owner, self, NULL);
413 if (__predict_true(value == self))
414 return 0;
415 return pthread__mutex_unlock_slow(ptm);
416 }
417
418 NOINLINE static int
419 pthread__mutex_unlock_slow(pthread_mutex_t *ptm)
420 {
421 pthread_t self, owner, new;
422 int weown, error, deferred;
423
424 pthread__error(EINVAL, "Invalid mutex",
425 ptm->ptm_magic == _PT_MUTEX_MAGIC);
426
427 self = pthread__self();
428 owner = ptm->ptm_owner;
429 weown = (MUTEX_OWNER(owner) == (uintptr_t)self);
430 deferred = (int)((uintptr_t)owner & MUTEX_DEFERRED_BIT);
431 error = 0;
432
433 if (__SIMPLELOCK_LOCKED_P(&ptm->ptm_errorcheck)) {
434 if (!weown) {
435 error = EPERM;
436 new = owner;
437 } else {
438 new = NULL;
439 }
440 } else if (MUTEX_RECURSIVE(owner)) {
441 if (!weown) {
442 error = EPERM;
443 new = owner;
444 } else if (ptm->ptm_recursed) {
445 ptm->ptm_recursed--;
446 new = owner;
447 } else {
448 new = (pthread_t)MUTEX_RECURSIVE_BIT;
449 }
450 } else {
451 pthread__error(EPERM,
452 "Unlocking unlocked mutex", (owner != NULL));
453 pthread__error(EPERM,
454 "Unlocking mutex owned by another thread", weown);
455 new = NULL;
456 }
457
458 /*
459 * Release the mutex. If there appear to be waiters, then
460 * wake them up.
461 */
462 if (new != owner) {
463 owner = atomic_swap_ptr(&ptm->ptm_owner, new);
464 if (MUTEX_HAS_WAITERS(owner) != 0) {
465 pthread__mutex_wakeup(self, ptm);
466 return 0;
467 }
468 }
469
470 /*
471 * There were no waiters, but we may have deferred waking
472 * other threads until mutex unlock - we must wake them now.
473 */
474 if (!deferred)
475 return error;
476
477 if (self->pt_nwaiters == 1) {
478 /*
479 * If the calling thread is about to block, defer
480 * unparking the target until _lwp_park() is called.
481 */
482 if (self->pt_willpark && self->pt_unpark == 0) {
483 self->pt_unpark = self->pt_waiters[0];
484 } else {
485 (void)_lwp_unpark(self->pt_waiters[0],
486 __UNVOLATILE(&ptm->ptm_waiters));
487 }
488 } else {
489 (void)_lwp_unpark_all(self->pt_waiters, self->pt_nwaiters,
490 __UNVOLATILE(&ptm->ptm_waiters));
491 }
492 self->pt_nwaiters = 0;
493
494 return error;
495 }
496
497 static void
498 pthread__mutex_wakeup(pthread_t self, pthread_mutex_t *ptm)
499 {
500 pthread_t thread, next;
501 ssize_t n, rv;
502
503 /*
504 * Take ownership of the current set of waiters. No
505 * need for a memory barrier following this, all loads
506 * are dependent upon 'thread'.
507 */
508 thread = atomic_swap_ptr(&ptm->ptm_waiters, NULL);
509
510 for (;;) {
511 /*
512 * Pull waiters from the queue and add to our list.
513 * Use a memory barrier to ensure that we safely
514 * read the value of pt_mutexnext before 'thread'
515 * sees pt_mutexwait being cleared.
516 */
517 for (n = self->pt_nwaiters, self->pt_nwaiters = 0;
518 n < pthread__unpark_max && thread != NULL;
519 thread = next) {
520 next = thread->pt_mutexnext;
521 if (thread != self) {
522 self->pt_waiters[n++] = thread->pt_lid;
523 membar_sync();
524 }
525 thread->pt_mutexwait = 0;
526 /* No longer safe to touch 'thread' */
527 }
528
529 switch (n) {
530 case 0:
531 return;
532 case 1:
533 /*
534 * If the calling thread is about to block,
535 * defer unparking the target until _lwp_park()
536 * is called.
537 */
538 if (self->pt_willpark && self->pt_unpark == 0) {
539 self->pt_unpark = self->pt_waiters[0];
540 return;
541 }
542 rv = (ssize_t)_lwp_unpark(self->pt_waiters[0],
543 __UNVOLATILE(&ptm->ptm_waiters));
544 if (rv != 0 && errno != EALREADY && errno != EINTR &&
545 errno != ESRCH) {
546 pthread__errorfunc(__FILE__, __LINE__,
547 __func__, "_lwp_unpark failed");
548 }
549 return;
550 default:
551 rv = _lwp_unpark_all(self->pt_waiters, (size_t)n,
552 __UNVOLATILE(&ptm->ptm_waiters));
553 if (rv != 0 && errno != EINTR) {
554 pthread__errorfunc(__FILE__, __LINE__,
555 __func__, "_lwp_unpark_all failed");
556 }
557 break;
558 }
559 }
560 }
561 int
562 pthread_mutexattr_init(pthread_mutexattr_t *attr)
563 {
564 if (__predict_false(__uselibcstub))
565 return __libc_mutexattr_init_stub(attr);
566
567 attr->ptma_magic = _PT_MUTEXATTR_MAGIC;
568 attr->ptma_private = (void *)PTHREAD_MUTEX_DEFAULT;
569 return 0;
570 }
571
572 int
573 pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
574 {
575 if (__predict_false(__uselibcstub))
576 return __libc_mutexattr_destroy_stub(attr);
577
578 pthread__error(EINVAL, "Invalid mutex attribute",
579 attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
580
581 return 0;
582 }
583
584
585 int
586 pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *typep)
587 {
588 pthread__error(EINVAL, "Invalid mutex attribute",
589 attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
590
591 *typep = (int)(intptr_t)attr->ptma_private;
592 return 0;
593 }
594
595
596 int
597 pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
598 {
599 if (__predict_false(__uselibcstub))
600 return __libc_mutexattr_settype_stub(attr, type);
601
602 pthread__error(EINVAL, "Invalid mutex attribute",
603 attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
604
605 switch (type) {
606 case PTHREAD_MUTEX_NORMAL:
607 case PTHREAD_MUTEX_ERRORCHECK:
608 case PTHREAD_MUTEX_RECURSIVE:
609 attr->ptma_private = (void *)(intptr_t)type;
610 return 0;
611 default:
612 return EINVAL;
613 }
614 }
615
616
617 static void
618 once_cleanup(void *closure)
619 {
620
621 pthread_mutex_unlock((pthread_mutex_t *)closure);
622 }
623
624
625 int
626 pthread_once(pthread_once_t *once_control, void (*routine)(void))
627 {
628 if (__predict_false(__uselibcstub))
629 return __libc_thr_once_stub(once_control, routine);
630
631 if (once_control->pto_done == 0) {
632 pthread_mutex_lock(&once_control->pto_mutex);
633 pthread_cleanup_push(&once_cleanup, &once_control->pto_mutex);
634 if (once_control->pto_done == 0) {
635 routine();
636 once_control->pto_done = 1;
637 }
638 pthread_cleanup_pop(1);
639 }
640
641 return 0;
642 }
643
644 void
645 pthread__mutex_deferwake(pthread_t self, pthread_mutex_t *ptm)
646 {
647
648 if (__predict_false(ptm == NULL ||
649 MUTEX_OWNER(ptm->ptm_owner) != (uintptr_t)self)) {
650 (void)_lwp_unpark_all(self->pt_waiters, self->pt_nwaiters,
651 __UNVOLATILE(&ptm->ptm_waiters));
652 self->pt_nwaiters = 0;
653 } else {
654 atomic_or_ulong((volatile unsigned long *)
655 (uintptr_t)&ptm->ptm_owner,
656 (unsigned long)MUTEX_DEFERRED_BIT);
657 }
658 }
659
660 int
661 _pthread_mutex_held_np(pthread_mutex_t *ptm)
662 {
663
664 return MUTEX_OWNER(ptm->ptm_owner) == (uintptr_t)pthread__self();
665 }
666
667 pthread_t
668 _pthread_mutex_owner_np(pthread_mutex_t *ptm)
669 {
670
671 return (pthread_t)MUTEX_OWNER(ptm->ptm_owner);
672 }
673