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