Home | History | Annotate | Line # | Download | only in kern
kern_mutex.c revision 1.23
      1 /*	$NetBSD: kern_mutex.c,v 1.23 2007/11/21 10:19:10 yamt Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2002, 2006, 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe and 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  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * Kernel mutex implementation, modeled after those found in Solaris,
     41  * a description of which can be found in:
     42  *
     43  *	Solaris Internals: Core Kernel Architecture, Jim Mauro and
     44  *	    Richard McDougall.
     45  */
     46 
     47 #define	__MUTEX_PRIVATE
     48 
     49 #include <sys/cdefs.h>
     50 __KERNEL_RCSID(0, "$NetBSD: kern_mutex.c,v 1.23 2007/11/21 10:19:10 yamt Exp $");
     51 
     52 #include "opt_multiprocessor.h"
     53 
     54 #include <sys/param.h>
     55 #include <sys/proc.h>
     56 #include <sys/mutex.h>
     57 #include <sys/sched.h>
     58 #include <sys/sleepq.h>
     59 #include <sys/systm.h>
     60 #include <sys/lockdebug.h>
     61 #include <sys/kernel.h>
     62 
     63 #include <dev/lockstat.h>
     64 
     65 #include <sys/intr.h>
     66 
     67 /*
     68  * When not running a debug kernel, spin mutexes are not much
     69  * more than an splraiseipl() and splx() pair.
     70  */
     71 
     72 #if defined(DIAGNOSTIC) || defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
     73 #define	FULL
     74 #endif
     75 
     76 /*
     77  * Debugging support.
     78  */
     79 
     80 #define	MUTEX_WANTLOCK(mtx)					\
     81     LOCKDEBUG_WANTLOCK(MUTEX_DEBUG_P(mtx), (mtx),		\
     82         (uintptr_t)__builtin_return_address(0), 0)
     83 #define	MUTEX_LOCKED(mtx)					\
     84     LOCKDEBUG_LOCKED(MUTEX_DEBUG_P(mtx), (mtx),			\
     85         (uintptr_t)__builtin_return_address(0), 0)
     86 #define	MUTEX_UNLOCKED(mtx)					\
     87     LOCKDEBUG_UNLOCKED(MUTEX_DEBUG_P(mtx), (mtx),		\
     88         (uintptr_t)__builtin_return_address(0), 0)
     89 #define	MUTEX_ABORT(mtx, msg)					\
     90     mutex_abort(mtx, __func__, msg)
     91 
     92 #if defined(LOCKDEBUG)
     93 
     94 #define	MUTEX_DASSERT(mtx, cond)				\
     95 do {								\
     96 	if (!(cond))						\
     97 		MUTEX_ABORT(mtx, "assertion failed: " #cond);	\
     98 } while (/* CONSTCOND */ 0);
     99 
    100 #else	/* LOCKDEBUG */
    101 
    102 #define	MUTEX_DASSERT(mtx, cond)	/* nothing */
    103 
    104 #endif /* LOCKDEBUG */
    105 
    106 #if defined(DIAGNOSTIC)
    107 
    108 #define	MUTEX_ASSERT(mtx, cond)					\
    109 do {								\
    110 	if (!(cond))						\
    111 		MUTEX_ABORT(mtx, "assertion failed: " #cond);	\
    112 } while (/* CONSTCOND */ 0)
    113 
    114 #else	/* DIAGNOSTIC */
    115 
    116 #define	MUTEX_ASSERT(mtx, cond)	/* nothing */
    117 
    118 #endif	/* DIAGNOSTIC */
    119 
    120 /*
    121  * Spin mutex SPL save / restore.
    122  */
    123 #ifndef MUTEX_COUNT_BIAS
    124 #define	MUTEX_COUNT_BIAS	0
    125 #endif
    126 
    127 #define	MUTEX_SPIN_SPLRAISE(mtx)					\
    128 do {									\
    129 	struct cpu_info *x__ci = curcpu();				\
    130 	int x__cnt, s;							\
    131 	x__cnt = x__ci->ci_mtx_count--;					\
    132 	s = splraiseipl(mtx->mtx_ipl);					\
    133 	if (x__cnt == MUTEX_COUNT_BIAS)					\
    134 		x__ci->ci_mtx_oldspl = (s);				\
    135 } while (/* CONSTCOND */ 0)
    136 
    137 #define	MUTEX_SPIN_SPLRESTORE(mtx)					\
    138 do {									\
    139 	struct cpu_info *x__ci = curcpu();				\
    140 	int s = x__ci->ci_mtx_oldspl;					\
    141 	__insn_barrier();						\
    142 	if (++(x__ci->ci_mtx_count) == MUTEX_COUNT_BIAS)		\
    143 		splx(s);						\
    144 } while (/* CONSTCOND */ 0)
    145 
    146 /*
    147  * For architectures that provide 'simple' mutexes: they provide a
    148  * CAS function that is either MP-safe, or does not need to be MP
    149  * safe.  Adaptive mutexes on these architectures do not require an
    150  * additional interlock.
    151  */
    152 
    153 #ifdef __HAVE_SIMPLE_MUTEXES
    154 
    155 #define	MUTEX_OWNER(owner)						\
    156 	(owner & MUTEX_THREAD)
    157 #define	MUTEX_HAS_WAITERS(mtx)						\
    158 	(((int)(mtx)->mtx_owner & MUTEX_BIT_WAITERS) != 0)
    159 
    160 #define	MUTEX_INITIALIZE_ADAPTIVE(mtx, dodebug)				\
    161 do {									\
    162 	if (dodebug)							\
    163 		(mtx)->mtx_owner |= MUTEX_BIT_DEBUG;			\
    164 } while (/* CONSTCOND */ 0);
    165 
    166 #define	MUTEX_INITIALIZE_SPIN(mtx, dodebug, ipl)			\
    167 do {									\
    168 	(mtx)->mtx_owner = MUTEX_BIT_SPIN;				\
    169 	if (dodebug)							\
    170 		(mtx)->mtx_owner |= MUTEX_BIT_DEBUG;			\
    171 	(mtx)->mtx_ipl = makeiplcookie((ipl));				\
    172 	__cpu_simple_lock_init(&(mtx)->mtx_lock);			\
    173 } while (/* CONSTCOND */ 0)
    174 
    175 #define	MUTEX_DESTROY(mtx)						\
    176 do {									\
    177 	(mtx)->mtx_owner = MUTEX_THREAD;				\
    178 } while (/* CONSTCOND */ 0);
    179 
    180 #define	MUTEX_SPIN_P(mtx)		\
    181     (((mtx)->mtx_owner & MUTEX_BIT_SPIN) != 0)
    182 #define	MUTEX_ADAPTIVE_P(mtx)		\
    183     (((mtx)->mtx_owner & MUTEX_BIT_SPIN) == 0)
    184 
    185 #define	MUTEX_DEBUG_P(mtx)	(((mtx)->mtx_owner & MUTEX_BIT_DEBUG) != 0)
    186 #if defined(LOCKDEBUG)
    187 #define	MUTEX_OWNED(owner)		(((owner) & ~MUTEX_BIT_DEBUG) != 0)
    188 #define	MUTEX_INHERITDEBUG(new, old)	(new) |= (old) & MUTEX_BIT_DEBUG
    189 #else /* defined(LOCKDEBUG) */
    190 #define	MUTEX_OWNED(owner)		((owner) != 0)
    191 #define	MUTEX_INHERITDEBUG(new, old)	/* nothing */
    192 #endif /* defined(LOCKDEBUG) */
    193 
    194 static inline int
    195 MUTEX_ACQUIRE(kmutex_t *mtx, uintptr_t curthread)
    196 {
    197 	int rv;
    198 	uintptr_t old = 0;
    199 	uintptr_t new = curthread;
    200 
    201 	MUTEX_INHERITDEBUG(old, mtx->mtx_owner);
    202 	MUTEX_INHERITDEBUG(new, old);
    203 	rv = MUTEX_CAS(&mtx->mtx_owner, old, new);
    204 	MUTEX_RECEIVE(mtx);
    205 	return rv;
    206 }
    207 
    208 static inline int
    209 MUTEX_SET_WAITERS(kmutex_t *mtx, uintptr_t owner)
    210 {
    211 	int rv;
    212 	rv = MUTEX_CAS(&mtx->mtx_owner, owner, owner | MUTEX_BIT_WAITERS);
    213 	MUTEX_RECEIVE(mtx);
    214 	return rv;
    215 }
    216 
    217 static inline void
    218 MUTEX_RELEASE(kmutex_t *mtx)
    219 {
    220 	uintptr_t new;
    221 
    222 	MUTEX_GIVE(mtx);
    223 	new = 0;
    224 	MUTEX_INHERITDEBUG(new, mtx->mtx_owner);
    225 	mtx->mtx_owner = new;
    226 }
    227 
    228 static inline void
    229 MUTEX_CLEAR_WAITERS(kmutex_t *mtx)
    230 {
    231 	/* nothing */
    232 }
    233 #endif	/* __HAVE_SIMPLE_MUTEXES */
    234 
    235 /*
    236  * Patch in stubs via strong alias where they are not available.
    237  */
    238 
    239 #if defined(LOCKDEBUG)
    240 #undef	__HAVE_MUTEX_STUBS
    241 #undef	__HAVE_SPIN_MUTEX_STUBS
    242 #endif
    243 
    244 #ifndef __HAVE_MUTEX_STUBS
    245 __strong_alias(mutex_enter,mutex_vector_enter);
    246 __strong_alias(mutex_exit,mutex_vector_exit);
    247 #endif
    248 
    249 #ifndef __HAVE_SPIN_MUTEX_STUBS
    250 __strong_alias(mutex_spin_enter,mutex_vector_enter);
    251 __strong_alias(mutex_spin_exit,mutex_vector_exit);
    252 #endif
    253 
    254 void	mutex_abort(kmutex_t *, const char *, const char *);
    255 void	mutex_dump(volatile void *);
    256 int	mutex_onproc(uintptr_t, struct cpu_info **);
    257 static struct lwp *mutex_owner(wchan_t);
    258 
    259 lockops_t mutex_spin_lockops = {
    260 	"Mutex",
    261 	0,
    262 	mutex_dump
    263 };
    264 
    265 lockops_t mutex_adaptive_lockops = {
    266 	"Mutex",
    267 	1,
    268 	mutex_dump
    269 };
    270 
    271 syncobj_t mutex_syncobj = {
    272 	SOBJ_SLEEPQ_SORTED,
    273 	turnstile_unsleep,
    274 	turnstile_changepri,
    275 	sleepq_lendpri,
    276 	mutex_owner,
    277 };
    278 
    279 /*
    280  * mutex_dump:
    281  *
    282  *	Dump the contents of a mutex structure.
    283  */
    284 void
    285 mutex_dump(volatile void *cookie)
    286 {
    287 	volatile kmutex_t *mtx = cookie;
    288 
    289 	printf_nolog("owner field  : %#018lx wait/spin: %16d/%d\n",
    290 	    (long)MUTEX_OWNER(mtx->mtx_owner), MUTEX_HAS_WAITERS(mtx),
    291 	    MUTEX_SPIN_P(mtx));
    292 }
    293 
    294 /*
    295  * mutex_abort:
    296  *
    297  *	Dump information about an error and panic the system.  This
    298  *	generates a lot of machine code in the DIAGNOSTIC case, so
    299  *	we ask the compiler to not inline it.
    300  */
    301 
    302 #if __GNUC_PREREQ__(3, 0)
    303 __attribute ((noinline)) __attribute ((noreturn))
    304 #endif
    305 void
    306 mutex_abort(kmutex_t *mtx, const char *func, const char *msg)
    307 {
    308 
    309 	LOCKDEBUG_ABORT(mtx, (MUTEX_SPIN_P(mtx) ?
    310 	    &mutex_spin_lockops : &mutex_adaptive_lockops), func, msg);
    311 	/* NOTREACHED */
    312 }
    313 
    314 /*
    315  * mutex_init:
    316  *
    317  *	Initialize a mutex for use.  Note that adaptive mutexes are in
    318  *	essence spin mutexes that can sleep to avoid deadlock and wasting
    319  *	CPU time.  We can't easily provide a type of mutex that always
    320  *	sleeps - see comments in mutex_vector_enter() about releasing
    321  *	mutexes unlocked.
    322  */
    323 void
    324 mutex_init(kmutex_t *mtx, kmutex_type_t type, int ipl)
    325 {
    326 	bool dodebug;
    327 
    328 	memset(mtx, 0, sizeof(*mtx));
    329 
    330 	switch (type) {
    331 	case MUTEX_ADAPTIVE:
    332 		KASSERT(ipl == IPL_NONE);
    333 		break;
    334 	case MUTEX_DEFAULT:
    335 	case MUTEX_DRIVER:
    336 		switch (ipl) {
    337 		case IPL_NONE:
    338 			type = MUTEX_ADAPTIVE;
    339 			break;
    340 		default:
    341 			type = MUTEX_SPIN;
    342 			break;
    343 		}
    344 		break;
    345 	default:
    346 		break;
    347 	}
    348 
    349 	switch (type) {
    350 	case MUTEX_NODEBUG:
    351 		dodebug = LOCKDEBUG_ALLOC(mtx, NULL,
    352 		    (uintptr_t)__builtin_return_address(0));
    353 		MUTEX_INITIALIZE_SPIN(mtx, dodebug, ipl);
    354 		break;
    355 	case MUTEX_ADAPTIVE:
    356 		dodebug = LOCKDEBUG_ALLOC(mtx, &mutex_adaptive_lockops,
    357 		    (uintptr_t)__builtin_return_address(0));
    358 		MUTEX_INITIALIZE_ADAPTIVE(mtx, dodebug);
    359 		break;
    360 	case MUTEX_SPIN:
    361 		dodebug = LOCKDEBUG_ALLOC(mtx, &mutex_spin_lockops,
    362 		    (uintptr_t)__builtin_return_address(0));
    363 		MUTEX_INITIALIZE_SPIN(mtx, dodebug, ipl);
    364 		break;
    365 	default:
    366 		panic("mutex_init: impossible type");
    367 		break;
    368 	}
    369 }
    370 
    371 /*
    372  * mutex_destroy:
    373  *
    374  *	Tear down a mutex.
    375  */
    376 void
    377 mutex_destroy(kmutex_t *mtx)
    378 {
    379 
    380 	if (MUTEX_ADAPTIVE_P(mtx)) {
    381 		MUTEX_ASSERT(mtx, !MUTEX_OWNED(mtx->mtx_owner) &&
    382 		    !MUTEX_HAS_WAITERS(mtx));
    383 	} else {
    384 		MUTEX_ASSERT(mtx, !__SIMPLELOCK_LOCKED_P(&mtx->mtx_lock));
    385 	}
    386 
    387 	LOCKDEBUG_FREE(MUTEX_DEBUG_P(mtx), mtx);
    388 	MUTEX_DESTROY(mtx);
    389 }
    390 
    391 /*
    392  * mutex_onproc:
    393  *
    394  *	Return true if an adaptive mutex owner is running on a CPU in the
    395  *	system.  If the target is waiting on the kernel big lock, then we
    396  *	must release it.  This is necessary to avoid deadlock.
    397  *
    398  *	Note that we can't use the mutex owner field as an LWP pointer.  We
    399  *	don't have full control over the timing of our execution, and so the
    400  *	pointer could be completely invalid by the time we dereference it.
    401  */
    402 #ifdef MULTIPROCESSOR
    403 int
    404 mutex_onproc(uintptr_t owner, struct cpu_info **cip)
    405 {
    406 	CPU_INFO_ITERATOR cii;
    407 	struct cpu_info *ci;
    408 	struct lwp *l;
    409 
    410 	if (!MUTEX_OWNED(owner))
    411 		return 0;
    412 	l = (struct lwp *)MUTEX_OWNER(owner);
    413 
    414 	/* See if the target is running on a CPU somewhere. */
    415 	if ((ci = *cip) != NULL && ci->ci_curlwp == l)
    416 		goto run;
    417 	for (CPU_INFO_FOREACH(cii, ci))
    418 		if (ci->ci_curlwp == l)
    419 			goto run;
    420 
    421 	/* No: it may be safe to block now. */
    422 	*cip = NULL;
    423 	return 0;
    424 
    425  run:
    426  	/* Target is running; do we need to block? */
    427  	*cip = ci;
    428 	return ci->ci_biglock_wanted != l;
    429 }
    430 #endif	/* MULTIPROCESSOR */
    431 
    432 /*
    433  * mutex_vector_enter:
    434  *
    435  *	Support routine for mutex_enter() that must handles all cases.  In
    436  *	the LOCKDEBUG case, mutex_enter() is always aliased here, even if
    437  *	fast-path stubs are available.  If an mutex_spin_enter() stub is
    438  *	not available, then it is also aliased directly here.
    439  */
    440 void
    441 mutex_vector_enter(kmutex_t *mtx)
    442 {
    443 	uintptr_t owner, curthread;
    444 	turnstile_t *ts;
    445 #ifdef MULTIPROCESSOR
    446 	struct cpu_info *ci = NULL;
    447 	u_int count;
    448 #endif
    449 	LOCKSTAT_COUNTER(spincnt);
    450 	LOCKSTAT_COUNTER(slpcnt);
    451 	LOCKSTAT_TIMER(spintime);
    452 	LOCKSTAT_TIMER(slptime);
    453 	LOCKSTAT_FLAG(lsflag);
    454 
    455 	/*
    456 	 * Handle spin mutexes.
    457 	 */
    458 	if (MUTEX_SPIN_P(mtx)) {
    459 #if defined(LOCKDEBUG) && defined(MULTIPROCESSOR)
    460 		u_int spins = 0;
    461 #endif
    462 		MUTEX_SPIN_SPLRAISE(mtx);
    463 		MUTEX_WANTLOCK(mtx);
    464 #ifdef FULL
    465 		if (__cpu_simple_lock_try(&mtx->mtx_lock)) {
    466 			MUTEX_LOCKED(mtx);
    467 			return;
    468 		}
    469 #if !defined(MULTIPROCESSOR)
    470 		MUTEX_ABORT(mtx, "locking against myself");
    471 #else /* !MULTIPROCESSOR */
    472 
    473 		LOCKSTAT_ENTER(lsflag);
    474 		LOCKSTAT_START_TIMER(lsflag, spintime);
    475 		count = SPINLOCK_BACKOFF_MIN;
    476 
    477 		/*
    478 		 * Spin testing the lock word and do exponential backoff
    479 		 * to reduce cache line ping-ponging between CPUs.
    480 		 */
    481 		do {
    482 			if (panicstr != NULL)
    483 				break;
    484 			while (__SIMPLELOCK_LOCKED_P(&mtx->mtx_lock)) {
    485 				SPINLOCK_BACKOFF(count);
    486 #ifdef LOCKDEBUG
    487 				if (SPINLOCK_SPINOUT(spins))
    488 					MUTEX_ABORT(mtx, "spinout");
    489 #endif	/* LOCKDEBUG */
    490 			}
    491 		} while (!__cpu_simple_lock_try(&mtx->mtx_lock));
    492 
    493 		if (count != SPINLOCK_BACKOFF_MIN) {
    494 			LOCKSTAT_STOP_TIMER(lsflag, spintime);
    495 			LOCKSTAT_EVENT(lsflag, mtx,
    496 			    LB_SPIN_MUTEX | LB_SPIN, 1, spintime);
    497 		}
    498 		LOCKSTAT_EXIT(lsflag);
    499 #endif	/* !MULTIPROCESSOR */
    500 #endif	/* FULL */
    501 		MUTEX_LOCKED(mtx);
    502 		return;
    503 	}
    504 
    505 	curthread = (uintptr_t)curlwp;
    506 
    507 	MUTEX_DASSERT(mtx, MUTEX_ADAPTIVE_P(mtx));
    508 	MUTEX_ASSERT(mtx, curthread != 0);
    509 	MUTEX_WANTLOCK(mtx);
    510 
    511 #ifdef LOCKDEBUG
    512 	if (panicstr == NULL) {
    513 		simple_lock_only_held(NULL, "mutex_enter");
    514 #ifdef MULTIPROCESSOR
    515 		LOCKDEBUG_BARRIER(&kernel_lock, 1);
    516 #else
    517 		LOCKDEBUG_BARRIER(NULL, 1);
    518 #endif
    519 	}
    520 #endif
    521 
    522 	LOCKSTAT_ENTER(lsflag);
    523 
    524 	/*
    525 	 * Adaptive mutex; spin trying to acquire the mutex.  If we
    526 	 * determine that the owner is not running on a processor,
    527 	 * then we stop spinning, and sleep instead.
    528 	 */
    529 	for (;;) {
    530 		owner = mtx->mtx_owner;
    531 		if (!MUTEX_OWNED(owner)) {
    532 			/*
    533 			 * Mutex owner clear could mean two things:
    534 			 *
    535 			 *	* The mutex has been released.
    536 			 *	* The owner field hasn't been set yet.
    537 			 *
    538 			 * Try to acquire it again.  If that fails,
    539 			 * we'll just loop again.
    540 			 */
    541 			if (MUTEX_ACQUIRE(mtx, curthread))
    542 				break;
    543 			continue;
    544 		}
    545 
    546 		if (panicstr != NULL)
    547 			return;
    548 		if (MUTEX_OWNER(owner) == curthread)
    549 			MUTEX_ABORT(mtx, "locking against myself");
    550 
    551 #ifdef MULTIPROCESSOR
    552 		/*
    553 		 * Check to see if the owner is running on a processor.
    554 		 * If so, then we should just spin, as the owner will
    555 		 * likely release the lock very soon.
    556 		 */
    557 		if (mutex_onproc(owner, &ci)) {
    558 			LOCKSTAT_START_TIMER(lsflag, spintime);
    559 			count = SPINLOCK_BACKOFF_MIN;
    560 			for (;;) {
    561 				owner = mtx->mtx_owner;
    562 				if (!mutex_onproc(owner, &ci))
    563 					break;
    564 				SPINLOCK_BACKOFF(count);
    565 			}
    566 			LOCKSTAT_STOP_TIMER(lsflag, spintime);
    567 			LOCKSTAT_COUNT(spincnt, 1);
    568 			if (!MUTEX_OWNED(owner))
    569 				continue;
    570 		}
    571 #endif
    572 
    573 		ts = turnstile_lookup(mtx);
    574 
    575 		/*
    576 		 * Once we have the turnstile chain interlock, mark the
    577 		 * mutex has having waiters.  If that fails, spin again:
    578 		 * chances are that the mutex has been released.
    579 		 */
    580 		if (!MUTEX_SET_WAITERS(mtx, owner)) {
    581 			turnstile_exit(mtx);
    582 			continue;
    583 		}
    584 
    585 #ifdef MULTIPROCESSOR
    586 		/*
    587 		 * mutex_exit() is permitted to release the mutex without
    588 		 * any interlocking instructions, and the following can
    589 		 * occur as a result:
    590 		 *
    591 		 *  CPU 1: MUTEX_SET_WAITERS()      CPU2: mutex_exit()
    592 		 * ---------------------------- ----------------------------
    593 		 *		..		    acquire cache line
    594 		 *		..                   test for waiters
    595 		 *	acquire cache line    <-      lose cache line
    596 		 *	 lock cache line	           ..
    597 		 *     verify mutex is held                ..
    598 		 *	    set waiters  	           ..
    599 		 *	 unlock cache line		   ..
    600 		 *	  lose cache line     ->    acquire cache line
    601 		 *		..	          clear lock word, waiters
    602 		 *	  return success
    603 		 *
    604 		 * There is a another race that can occur: a third CPU could
    605 		 * acquire the mutex as soon as it is released.  Since
    606 		 * adaptive mutexes are primarily spin mutexes, this is not
    607 		 * something that we need to worry about too much.  What we
    608 		 * do need to ensure is that the waiters bit gets set.
    609 		 *
    610 		 * To allow the unlocked release, we need to make some
    611 		 * assumptions here:
    612 		 *
    613 		 * o Release is the only non-atomic/unlocked operation
    614 		 *   that can be performed on the mutex.  (It must still
    615 		 *   be atomic on the local CPU, e.g. in case interrupted
    616 		 *   or preempted).
    617 		 *
    618 		 * o At any given time, MUTEX_SET_WAITERS() can only ever
    619 		 *   be in progress on one CPU in the system - guaranteed
    620 		 *   by the turnstile chain lock.
    621 		 *
    622 		 * o No other operations other than MUTEX_SET_WAITERS()
    623 		 *   and release can modify a mutex with a non-zero
    624 		 *   owner field.
    625 		 *
    626 		 * o The result of a successful MUTEX_SET_WAITERS() call
    627 		 *   is an unbuffered write that is immediately visible
    628 		 *   to all other processors in the system.
    629 		 *
    630 		 * o If the holding LWP switches away, it posts a store
    631 		 *   fence before changing curlwp, ensuring that any
    632 		 *   overwrite of the mutex waiters flag by mutex_exit()
    633 		 *   completes before the modification of curlwp becomes
    634 		 *   visible to this CPU.
    635 		 *
    636 		 * o mi_switch() posts a store fence before setting curlwp
    637 		 *   and before resuming execution of an LWP.
    638 		 *
    639 		 * o _kernel_lock() posts a store fence before setting
    640 		 *   curcpu()->ci_biglock_wanted, and after clearing it.
    641 		 *   This ensures that any overwrite of the mutex waiters
    642 		 *   flag by mutex_exit() completes before the modification
    643 		 *   of ci_biglock_wanted becomes visible.
    644 		 *
    645 		 * We now post a read memory barrier (after setting the
    646 		 * waiters field) and check the lock holder's status again.
    647 		 * Some of the possible outcomes (not an exhaustive list):
    648 		 *
    649 		 * 1. The onproc check returns true: the holding LWP is
    650 		 *    running again.  The lock may be released soon and
    651 		 *    we should spin.  Importantly, we can't trust the
    652 		 *    value of the waiters flag.
    653 		 *
    654 		 * 2. The onproc check returns false: the holding LWP is
    655 		 *    not running.  We now have the oppertunity to check
    656 		 *    if mutex_exit() has blatted the modifications made
    657 		 *    by MUTEX_SET_WAITERS().
    658 		 *
    659 		 * 3. The onproc check returns false: the holding LWP may
    660 		 *    or may not be running.  It has context switched at
    661 		 *    some point during our check.  Again, we have the
    662 		 *    chance to see if the waiters bit is still set or
    663 		 *    has been overwritten.
    664 		 *
    665 		 * 4. The onproc check returns false: the holding LWP is
    666 		 *    running on a CPU, but wants the big lock.  It's OK
    667 		 *    to check the waiters field in this case.
    668 		 *
    669 		 * 5. The has-waiters check fails: the mutex has been
    670 		 *    released, the waiters flag cleared and another LWP
    671 		 *    now owns the mutex.
    672 		 *
    673 		 * 6. The has-waiters check fails: the mutex has been
    674 		 *    released.
    675 		 *
    676 		 * If the waiters bit is not set it's unsafe to go asleep,
    677 		 * as we might never be awoken.
    678 		 */
    679 		if ((mb_read(), mutex_onproc(owner, &ci)) ||
    680 		    (mb_read(), !MUTEX_HAS_WAITERS(mtx))) {
    681 			turnstile_exit(mtx);
    682 			continue;
    683 		}
    684 #endif	/* MULTIPROCESSOR */
    685 
    686 		LOCKSTAT_START_TIMER(lsflag, slptime);
    687 
    688 		turnstile_block(ts, TS_WRITER_Q, mtx, &mutex_syncobj);
    689 
    690 		LOCKSTAT_STOP_TIMER(lsflag, slptime);
    691 		LOCKSTAT_COUNT(slpcnt, 1);
    692 	}
    693 
    694 	LOCKSTAT_EVENT(lsflag, mtx, LB_ADAPTIVE_MUTEX | LB_SLEEP1,
    695 	    slpcnt, slptime);
    696 	LOCKSTAT_EVENT(lsflag, mtx, LB_ADAPTIVE_MUTEX | LB_SPIN,
    697 	    spincnt, spintime);
    698 	LOCKSTAT_EXIT(lsflag);
    699 
    700 	MUTEX_DASSERT(mtx, MUTEX_OWNER(mtx->mtx_owner) == curthread);
    701 	MUTEX_LOCKED(mtx);
    702 }
    703 
    704 /*
    705  * mutex_vector_exit:
    706  *
    707  *	Support routine for mutex_exit() that handles all cases.
    708  */
    709 void
    710 mutex_vector_exit(kmutex_t *mtx)
    711 {
    712 	turnstile_t *ts;
    713 	uintptr_t curthread;
    714 
    715 	if (MUTEX_SPIN_P(mtx)) {
    716 #ifdef FULL
    717 		if (!__SIMPLELOCK_LOCKED_P(&mtx->mtx_lock))
    718 			MUTEX_ABORT(mtx, "exiting unheld spin mutex");
    719 		MUTEX_UNLOCKED(mtx);
    720 		__cpu_simple_unlock(&mtx->mtx_lock);
    721 #endif
    722 		MUTEX_SPIN_SPLRESTORE(mtx);
    723 		return;
    724 	}
    725 
    726 	if (__predict_false((uintptr_t)panicstr | cold)) {
    727 		MUTEX_UNLOCKED(mtx);
    728 		MUTEX_RELEASE(mtx);
    729 		return;
    730 	}
    731 
    732 	curthread = (uintptr_t)curlwp;
    733 	MUTEX_DASSERT(mtx, curthread != 0);
    734 	MUTEX_ASSERT(mtx, MUTEX_OWNER(mtx->mtx_owner) == curthread);
    735 	MUTEX_UNLOCKED(mtx);
    736 
    737 #ifdef LOCKDEBUG
    738 	/*
    739 	 * Avoid having to take the turnstile chain lock every time
    740 	 * around.  Raise the priority level to splhigh() in order
    741 	 * to disable preemption and so make the following atomic.
    742 	 */
    743 	{
    744 		int s = splhigh();
    745 		if (!MUTEX_HAS_WAITERS(mtx)) {
    746 			MUTEX_RELEASE(mtx);
    747 			splx(s);
    748 			return;
    749 		}
    750 		splx(s);
    751 	}
    752 #endif
    753 
    754 	/*
    755 	 * Get this lock's turnstile.  This gets the interlock on
    756 	 * the sleep queue.  Once we have that, we can clear the
    757 	 * lock.  If there was no turnstile for the lock, there
    758 	 * were no waiters remaining.
    759 	 */
    760 	ts = turnstile_lookup(mtx);
    761 
    762 	if (ts == NULL) {
    763 		MUTEX_RELEASE(mtx);
    764 		turnstile_exit(mtx);
    765 	} else {
    766 		MUTEX_RELEASE(mtx);
    767 		turnstile_wakeup(ts, TS_WRITER_Q,
    768 		    TS_WAITERS(ts, TS_WRITER_Q), NULL);
    769 	}
    770 }
    771 
    772 #ifndef __HAVE_SIMPLE_MUTEXES
    773 /*
    774  * mutex_wakeup:
    775  *
    776  *	Support routine for mutex_exit() that wakes up all waiters.
    777  *	We assume that the mutex has been released, but it need not
    778  *	be.
    779  */
    780 void
    781 mutex_wakeup(kmutex_t *mtx)
    782 {
    783 	turnstile_t *ts;
    784 
    785 	ts = turnstile_lookup(mtx);
    786 	if (ts == NULL) {
    787 		turnstile_exit(mtx);
    788 		return;
    789 	}
    790 	MUTEX_CLEAR_WAITERS(mtx);
    791 	turnstile_wakeup(ts, TS_WRITER_Q, TS_WAITERS(ts, TS_WRITER_Q), NULL);
    792 }
    793 #endif	/* !__HAVE_SIMPLE_MUTEXES */
    794 
    795 /*
    796  * mutex_owned:
    797  *
    798  *	Return true if the current LWP (adaptive) or CPU (spin)
    799  *	holds the mutex.
    800  */
    801 int
    802 mutex_owned(kmutex_t *mtx)
    803 {
    804 
    805 	if (MUTEX_ADAPTIVE_P(mtx))
    806 		return MUTEX_OWNER(mtx->mtx_owner) == (uintptr_t)curlwp;
    807 #ifdef FULL
    808 	return __SIMPLELOCK_LOCKED_P(&mtx->mtx_lock);
    809 #else
    810 	return 1;
    811 #endif
    812 }
    813 
    814 /*
    815  * mutex_owner:
    816  *
    817  *	Return the current owner of an adaptive mutex.  Used for
    818  *	priority inheritance.
    819  */
    820 static struct lwp *
    821 mutex_owner(wchan_t obj)
    822 {
    823 	kmutex_t *mtx = (void *)(uintptr_t)obj; /* discard qualifiers */
    824 
    825 	MUTEX_ASSERT(mtx, MUTEX_ADAPTIVE_P(mtx));
    826 	return (struct lwp *)MUTEX_OWNER(mtx->mtx_owner);
    827 }
    828 
    829 /*
    830  * mutex_tryenter:
    831  *
    832  *	Try to acquire the mutex; return non-zero if we did.
    833  */
    834 int
    835 mutex_tryenter(kmutex_t *mtx)
    836 {
    837 	uintptr_t curthread;
    838 
    839 	/*
    840 	 * Handle spin mutexes.
    841 	 */
    842 	if (MUTEX_SPIN_P(mtx)) {
    843 		MUTEX_SPIN_SPLRAISE(mtx);
    844 #ifdef FULL
    845 		if (__cpu_simple_lock_try(&mtx->mtx_lock)) {
    846 			MUTEX_WANTLOCK(mtx);
    847 			MUTEX_LOCKED(mtx);
    848 			return 1;
    849 		}
    850 		MUTEX_SPIN_SPLRESTORE(mtx);
    851 #else
    852 		MUTEX_WANTLOCK(mtx);
    853 		MUTEX_LOCKED(mtx);
    854 		return 1;
    855 #endif
    856 	} else {
    857 		curthread = (uintptr_t)curlwp;
    858 		MUTEX_ASSERT(mtx, curthread != 0);
    859 		if (MUTEX_ACQUIRE(mtx, curthread)) {
    860 			MUTEX_WANTLOCK(mtx);
    861 			MUTEX_LOCKED(mtx);
    862 			MUTEX_DASSERT(mtx,
    863 			    MUTEX_OWNER(mtx->mtx_owner) == curthread);
    864 			return 1;
    865 		}
    866 	}
    867 
    868 	return 0;
    869 }
    870 
    871 #if defined(__HAVE_SPIN_MUTEX_STUBS) || defined(FULL)
    872 /*
    873  * mutex_spin_retry:
    874  *
    875  *	Support routine for mutex_spin_enter().  Assumes that the caller
    876  *	has already raised the SPL, and adjusted counters.
    877  */
    878 void
    879 mutex_spin_retry(kmutex_t *mtx)
    880 {
    881 #ifdef MULTIPROCESSOR
    882 	u_int count;
    883 	LOCKSTAT_TIMER(spintime);
    884 	LOCKSTAT_FLAG(lsflag);
    885 #ifdef LOCKDEBUG
    886 	u_int spins = 0;
    887 #endif	/* LOCKDEBUG */
    888 
    889 	MUTEX_WANTLOCK(mtx);
    890 
    891 	LOCKSTAT_ENTER(lsflag);
    892 	LOCKSTAT_START_TIMER(lsflag, spintime);
    893 	count = SPINLOCK_BACKOFF_MIN;
    894 
    895 	/*
    896 	 * Spin testing the lock word and do exponential backoff
    897 	 * to reduce cache line ping-ponging between CPUs.
    898 	 */
    899 	do {
    900 		if (panicstr != NULL)
    901 			break;
    902 		while (__SIMPLELOCK_LOCKED_P(&mtx->mtx_lock)) {
    903 			SPINLOCK_BACKOFF(count);
    904 #ifdef LOCKDEBUG
    905 			if (SPINLOCK_SPINOUT(spins))
    906 				MUTEX_ABORT(mtx, "spinout");
    907 #endif	/* LOCKDEBUG */
    908 		}
    909 	} while (!__cpu_simple_lock_try(&mtx->mtx_lock));
    910 
    911 	LOCKSTAT_STOP_TIMER(lsflag, spintime);
    912 	LOCKSTAT_EVENT(lsflag, mtx, LB_SPIN_MUTEX | LB_SPIN, 1, spintime);
    913 	LOCKSTAT_EXIT(lsflag);
    914 
    915 	MUTEX_LOCKED(mtx);
    916 #else	/* MULTIPROCESSOR */
    917 	MUTEX_ABORT(mtx, "locking against myself");
    918 #endif	/* MULTIPROCESSOR */
    919 }
    920 #endif	/* defined(__HAVE_SPIN_MUTEX_STUBS) || defined(FULL) */
    921