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