Home | History | Annotate | Line # | Download | only in libpthread
pthread_mutex.c revision 1.66
      1 /*	$NetBSD: pthread_mutex.c,v 1.66 2020/01/13 18:22:56 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2001, 2003, 2006, 2007, 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Nathan J. Williams, by Jason R. Thorpe, and by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     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.66 2020/01/13 18:22:56 ad 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 0
    126 	/*
    127 	 * Always initialize the mutex structure, maybe be used later
    128 	 * and the cost should be minimal.
    129 	 */
    130 	if (__predict_false(__uselibcstub))
    131 		return __libc_mutex_init_stub(ptm, attr);
    132 #endif
    133 
    134 	if (attr == NULL) {
    135 		type = PTHREAD_MUTEX_NORMAL;
    136 		proto = PTHREAD_PRIO_NONE;
    137 		ceil = 0;
    138 	} else {
    139 		val = (uintptr_t)attr->ptma_private;
    140 
    141 		type = MUTEX_GET_TYPE(val);
    142 		proto = MUTEX_GET_PROTOCOL(val);
    143 		ceil = MUTEX_GET_CEILING(val);
    144 	}
    145 	switch (type) {
    146 	case PTHREAD_MUTEX_ERRORCHECK:
    147 		__cpu_simple_lock_set(&ptm->ptm_errorcheck);
    148 		ptm->ptm_owner = NULL;
    149 		break;
    150 	case PTHREAD_MUTEX_RECURSIVE:
    151 		__cpu_simple_lock_clear(&ptm->ptm_errorcheck);
    152 		ptm->ptm_owner = (void *)MUTEX_RECURSIVE_BIT;
    153 		break;
    154 	default:
    155 		__cpu_simple_lock_clear(&ptm->ptm_errorcheck);
    156 		ptm->ptm_owner = NULL;
    157 		break;
    158 	}
    159 	switch (proto) {
    160 	case PTHREAD_PRIO_PROTECT:
    161 		val = (uintptr_t)ptm->ptm_owner;
    162 		val |= MUTEX_PROTECT_BIT;
    163 		ptm->ptm_owner = (void *)val;
    164 		break;
    165 
    166 	}
    167 	ptm->ptm_magic = _PT_MUTEX_MAGIC;
    168 	ptm->ptm_waiters = NULL;
    169 	ptm->ptm_recursed = 0;
    170 	ptm->ptm_ceiling = (unsigned char)ceil;
    171 
    172 	return 0;
    173 }
    174 
    175 int
    176 pthread_mutex_destroy(pthread_mutex_t *ptm)
    177 {
    178 
    179 	if (__predict_false(__uselibcstub))
    180 		return __libc_mutex_destroy_stub(ptm);
    181 
    182 	pthread__error(EINVAL, "Invalid mutex",
    183 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    184 	pthread__error(EBUSY, "Destroying locked mutex",
    185 	    MUTEX_OWNER(ptm->ptm_owner) == 0);
    186 
    187 	ptm->ptm_magic = _PT_MUTEX_DEAD;
    188 	return 0;
    189 }
    190 
    191 int
    192 pthread_mutex_lock(pthread_mutex_t *ptm)
    193 {
    194 	pthread_t self;
    195 	void *val;
    196 
    197 	if (__predict_false(__uselibcstub))
    198 		return __libc_mutex_lock_stub(ptm);
    199 
    200 	self = pthread__self();
    201 	val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
    202 	if (__predict_true(val == NULL)) {
    203 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    204 		membar_enter();
    205 #endif
    206 		return 0;
    207 	}
    208 	return pthread__mutex_lock_slow(ptm, NULL);
    209 }
    210 
    211 int
    212 pthread_mutex_timedlock(pthread_mutex_t* ptm, const struct timespec *ts)
    213 {
    214 	pthread_t self;
    215 	void *val;
    216 
    217 	self = pthread__self();
    218 	val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
    219 	if (__predict_true(val == NULL)) {
    220 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    221 		membar_enter();
    222 #endif
    223 		return 0;
    224 	}
    225 	return pthread__mutex_lock_slow(ptm, ts);
    226 }
    227 
    228 /* We want function call overhead. */
    229 NOINLINE static void
    230 pthread__mutex_pause(void)
    231 {
    232 
    233 	pthread__smt_pause();
    234 }
    235 
    236 /*
    237  * Spin while the holder is running.  'lwpctl' gives us the true
    238  * status of the thread.
    239  */
    240 NOINLINE static void *
    241 pthread__mutex_spin(pthread_mutex_t *ptm, pthread_t owner)
    242 {
    243 	pthread_t thread;
    244 	unsigned int count, i;
    245 
    246 	for (count = 2;; owner = ptm->ptm_owner) {
    247 		thread = (pthread_t)MUTEX_OWNER(owner);
    248 		if (thread == NULL)
    249 			break;
    250 		if (thread->pt_lwpctl->lc_curcpu == LWPCTL_CPU_NONE)
    251 			break;
    252 		if (count < 128)
    253 			count += count;
    254 		for (i = count; i != 0; i--)
    255 			pthread__mutex_pause();
    256 	}
    257 
    258 	return owner;
    259 }
    260 
    261 NOINLINE static bool
    262 pthread__mutex_setwaiters(pthread_t self, pthread_mutex_t *ptm)
    263 {
    264 	void *owner, *next;
    265 
    266 	/*
    267 	 * Note that the mutex can become unlocked before we set
    268 	 * the waiters bit.  If that happens it's not safe to sleep
    269 	 * as we may never be awoken: we must remove the current
    270 	 * thread from the waiters list and try again.
    271 	 *
    272 	 * Because we are doing this atomically, we can't remove
    273 	 * one waiter: we must remove all waiters and awken them,
    274 	 * then sleep in _lwp_park() until we have been awoken.
    275 	 *
    276 	 * Issue a memory barrier to ensure that we are reading
    277 	 * the value of ptm_owner/pt_mutexwait after we have entered
    278 	 * the waiters list (the CAS itself must be atomic).
    279 	 */
    280 	for (owner = ptm->ptm_owner;; owner = next) {
    281 		if (MUTEX_OWNER(owner) == 0) {
    282 			pthread__mutex_wakeup(self, ptm);
    283 			return true;
    284 		}
    285 		if (MUTEX_HAS_WAITERS(owner)) {
    286 			return false;
    287 		}
    288 		next = atomic_cas_ptr(&ptm->ptm_owner, owner,
    289 		    (void *)((uintptr_t)owner | MUTEX_WAITERS_BIT));
    290 	}
    291 }
    292 
    293 NOINLINE static int
    294 pthread__mutex_lock_slow(pthread_mutex_t *ptm, const struct timespec *ts)
    295 {
    296 	void *waiters, *new, *owner, *next;
    297 	pthread_t self;
    298 	int serrno;
    299 	int error;
    300 
    301 	pthread__error(EINVAL, "Invalid mutex",
    302 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    303 
    304 	owner = ptm->ptm_owner;
    305 	self = pthread__self();
    306 
    307 	/* Recursive or errorcheck? */
    308 	if (MUTEX_OWNER(owner) == (uintptr_t)self) {
    309 		if (MUTEX_RECURSIVE(owner)) {
    310 			if (ptm->ptm_recursed == INT_MAX)
    311 				return EAGAIN;
    312 			ptm->ptm_recursed++;
    313 			return 0;
    314 		}
    315 		if (__SIMPLELOCK_LOCKED_P(&ptm->ptm_errorcheck))
    316 			return EDEADLK;
    317 	}
    318 
    319 	/* priority protect */
    320 	if (MUTEX_PROTECT(owner) && _sched_protect(ptm->ptm_ceiling) == -1) {
    321 		return errno;
    322 	}
    323 	serrno = errno;
    324 	for (;; owner = ptm->ptm_owner) {
    325 		/* Spin while the owner is running. */
    326 		if (MUTEX_OWNER(owner) != (uintptr_t)self)
    327 			owner = pthread__mutex_spin(ptm, owner);
    328 
    329 		/* If it has become free, try to acquire it again. */
    330 		if (MUTEX_OWNER(owner) == 0) {
    331 			do {
    332 				new = (void *)
    333 				    ((uintptr_t)self | (uintptr_t)owner);
    334 				next = atomic_cas_ptr(&ptm->ptm_owner, owner,
    335 				    new);
    336 				if (next == owner) {
    337 					errno = serrno;
    338 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    339 					membar_enter();
    340 #endif
    341 					return 0;
    342 				}
    343 				owner = next;
    344 			} while (MUTEX_OWNER(owner) == 0);
    345 			/*
    346 			 * We have lost the race to acquire the mutex.
    347 			 * The new owner could be running on another
    348 			 * CPU, in which case we should spin and avoid
    349 			 * the overhead of blocking.
    350 			 */
    351 			continue;
    352 		}
    353 
    354 		/*
    355 		 * Nope, still held.  Add thread to the list of waiters.
    356 		 * Issue a memory barrier to ensure mutexwait/mutexnext
    357 		 * are visible before we enter the waiters list.
    358 		 */
    359 		self->pt_mutexwait = 1;
    360 		for (waiters = ptm->ptm_waiters;; waiters = next) {
    361 			self->pt_mutexnext = waiters;
    362 			membar_producer();
    363 			next = atomic_cas_ptr(&ptm->ptm_waiters, waiters, self);
    364 			if (next == waiters)
    365 			    	break;
    366 		}
    367 
    368 		/* Set the waiters bit and block. */
    369 		membar_sync();
    370 		if (pthread__mutex_setwaiters(self, ptm)) {
    371 			continue;
    372 		}
    373 
    374 		/*
    375 		 * We may have been awoken by the current thread above,
    376 		 * or will be awoken by the current holder of the mutex.
    377 		 * The key requirement is that we must not proceed until
    378 		 * told that we are no longer waiting (via pt_mutexwait
    379 		 * being set to zero).  Otherwise it is unsafe to re-enter
    380 		 * the thread onto the waiters list.
    381 		 */
    382 		membar_sync();
    383 		while (self->pt_mutexwait) {
    384 			error = _lwp_park(CLOCK_REALTIME, TIMER_ABSTIME,
    385 			    __UNCONST(ts), self->pt_unpark,
    386 			    __UNVOLATILE(&ptm->ptm_waiters),
    387 			    __UNVOLATILE(&ptm->ptm_waiters));
    388 			self->pt_unpark = 0;
    389 			if (__predict_true(error != -1)) {
    390 				continue;
    391 			}
    392 			if (errno == ETIMEDOUT && self->pt_mutexwait) {
    393 				/*Remove self from waiters list*/
    394 				pthread__mutex_wakeup(self, ptm);
    395 				/*priority protect*/
    396 				if (MUTEX_PROTECT(owner))
    397 					(void)_sched_protect(-1);
    398 				return ETIMEDOUT;
    399 			}
    400 		}
    401 	}
    402 }
    403 
    404 int
    405 pthread_mutex_trylock(pthread_mutex_t *ptm)
    406 {
    407 	pthread_t self;
    408 	void *val, *new, *next;
    409 
    410 	if (__predict_false(__uselibcstub))
    411 		return __libc_mutex_trylock_stub(ptm);
    412 
    413 	self = pthread__self();
    414 	val = atomic_cas_ptr(&ptm->ptm_owner, NULL, self);
    415 	if (__predict_true(val == NULL)) {
    416 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    417 		membar_enter();
    418 #endif
    419 		return 0;
    420 	}
    421 
    422 	if (MUTEX_RECURSIVE(val)) {
    423 		if (MUTEX_OWNER(val) == 0) {
    424 			new = (void *)((uintptr_t)self | (uintptr_t)val);
    425 			next = atomic_cas_ptr(&ptm->ptm_owner, val, new);
    426 			if (__predict_true(next == val)) {
    427 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    428 				membar_enter();
    429 #endif
    430 				return 0;
    431 			}
    432 		}
    433 		if (MUTEX_OWNER(val) == (uintptr_t)self) {
    434 			if (ptm->ptm_recursed == INT_MAX)
    435 				return EAGAIN;
    436 			ptm->ptm_recursed++;
    437 			return 0;
    438 		}
    439 	}
    440 
    441 	return EBUSY;
    442 }
    443 
    444 int
    445 pthread_mutex_unlock(pthread_mutex_t *ptm)
    446 {
    447 	pthread_t self;
    448 	void *value;
    449 
    450 	if (__predict_false(__uselibcstub))
    451 		return __libc_mutex_unlock_stub(ptm);
    452 
    453 #ifndef PTHREAD__ATOMIC_IS_MEMBAR
    454 	membar_exit();
    455 #endif
    456 	self = pthread__self();
    457 	value = atomic_cas_ptr(&ptm->ptm_owner, self, NULL);
    458 	if (__predict_true(value == self)) {
    459 		pthread__smt_wake();
    460 		return 0;
    461 	}
    462 	return pthread__mutex_unlock_slow(ptm);
    463 }
    464 
    465 NOINLINE static int
    466 pthread__mutex_unlock_slow(pthread_mutex_t *ptm)
    467 {
    468 	pthread_t self, owner, new;
    469 	int weown, error, deferred;
    470 
    471 	pthread__error(EINVAL, "Invalid mutex",
    472 	    ptm->ptm_magic == _PT_MUTEX_MAGIC);
    473 
    474 	self = pthread__self();
    475 	owner = ptm->ptm_owner;
    476 	weown = (MUTEX_OWNER(owner) == (uintptr_t)self);
    477 	deferred = (int)((uintptr_t)owner & MUTEX_DEFERRED_BIT);
    478 	error = 0;
    479 
    480 	if (__SIMPLELOCK_LOCKED_P(&ptm->ptm_errorcheck)) {
    481 		if (!weown) {
    482 			error = EPERM;
    483 			new = owner;
    484 		} else {
    485 			new = NULL;
    486 		}
    487 	} else if (MUTEX_RECURSIVE(owner)) {
    488 		if (!weown) {
    489 			error = EPERM;
    490 			new = owner;
    491 		} else if (ptm->ptm_recursed) {
    492 			ptm->ptm_recursed--;
    493 			new = owner;
    494 		} else {
    495 			new = (pthread_t)MUTEX_RECURSIVE_BIT;
    496 		}
    497 	} else {
    498 		pthread__error(EPERM,
    499 		    "Unlocking unlocked mutex", (owner != NULL));
    500 		pthread__error(EPERM,
    501 		    "Unlocking mutex owned by another thread", weown);
    502 		new = NULL;
    503 	}
    504 
    505 	/*
    506 	 * Release the mutex.  If there appear to be waiters, then
    507 	 * wake them up.
    508 	 */
    509 	if (new != owner) {
    510 		owner = atomic_swap_ptr(&ptm->ptm_owner, new);
    511 		if (__predict_false(MUTEX_PROTECT(owner))) {
    512 			/* restore elevated priority */
    513 			(void)_sched_protect(-1);
    514 		}
    515 		if (MUTEX_HAS_WAITERS(owner) != 0) {
    516 			pthread__mutex_wakeup(self, ptm);
    517 			return 0;
    518 		}
    519 	}
    520 
    521 	/*
    522 	 * There were no waiters, but we may have deferred waking
    523 	 * other threads until mutex unlock - we must wake them now.
    524 	 */
    525 	if (!deferred)
    526 		return error;
    527 
    528 	if (self->pt_nwaiters == 1) {
    529 		/*
    530 		 * If the calling thread is about to block, defer
    531 		 * unparking the target until _lwp_park() is called.
    532 		 */
    533 		if (self->pt_willpark && self->pt_unpark == 0) {
    534 			self->pt_unpark = self->pt_waiters[0];
    535 		} else {
    536 			(void)_lwp_unpark(self->pt_waiters[0],
    537 			    __UNVOLATILE(&ptm->ptm_waiters));
    538 		}
    539 	} else {
    540 		(void)_lwp_unpark_all(self->pt_waiters, self->pt_nwaiters,
    541 		    __UNVOLATILE(&ptm->ptm_waiters));
    542 	}
    543 	self->pt_nwaiters = 0;
    544 
    545 	return error;
    546 }
    547 
    548 /*
    549  * pthread__mutex_wakeup: unpark threads waiting for us
    550  *
    551  * unpark threads on the ptm->ptm_waiters list and self->pt_waiters.
    552  */
    553 
    554 static void
    555 pthread__mutex_wakeup(pthread_t self, pthread_mutex_t *ptm)
    556 {
    557 	pthread_t thread, next;
    558 	ssize_t n, rv;
    559 
    560 	/* Take ownership of the current set of waiters. */
    561 	thread = atomic_swap_ptr(&ptm->ptm_waiters, NULL);
    562 	membar_datadep_consumer(); /* for alpha */
    563 	pthread__smt_wake();
    564 
    565 	for (;;) {
    566 		/*
    567 		 * Pull waiters from the queue and add to our list.
    568 		 * Use a memory barrier to ensure that we safely
    569 		 * read the value of pt_mutexnext before 'thread'
    570 		 * sees pt_mutexwait being cleared.
    571 		 */
    572 		for (n = self->pt_nwaiters, self->pt_nwaiters = 0;
    573 		    n < pthread__unpark_max && thread != NULL;
    574 		    thread = next) {
    575 		    	next = thread->pt_mutexnext;
    576 		    	if (thread != self) {
    577 				self->pt_waiters[n++] = thread->pt_lid;
    578 				membar_sync();
    579 			}
    580 			thread->pt_mutexwait = 0;
    581 			/* No longer safe to touch 'thread' */
    582 		}
    583 
    584 		switch (n) {
    585 		case 0:
    586 			return;
    587 		case 1:
    588 			/*
    589 			 * If the calling thread is about to block,
    590 			 * defer unparking the target until _lwp_park()
    591 			 * is called.
    592 			 */
    593 			if (self->pt_willpark && self->pt_unpark == 0) {
    594 				self->pt_unpark = self->pt_waiters[0];
    595 				return;
    596 			}
    597 			rv = (ssize_t)_lwp_unpark(self->pt_waiters[0],
    598 			    __UNVOLATILE(&ptm->ptm_waiters));
    599 			if (rv != 0 && errno != EALREADY && errno != EINTR &&
    600 			    errno != ESRCH) {
    601 				pthread__errorfunc(__FILE__, __LINE__,
    602 				    __func__, "_lwp_unpark failed");
    603 			}
    604 			return;
    605 		default:
    606 			rv = _lwp_unpark_all(self->pt_waiters, (size_t)n,
    607 			    __UNVOLATILE(&ptm->ptm_waiters));
    608 			if (rv != 0 && errno != EINTR) {
    609 				pthread__errorfunc(__FILE__, __LINE__,
    610 				    __func__, "_lwp_unpark_all failed");
    611 			}
    612 			break;
    613 		}
    614 	}
    615 }
    616 
    617 int
    618 pthread_mutexattr_init(pthread_mutexattr_t *attr)
    619 {
    620 	if (__predict_false(__uselibcstub))
    621 		return __libc_mutexattr_init_stub(attr);
    622 
    623 	attr->ptma_magic = _PT_MUTEXATTR_MAGIC;
    624 	attr->ptma_private = (void *)PTHREAD_MUTEX_DEFAULT;
    625 	return 0;
    626 }
    627 
    628 int
    629 pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
    630 {
    631 	if (__predict_false(__uselibcstub))
    632 		return __libc_mutexattr_destroy_stub(attr);
    633 
    634 	pthread__error(EINVAL, "Invalid mutex attribute",
    635 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    636 
    637 	return 0;
    638 }
    639 
    640 int
    641 pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *typep)
    642 {
    643 
    644 	pthread__error(EINVAL, "Invalid mutex attribute",
    645 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    646 
    647 	*typep = MUTEX_GET_TYPE(attr->ptma_private);
    648 	return 0;
    649 }
    650 
    651 int
    652 pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
    653 {
    654 
    655 	if (__predict_false(__uselibcstub))
    656 		return __libc_mutexattr_settype_stub(attr, type);
    657 
    658 	pthread__error(EINVAL, "Invalid mutex attribute",
    659 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    660 
    661 	switch (type) {
    662 	case PTHREAD_MUTEX_NORMAL:
    663 	case PTHREAD_MUTEX_ERRORCHECK:
    664 	case PTHREAD_MUTEX_RECURSIVE:
    665 		MUTEX_SET_TYPE(attr->ptma_private, type);
    666 		return 0;
    667 	default:
    668 		return EINVAL;
    669 	}
    670 }
    671 
    672 int
    673 pthread_mutexattr_getprotocol(const pthread_mutexattr_t *attr, int*proto)
    674 {
    675 
    676 	pthread__error(EINVAL, "Invalid mutex attribute",
    677 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    678 
    679 	*proto = MUTEX_GET_PROTOCOL(attr->ptma_private);
    680 	return 0;
    681 }
    682 
    683 int
    684 pthread_mutexattr_setprotocol(pthread_mutexattr_t* attr, int proto)
    685 {
    686 
    687 	pthread__error(EINVAL, "Invalid mutex attribute",
    688 	    attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    689 
    690 	switch (proto) {
    691 	case PTHREAD_PRIO_NONE:
    692 	case PTHREAD_PRIO_PROTECT:
    693 		MUTEX_SET_PROTOCOL(attr->ptma_private, proto);
    694 		return 0;
    695 	case PTHREAD_PRIO_INHERIT:
    696 		return ENOTSUP;
    697 	default:
    698 		return EINVAL;
    699 	}
    700 }
    701 
    702 int
    703 pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *attr, int *ceil)
    704 {
    705 
    706 	pthread__error(EINVAL, "Invalid mutex attribute",
    707 		attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    708 
    709 	*ceil = MUTEX_GET_CEILING(attr->ptma_private);
    710 	return 0;
    711 }
    712 
    713 int
    714 pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, int ceil)
    715 {
    716 
    717 	pthread__error(EINVAL, "Invalid mutex attribute",
    718 		attr->ptma_magic == _PT_MUTEXATTR_MAGIC);
    719 
    720 	if (ceil & ~0xff)
    721 		return EINVAL;
    722 
    723 	MUTEX_SET_CEILING(attr->ptma_private, ceil);
    724 	return 0;
    725 }
    726 
    727 #ifdef _PTHREAD_PSHARED
    728 int
    729 pthread_mutexattr_getpshared(const pthread_mutexattr_t * __restrict attr,
    730     int * __restrict pshared)
    731 {
    732 
    733 	*pshared = PTHREAD_PROCESS_PRIVATE;
    734 	return 0;
    735 }
    736 
    737 int
    738 pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
    739 {
    740 
    741 	switch(pshared) {
    742 	case PTHREAD_PROCESS_PRIVATE:
    743 		return 0;
    744 	case PTHREAD_PROCESS_SHARED:
    745 		return ENOSYS;
    746 	}
    747 	return EINVAL;
    748 }
    749 #endif
    750 
    751 /*
    752  * pthread__mutex_deferwake: try to defer unparking threads in self->pt_waiters
    753  *
    754  * In order to avoid unnecessary contention on the interlocking mutex,
    755  * we defer waking up threads until we unlock the mutex.  The threads will
    756  * be woken up when the calling thread (self) releases the first mutex with
    757  * MUTEX_DEFERRED_BIT set.  It likely be the mutex 'ptm', but no problem
    758  * even if it isn't.
    759  */
    760 
    761 void
    762 pthread__mutex_deferwake(pthread_t self, pthread_mutex_t *ptm)
    763 {
    764 
    765 	if (__predict_false(ptm == NULL ||
    766 	    MUTEX_OWNER(ptm->ptm_owner) != (uintptr_t)self)) {
    767 	    	(void)_lwp_unpark_all(self->pt_waiters, self->pt_nwaiters,
    768 	    	    __UNVOLATILE(&ptm->ptm_waiters));
    769 	    	self->pt_nwaiters = 0;
    770 	} else {
    771 		atomic_or_ulong((volatile unsigned long *)
    772 		    (uintptr_t)&ptm->ptm_owner,
    773 		    (unsigned long)MUTEX_DEFERRED_BIT);
    774 	}
    775 }
    776 
    777 int
    778 pthread_mutex_getprioceiling(const pthread_mutex_t *ptm, int *ceil)
    779 {
    780 	*ceil = ptm->ptm_ceiling;
    781 	return 0;
    782 }
    783 
    784 int
    785 pthread_mutex_setprioceiling(pthread_mutex_t *ptm, int ceil, int *old_ceil)
    786 {
    787 	int error;
    788 
    789 	error = pthread_mutex_lock(ptm);
    790 	if (error == 0) {
    791 		*old_ceil = ptm->ptm_ceiling;
    792 		/*check range*/
    793 		ptm->ptm_ceiling = ceil;
    794 		pthread_mutex_unlock(ptm);
    795 	}
    796 	return error;
    797 }
    798 
    799 int
    800 _pthread_mutex_held_np(pthread_mutex_t *ptm)
    801 {
    802 
    803 	return MUTEX_OWNER(ptm->ptm_owner) == (uintptr_t)pthread__self();
    804 }
    805 
    806 pthread_t
    807 _pthread_mutex_owner_np(pthread_mutex_t *ptm)
    808 {
    809 
    810 	return (pthread_t)MUTEX_OWNER(ptm->ptm_owner);
    811 }
    812