Home | History | Annotate | Line # | Download | only in libpthread
pthread_mutex.c revision 1.65
      1  1.65  christos /*	$NetBSD: pthread_mutex.c,v 1.65 2019/03/05 22:49:38 christos 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.65  christos __RCSID("$NetBSD: pthread_mutex.c,v 1.65 2019/03/05 22:49:38 christos Exp $");
     51  1.40        ad 
     52  1.40        ad #include <sys/types.h>
     53  1.44        ad #include <sys/lwpctl.h>
     54  1.60  christos #include <sys/sched.h>
     55  1.51      matt #include <sys/lock.h>
     56  1.10     lukem 
     57   1.2   thorpej #include <errno.h>
     58   1.2   thorpej #include <limits.h>
     59   1.2   thorpej #include <stdlib.h>
     60  1.56  christos #include <time.h>
     61   1.6       scw #include <string.h>
     62  1.44        ad #include <stdio.h>
     63   1.2   thorpej 
     64   1.2   thorpej #include "pthread.h"
     65   1.2   thorpej #include "pthread_int.h"
     66  1.56  christos #include "reentrant.h"
     67   1.2   thorpej 
     68  1.44        ad #define	MUTEX_WAITERS_BIT		((uintptr_t)0x01)
     69  1.44        ad #define	MUTEX_RECURSIVE_BIT		((uintptr_t)0x02)
     70  1.44        ad #define	MUTEX_DEFERRED_BIT		((uintptr_t)0x04)
     71  1.60  christos #define	MUTEX_PROTECT_BIT		((uintptr_t)0x08)
     72  1.60  christos #define	MUTEX_THREAD			((uintptr_t)~0x0f)
     73  1.44        ad 
     74  1.44        ad #define	MUTEX_HAS_WAITERS(x)		((uintptr_t)(x) & MUTEX_WAITERS_BIT)
     75  1.44        ad #define	MUTEX_RECURSIVE(x)		((uintptr_t)(x) & MUTEX_RECURSIVE_BIT)
     76  1.60  christos #define	MUTEX_PROTECT(x)		((uintptr_t)(x) & MUTEX_PROTECT_BIT)
     77  1.44        ad #define	MUTEX_OWNER(x)			((uintptr_t)(x) & MUTEX_THREAD)
     78  1.44        ad 
     79  1.60  christos #define	MUTEX_GET_TYPE(x)		\
     80  1.60  christos     ((int)(((uintptr_t)(x) & 0x000000ff) >> 0))
     81  1.60  christos #define	MUTEX_SET_TYPE(x, t) 		\
     82  1.60  christos     (x) = (void *)(((uintptr_t)(x) & ~0x000000ff) | ((t) << 0))
     83  1.60  christos #define	MUTEX_GET_PROTOCOL(x)		\
     84  1.60  christos     ((int)(((uintptr_t)(x) & 0x0000ff00) >> 8))
     85  1.60  christos #define	MUTEX_SET_PROTOCOL(x, p)	\
     86  1.60  christos     (x) = (void *)(((uintptr_t)(x) & ~0x0000ff00) | ((p) << 8))
     87  1.60  christos #define	MUTEX_GET_CEILING(x)		\
     88  1.60  christos     ((int)(((uintptr_t)(x) & 0x00ff0000) >> 16))
     89  1.60  christos #define	MUTEX_SET_CEILING(x, c)	\
     90  1.60  christos     (x) = (void *)(((uintptr_t)(x) & ~0x00ff0000) | ((c) << 16))
     91  1.60  christos 
     92  1.44        ad #if __GNUC_PREREQ__(3, 0)
     93  1.44        ad #define	NOINLINE		__attribute ((noinline))
     94  1.44        ad #else
     95  1.44        ad #define	NOINLINE		/* nothing */
     96  1.44        ad #endif
     97  1.44        ad 
     98  1.44        ad static void	pthread__mutex_wakeup(pthread_t, pthread_mutex_t *);
     99  1.60  christos static int	pthread__mutex_lock_slow(pthread_mutex_t *,
    100  1.60  christos     const struct timespec *);
    101  1.44        ad static int	pthread__mutex_unlock_slow(pthread_mutex_t *);
    102  1.44        ad static void	pthread__mutex_pause(void);
    103   1.2   thorpej 
    104  1.39        ad int		_pthread_mutex_held_np(pthread_mutex_t *);
    105  1.39        ad pthread_t	_pthread_mutex_owner_np(pthread_mutex_t *);
    106  1.39        ad 
    107  1.39        ad __weak_alias(pthread_mutex_held_np,_pthread_mutex_held_np)
    108  1.39        ad __weak_alias(pthread_mutex_owner_np,_pthread_mutex_owner_np)
    109  1.39        ad 
    110   1.2   thorpej __strong_alias(__libc_mutex_init,pthread_mutex_init)
    111   1.2   thorpej __strong_alias(__libc_mutex_lock,pthread_mutex_lock)
    112   1.2   thorpej __strong_alias(__libc_mutex_trylock,pthread_mutex_trylock)
    113   1.2   thorpej __strong_alias(__libc_mutex_unlock,pthread_mutex_unlock)
    114   1.2   thorpej __strong_alias(__libc_mutex_destroy,pthread_mutex_destroy)
    115   1.4   thorpej 
    116   1.4   thorpej __strong_alias(__libc_mutexattr_init,pthread_mutexattr_init)
    117   1.4   thorpej __strong_alias(__libc_mutexattr_destroy,pthread_mutexattr_destroy)
    118   1.5   thorpej __strong_alias(__libc_mutexattr_settype,pthread_mutexattr_settype)
    119   1.2   thorpej 
    120   1.2   thorpej int
    121  1.44        ad pthread_mutex_init(pthread_mutex_t *ptm, const pthread_mutexattr_t *attr)
    122   1.2   thorpej {
    123  1.60  christos 	uintptr_t type, proto, val, ceil;
    124   1.2   thorpej 
    125  1.65  christos #if 0
    126  1.65  christos 	/*
    127  1.65  christos 	 * Always initialize the mutex structure, maybe be used later
    128  1.65  christos 	 * and the cost should be minimal.
    129  1.65  christos 	 */
    130  1.56  christos 	if (__predict_false(__uselibcstub))
    131  1.56  christos 		return __libc_mutex_init_stub(ptm, attr);
    132  1.65  christos #endif
    133  1.56  christos 
    134  1.60  christos 	if (attr == NULL) {
    135  1.44        ad 		type = PTHREAD_MUTEX_NORMAL;
    136  1.60  christos 		proto = PTHREAD_PRIO_NONE;
    137  1.60  christos 		ceil = 0;
    138  1.60  christos 	} else {
    139  1.60  christos 		val = (uintptr_t)attr->ptma_private;
    140   1.2   thorpej 
    141  1.60  christos 		type = MUTEX_GET_TYPE(val);
    142  1.60  christos 		proto = MUTEX_GET_PROTOCOL(val);
    143  1.60  christos 		ceil = MUTEX_GET_CEILING(val);
    144  1.60  christos 	}
    145  1.44        ad 	switch (type) {
    146  1.44        ad 	case PTHREAD_MUTEX_ERRORCHECK:
    147  1.51      matt 		__cpu_simple_lock_set(&ptm->ptm_errorcheck);
    148  1.44        ad 		ptm->ptm_owner = NULL;
    149  1.44        ad 		break;
    150  1.44        ad 	case PTHREAD_MUTEX_RECURSIVE:
    151  1.51      matt 		__cpu_simple_lock_clear(&ptm->ptm_errorcheck);
    152  1.44        ad 		ptm->ptm_owner = (void *)MUTEX_RECURSIVE_BIT;
    153  1.44        ad 		break;
    154  1.44        ad 	default:
    155  1.51      matt 		__cpu_simple_lock_clear(&ptm->ptm_errorcheck);
    156  1.44        ad 		ptm->ptm_owner = NULL;
    157  1.44        ad 		break;
    158   1.2   thorpej 	}
    159  1.60  christos 	switch (proto) {
    160  1.60  christos 	case PTHREAD_PRIO_PROTECT:
    161  1.60  christos 		val = (uintptr_t)ptm->ptm_owner;
    162  1.60  christos 		val |= MUTEX_PROTECT_BIT;
    163  1.60  christos 		ptm->ptm_owner = (void *)val;
    164  1.60  christos 		break;
    165   1.2   thorpej 
    166  1.60  christos 	}
    167  1.44        ad 	ptm->ptm_magic = _PT_MUTEX_MAGIC;
    168  1.44        ad 	ptm->ptm_waiters = NULL;
    169  1.45        ad 	ptm->ptm_recursed = 0;
    170  1.60  christos 	ptm->ptm_ceiling = (unsigned char)ceil;
    171   1.2   thorpej 
    172   1.2   thorpej 	return 0;
    173   1.2   thorpej }
    174   1.2   thorpej 
    175   1.2   thorpej int
    176  1.44        ad pthread_mutex_destroy(pthread_mutex_t *ptm)
    177   1.2   thorpej {
    178   1.2   thorpej 
    179  1.56  christos 	if (__predict_false(__uselibcstub))
    180  1.56  christos 		return __libc_mutex_destroy_stub(ptm);
    181  1.56  christos 
    182  1.14   nathanw 	pthread__error(EINVAL, "Invalid mutex",
    183  1.44        ad 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    184  1.14   nathanw 	pthread__error(EBUSY, "Destroying locked mutex",
    185  1.44        ad 	    MUTEX_OWNER(ptm->ptm_owner) == 0);
    186   1.2   thorpej 
    187  1.44        ad 	ptm->ptm_magic = _PT_MUTEX_DEAD;
    188   1.2   thorpej 	return 0;
    189   1.2   thorpej }
    190   1.2   thorpej 
    191   1.2   thorpej int
    192  1.44        ad pthread_mutex_lock(pthread_mutex_t *ptm)
    193   1.2   thorpej {
    194  1.27        ad 	pthread_t self;
    195  1.44        ad 	void *val;
    196   1.2   thorpej 
    197  1.56  christos 	if (__predict_false(__uselibcstub))
    198  1.56  christos 		return __libc_mutex_lock_stub(ptm);
    199  1.56  christos 
    200  1.27        ad 	self = pthread__self();
    201  1.44        ad 	val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
    202  1.44        ad 	if (__predict_true(val == NULL)) {
    203  1.44        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    204  1.44        ad 		membar_enter();
    205  1.44        ad #endif
    206  1.44        ad 		return 0;
    207   1.2   thorpej 	}
    208  1.60  christos 	return pthread__mutex_lock_slow(ptm, NULL);
    209  1.60  christos }
    210  1.60  christos 
    211  1.60  christos int
    212  1.60  christos pthread_mutex_timedlock(pthread_mutex_t* ptm, const struct timespec *ts)
    213  1.60  christos {
    214  1.60  christos 	pthread_t self;
    215  1.60  christos 	void *val;
    216  1.60  christos 
    217  1.60  christos 	self = pthread__self();
    218  1.60  christos 	val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
    219  1.60  christos 	if (__predict_true(val == NULL)) {
    220  1.60  christos #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    221  1.60  christos 		membar_enter();
    222  1.60  christos #endif
    223  1.60  christos 		return 0;
    224  1.60  christos 	}
    225  1.60  christos 	return pthread__mutex_lock_slow(ptm, ts);
    226  1.44        ad }
    227   1.2   thorpej 
    228  1.44        ad /* We want function call overhead. */
    229  1.44        ad NOINLINE static void
    230  1.44        ad pthread__mutex_pause(void)
    231  1.44        ad {
    232   1.2   thorpej 
    233  1.44        ad 	pthread__smt_pause();
    234   1.2   thorpej }
    235   1.2   thorpej 
    236  1.44        ad /*
    237  1.44        ad  * Spin while the holder is running.  'lwpctl' gives us the true
    238  1.44        ad  * status of the thread.  pt_blocking is set by libpthread in order
    239  1.44        ad  * to cut out system call and kernel spinlock overhead on remote CPUs
    240  1.44        ad  * (could represent many thousands of clock cycles).  pt_blocking also
    241  1.44        ad  * makes this thread yield if the target is calling sched_yield().
    242  1.44        ad  */
    243  1.44        ad NOINLINE static void *
    244  1.44        ad pthread__mutex_spin(pthread_mutex_t *ptm, pthread_t owner)
    245  1.44        ad {
    246  1.44        ad 	pthread_t thread;
    247  1.44        ad 	unsigned int count, i;
    248  1.44        ad 
    249  1.44        ad 	for (count = 2;; owner = ptm->ptm_owner) {
    250  1.44        ad 		thread = (pthread_t)MUTEX_OWNER(owner);
    251  1.44        ad 		if (thread == NULL)
    252  1.44        ad 			break;
    253  1.44        ad 		if (thread->pt_lwpctl->lc_curcpu == LWPCTL_CPU_NONE ||
    254  1.44        ad 		    thread->pt_blocking)
    255  1.44        ad 			break;
    256  1.44        ad 		if (count < 128)
    257  1.44        ad 			count += count;
    258  1.44        ad 		for (i = count; i != 0; i--)
    259  1.44        ad 			pthread__mutex_pause();
    260  1.44        ad 	}
    261   1.2   thorpej 
    262  1.44        ad 	return owner;
    263  1.44        ad }
    264  1.44        ad 
    265  1.59     rmind NOINLINE static void
    266  1.59     rmind pthread__mutex_setwaiters(pthread_t self, pthread_mutex_t *ptm)
    267  1.59     rmind {
    268  1.59     rmind 	void *new, *owner;
    269  1.59     rmind 
    270  1.59     rmind 	/*
    271  1.59     rmind 	 * Note that the mutex can become unlocked before we set
    272  1.59     rmind 	 * the waiters bit.  If that happens it's not safe to sleep
    273  1.59     rmind 	 * as we may never be awoken: we must remove the current
    274  1.59     rmind 	 * thread from the waiters list and try again.
    275  1.59     rmind 	 *
    276  1.59     rmind 	 * Because we are doing this atomically, we can't remove
    277  1.59     rmind 	 * one waiter: we must remove all waiters and awken them,
    278  1.59     rmind 	 * then sleep in _lwp_park() until we have been awoken.
    279  1.59     rmind 	 *
    280  1.59     rmind 	 * Issue a memory barrier to ensure that we are reading
    281  1.59     rmind 	 * the value of ptm_owner/pt_mutexwait after we have entered
    282  1.59     rmind 	 * the waiters list (the CAS itself must be atomic).
    283  1.59     rmind 	 */
    284  1.59     rmind again:
    285  1.59     rmind 	membar_consumer();
    286  1.59     rmind 	owner = ptm->ptm_owner;
    287  1.59     rmind 
    288  1.59     rmind 	if (MUTEX_OWNER(owner) == 0) {
    289  1.59     rmind 		pthread__mutex_wakeup(self, ptm);
    290  1.59     rmind 		return;
    291  1.59     rmind 	}
    292  1.59     rmind 	if (!MUTEX_HAS_WAITERS(owner)) {
    293  1.59     rmind 		new = (void *)((uintptr_t)owner | MUTEX_WAITERS_BIT);
    294  1.59     rmind 		if (atomic_cas_ptr(&ptm->ptm_owner, owner, new) != owner) {
    295  1.59     rmind 			goto again;
    296  1.59     rmind 		}
    297  1.59     rmind 	}
    298  1.59     rmind 
    299  1.59     rmind 	/*
    300  1.59     rmind 	 * Note that pthread_mutex_unlock() can do a non-interlocked CAS.
    301  1.59     rmind 	 * We cannot know if the presence of the waiters bit is stable
    302  1.59     rmind 	 * while the holding thread is running.  There are many assumptions;
    303  1.59     rmind 	 * see sys/kern/kern_mutex.c for details.  In short, we must spin if
    304  1.59     rmind 	 * we see that the holder is running again.
    305  1.59     rmind 	 */
    306  1.59     rmind 	membar_sync();
    307  1.63  christos 	if (MUTEX_OWNER(owner) != (uintptr_t)self)
    308  1.63  christos 		pthread__mutex_spin(ptm, owner);
    309  1.59     rmind 
    310  1.59     rmind 	if (membar_consumer(), !MUTEX_HAS_WAITERS(ptm->ptm_owner)) {
    311  1.59     rmind 		goto again;
    312  1.59     rmind 	}
    313  1.59     rmind }
    314  1.59     rmind 
    315  1.44        ad NOINLINE static int
    316  1.60  christos pthread__mutex_lock_slow(pthread_mutex_t *ptm, const struct timespec *ts)
    317   1.2   thorpej {
    318  1.44        ad 	void *waiters, *new, *owner, *next;
    319  1.44        ad 	pthread_t self;
    320  1.57  christos 	int serrno;
    321  1.60  christos 	int error;
    322   1.2   thorpej 
    323  1.14   nathanw 	pthread__error(EINVAL, "Invalid mutex",
    324  1.44        ad 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    325  1.44        ad 
    326  1.44        ad 	owner = ptm->ptm_owner;
    327  1.44        ad 	self = pthread__self();
    328  1.13   nathanw 
    329  1.44        ad 	/* Recursive or errorcheck? */
    330  1.44        ad 	if (MUTEX_OWNER(owner) == (uintptr_t)self) {
    331  1.44        ad 		if (MUTEX_RECURSIVE(owner)) {
    332  1.45        ad 			if (ptm->ptm_recursed == INT_MAX)
    333  1.44        ad 				return EAGAIN;
    334  1.45        ad 			ptm->ptm_recursed++;
    335  1.44        ad 			return 0;
    336  1.29        ad 		}
    337  1.51      matt 		if (__SIMPLELOCK_LOCKED_P(&ptm->ptm_errorcheck))
    338  1.44        ad 			return EDEADLK;
    339  1.44        ad 	}
    340  1.29        ad 
    341  1.60  christos 	/* priority protect */
    342  1.60  christos 	if (MUTEX_PROTECT(owner) && _sched_protect(ptm->ptm_ceiling) == -1) {
    343  1.60  christos 		return errno;
    344  1.60  christos 	}
    345  1.57  christos 	serrno = errno;
    346  1.44        ad 	for (;; owner = ptm->ptm_owner) {
    347  1.44        ad 		/* Spin while the owner is running. */
    348  1.63  christos 		if (MUTEX_OWNER(owner) != (uintptr_t)self)
    349  1.63  christos 			owner = pthread__mutex_spin(ptm, owner);
    350  1.44        ad 
    351  1.44        ad 		/* If it has become free, try to acquire it again. */
    352  1.44        ad 		if (MUTEX_OWNER(owner) == 0) {
    353  1.47        ad 			do {
    354  1.44        ad 				new = (void *)
    355  1.44        ad 				    ((uintptr_t)self | (uintptr_t)owner);
    356  1.44        ad 				next = atomic_cas_ptr(&ptm->ptm_owner, owner,
    357  1.44        ad 				    new);
    358  1.44        ad 				if (next == owner) {
    359  1.57  christos 					errno = serrno;
    360  1.44        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    361  1.44        ad 					membar_enter();
    362  1.44        ad #endif
    363  1.44        ad 					return 0;
    364  1.44        ad 				}
    365  1.47        ad 				owner = next;
    366  1.47        ad 			} while (MUTEX_OWNER(owner) == 0);
    367  1.44        ad 			/*
    368  1.44        ad 			 * We have lost the race to acquire the mutex.
    369  1.44        ad 			 * The new owner could be running on another
    370  1.44        ad 			 * CPU, in which case we should spin and avoid
    371  1.44        ad 			 * the overhead of blocking.
    372  1.44        ad 			 */
    373  1.47        ad 			continue;
    374  1.44        ad 		}
    375  1.21       chs 
    376   1.2   thorpej 		/*
    377  1.44        ad 		 * Nope, still held.  Add thread to the list of waiters.
    378  1.50        ad 		 * Issue a memory barrier to ensure mutexwait/mutexnext
    379  1.44        ad 		 * are visible before we enter the waiters list.
    380   1.2   thorpej 		 */
    381  1.50        ad 		self->pt_mutexwait = 1;
    382  1.44        ad 		for (waiters = ptm->ptm_waiters;; waiters = next) {
    383  1.50        ad 			self->pt_mutexnext = waiters;
    384  1.44        ad 			membar_producer();
    385  1.44        ad 			next = atomic_cas_ptr(&ptm->ptm_waiters, waiters, self);
    386  1.44        ad 			if (next == waiters)
    387  1.44        ad 			    	break;
    388  1.44        ad 		}
    389  1.21       chs 
    390  1.59     rmind 		/* Set the waiters bit and block. */
    391  1.59     rmind 		pthread__mutex_setwaiters(self, ptm);
    392  1.21       chs 
    393  1.29        ad 		/*
    394  1.44        ad 		 * We may have been awoken by the current thread above,
    395  1.44        ad 		 * or will be awoken by the current holder of the mutex.
    396  1.44        ad 		 * The key requirement is that we must not proceed until
    397  1.50        ad 		 * told that we are no longer waiting (via pt_mutexwait
    398  1.44        ad 		 * being set to zero).  Otherwise it is unsafe to re-enter
    399  1.44        ad 		 * the thread onto the waiters list.
    400  1.29        ad 		 */
    401  1.50        ad 		while (self->pt_mutexwait) {
    402  1.44        ad 			self->pt_blocking++;
    403  1.64       kre 			error = _lwp_park(CLOCK_REALTIME, TIMER_ABSTIME,
    404  1.64       kre 			    __UNCONST(ts), self->pt_unpark,
    405  1.64       kre 			    __UNVOLATILE(&ptm->ptm_waiters),
    406  1.50        ad 			    __UNVOLATILE(&ptm->ptm_waiters));
    407  1.50        ad 			self->pt_unpark = 0;
    408  1.44        ad 			self->pt_blocking--;
    409  1.44        ad 			membar_sync();
    410  1.60  christos 			if (__predict_true(error != -1)) {
    411  1.60  christos 				continue;
    412  1.60  christos 			}
    413  1.60  christos 			if (errno == ETIMEDOUT && self->pt_mutexwait) {
    414  1.60  christos 				/*Remove self from waiters list*/
    415  1.60  christos 				pthread__mutex_wakeup(self, ptm);
    416  1.60  christos 				/*priority protect*/
    417  1.60  christos 				if (MUTEX_PROTECT(owner))
    418  1.60  christos 					(void)_sched_protect(-1);
    419  1.60  christos 				return ETIMEDOUT;
    420  1.60  christos 			}
    421  1.44        ad 		}
    422   1.2   thorpej 	}
    423   1.2   thorpej }
    424   1.2   thorpej 
    425   1.2   thorpej int
    426  1.44        ad pthread_mutex_trylock(pthread_mutex_t *ptm)
    427   1.2   thorpej {
    428  1.27        ad 	pthread_t self;
    429  1.46        ad 	void *val, *new, *next;
    430   1.2   thorpej 
    431  1.56  christos 	if (__predict_false(__uselibcstub))
    432  1.56  christos 		return __libc_mutex_trylock_stub(ptm);
    433  1.56  christos 
    434  1.27        ad 	self = pthread__self();
    435  1.44        ad 	val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
    436  1.44        ad 	if (__predict_true(val == NULL)) {
    437  1.44        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    438  1.44        ad 		membar_enter();
    439  1.44        ad #endif
    440  1.44        ad 		return 0;
    441  1.44        ad 	}
    442  1.27        ad 
    443  1.46        ad 	if (MUTEX_RECURSIVE(val)) {
    444  1.46        ad 		if (MUTEX_OWNER(val) == 0) {
    445  1.46        ad 			new = (void *)((uintptr_t)self | (uintptr_t)val);
    446  1.46        ad 			next = atomic_cas_ptr(&ptm->ptm_owner, val, new);
    447  1.46        ad 			if (__predict_true(next == val)) {
    448  1.46        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    449  1.46        ad 				membar_enter();
    450  1.46        ad #endif
    451  1.46        ad 				return 0;
    452  1.46        ad 			}
    453  1.46        ad 		}
    454  1.46        ad 		if (MUTEX_OWNER(val) == (uintptr_t)self) {
    455  1.46        ad 			if (ptm->ptm_recursed == INT_MAX)
    456  1.46        ad 				return EAGAIN;
    457  1.46        ad 			ptm->ptm_recursed++;
    458  1.46        ad 			return 0;
    459  1.46        ad 		}
    460   1.2   thorpej 	}
    461   1.2   thorpej 
    462  1.44        ad 	return EBUSY;
    463   1.2   thorpej }
    464   1.2   thorpej 
    465   1.2   thorpej int
    466  1.44        ad pthread_mutex_unlock(pthread_mutex_t *ptm)
    467   1.2   thorpej {
    468  1.27        ad 	pthread_t self;
    469  1.44        ad 	void *value;
    470  1.44        ad 
    471  1.56  christos 	if (__predict_false(__uselibcstub))
    472  1.56  christos 		return __libc_mutex_unlock_stub(ptm);
    473  1.56  christos 
    474  1.44        ad 	/*
    475  1.44        ad 	 * Note this may be a non-interlocked CAS.  See lock_slow()
    476  1.44        ad 	 * above and sys/kern/kern_mutex.c for details.
    477  1.44        ad 	 */
    478  1.44        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    479  1.44        ad 	membar_exit();
    480  1.44        ad #endif
    481  1.44        ad 	self = pthread__self();
    482  1.44        ad 	value = atomic_cas_ptr_ni(&ptm->ptm_owner, self, NULL);
    483  1.54      matt 	if (__predict_true(value == self)) {
    484  1.54      matt 		pthread__smt_wake();
    485  1.44        ad 		return 0;
    486  1.54      matt 	}
    487  1.44        ad 	return pthread__mutex_unlock_slow(ptm);
    488  1.44        ad }
    489  1.44        ad 
    490  1.44        ad NOINLINE static int
    491  1.44        ad pthread__mutex_unlock_slow(pthread_mutex_t *ptm)
    492  1.44        ad {
    493  1.44        ad 	pthread_t self, owner, new;
    494  1.44        ad 	int weown, error, deferred;
    495  1.13   nathanw 
    496  1.14   nathanw 	pthread__error(EINVAL, "Invalid mutex",
    497  1.44        ad 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    498  1.44        ad 
    499  1.44        ad 	self = pthread__self();
    500  1.44        ad 	owner = ptm->ptm_owner;
    501  1.44        ad 	weown = (MUTEX_OWNER(owner) == (uintptr_t)self);
    502  1.44        ad 	deferred = (int)((uintptr_t)owner & MUTEX_DEFERRED_BIT);
    503  1.44        ad 	error = 0;
    504  1.44        ad 
    505  1.51      matt 	if (__SIMPLELOCK_LOCKED_P(&ptm->ptm_errorcheck)) {
    506  1.44        ad 		if (!weown) {
    507  1.44        ad 			error = EPERM;
    508  1.44        ad 			new = owner;
    509  1.44        ad 		} else {
    510  1.44        ad 			new = NULL;
    511  1.44        ad 		}
    512  1.44        ad 	} else if (MUTEX_RECURSIVE(owner)) {
    513  1.44        ad 		if (!weown) {
    514  1.44        ad 			error = EPERM;
    515  1.44        ad 			new = owner;
    516  1.45        ad 		} else if (ptm->ptm_recursed) {
    517  1.45        ad 			ptm->ptm_recursed--;
    518  1.44        ad 			new = owner;
    519  1.44        ad 		} else {
    520  1.44        ad 			new = (pthread_t)MUTEX_RECURSIVE_BIT;
    521  1.44        ad 		}
    522  1.44        ad 	} else {
    523  1.44        ad 		pthread__error(EPERM,
    524  1.44        ad 		    "Unlocking unlocked mutex", (owner != NULL));
    525  1.44        ad 		pthread__error(EPERM,
    526  1.44        ad 		    "Unlocking mutex owned by another thread", weown);
    527  1.44        ad 		new = NULL;
    528  1.44        ad 	}
    529   1.2   thorpej 
    530   1.2   thorpej 	/*
    531  1.44        ad 	 * Release the mutex.  If there appear to be waiters, then
    532  1.44        ad 	 * wake them up.
    533   1.2   thorpej 	 */
    534  1.44        ad 	if (new != owner) {
    535  1.44        ad 		owner = atomic_swap_ptr(&ptm->ptm_owner, new);
    536  1.60  christos 		if (__predict_false(MUTEX_PROTECT(owner))) {
    537  1.60  christos 			/* restore elevated priority */
    538  1.60  christos 			(void)_sched_protect(-1);
    539  1.60  christos 		}
    540  1.44        ad 		if (MUTEX_HAS_WAITERS(owner) != 0) {
    541  1.44        ad 			pthread__mutex_wakeup(self, ptm);
    542   1.2   thorpej 			return 0;
    543   1.2   thorpej 		}
    544  1.44        ad 	}
    545  1.44        ad 
    546  1.44        ad 	/*
    547  1.44        ad 	 * There were no waiters, but we may have deferred waking
    548  1.44        ad 	 * other threads until mutex unlock - we must wake them now.
    549  1.44        ad 	 */
    550  1.44        ad 	if (!deferred)
    551  1.44        ad 		return error;
    552  1.44        ad 
    553  1.44        ad 	if (self->pt_nwaiters == 1) {
    554  1.44        ad 		/*
    555  1.44        ad 		 * If the calling thread is about to block, defer
    556  1.44        ad 		 * unparking the target until _lwp_park() is called.
    557  1.44        ad 		 */
    558  1.44        ad 		if (self->pt_willpark && self->pt_unpark == 0) {
    559  1.44        ad 			self->pt_unpark = self->pt_waiters[0];
    560  1.44        ad 		} else {
    561  1.44        ad 			(void)_lwp_unpark(self->pt_waiters[0],
    562  1.45        ad 			    __UNVOLATILE(&ptm->ptm_waiters));
    563  1.15   nathanw 		}
    564  1.44        ad 	} else {
    565  1.44        ad 		(void)_lwp_unpark_all(self->pt_waiters, self->pt_nwaiters,
    566  1.45        ad 		    __UNVOLATILE(&ptm->ptm_waiters));
    567   1.2   thorpej 	}
    568  1.44        ad 	self->pt_nwaiters = 0;
    569   1.2   thorpej 
    570  1.44        ad 	return error;
    571  1.44        ad }
    572  1.44        ad 
    573  1.55      yamt /*
    574  1.55      yamt  * pthread__mutex_wakeup: unpark threads waiting for us
    575  1.55      yamt  *
    576  1.55      yamt  * unpark threads on the ptm->ptm_waiters list and self->pt_waiters.
    577  1.55      yamt  */
    578  1.55      yamt 
    579  1.44        ad static void
    580  1.44        ad pthread__mutex_wakeup(pthread_t self, pthread_mutex_t *ptm)
    581  1.44        ad {
    582  1.44        ad 	pthread_t thread, next;
    583  1.44        ad 	ssize_t n, rv;
    584  1.27        ad 
    585   1.8   nathanw 	/*
    586  1.44        ad 	 * Take ownership of the current set of waiters.  No
    587  1.44        ad 	 * need for a memory barrier following this, all loads
    588  1.44        ad 	 * are dependent upon 'thread'.
    589   1.8   nathanw 	 */
    590  1.44        ad 	thread = atomic_swap_ptr(&ptm->ptm_waiters, NULL);
    591  1.54      matt 	pthread__smt_wake();
    592  1.44        ad 
    593  1.44        ad 	for (;;) {
    594  1.44        ad 		/*
    595  1.44        ad 		 * Pull waiters from the queue and add to our list.
    596  1.44        ad 		 * Use a memory barrier to ensure that we safely
    597  1.50        ad 		 * read the value of pt_mutexnext before 'thread'
    598  1.50        ad 		 * sees pt_mutexwait being cleared.
    599  1.44        ad 		 */
    600  1.44        ad 		for (n = self->pt_nwaiters, self->pt_nwaiters = 0;
    601  1.44        ad 		    n < pthread__unpark_max && thread != NULL;
    602  1.44        ad 		    thread = next) {
    603  1.50        ad 		    	next = thread->pt_mutexnext;
    604  1.44        ad 		    	if (thread != self) {
    605  1.44        ad 				self->pt_waiters[n++] = thread->pt_lid;
    606  1.44        ad 				membar_sync();
    607  1.44        ad 			}
    608  1.50        ad 			thread->pt_mutexwait = 0;
    609  1.44        ad 			/* No longer safe to touch 'thread' */
    610  1.44        ad 		}
    611  1.44        ad 
    612  1.44        ad 		switch (n) {
    613  1.44        ad 		case 0:
    614  1.44        ad 			return;
    615  1.44        ad 		case 1:
    616  1.44        ad 			/*
    617  1.44        ad 			 * If the calling thread is about to block,
    618  1.44        ad 			 * defer unparking the target until _lwp_park()
    619  1.44        ad 			 * is called.
    620  1.44        ad 			 */
    621  1.44        ad 			if (self->pt_willpark && self->pt_unpark == 0) {
    622  1.44        ad 				self->pt_unpark = self->pt_waiters[0];
    623  1.44        ad 				return;
    624  1.44        ad 			}
    625  1.44        ad 			rv = (ssize_t)_lwp_unpark(self->pt_waiters[0],
    626  1.45        ad 			    __UNVOLATILE(&ptm->ptm_waiters));
    627  1.44        ad 			if (rv != 0 && errno != EALREADY && errno != EINTR &&
    628  1.44        ad 			    errno != ESRCH) {
    629  1.44        ad 				pthread__errorfunc(__FILE__, __LINE__,
    630  1.44        ad 				    __func__, "_lwp_unpark failed");
    631  1.44        ad 			}
    632  1.44        ad 			return;
    633  1.44        ad 		default:
    634  1.44        ad 			rv = _lwp_unpark_all(self->pt_waiters, (size_t)n,
    635  1.45        ad 			    __UNVOLATILE(&ptm->ptm_waiters));
    636  1.44        ad 			if (rv != 0 && errno != EINTR) {
    637  1.44        ad 				pthread__errorfunc(__FILE__, __LINE__,
    638  1.44        ad 				    __func__, "_lwp_unpark_all failed");
    639  1.44        ad 			}
    640  1.44        ad 			break;
    641  1.44        ad 		}
    642  1.44        ad 	}
    643   1.2   thorpej }
    644  1.55      yamt 
    645   1.2   thorpej int
    646   1.2   thorpej pthread_mutexattr_init(pthread_mutexattr_t *attr)
    647   1.2   thorpej {
    648  1.56  christos 	if (__predict_false(__uselibcstub))
    649  1.56  christos 		return __libc_mutexattr_init_stub(attr);
    650   1.2   thorpej 
    651   1.2   thorpej 	attr->ptma_magic = _PT_MUTEXATTR_MAGIC;
    652  1.44        ad 	attr->ptma_private = (void *)PTHREAD_MUTEX_DEFAULT;
    653   1.2   thorpej 	return 0;
    654   1.2   thorpej }
    655   1.2   thorpej 
    656   1.2   thorpej int
    657   1.2   thorpej pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
    658   1.2   thorpej {
    659  1.56  christos 	if (__predict_false(__uselibcstub))
    660  1.56  christos 		return __libc_mutexattr_destroy_stub(attr);
    661   1.2   thorpej 
    662  1.14   nathanw 	pthread__error(EINVAL, "Invalid mutex attribute",
    663  1.14   nathanw 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    664   1.2   thorpej 
    665   1.2   thorpej 	return 0;
    666   1.2   thorpej }
    667   1.2   thorpej 
    668   1.2   thorpej int
    669   1.2   thorpej pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *typep)
    670   1.2   thorpej {
    671  1.60  christos 
    672  1.14   nathanw 	pthread__error(EINVAL, "Invalid mutex attribute",
    673  1.14   nathanw 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    674   1.2   thorpej 
    675  1.60  christos 	*typep = MUTEX_GET_TYPE(attr->ptma_private);
    676   1.2   thorpej 	return 0;
    677   1.2   thorpej }
    678   1.2   thorpej 
    679   1.2   thorpej int
    680   1.2   thorpej pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
    681   1.2   thorpej {
    682  1.60  christos 
    683  1.56  christos 	if (__predict_false(__uselibcstub))
    684  1.56  christos 		return __libc_mutexattr_settype_stub(attr, type);
    685   1.2   thorpej 
    686  1.14   nathanw 	pthread__error(EINVAL, "Invalid mutex attribute",
    687  1.14   nathanw 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    688  1.13   nathanw 
    689   1.2   thorpej 	switch (type) {
    690   1.2   thorpej 	case PTHREAD_MUTEX_NORMAL:
    691   1.2   thorpej 	case PTHREAD_MUTEX_ERRORCHECK:
    692   1.2   thorpej 	case PTHREAD_MUTEX_RECURSIVE:
    693  1.60  christos 		MUTEX_SET_TYPE(attr->ptma_private, type);
    694  1.60  christos 		return 0;
    695  1.60  christos 	default:
    696  1.60  christos 		return EINVAL;
    697  1.60  christos 	}
    698  1.60  christos }
    699  1.60  christos 
    700  1.60  christos int
    701  1.60  christos pthread_mutexattr_getprotocol(const pthread_mutexattr_t *attr, int*proto)
    702  1.60  christos {
    703  1.60  christos 
    704  1.60  christos 	pthread__error(EINVAL, "Invalid mutex attribute",
    705  1.60  christos 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    706  1.60  christos 
    707  1.60  christos 	*proto = MUTEX_GET_PROTOCOL(attr->ptma_private);
    708  1.60  christos 	return 0;
    709  1.60  christos }
    710  1.60  christos 
    711  1.60  christos int
    712  1.60  christos pthread_mutexattr_setprotocol(pthread_mutexattr_t* attr, int proto)
    713  1.60  christos {
    714  1.60  christos 
    715  1.60  christos 	pthread__error(EINVAL, "Invalid mutex attribute",
    716  1.60  christos 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    717  1.60  christos 
    718  1.60  christos 	switch (proto) {
    719  1.60  christos 	case PTHREAD_PRIO_NONE:
    720  1.60  christos 	case PTHREAD_PRIO_PROTECT:
    721  1.60  christos 		MUTEX_SET_PROTOCOL(attr->ptma_private, proto);
    722  1.44        ad 		return 0;
    723  1.60  christos 	case PTHREAD_PRIO_INHERIT:
    724  1.60  christos 		return ENOTSUP;
    725   1.2   thorpej 	default:
    726   1.2   thorpej 		return EINVAL;
    727   1.2   thorpej 	}
    728   1.2   thorpej }
    729   1.2   thorpej 
    730  1.60  christos int
    731  1.60  christos pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *attr, int *ceil)
    732  1.60  christos {
    733  1.60  christos 
    734  1.60  christos 	pthread__error(EINVAL, "Invalid mutex attribute",
    735  1.60  christos 		attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    736  1.60  christos 
    737  1.60  christos 	*ceil = MUTEX_GET_CEILING(attr->ptma_private);
    738  1.60  christos 	return 0;
    739  1.60  christos }
    740  1.60  christos 
    741  1.60  christos int
    742  1.60  christos pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, int ceil)
    743  1.60  christos {
    744  1.60  christos 
    745  1.60  christos 	pthread__error(EINVAL, "Invalid mutex attribute",
    746  1.60  christos 		attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    747  1.60  christos 
    748  1.60  christos 	if (ceil & ~0xff)
    749  1.60  christos 		return EINVAL;
    750  1.60  christos 
    751  1.60  christos 	MUTEX_SET_CEILING(attr->ptma_private, ceil);
    752  1.60  christos 	return 0;
    753  1.60  christos }
    754  1.60  christos 
    755  1.60  christos #ifdef _PTHREAD_PSHARED
    756  1.60  christos int
    757  1.60  christos pthread_mutexattr_getpshared(const pthread_mutexattr_t * __restrict attr,
    758  1.60  christos     int * __restrict pshared)
    759  1.60  christos {
    760  1.60  christos 
    761  1.60  christos 	*pshared = PTHREAD_PROCESS_PRIVATE;
    762  1.60  christos 	return 0;
    763  1.60  christos }
    764  1.60  christos 
    765  1.60  christos int
    766  1.60  christos pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
    767  1.60  christos {
    768  1.60  christos 
    769  1.60  christos 	switch(pshared) {
    770  1.60  christos 	case PTHREAD_PROCESS_PRIVATE:
    771  1.60  christos 		return 0;
    772  1.60  christos 	case PTHREAD_PROCESS_SHARED:
    773  1.60  christos 		return ENOSYS;
    774  1.60  christos 	}
    775  1.60  christos 	return EINVAL;
    776  1.60  christos }
    777  1.60  christos #endif
    778  1.60  christos 
    779  1.55      yamt /*
    780  1.55      yamt  * pthread__mutex_deferwake: try to defer unparking threads in self->pt_waiters
    781  1.55      yamt  *
    782  1.55      yamt  * In order to avoid unnecessary contention on the interlocking mutex,
    783  1.55      yamt  * we defer waking up threads until we unlock the mutex.  The threads will
    784  1.55      yamt  * be woken up when the calling thread (self) releases the first mutex with
    785  1.55      yamt  * MUTEX_DEFERRED_BIT set.  It likely be the mutex 'ptm', but no problem
    786  1.55      yamt  * even if it isn't.
    787  1.55      yamt  */
    788  1.55      yamt 
    789  1.50        ad void
    790  1.50        ad pthread__mutex_deferwake(pthread_t self, pthread_mutex_t *ptm)
    791  1.33        ad {
    792  1.33        ad 
    793  1.50        ad 	if (__predict_false(ptm == NULL ||
    794  1.50        ad 	    MUTEX_OWNER(ptm->ptm_owner) != (uintptr_t)self)) {
    795  1.50        ad 	    	(void)_lwp_unpark_all(self->pt_waiters, self->pt_nwaiters,
    796  1.50        ad 	    	    __UNVOLATILE(&ptm->ptm_waiters));
    797  1.50        ad 	    	self->pt_nwaiters = 0;
    798  1.50        ad 	} else {
    799  1.50        ad 		atomic_or_ulong((volatile unsigned long *)
    800  1.50        ad 		    (uintptr_t)&ptm->ptm_owner,
    801  1.50        ad 		    (unsigned long)MUTEX_DEFERRED_BIT);
    802  1.50        ad 	}
    803  1.33        ad }
    804  1.33        ad 
    805  1.39        ad int
    806  1.61     skrll pthread_mutex_getprioceiling(const pthread_mutex_t *ptm, int *ceil)
    807  1.60  christos {
    808  1.62     skrll 	*ceil = ptm->ptm_ceiling;
    809  1.60  christos 	return 0;
    810  1.60  christos }
    811  1.60  christos 
    812  1.60  christos int
    813  1.60  christos pthread_mutex_setprioceiling(pthread_mutex_t *ptm, int ceil, int *old_ceil)
    814  1.60  christos {
    815  1.60  christos 	int error;
    816  1.60  christos 
    817  1.60  christos 	error = pthread_mutex_lock(ptm);
    818  1.60  christos 	if (error == 0) {
    819  1.62     skrll 		*old_ceil = ptm->ptm_ceiling;
    820  1.60  christos 		/*check range*/
    821  1.62     skrll 		ptm->ptm_ceiling = ceil;
    822  1.60  christos 		pthread_mutex_unlock(ptm);
    823  1.60  christos 	}
    824  1.60  christos 	return error;
    825  1.60  christos }
    826  1.60  christos 
    827  1.60  christos int
    828  1.44        ad _pthread_mutex_held_np(pthread_mutex_t *ptm)
    829  1.39        ad {
    830  1.39        ad 
    831  1.44        ad 	return MUTEX_OWNER(ptm->ptm_owner) == (uintptr_t)pthread__self();
    832  1.39        ad }
    833  1.39        ad 
    834  1.39        ad pthread_t
    835  1.44        ad _pthread_mutex_owner_np(pthread_mutex_t *ptm)
    836  1.39        ad {
    837  1.39        ad 
    838  1.44        ad 	return (pthread_t)MUTEX_OWNER(ptm->ptm_owner);
    839  1.39        ad }
    840