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