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