Home | History | Annotate | Line # | Download | only in libpthread
pthread_mutex.c revision 1.80
      1  1.80        ad /*	$NetBSD: pthread_mutex.c,v 1.80 2020/06/10 22:45:15 ad Exp $	*/
      2   1.2   thorpej 
      3   1.2   thorpej /*-
      4  1.77        ad  * Copyright (c) 2001, 2003, 2006, 2007, 2008, 2020 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.80        ad __RCSID("$NetBSD: pthread_mutex.c,v 1.80 2020/06/10 22:45:15 ad 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_RECURSIVE_BIT		((uintptr_t)0x02)
     69  1.60  christos #define	MUTEX_PROTECT_BIT		((uintptr_t)0x08)
     70  1.60  christos #define	MUTEX_THREAD			((uintptr_t)~0x0f)
     71  1.44        ad 
     72  1.44        ad #define	MUTEX_RECURSIVE(x)		((uintptr_t)(x) & MUTEX_RECURSIVE_BIT)
     73  1.60  christos #define	MUTEX_PROTECT(x)		((uintptr_t)(x) & MUTEX_PROTECT_BIT)
     74  1.44        ad #define	MUTEX_OWNER(x)			((uintptr_t)(x) & MUTEX_THREAD)
     75  1.44        ad 
     76  1.60  christos #define	MUTEX_GET_TYPE(x)		\
     77  1.60  christos     ((int)(((uintptr_t)(x) & 0x000000ff) >> 0))
     78  1.60  christos #define	MUTEX_SET_TYPE(x, t) 		\
     79  1.60  christos     (x) = (void *)(((uintptr_t)(x) & ~0x000000ff) | ((t) << 0))
     80  1.60  christos #define	MUTEX_GET_PROTOCOL(x)		\
     81  1.60  christos     ((int)(((uintptr_t)(x) & 0x0000ff00) >> 8))
     82  1.60  christos #define	MUTEX_SET_PROTOCOL(x, p)	\
     83  1.60  christos     (x) = (void *)(((uintptr_t)(x) & ~0x0000ff00) | ((p) << 8))
     84  1.60  christos #define	MUTEX_GET_CEILING(x)		\
     85  1.60  christos     ((int)(((uintptr_t)(x) & 0x00ff0000) >> 16))
     86  1.60  christos #define	MUTEX_SET_CEILING(x, c)	\
     87  1.60  christos     (x) = (void *)(((uintptr_t)(x) & ~0x00ff0000) | ((c) << 16))
     88  1.60  christos 
     89  1.44        ad #if __GNUC_PREREQ__(3, 0)
     90  1.44        ad #define	NOINLINE		__attribute ((noinline))
     91  1.44        ad #else
     92  1.44        ad #define	NOINLINE		/* nothing */
     93  1.44        ad #endif
     94  1.44        ad 
     95  1.80        ad struct waiter {
     96  1.80        ad 	struct waiter	*volatile next;
     97  1.80        ad 	lwpid_t		volatile lid;
     98  1.80        ad };
     99  1.80        ad 
    100  1.80        ad static void	pthread__mutex_wakeup(pthread_t, struct pthread__waiter *);
    101  1.60  christos static int	pthread__mutex_lock_slow(pthread_mutex_t *,
    102  1.60  christos     const struct timespec *);
    103  1.44        ad static void	pthread__mutex_pause(void);
    104   1.2   thorpej 
    105  1.39        ad int		_pthread_mutex_held_np(pthread_mutex_t *);
    106  1.39        ad pthread_t	_pthread_mutex_owner_np(pthread_mutex_t *);
    107  1.39        ad 
    108  1.39        ad __weak_alias(pthread_mutex_held_np,_pthread_mutex_held_np)
    109  1.39        ad __weak_alias(pthread_mutex_owner_np,_pthread_mutex_owner_np)
    110  1.39        ad 
    111   1.2   thorpej __strong_alias(__libc_mutex_init,pthread_mutex_init)
    112   1.2   thorpej __strong_alias(__libc_mutex_lock,pthread_mutex_lock)
    113   1.2   thorpej __strong_alias(__libc_mutex_trylock,pthread_mutex_trylock)
    114   1.2   thorpej __strong_alias(__libc_mutex_unlock,pthread_mutex_unlock)
    115   1.2   thorpej __strong_alias(__libc_mutex_destroy,pthread_mutex_destroy)
    116   1.4   thorpej 
    117   1.4   thorpej __strong_alias(__libc_mutexattr_init,pthread_mutexattr_init)
    118   1.4   thorpej __strong_alias(__libc_mutexattr_destroy,pthread_mutexattr_destroy)
    119   1.5   thorpej __strong_alias(__libc_mutexattr_settype,pthread_mutexattr_settype)
    120   1.2   thorpej 
    121   1.2   thorpej int
    122  1.44        ad pthread_mutex_init(pthread_mutex_t *ptm, const pthread_mutexattr_t *attr)
    123   1.2   thorpej {
    124  1.60  christos 	uintptr_t type, proto, val, ceil;
    125   1.2   thorpej 
    126  1.76     kamil #if 0
    127  1.65  christos 	/*
    128  1.65  christos 	 * Always initialize the mutex structure, maybe be used later
    129  1.65  christos 	 * and the cost should be minimal.
    130  1.65  christos 	 */
    131  1.56  christos 	if (__predict_false(__uselibcstub))
    132  1.56  christos 		return __libc_mutex_init_stub(ptm, attr);
    133  1.76     kamil #endif
    134  1.56  christos 
    135  1.72     kamil 	pthread__error(EINVAL, "Invalid mutes attribute",
    136  1.72     kamil 	    attr == NULL || attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    137  1.72     kamil 
    138  1.60  christos 	if (attr == NULL) {
    139  1.44        ad 		type = PTHREAD_MUTEX_NORMAL;
    140  1.60  christos 		proto = PTHREAD_PRIO_NONE;
    141  1.60  christos 		ceil = 0;
    142  1.60  christos 	} else {
    143  1.60  christos 		val = (uintptr_t)attr->ptma_private;
    144   1.2   thorpej 
    145  1.60  christos 		type = MUTEX_GET_TYPE(val);
    146  1.60  christos 		proto = MUTEX_GET_PROTOCOL(val);
    147  1.60  christos 		ceil = MUTEX_GET_CEILING(val);
    148  1.60  christos 	}
    149  1.44        ad 	switch (type) {
    150  1.44        ad 	case PTHREAD_MUTEX_ERRORCHECK:
    151  1.51      matt 		__cpu_simple_lock_set(&ptm->ptm_errorcheck);
    152  1.44        ad 		ptm->ptm_owner = NULL;
    153  1.44        ad 		break;
    154  1.44        ad 	case PTHREAD_MUTEX_RECURSIVE:
    155  1.51      matt 		__cpu_simple_lock_clear(&ptm->ptm_errorcheck);
    156  1.44        ad 		ptm->ptm_owner = (void *)MUTEX_RECURSIVE_BIT;
    157  1.44        ad 		break;
    158  1.44        ad 	default:
    159  1.51      matt 		__cpu_simple_lock_clear(&ptm->ptm_errorcheck);
    160  1.44        ad 		ptm->ptm_owner = NULL;
    161  1.44        ad 		break;
    162   1.2   thorpej 	}
    163  1.60  christos 	switch (proto) {
    164  1.60  christos 	case PTHREAD_PRIO_PROTECT:
    165  1.60  christos 		val = (uintptr_t)ptm->ptm_owner;
    166  1.60  christos 		val |= MUTEX_PROTECT_BIT;
    167  1.60  christos 		ptm->ptm_owner = (void *)val;
    168  1.60  christos 		break;
    169   1.2   thorpej 
    170  1.60  christos 	}
    171  1.44        ad 	ptm->ptm_magic = _PT_MUTEX_MAGIC;
    172  1.44        ad 	ptm->ptm_waiters = NULL;
    173  1.45        ad 	ptm->ptm_recursed = 0;
    174  1.60  christos 	ptm->ptm_ceiling = (unsigned char)ceil;
    175   1.2   thorpej 
    176   1.2   thorpej 	return 0;
    177   1.2   thorpej }
    178   1.2   thorpej 
    179   1.2   thorpej int
    180  1.44        ad pthread_mutex_destroy(pthread_mutex_t *ptm)
    181   1.2   thorpej {
    182   1.2   thorpej 
    183  1.56  christos 	if (__predict_false(__uselibcstub))
    184  1.56  christos 		return __libc_mutex_destroy_stub(ptm);
    185  1.56  christos 
    186  1.14   nathanw 	pthread__error(EINVAL, "Invalid mutex",
    187  1.44        ad 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    188  1.14   nathanw 	pthread__error(EBUSY, "Destroying locked mutex",
    189  1.44        ad 	    MUTEX_OWNER(ptm->ptm_owner) == 0);
    190   1.2   thorpej 
    191  1.44        ad 	ptm->ptm_magic = _PT_MUTEX_DEAD;
    192   1.2   thorpej 	return 0;
    193   1.2   thorpej }
    194   1.2   thorpej 
    195   1.2   thorpej int
    196  1.44        ad pthread_mutex_lock(pthread_mutex_t *ptm)
    197   1.2   thorpej {
    198  1.27        ad 	pthread_t self;
    199  1.44        ad 	void *val;
    200   1.2   thorpej 
    201  1.56  christos 	if (__predict_false(__uselibcstub))
    202  1.56  christos 		return __libc_mutex_lock_stub(ptm);
    203  1.56  christos 
    204  1.70     kamil 	pthread__error(EINVAL, "Invalid mutex",
    205  1.70     kamil 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    206  1.70     kamil 
    207  1.27        ad 	self = pthread__self();
    208  1.44        ad 	val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
    209  1.44        ad 	if (__predict_true(val == NULL)) {
    210  1.44        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    211  1.44        ad 		membar_enter();
    212  1.44        ad #endif
    213  1.44        ad 		return 0;
    214   1.2   thorpej 	}
    215  1.60  christos 	return pthread__mutex_lock_slow(ptm, NULL);
    216  1.60  christos }
    217  1.60  christos 
    218  1.60  christos int
    219  1.60  christos pthread_mutex_timedlock(pthread_mutex_t* ptm, const struct timespec *ts)
    220  1.60  christos {
    221  1.60  christos 	pthread_t self;
    222  1.60  christos 	void *val;
    223  1.60  christos 
    224  1.70     kamil 	pthread__error(EINVAL, "Invalid mutex",
    225  1.70     kamil 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    226  1.70     kamil 
    227  1.60  christos 	self = pthread__self();
    228  1.60  christos 	val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
    229  1.60  christos 	if (__predict_true(val == NULL)) {
    230  1.60  christos #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    231  1.60  christos 		membar_enter();
    232  1.60  christos #endif
    233  1.60  christos 		return 0;
    234  1.60  christos 	}
    235  1.60  christos 	return pthread__mutex_lock_slow(ptm, ts);
    236  1.44        ad }
    237   1.2   thorpej 
    238  1.44        ad /* We want function call overhead. */
    239  1.44        ad NOINLINE static void
    240  1.44        ad pthread__mutex_pause(void)
    241  1.44        ad {
    242   1.2   thorpej 
    243  1.44        ad 	pthread__smt_pause();
    244   1.2   thorpej }
    245   1.2   thorpej 
    246  1.44        ad /*
    247  1.44        ad  * Spin while the holder is running.  'lwpctl' gives us the true
    248  1.66        ad  * status of the thread.
    249  1.44        ad  */
    250  1.44        ad NOINLINE static void *
    251  1.44        ad pthread__mutex_spin(pthread_mutex_t *ptm, pthread_t owner)
    252  1.44        ad {
    253  1.44        ad 	pthread_t thread;
    254  1.44        ad 	unsigned int count, i;
    255  1.44        ad 
    256  1.44        ad 	for (count = 2;; owner = ptm->ptm_owner) {
    257  1.44        ad 		thread = (pthread_t)MUTEX_OWNER(owner);
    258  1.44        ad 		if (thread == NULL)
    259  1.44        ad 			break;
    260  1.66        ad 		if (thread->pt_lwpctl->lc_curcpu == LWPCTL_CPU_NONE)
    261  1.44        ad 			break;
    262  1.44        ad 		if (count < 128)
    263  1.44        ad 			count += count;
    264  1.44        ad 		for (i = count; i != 0; i--)
    265  1.44        ad 			pthread__mutex_pause();
    266  1.44        ad 	}
    267   1.2   thorpej 
    268  1.44        ad 	return owner;
    269  1.44        ad }
    270  1.44        ad 
    271  1.44        ad NOINLINE static int
    272  1.60  christos pthread__mutex_lock_slow(pthread_mutex_t *ptm, const struct timespec *ts)
    273   1.2   thorpej {
    274  1.80        ad 	void *newval, *owner, *next;
    275  1.80        ad 	struct waiter waiter;
    276  1.44        ad 	pthread_t self;
    277  1.57  christos 	int serrno;
    278  1.60  christos 	int error;
    279   1.2   thorpej 
    280  1.44        ad 	owner = ptm->ptm_owner;
    281  1.44        ad 	self = pthread__self();
    282  1.77        ad 	serrno = errno;
    283  1.77        ad 
    284  1.80        ad 	pthread__assert(self->pt_lid != 0);
    285  1.13   nathanw 
    286  1.44        ad 	/* Recursive or errorcheck? */
    287  1.44        ad 	if (MUTEX_OWNER(owner) == (uintptr_t)self) {
    288  1.44        ad 		if (MUTEX_RECURSIVE(owner)) {
    289  1.45        ad 			if (ptm->ptm_recursed == INT_MAX)
    290  1.44        ad 				return EAGAIN;
    291  1.45        ad 			ptm->ptm_recursed++;
    292  1.44        ad 			return 0;
    293  1.29        ad 		}
    294  1.51      matt 		if (__SIMPLELOCK_LOCKED_P(&ptm->ptm_errorcheck))
    295  1.44        ad 			return EDEADLK;
    296  1.44        ad 	}
    297  1.29        ad 
    298  1.60  christos 	/* priority protect */
    299  1.60  christos 	if (MUTEX_PROTECT(owner) && _sched_protect(ptm->ptm_ceiling) == -1) {
    300  1.77        ad 		error = errno;
    301  1.77        ad 		errno = serrno;
    302  1.77        ad 		return error;
    303  1.60  christos 	}
    304  1.44        ad 
    305  1.77        ad 	for (;;) {
    306  1.44        ad 		/* If it has become free, try to acquire it again. */
    307  1.44        ad 		if (MUTEX_OWNER(owner) == 0) {
    308  1.77        ad 			newval = (void *)((uintptr_t)self | (uintptr_t)owner);
    309  1.77        ad 			next = atomic_cas_ptr(&ptm->ptm_owner, owner, newval);
    310  1.77        ad 			if (__predict_false(next != owner)) {
    311  1.77        ad 				owner = next;
    312  1.77        ad 				continue;
    313  1.77        ad 			}
    314  1.77        ad 			errno = serrno;
    315  1.44        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    316  1.77        ad 			membar_enter();
    317  1.44        ad #endif
    318  1.77        ad 			return 0;
    319  1.77        ad 		} else if (MUTEX_OWNER(owner) != (uintptr_t)self) {
    320  1.77        ad 			/* Spin while the owner is running. */
    321  1.77        ad 			owner = pthread__mutex_spin(ptm, owner);
    322  1.77        ad 			if (MUTEX_OWNER(owner) == 0) {
    323  1.77        ad 				continue;
    324  1.77        ad 			}
    325  1.44        ad 		}
    326  1.21       chs 
    327   1.2   thorpej 		/*
    328  1.44        ad 		 * Nope, still held.  Add thread to the list of waiters.
    329  1.80        ad 		 * Issue a memory barrier to ensure stores to 'waiter'
    330  1.80        ad 		 * are visible before we enter the list.
    331   1.2   thorpej 		 */
    332  1.80        ad 		waiter.next = ptm->ptm_waiters;
    333  1.80        ad 		waiter.lid = self->pt_lid;
    334  1.77        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    335  1.80        ad 		membar_producer();
    336  1.77        ad #endif
    337  1.80        ad 		next = atomic_cas_ptr(&ptm->ptm_waiters, waiter.next, &waiter);
    338  1.80        ad 		if (next != waiter.next) {
    339  1.80        ad 			owner = ptm->ptm_owner;
    340  1.80        ad 			continue;
    341  1.44        ad 		}
    342  1.80        ad 
    343  1.77        ad 		/*
    344  1.80        ad 		 * If the mutex has become free since entering self onto the
    345  1.80        ad 		 * waiters list, need to wake everybody up (including self)
    346  1.80        ad 		 * and retry.  It's possible to race with an unlocking
    347  1.80        ad 		 * thread, so self may have already been awoken.
    348  1.77        ad 		 */
    349  1.77        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    350  1.80        ad 		membar_enter();
    351  1.77        ad #endif
    352  1.80        ad 		if (MUTEX_OWNER(ptm->ptm_owner) == 0) {
    353  1.80        ad 			pthread__mutex_wakeup(self,
    354  1.80        ad 			    atomic_swap_ptr(&ptm->ptm_waiters, NULL));
    355  1.66        ad 		}
    356  1.21       chs 
    357  1.29        ad 		/*
    358  1.77        ad 		 * We must not proceed until told that we are no longer
    359  1.80        ad 		 * waiting (via waiter.lid being set to zero).  Otherwise
    360  1.80        ad 		 * it's unsafe to re-enter "waiter" onto the waiters list.
    361  1.29        ad 		 */
    362  1.80        ad 		while (waiter.lid != 0) {
    363  1.64       kre 			error = _lwp_park(CLOCK_REALTIME, TIMER_ABSTIME,
    364  1.80        ad 			    __UNCONST(ts), 0, NULL, NULL);
    365  1.78        ad 			if (error < 0 && errno == ETIMEDOUT) {
    366  1.78        ad 				/* Remove self from waiters list */
    367  1.80        ad 				pthread__mutex_wakeup(self,
    368  1.80        ad 				    atomic_swap_ptr(&ptm->ptm_waiters, NULL));
    369  1.79        ad 
    370  1.79        ad 				/*
    371  1.79        ad 				 * Might have raced with another thread to
    372  1.79        ad 				 * do the wakeup.  In any case there will be
    373  1.79        ad 				 * a wakeup for sure.  Eat it and wait for
    374  1.80        ad 				 * waiter.lid to clear.
    375  1.79        ad 				 */
    376  1.80        ad 				while (waiter.lid != 0) {
    377  1.80        ad 					(void)_lwp_park(CLOCK_MONOTONIC, 0,
    378  1.80        ad 					    NULL, 0, NULL, NULL);
    379  1.80        ad 				}
    380  1.79        ad 
    381  1.78        ad 				/* Priority protect */
    382  1.60  christos 				if (MUTEX_PROTECT(owner))
    383  1.60  christos 					(void)_sched_protect(-1);
    384  1.77        ad 				errno = serrno;
    385  1.60  christos 				return ETIMEDOUT;
    386  1.60  christos 			}
    387  1.80        ad 		}
    388  1.77        ad 		owner = ptm->ptm_owner;
    389   1.2   thorpej 	}
    390   1.2   thorpej }
    391   1.2   thorpej 
    392   1.2   thorpej int
    393  1.44        ad pthread_mutex_trylock(pthread_mutex_t *ptm)
    394   1.2   thorpej {
    395  1.27        ad 	pthread_t self;
    396  1.46        ad 	void *val, *new, *next;
    397   1.2   thorpej 
    398  1.56  christos 	if (__predict_false(__uselibcstub))
    399  1.56  christos 		return __libc_mutex_trylock_stub(ptm);
    400  1.56  christos 
    401  1.70     kamil 	pthread__error(EINVAL, "Invalid mutex",
    402  1.70     kamil 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    403  1.70     kamil 
    404  1.27        ad 	self = pthread__self();
    405  1.44        ad 	val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
    406  1.44        ad 	if (__predict_true(val == NULL)) {
    407  1.44        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    408  1.44        ad 		membar_enter();
    409  1.44        ad #endif
    410  1.44        ad 		return 0;
    411  1.44        ad 	}
    412  1.27        ad 
    413  1.46        ad 	if (MUTEX_RECURSIVE(val)) {
    414  1.46        ad 		if (MUTEX_OWNER(val) == 0) {
    415  1.46        ad 			new = (void *)((uintptr_t)self | (uintptr_t)val);
    416  1.46        ad 			next = atomic_cas_ptr(&ptm->ptm_owner, val, new);
    417  1.46        ad 			if (__predict_true(next == val)) {
    418  1.46        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    419  1.46        ad 				membar_enter();
    420  1.46        ad #endif
    421  1.46        ad 				return 0;
    422  1.46        ad 			}
    423  1.46        ad 		}
    424  1.46        ad 		if (MUTEX_OWNER(val) == (uintptr_t)self) {
    425  1.46        ad 			if (ptm->ptm_recursed == INT_MAX)
    426  1.46        ad 				return EAGAIN;
    427  1.46        ad 			ptm->ptm_recursed++;
    428  1.46        ad 			return 0;
    429  1.46        ad 		}
    430   1.2   thorpej 	}
    431   1.2   thorpej 
    432  1.44        ad 	return EBUSY;
    433   1.2   thorpej }
    434   1.2   thorpej 
    435   1.2   thorpej int
    436  1.44        ad pthread_mutex_unlock(pthread_mutex_t *ptm)
    437   1.2   thorpej {
    438  1.27        ad 	pthread_t self;
    439  1.80        ad 	void *val, *newval;
    440  1.77        ad 	int error;
    441  1.44        ad 
    442  1.56  christos 	if (__predict_false(__uselibcstub))
    443  1.56  christos 		return __libc_mutex_unlock_stub(ptm);
    444  1.56  christos 
    445  1.70     kamil 	pthread__error(EINVAL, "Invalid mutex",
    446  1.70     kamil 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    447  1.70     kamil 
    448  1.44        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    449  1.44        ad 	membar_exit();
    450  1.44        ad #endif
    451  1.77        ad 	error = 0;
    452  1.44        ad 	self = pthread__self();
    453  1.80        ad 	newval = NULL;
    454  1.44        ad 
    455  1.80        ad 	val = atomic_cas_ptr(&ptm->ptm_owner, self, newval);
    456  1.77        ad 	if (__predict_false(val != self)) {
    457  1.77        ad 		bool weown = (MUTEX_OWNER(val) == (uintptr_t)self);
    458  1.77        ad 		if (__SIMPLELOCK_LOCKED_P(&ptm->ptm_errorcheck)) {
    459  1.77        ad 			if (!weown) {
    460  1.77        ad 				error = EPERM;
    461  1.77        ad 				newval = val;
    462  1.77        ad 			} else {
    463  1.77        ad 				newval = NULL;
    464  1.77        ad 			}
    465  1.77        ad 		} else if (MUTEX_RECURSIVE(val)) {
    466  1.77        ad 			if (!weown) {
    467  1.77        ad 				error = EPERM;
    468  1.77        ad 				newval = val;
    469  1.77        ad 			} else if (ptm->ptm_recursed) {
    470  1.77        ad 				ptm->ptm_recursed--;
    471  1.77        ad 				newval = val;
    472  1.77        ad 			} else {
    473  1.77        ad 				newval = (pthread_t)MUTEX_RECURSIVE_BIT;
    474  1.77        ad 			}
    475  1.44        ad 		} else {
    476  1.77        ad 			pthread__error(EPERM,
    477  1.77        ad 			    "Unlocking unlocked mutex", (val != NULL));
    478  1.77        ad 			pthread__error(EPERM,
    479  1.77        ad 			    "Unlocking mutex owned by another thread", weown);
    480  1.77        ad 			newval = NULL;
    481  1.44        ad 		}
    482  1.77        ad 
    483  1.77        ad 		/*
    484  1.77        ad 		 * Release the mutex.  If there appear to be waiters, then
    485  1.77        ad 		 * wake them up.
    486  1.77        ad 		 */
    487  1.77        ad 		if (newval != val) {
    488  1.77        ad 			val = atomic_swap_ptr(&ptm->ptm_owner, newval);
    489  1.77        ad 			if (__predict_false(MUTEX_PROTECT(val))) {
    490  1.77        ad 				/* restore elevated priority */
    491  1.77        ad 				(void)_sched_protect(-1);
    492  1.77        ad 			}
    493  1.44        ad 		}
    494  1.44        ad 	}
    495   1.2   thorpej 
    496   1.2   thorpej 	/*
    497  1.77        ad 	 * Finally, wake any waiters and return.
    498   1.2   thorpej 	 */
    499  1.77        ad #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    500  1.77        ad 	membar_enter();
    501  1.77        ad #endif
    502  1.80        ad 	if (MUTEX_OWNER(newval) == 0 && ptm->ptm_waiters != NULL) {
    503  1.80        ad 		pthread__mutex_wakeup(self,
    504  1.80        ad 		    atomic_swap_ptr(&ptm->ptm_waiters, NULL));
    505   1.2   thorpej 	}
    506  1.44        ad 	return error;
    507  1.44        ad }
    508  1.44        ad 
    509  1.55      yamt /*
    510  1.55      yamt  * pthread__mutex_wakeup: unpark threads waiting for us
    511  1.55      yamt  */
    512  1.55      yamt 
    513  1.44        ad static void
    514  1.80        ad pthread__mutex_wakeup(pthread_t self, struct pthread__waiter *cur)
    515  1.44        ad {
    516  1.80        ad 	lwpid_t lids[PTHREAD__UNPARK_MAX];
    517  1.80        ad 	const size_t mlid = pthread__unpark_max;
    518  1.80        ad 	struct pthread__waiter *next;
    519  1.80        ad 	size_t nlid;
    520  1.44        ad 
    521  1.77        ad 	/*
    522  1.77        ad 	 * Pull waiters from the queue and add to our list.  Use a memory
    523  1.80        ad 	 * barrier to ensure that we safely read the value of waiter->next
    524  1.80        ad 	 * before the awoken thread sees waiter->lid being cleared.
    525  1.77        ad 	 */
    526  1.80        ad 	membar_datadep_consumer(); /* for alpha */
    527  1.80        ad 	for (nlid = 0; cur != NULL; cur = next) {
    528  1.80        ad 		if (nlid == mlid) {
    529  1.80        ad 			(void)_lwp_unpark_all(lids, nlid, NULL);
    530  1.80        ad 			nlid = 0;
    531  1.44        ad 		}
    532  1.80        ad 		next = cur->next;
    533  1.80        ad 		pthread__assert(cur->lid != 0);
    534  1.80        ad 		lids[nlid++] = cur->lid;
    535  1.78        ad 		membar_sync();
    536  1.80        ad 		cur->lid = 0;
    537  1.80        ad 		/* No longer safe to touch 'cur' */
    538  1.80        ad 	}
    539  1.80        ad 	if (nlid == 1) {
    540  1.80        ad 		(void)_lwp_unpark(lids[0], NULL);
    541  1.80        ad 	} else if (nlid > 1) {
    542  1.80        ad 		(void)_lwp_unpark_all(lids, nlid, NULL);
    543  1.44        ad 	}
    544   1.2   thorpej }
    545  1.55      yamt 
    546   1.2   thorpej int
    547   1.2   thorpej pthread_mutexattr_init(pthread_mutexattr_t *attr)
    548   1.2   thorpej {
    549  1.76     kamil #if 0
    550  1.56  christos 	if (__predict_false(__uselibcstub))
    551  1.56  christos 		return __libc_mutexattr_init_stub(attr);
    552  1.76     kamil #endif
    553   1.2   thorpej 
    554   1.2   thorpej 	attr->ptma_magic = _PT_MUTEXATTR_MAGIC;
    555  1.44        ad 	attr->ptma_private = (void *)PTHREAD_MUTEX_DEFAULT;
    556   1.2   thorpej 	return 0;
    557   1.2   thorpej }
    558   1.2   thorpej 
    559   1.2   thorpej int
    560   1.2   thorpej pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
    561   1.2   thorpej {
    562  1.56  christos 	if (__predict_false(__uselibcstub))
    563  1.56  christos 		return __libc_mutexattr_destroy_stub(attr);
    564   1.2   thorpej 
    565  1.14   nathanw 	pthread__error(EINVAL, "Invalid mutex attribute",
    566  1.14   nathanw 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    567   1.2   thorpej 
    568  1.69     kamil 	attr->ptma_magic = _PT_MUTEXATTR_DEAD;
    569  1.69     kamil 
    570   1.2   thorpej 	return 0;
    571   1.2   thorpej }
    572   1.2   thorpej 
    573   1.2   thorpej int
    574   1.2   thorpej pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *typep)
    575   1.2   thorpej {
    576  1.60  christos 
    577  1.14   nathanw 	pthread__error(EINVAL, "Invalid mutex attribute",
    578  1.14   nathanw 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    579   1.2   thorpej 
    580  1.60  christos 	*typep = MUTEX_GET_TYPE(attr->ptma_private);
    581   1.2   thorpej 	return 0;
    582   1.2   thorpej }
    583   1.2   thorpej 
    584   1.2   thorpej int
    585   1.2   thorpej pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
    586   1.2   thorpej {
    587  1.60  christos 
    588  1.56  christos 	if (__predict_false(__uselibcstub))
    589  1.56  christos 		return __libc_mutexattr_settype_stub(attr, type);
    590   1.2   thorpej 
    591  1.14   nathanw 	pthread__error(EINVAL, "Invalid mutex attribute",
    592  1.14   nathanw 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    593  1.13   nathanw 
    594   1.2   thorpej 	switch (type) {
    595   1.2   thorpej 	case PTHREAD_MUTEX_NORMAL:
    596   1.2   thorpej 	case PTHREAD_MUTEX_ERRORCHECK:
    597   1.2   thorpej 	case PTHREAD_MUTEX_RECURSIVE:
    598  1.60  christos 		MUTEX_SET_TYPE(attr->ptma_private, type);
    599  1.60  christos 		return 0;
    600  1.60  christos 	default:
    601  1.60  christos 		return EINVAL;
    602  1.60  christos 	}
    603  1.60  christos }
    604  1.60  christos 
    605  1.60  christos int
    606  1.60  christos pthread_mutexattr_getprotocol(const pthread_mutexattr_t *attr, int*proto)
    607  1.60  christos {
    608  1.60  christos 
    609  1.60  christos 	pthread__error(EINVAL, "Invalid mutex attribute",
    610  1.60  christos 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    611  1.60  christos 
    612  1.60  christos 	*proto = MUTEX_GET_PROTOCOL(attr->ptma_private);
    613  1.60  christos 	return 0;
    614  1.60  christos }
    615  1.60  christos 
    616  1.60  christos int
    617  1.60  christos pthread_mutexattr_setprotocol(pthread_mutexattr_t* attr, int proto)
    618  1.60  christos {
    619  1.60  christos 
    620  1.60  christos 	pthread__error(EINVAL, "Invalid mutex attribute",
    621  1.60  christos 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    622  1.60  christos 
    623  1.60  christos 	switch (proto) {
    624  1.60  christos 	case PTHREAD_PRIO_NONE:
    625  1.60  christos 	case PTHREAD_PRIO_PROTECT:
    626  1.60  christos 		MUTEX_SET_PROTOCOL(attr->ptma_private, proto);
    627  1.44        ad 		return 0;
    628  1.60  christos 	case PTHREAD_PRIO_INHERIT:
    629  1.60  christos 		return ENOTSUP;
    630   1.2   thorpej 	default:
    631   1.2   thorpej 		return EINVAL;
    632   1.2   thorpej 	}
    633   1.2   thorpej }
    634   1.2   thorpej 
    635  1.60  christos int
    636  1.60  christos pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *attr, int *ceil)
    637  1.60  christos {
    638  1.60  christos 
    639  1.60  christos 	pthread__error(EINVAL, "Invalid mutex attribute",
    640  1.60  christos 		attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    641  1.60  christos 
    642  1.60  christos 	*ceil = MUTEX_GET_CEILING(attr->ptma_private);
    643  1.60  christos 	return 0;
    644  1.60  christos }
    645  1.60  christos 
    646  1.60  christos int
    647  1.60  christos pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, int ceil)
    648  1.60  christos {
    649  1.60  christos 
    650  1.60  christos 	pthread__error(EINVAL, "Invalid mutex attribute",
    651  1.60  christos 		attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    652  1.60  christos 
    653  1.60  christos 	if (ceil & ~0xff)
    654  1.60  christos 		return EINVAL;
    655  1.60  christos 
    656  1.60  christos 	MUTEX_SET_CEILING(attr->ptma_private, ceil);
    657  1.60  christos 	return 0;
    658  1.60  christos }
    659  1.60  christos 
    660  1.60  christos #ifdef _PTHREAD_PSHARED
    661  1.60  christos int
    662  1.60  christos pthread_mutexattr_getpshared(const pthread_mutexattr_t * __restrict attr,
    663  1.60  christos     int * __restrict pshared)
    664  1.60  christos {
    665  1.60  christos 
    666  1.70     kamil 	pthread__error(EINVAL, "Invalid mutex attribute",
    667  1.70     kamil 		attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    668  1.70     kamil 
    669  1.60  christos 	*pshared = PTHREAD_PROCESS_PRIVATE;
    670  1.60  christos 	return 0;
    671  1.60  christos }
    672  1.60  christos 
    673  1.60  christos int
    674  1.60  christos pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
    675  1.60  christos {
    676  1.60  christos 
    677  1.70     kamil 	pthread__error(EINVAL, "Invalid mutex attribute",
    678  1.70     kamil 		attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    679  1.70     kamil 
    680  1.60  christos 	switch(pshared) {
    681  1.60  christos 	case PTHREAD_PROCESS_PRIVATE:
    682  1.60  christos 		return 0;
    683  1.60  christos 	case PTHREAD_PROCESS_SHARED:
    684  1.60  christos 		return ENOSYS;
    685  1.60  christos 	}
    686  1.60  christos 	return EINVAL;
    687  1.60  christos }
    688  1.60  christos #endif
    689  1.60  christos 
    690  1.55      yamt /*
    691  1.77        ad  * In order to avoid unnecessary contention on interlocking mutexes, we try
    692  1.77        ad  * to defer waking up threads until we unlock the mutex.  The threads will
    693  1.80        ad  * be woken up when the calling thread (self) releases the mutex.
    694  1.55      yamt  */
    695  1.50        ad void
    696  1.80        ad pthread__mutex_deferwake(pthread_t self, pthread_mutex_t *ptm,
    697  1.80        ad     struct pthread__waiter *head)
    698  1.33        ad {
    699  1.80        ad 	struct pthread__waiter *tail, *n, *o;
    700  1.80        ad 
    701  1.80        ad 	pthread__assert(head != NULL);
    702  1.33        ad 
    703  1.50        ad 	if (__predict_false(ptm == NULL ||
    704  1.50        ad 	    MUTEX_OWNER(ptm->ptm_owner) != (uintptr_t)self)) {
    705  1.80        ad 	    	pthread__mutex_wakeup(self, head);
    706  1.80        ad 	    	return;
    707  1.80        ad 	}
    708  1.80        ad 
    709  1.80        ad 	/* This is easy if no existing waiters on mutex. */
    710  1.80        ad 	if (atomic_cas_ptr(&ptm->ptm_waiters, NULL, head) == NULL) {
    711  1.80        ad 		return;
    712  1.80        ad 	}
    713  1.80        ad 
    714  1.80        ad 	/* Oops need to append.  Find the tail of the new queue. */
    715  1.80        ad 	for (tail = head; tail->next != NULL; tail = tail->next) {
    716  1.80        ad 		/* nothing */
    717  1.80        ad 	}
    718  1.80        ad 
    719  1.80        ad 	/* Append atomically. */
    720  1.80        ad 	for (o = ptm->ptm_waiters;; o = n) {
    721  1.80        ad 		tail->next = o;
    722  1.80        ad 		n = atomic_cas_ptr(&ptm->ptm_waiters, o, head);
    723  1.80        ad 		if (__predict_true(n == o)) {
    724  1.80        ad 			break;
    725  1.80        ad 		}
    726  1.50        ad 	}
    727  1.33        ad }
    728  1.33        ad 
    729  1.39        ad int
    730  1.61     skrll pthread_mutex_getprioceiling(const pthread_mutex_t *ptm, int *ceil)
    731  1.60  christos {
    732  1.70     kamil 
    733  1.70     kamil 	pthread__error(EINVAL, "Invalid mutex",
    734  1.70     kamil 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    735  1.70     kamil 
    736  1.62     skrll 	*ceil = ptm->ptm_ceiling;
    737  1.60  christos 	return 0;
    738  1.60  christos }
    739  1.60  christos 
    740  1.60  christos int
    741  1.60  christos pthread_mutex_setprioceiling(pthread_mutex_t *ptm, int ceil, int *old_ceil)
    742  1.60  christos {
    743  1.60  christos 	int error;
    744  1.60  christos 
    745  1.70     kamil 	pthread__error(EINVAL, "Invalid mutex",
    746  1.70     kamil 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    747  1.70     kamil 
    748  1.60  christos 	error = pthread_mutex_lock(ptm);
    749  1.60  christos 	if (error == 0) {
    750  1.62     skrll 		*old_ceil = ptm->ptm_ceiling;
    751  1.60  christos 		/*check range*/
    752  1.62     skrll 		ptm->ptm_ceiling = ceil;
    753  1.60  christos 		pthread_mutex_unlock(ptm);
    754  1.60  christos 	}
    755  1.60  christos 	return error;
    756  1.60  christos }
    757  1.60  christos 
    758  1.60  christos int
    759  1.44        ad _pthread_mutex_held_np(pthread_mutex_t *ptm)
    760  1.39        ad {
    761  1.39        ad 
    762  1.44        ad 	return MUTEX_OWNER(ptm->ptm_owner) == (uintptr_t)pthread__self();
    763  1.39        ad }
    764  1.39        ad 
    765  1.39        ad pthread_t
    766  1.44        ad _pthread_mutex_owner_np(pthread_mutex_t *ptm)
    767  1.39        ad {
    768  1.39        ad 
    769  1.44        ad 	return (pthread_t)MUTEX_OWNER(ptm->ptm_owner);
    770  1.39        ad }
    771