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