Home | History | Annotate | Line # | Download | only in kern
kern_mutex.c revision 1.66
      1 /*	$NetBSD: kern_mutex.c,v 1.66 2017/09/16 23:25:34 christos 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.66 2017/09/16 23:25:34 christos 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 /*
     63  * When not running a debug kernel, spin mutexes are not much
     64  * more than an splraiseipl() and splx() pair.
     65  */
     66 
     67 #if defined(DIAGNOSTIC) || defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
     68 #define	FULL
     69 #endif
     70 
     71 /*
     72  * Debugging support.
     73  */
     74 
     75 #define	MUTEX_WANTLOCK(mtx)					\
     76     LOCKDEBUG_WANTLOCK(MUTEX_DEBUG_P(mtx), (mtx),		\
     77         (uintptr_t)__builtin_return_address(0), 0)
     78 #define	MUTEX_TESTLOCK(mtx)					\
     79     LOCKDEBUG_WANTLOCK(MUTEX_DEBUG_P(mtx), (mtx),		\
     80         (uintptr_t)__builtin_return_address(0), -1)
     81 #define	MUTEX_LOCKED(mtx)					\
     82     LOCKDEBUG_LOCKED(MUTEX_DEBUG_P(mtx), (mtx), NULL,		\
     83         (uintptr_t)__builtin_return_address(0), 0)
     84 #define	MUTEX_UNLOCKED(mtx)					\
     85     LOCKDEBUG_UNLOCKED(MUTEX_DEBUG_P(mtx), (mtx),		\
     86         (uintptr_t)__builtin_return_address(0), 0)
     87 #define	MUTEX_ABORT(mtx, msg)					\
     88     mutex_abort(__func__, __LINE__, mtx, msg)
     89 
     90 #if defined(LOCKDEBUG)
     91 
     92 #define	MUTEX_DASSERT(mtx, cond)				\
     93 do {								\
     94 	if (!(cond))						\
     95 		MUTEX_ABORT(mtx, "assertion failed: " #cond);	\
     96 } while (/* CONSTCOND */ 0);
     97 
     98 #else	/* LOCKDEBUG */
     99 
    100 #define	MUTEX_DASSERT(mtx, cond)	/* nothing */
    101 
    102 #endif /* LOCKDEBUG */
    103 
    104 #if defined(DIAGNOSTIC)
    105 
    106 #define	MUTEX_ASSERT(mtx, cond)					\
    107 do {								\
    108 	if (!(cond))						\
    109 		MUTEX_ABORT(mtx, "assertion failed: " #cond);	\
    110 } while (/* CONSTCOND */ 0)
    111 
    112 #else	/* DIAGNOSTIC */
    113 
    114 #define	MUTEX_ASSERT(mtx, cond)	/* nothing */
    115 
    116 #endif	/* DIAGNOSTIC */
    117 
    118 /*
    119  * Some architectures can't use __cpu_simple_lock as is so allow a way
    120  * for them to use an alternate definition.
    121  */
    122 #ifndef MUTEX_SPINBIT_LOCK_INIT
    123 #define MUTEX_SPINBIT_LOCK_INIT(mtx)	__cpu_simple_lock_init(&(mtx)->mtx_lock)
    124 #endif
    125 #ifndef MUTEX_SPINBIT_LOCKED_P
    126 #define MUTEX_SPINBIT_LOCKED_P(mtx)	__SIMPLELOCK_LOCKED_P(&(mtx)->mtx_lock)
    127 #endif
    128 #ifndef MUTEX_SPINBIT_LOCK_TRY
    129 #define MUTEX_SPINBIT_LOCK_TRY(mtx)	__cpu_simple_lock_try(&(mtx)->mtx_lock)
    130 #endif
    131 #ifndef MUTEX_SPINBIT_LOCK_UNLOCK
    132 #define MUTEX_SPINBIT_LOCK_UNLOCK(mtx)	__cpu_simple_unlock(&(mtx)->mtx_lock)
    133 #endif
    134 
    135 #ifndef MUTEX_INITIALIZE_SPIN_IPL
    136 #define MUTEX_INITIALIZE_SPIN_IPL(mtx, ipl) \
    137 					((mtx)->mtx_ipl = makeiplcookie((ipl)))
    138 #endif
    139 
    140 /*
    141  * Spin mutex SPL save / restore.
    142  */
    143 
    144 #define	MUTEX_SPIN_SPLRAISE(mtx)					\
    145 do {									\
    146 	struct cpu_info *x__ci;						\
    147 	int x__cnt, s;							\
    148 	s = splraiseipl(MUTEX_SPIN_IPL(mtx));				\
    149 	x__ci = curcpu();						\
    150 	x__cnt = x__ci->ci_mtx_count--;					\
    151 	__insn_barrier();						\
    152 	if (x__cnt == 0)						\
    153 		x__ci->ci_mtx_oldspl = (s);				\
    154 } while (/* CONSTCOND */ 0)
    155 
    156 #define	MUTEX_SPIN_SPLRESTORE(mtx)					\
    157 do {									\
    158 	struct cpu_info *x__ci = curcpu();				\
    159 	int s = x__ci->ci_mtx_oldspl;					\
    160 	__insn_barrier();						\
    161 	if (++(x__ci->ci_mtx_count) == 0)			\
    162 		splx(s);						\
    163 } while (/* CONSTCOND */ 0)
    164 
    165 /*
    166  * For architectures that provide 'simple' mutexes: they provide a
    167  * CAS function that is either MP-safe, or does not need to be MP
    168  * safe.  Adaptive mutexes on these architectures do not require an
    169  * additional interlock.
    170  */
    171 
    172 #ifdef __HAVE_SIMPLE_MUTEXES
    173 
    174 #define	MUTEX_OWNER(owner)						\
    175 	(owner & MUTEX_THREAD)
    176 #define	MUTEX_HAS_WAITERS(mtx)						\
    177 	(((int)(mtx)->mtx_owner & MUTEX_BIT_WAITERS) != 0)
    178 
    179 #define	MUTEX_INITIALIZE_ADAPTIVE(mtx, dodebug)				\
    180 	if (!dodebug)							\
    181 		(mtx)->mtx_owner |= MUTEX_BIT_NODEBUG;			\
    182 do {									\
    183 } while (/* CONSTCOND */ 0);
    184 
    185 #define	MUTEX_INITIALIZE_SPIN(mtx, dodebug, ipl)			\
    186 do {									\
    187 	(mtx)->mtx_owner = MUTEX_BIT_SPIN;				\
    188 	if (!dodebug)							\
    189 		(mtx)->mtx_owner |= MUTEX_BIT_NODEBUG;			\
    190 	MUTEX_INITIALIZE_SPIN_IPL((mtx), (ipl));			\
    191 	MUTEX_SPINBIT_LOCK_INIT((mtx));					\
    192 } while (/* CONSTCOND */ 0)
    193 
    194 #define	MUTEX_DESTROY(mtx)						\
    195 do {									\
    196 	(mtx)->mtx_owner = MUTEX_THREAD;				\
    197 } while (/* CONSTCOND */ 0);
    198 
    199 #define	MUTEX_SPIN_P(mtx)		\
    200     (((mtx)->mtx_owner & MUTEX_BIT_SPIN) != 0)
    201 #define	MUTEX_ADAPTIVE_P(mtx)		\
    202     (((mtx)->mtx_owner & MUTEX_BIT_SPIN) == 0)
    203 
    204 #define	MUTEX_DEBUG_P(mtx)	(((mtx)->mtx_owner & MUTEX_BIT_NODEBUG) == 0)
    205 #if defined(LOCKDEBUG)
    206 #define	MUTEX_OWNED(owner)		(((owner) & ~MUTEX_BIT_NODEBUG) != 0)
    207 #define	MUTEX_INHERITDEBUG(n, o)	(n) |= (o) & MUTEX_BIT_NODEBUG
    208 #else /* defined(LOCKDEBUG) */
    209 #define	MUTEX_OWNED(owner)		((owner) != 0)
    210 #define	MUTEX_INHERITDEBUG(n, o)	/* nothing */
    211 #endif /* defined(LOCKDEBUG) */
    212 
    213 static inline int
    214 MUTEX_ACQUIRE(kmutex_t *mtx, uintptr_t curthread)
    215 {
    216 	int rv;
    217 	uintptr_t oldown = 0;
    218 	uintptr_t newown = curthread;
    219 
    220 	MUTEX_INHERITDEBUG(oldown, mtx->mtx_owner);
    221 	MUTEX_INHERITDEBUG(newown, oldown);
    222 	rv = MUTEX_CAS(&mtx->mtx_owner, oldown, newown);
    223 	MUTEX_RECEIVE(mtx);
    224 	return rv;
    225 }
    226 
    227 static inline int
    228 MUTEX_SET_WAITERS(kmutex_t *mtx, uintptr_t owner)
    229 {
    230 	int rv;
    231 	rv = MUTEX_CAS(&mtx->mtx_owner, owner, owner | MUTEX_BIT_WAITERS);
    232 	MUTEX_RECEIVE(mtx);
    233 	return rv;
    234 }
    235 
    236 static inline void
    237 MUTEX_RELEASE(kmutex_t *mtx)
    238 {
    239 	uintptr_t newown;
    240 
    241 	MUTEX_GIVE(mtx);
    242 	newown = 0;
    243 	MUTEX_INHERITDEBUG(newown, mtx->mtx_owner);
    244 	mtx->mtx_owner = newown;
    245 }
    246 #endif	/* __HAVE_SIMPLE_MUTEXES */
    247 
    248 /*
    249  * Patch in stubs via strong alias where they are not available.
    250  */
    251 
    252 #if defined(LOCKDEBUG)
    253 #undef	__HAVE_MUTEX_STUBS
    254 #undef	__HAVE_SPIN_MUTEX_STUBS
    255 #endif
    256 
    257 #ifndef __HAVE_MUTEX_STUBS
    258 __strong_alias(mutex_enter,mutex_vector_enter);
    259 __strong_alias(mutex_exit,mutex_vector_exit);
    260 #endif
    261 
    262 #ifndef __HAVE_SPIN_MUTEX_STUBS
    263 __strong_alias(mutex_spin_enter,mutex_vector_enter);
    264 __strong_alias(mutex_spin_exit,mutex_vector_exit);
    265 #endif
    266 
    267 static void	mutex_abort(const char *, size_t, kmutex_t *, const char *);
    268 static void	mutex_dump(volatile void *);
    269 
    270 lockops_t mutex_spin_lockops = {
    271 	"Mutex",
    272 	LOCKOPS_SPIN,
    273 	mutex_dump
    274 };
    275 
    276 lockops_t mutex_adaptive_lockops = {
    277 	"Mutex",
    278 	LOCKOPS_SLEEP,
    279 	mutex_dump
    280 };
    281 
    282 syncobj_t mutex_syncobj = {
    283 	SOBJ_SLEEPQ_SORTED,
    284 	turnstile_unsleep,
    285 	turnstile_changepri,
    286 	sleepq_lendpri,
    287 	(void *)mutex_owner,
    288 };
    289 
    290 /*
    291  * mutex_dump:
    292  *
    293  *	Dump the contents of a mutex structure.
    294  */
    295 void
    296 mutex_dump(volatile void *cookie)
    297 {
    298 	volatile kmutex_t *mtx = cookie;
    299 
    300 	printf_nolog("owner field  : %#018lx wait/spin: %16d/%d\n",
    301 	    (long)MUTEX_OWNER(mtx->mtx_owner), MUTEX_HAS_WAITERS(mtx),
    302 	    MUTEX_SPIN_P(mtx));
    303 }
    304 
    305 /*
    306  * mutex_abort:
    307  *
    308  *	Dump information about an error and panic the system.  This
    309  *	generates a lot of machine code in the DIAGNOSTIC case, so
    310  *	we ask the compiler to not inline it.
    311  */
    312 void __noinline
    313 mutex_abort(const char *func, size_t line, kmutex_t *mtx, const char *msg)
    314 {
    315 
    316 	LOCKDEBUG_ABORT(func, line, mtx, (MUTEX_SPIN_P(mtx) ?
    317 	    &mutex_spin_lockops : &mutex_adaptive_lockops), msg);
    318 }
    319 
    320 /*
    321  * mutex_init:
    322  *
    323  *	Initialize a mutex for use.  Note that adaptive mutexes are in
    324  *	essence spin mutexes that can sleep to avoid deadlock and wasting
    325  *	CPU time.  We can't easily provide a type of mutex that always
    326  *	sleeps - see comments in mutex_vector_enter() about releasing
    327  *	mutexes unlocked.
    328  */
    329 void
    330 mutex_init(kmutex_t *mtx, kmutex_type_t type, int ipl)
    331 {
    332 	bool dodebug;
    333 
    334 	memset(mtx, 0, sizeof(*mtx));
    335 
    336 	switch (type) {
    337 	case MUTEX_ADAPTIVE:
    338 		KASSERT(ipl == IPL_NONE);
    339 		break;
    340 	case MUTEX_DEFAULT:
    341 	case MUTEX_DRIVER:
    342 		if (ipl == IPL_NONE || ipl == IPL_SOFTCLOCK ||
    343 		    ipl == IPL_SOFTBIO || ipl == IPL_SOFTNET ||
    344 		    ipl == IPL_SOFTSERIAL) {
    345 			type = MUTEX_ADAPTIVE;
    346 		} else {
    347 			type = MUTEX_SPIN;
    348 		}
    349 		break;
    350 	default:
    351 		break;
    352 	}
    353 
    354 	switch (type) {
    355 	case MUTEX_NODEBUG:
    356 		dodebug = LOCKDEBUG_ALLOC(mtx, NULL,
    357 		    (uintptr_t)__builtin_return_address(0));
    358 		MUTEX_INITIALIZE_SPIN(mtx, dodebug, ipl);
    359 		break;
    360 	case MUTEX_ADAPTIVE:
    361 		dodebug = LOCKDEBUG_ALLOC(mtx, &mutex_adaptive_lockops,
    362 		    (uintptr_t)__builtin_return_address(0));
    363 		MUTEX_INITIALIZE_ADAPTIVE(mtx, dodebug);
    364 		break;
    365 	case MUTEX_SPIN:
    366 		dodebug = LOCKDEBUG_ALLOC(mtx, &mutex_spin_lockops,
    367 		    (uintptr_t)__builtin_return_address(0));
    368 		MUTEX_INITIALIZE_SPIN(mtx, dodebug, ipl);
    369 		break;
    370 	default:
    371 		panic("mutex_init: impossible type");
    372 		break;
    373 	}
    374 }
    375 
    376 /*
    377  * mutex_destroy:
    378  *
    379  *	Tear down a mutex.
    380  */
    381 void
    382 mutex_destroy(kmutex_t *mtx)
    383 {
    384 
    385 	if (MUTEX_ADAPTIVE_P(mtx)) {
    386 		MUTEX_ASSERT(mtx, !MUTEX_OWNED(mtx->mtx_owner) &&
    387 		    !MUTEX_HAS_WAITERS(mtx));
    388 	} else {
    389 		MUTEX_ASSERT(mtx, !MUTEX_SPINBIT_LOCKED_P(mtx));
    390 	}
    391 
    392 	LOCKDEBUG_FREE(MUTEX_DEBUG_P(mtx), mtx);
    393 	MUTEX_DESTROY(mtx);
    394 }
    395 
    396 #ifdef MULTIPROCESSOR
    397 /*
    398  * mutex_oncpu:
    399  *
    400  *	Return true if an adaptive mutex owner is running on a CPU in the
    401  *	system.  If the target is waiting on the kernel big lock, then we
    402  *	must release it.  This is necessary to avoid deadlock.
    403  */
    404 static bool
    405 mutex_oncpu(uintptr_t owner)
    406 {
    407 	struct cpu_info *ci;
    408 	lwp_t *l;
    409 
    410 	KASSERT(kpreempt_disabled());
    411 
    412 	if (!MUTEX_OWNED(owner)) {
    413 		return false;
    414 	}
    415 
    416 	/*
    417 	 * See lwp_dtor() why dereference of the LWP pointer is safe.
    418 	 * We must have kernel preemption disabled for that.
    419 	 */
    420 	l = (lwp_t *)MUTEX_OWNER(owner);
    421 	ci = l->l_cpu;
    422 
    423 	if (ci && ci->ci_curlwp == l) {
    424 		/* Target is running; do we need to block? */
    425 		return (ci->ci_biglock_wanted != l);
    426 	}
    427 
    428 	/* Not running.  It may be safe to block now. */
    429 	return false;
    430 }
    431 #endif	/* MULTIPROCESSOR */
    432 
    433 /*
    434  * mutex_vector_enter:
    435  *
    436  *	Support routine for mutex_enter() that must handle all cases.  In
    437  *	the LOCKDEBUG case, mutex_enter() is always aliased here, even if
    438  *	fast-path stubs are available.  If a mutex_spin_enter() stub is
    439  *	not available, then it is also aliased directly here.
    440  */
    441 void
    442 mutex_vector_enter(kmutex_t *mtx)
    443 {
    444 	uintptr_t owner, curthread;
    445 	turnstile_t *ts;
    446 #ifdef MULTIPROCESSOR
    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 (MUTEX_SPINBIT_LOCK_TRY(mtx)) {
    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 (MUTEX_SPINBIT_LOCKED_P(mtx)) {
    485 				SPINLOCK_BACKOFF(count);
    486 #ifdef LOCKDEBUG
    487 				if (SPINLOCK_SPINOUT(spins))
    488 					MUTEX_ABORT(mtx, "spinout");
    489 #endif	/* LOCKDEBUG */
    490 			}
    491 		} while (!MUTEX_SPINBIT_LOCK_TRY(mtx));
    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 	if (panicstr == NULL) {
    512 		LOCKDEBUG_BARRIER(&kernel_lock, 1);
    513 	}
    514 
    515 	LOCKSTAT_ENTER(lsflag);
    516 
    517 	/*
    518 	 * Adaptive mutex; spin trying to acquire the mutex.  If we
    519 	 * determine that the owner is not running on a processor,
    520 	 * then we stop spinning, and sleep instead.
    521 	 */
    522 	KPREEMPT_DISABLE(curlwp);
    523 	for (owner = mtx->mtx_owner;;) {
    524 		if (!MUTEX_OWNED(owner)) {
    525 			/*
    526 			 * Mutex owner clear could mean two things:
    527 			 *
    528 			 *	* The mutex has been released.
    529 			 *	* The owner field hasn't been set yet.
    530 			 *
    531 			 * Try to acquire it again.  If that fails,
    532 			 * we'll just loop again.
    533 			 */
    534 			if (MUTEX_ACQUIRE(mtx, curthread))
    535 				break;
    536 			owner = mtx->mtx_owner;
    537 			continue;
    538 		}
    539 		if (__predict_false(panicstr != NULL)) {
    540 			KPREEMPT_ENABLE(curlwp);
    541 			return;
    542 		}
    543 		if (__predict_false(MUTEX_OWNER(owner) == curthread)) {
    544 			MUTEX_ABORT(mtx, "locking against myself");
    545 		}
    546 #ifdef MULTIPROCESSOR
    547 		/*
    548 		 * Check to see if the owner is running on a processor.
    549 		 * If so, then we should just spin, as the owner will
    550 		 * likely release the lock very soon.
    551 		 */
    552 		if (mutex_oncpu(owner)) {
    553 			LOCKSTAT_START_TIMER(lsflag, spintime);
    554 			count = SPINLOCK_BACKOFF_MIN;
    555 			do {
    556 				KPREEMPT_ENABLE(curlwp);
    557 				SPINLOCK_BACKOFF(count);
    558 				KPREEMPT_DISABLE(curlwp);
    559 				owner = mtx->mtx_owner;
    560 			} while (mutex_oncpu(owner));
    561 			LOCKSTAT_STOP_TIMER(lsflag, spintime);
    562 			LOCKSTAT_COUNT(spincnt, 1);
    563 			if (!MUTEX_OWNED(owner))
    564 				continue;
    565 		}
    566 #endif
    567 
    568 		ts = turnstile_lookup(mtx);
    569 
    570 		/*
    571 		 * Once we have the turnstile chain interlock, mark the
    572 		 * mutex has having waiters.  If that fails, spin again:
    573 		 * chances are that the mutex has been released.
    574 		 */
    575 		if (!MUTEX_SET_WAITERS(mtx, owner)) {
    576 			turnstile_exit(mtx);
    577 			owner = mtx->mtx_owner;
    578 			continue;
    579 		}
    580 
    581 #ifdef MULTIPROCESSOR
    582 		/*
    583 		 * mutex_exit() is permitted to release the mutex without
    584 		 * any interlocking instructions, and the following can
    585 		 * occur as a result:
    586 		 *
    587 		 *  CPU 1: MUTEX_SET_WAITERS()      CPU2: mutex_exit()
    588 		 * ---------------------------- ----------------------------
    589 		 *		..		    acquire cache line
    590 		 *		..                   test for waiters
    591 		 *	acquire cache line    <-      lose cache line
    592 		 *	 lock cache line	           ..
    593 		 *     verify mutex is held                ..
    594 		 *	    set waiters  	           ..
    595 		 *	 unlock cache line		   ..
    596 		 *	  lose cache line     ->    acquire cache line
    597 		 *		..	          clear lock word, waiters
    598 		 *	  return success
    599 		 *
    600 		 * There is another race that can occur: a third CPU could
    601 		 * acquire the mutex as soon as it is released.  Since
    602 		 * adaptive mutexes are primarily spin mutexes, this is not
    603 		 * something that we need to worry about too much.  What we
    604 		 * do need to ensure is that the waiters bit gets set.
    605 		 *
    606 		 * To allow the unlocked release, we need to make some
    607 		 * assumptions here:
    608 		 *
    609 		 * o Release is the only non-atomic/unlocked operation
    610 		 *   that can be performed on the mutex.  (It must still
    611 		 *   be atomic on the local CPU, e.g. in case interrupted
    612 		 *   or preempted).
    613 		 *
    614 		 * o At any given time, MUTEX_SET_WAITERS() can only ever
    615 		 *   be in progress on one CPU in the system - guaranteed
    616 		 *   by the turnstile chain lock.
    617 		 *
    618 		 * o No other operations other than MUTEX_SET_WAITERS()
    619 		 *   and release can modify a mutex with a non-zero
    620 		 *   owner field.
    621 		 *
    622 		 * o The result of a successful MUTEX_SET_WAITERS() call
    623 		 *   is an unbuffered write that is immediately visible
    624 		 *   to all other processors in the system.
    625 		 *
    626 		 * o If the holding LWP switches away, it posts a store
    627 		 *   fence before changing curlwp, ensuring that any
    628 		 *   overwrite of the mutex waiters flag by mutex_exit()
    629 		 *   completes before the modification of curlwp becomes
    630 		 *   visible to this CPU.
    631 		 *
    632 		 * o mi_switch() posts a store fence before setting curlwp
    633 		 *   and before resuming execution of an LWP.
    634 		 *
    635 		 * o _kernel_lock() posts a store fence before setting
    636 		 *   curcpu()->ci_biglock_wanted, and after clearing it.
    637 		 *   This ensures that any overwrite of the mutex waiters
    638 		 *   flag by mutex_exit() completes before the modification
    639 		 *   of ci_biglock_wanted becomes visible.
    640 		 *
    641 		 * We now post a read memory barrier (after setting the
    642 		 * waiters field) and check the lock holder's status again.
    643 		 * Some of the possible outcomes (not an exhaustive list):
    644 		 *
    645 		 * 1. The on-CPU check returns true: the holding LWP is
    646 		 *    running again.  The lock may be released soon and
    647 		 *    we should spin.  Importantly, we can't trust the
    648 		 *    value of the waiters flag.
    649 		 *
    650 		 * 2. The on-CPU check returns false: the holding LWP is
    651 		 *    not running.  We now have the opportunity to check
    652 		 *    if mutex_exit() has blatted the modifications made
    653 		 *    by MUTEX_SET_WAITERS().
    654 		 *
    655 		 * 3. The on-CPU check returns false: the holding LWP may
    656 		 *    or may not be running.  It has context switched at
    657 		 *    some point during our check.  Again, we have the
    658 		 *    chance to see if the waiters bit is still set or
    659 		 *    has been overwritten.
    660 		 *
    661 		 * 4. The on-CPU check returns false: the holding LWP is
    662 		 *    running on a CPU, but wants the big lock.  It's OK
    663 		 *    to check the waiters field in this case.
    664 		 *
    665 		 * 5. The has-waiters check fails: the mutex has been
    666 		 *    released, the waiters flag cleared and another LWP
    667 		 *    now owns the mutex.
    668 		 *
    669 		 * 6. The has-waiters check fails: the mutex has been
    670 		 *    released.
    671 		 *
    672 		 * If the waiters bit is not set it's unsafe to go asleep,
    673 		 * as we might never be awoken.
    674 		 */
    675 		if ((membar_consumer(), mutex_oncpu(owner)) ||
    676 		    (membar_consumer(), !MUTEX_HAS_WAITERS(mtx))) {
    677 			turnstile_exit(mtx);
    678 			owner = mtx->mtx_owner;
    679 			continue;
    680 		}
    681 #endif	/* MULTIPROCESSOR */
    682 
    683 		LOCKSTAT_START_TIMER(lsflag, slptime);
    684 
    685 		turnstile_block(ts, TS_WRITER_Q, mtx, &mutex_syncobj);
    686 
    687 		LOCKSTAT_STOP_TIMER(lsflag, slptime);
    688 		LOCKSTAT_COUNT(slpcnt, 1);
    689 
    690 		owner = mtx->mtx_owner;
    691 	}
    692 	KPREEMPT_ENABLE(curlwp);
    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 (__predict_false(!MUTEX_SPINBIT_LOCKED_P(mtx))) {
    718 			if (panicstr != NULL)
    719 				return;
    720 			MUTEX_ABORT(mtx, "exiting unheld spin mutex");
    721 		}
    722 		MUTEX_UNLOCKED(mtx);
    723 		MUTEX_SPINBIT_LOCK_UNLOCK(mtx);
    724 #endif
    725 		MUTEX_SPIN_SPLRESTORE(mtx);
    726 		return;
    727 	}
    728 
    729 	if (__predict_false((uintptr_t)panicstr | cold)) {
    730 		MUTEX_UNLOCKED(mtx);
    731 		MUTEX_RELEASE(mtx);
    732 		return;
    733 	}
    734 
    735 	curthread = (uintptr_t)curlwp;
    736 	MUTEX_DASSERT(mtx, curthread != 0);
    737 	MUTEX_ASSERT(mtx, MUTEX_OWNER(mtx->mtx_owner) == curthread);
    738 	MUTEX_UNLOCKED(mtx);
    739 #if !defined(LOCKDEBUG)
    740 	__USE(curthread);
    741 #endif
    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(const 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 MUTEX_SPINBIT_LOCKED_P(mtx);
    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(const 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_ownable:
    838  *
    839  *	When compiled with DEBUG and LOCKDEBUG defined, ensure that
    840  *	the mutex is available.  We cannot use !mutex_owned() since
    841  *	that won't work correctly for spin mutexes.
    842  */
    843 int
    844 mutex_ownable(const kmutex_t *mtx)
    845 {
    846 
    847 #ifdef LOCKDEBUG
    848 	MUTEX_TESTLOCK(mtx);
    849 #endif
    850 	return 1;
    851 }
    852 
    853 /*
    854  * mutex_tryenter:
    855  *
    856  *	Try to acquire the mutex; return non-zero if we did.
    857  */
    858 int
    859 mutex_tryenter(kmutex_t *mtx)
    860 {
    861 	uintptr_t curthread;
    862 
    863 	/*
    864 	 * Handle spin mutexes.
    865 	 */
    866 	if (MUTEX_SPIN_P(mtx)) {
    867 		MUTEX_SPIN_SPLRAISE(mtx);
    868 #ifdef FULL
    869 		if (MUTEX_SPINBIT_LOCK_TRY(mtx)) {
    870 			MUTEX_WANTLOCK(mtx);
    871 			MUTEX_LOCKED(mtx);
    872 			return 1;
    873 		}
    874 		MUTEX_SPIN_SPLRESTORE(mtx);
    875 #else
    876 		MUTEX_WANTLOCK(mtx);
    877 		MUTEX_LOCKED(mtx);
    878 		return 1;
    879 #endif
    880 	} else {
    881 		curthread = (uintptr_t)curlwp;
    882 		MUTEX_ASSERT(mtx, curthread != 0);
    883 		if (MUTEX_ACQUIRE(mtx, curthread)) {
    884 			MUTEX_WANTLOCK(mtx);
    885 			MUTEX_LOCKED(mtx);
    886 			MUTEX_DASSERT(mtx,
    887 			    MUTEX_OWNER(mtx->mtx_owner) == curthread);
    888 			return 1;
    889 		}
    890 	}
    891 
    892 	return 0;
    893 }
    894 
    895 #if defined(__HAVE_SPIN_MUTEX_STUBS) || defined(FULL)
    896 /*
    897  * mutex_spin_retry:
    898  *
    899  *	Support routine for mutex_spin_enter().  Assumes that the caller
    900  *	has already raised the SPL, and adjusted counters.
    901  */
    902 void
    903 mutex_spin_retry(kmutex_t *mtx)
    904 {
    905 #ifdef MULTIPROCESSOR
    906 	u_int count;
    907 	LOCKSTAT_TIMER(spintime);
    908 	LOCKSTAT_FLAG(lsflag);
    909 #ifdef LOCKDEBUG
    910 	u_int spins = 0;
    911 #endif	/* LOCKDEBUG */
    912 
    913 	MUTEX_WANTLOCK(mtx);
    914 
    915 	LOCKSTAT_ENTER(lsflag);
    916 	LOCKSTAT_START_TIMER(lsflag, spintime);
    917 	count = SPINLOCK_BACKOFF_MIN;
    918 
    919 	/*
    920 	 * Spin testing the lock word and do exponential backoff
    921 	 * to reduce cache line ping-ponging between CPUs.
    922 	 */
    923 	do {
    924 		if (panicstr != NULL)
    925 			break;
    926 		while (MUTEX_SPINBIT_LOCKED_P(mtx)) {
    927 			SPINLOCK_BACKOFF(count);
    928 #ifdef LOCKDEBUG
    929 			if (SPINLOCK_SPINOUT(spins))
    930 				MUTEX_ABORT(mtx, "spinout");
    931 #endif	/* LOCKDEBUG */
    932 		}
    933 	} while (!MUTEX_SPINBIT_LOCK_TRY(mtx));
    934 
    935 	LOCKSTAT_STOP_TIMER(lsflag, spintime);
    936 	LOCKSTAT_EVENT(lsflag, mtx, LB_SPIN_MUTEX | LB_SPIN, 1, spintime);
    937 	LOCKSTAT_EXIT(lsflag);
    938 
    939 	MUTEX_LOCKED(mtx);
    940 #else	/* MULTIPROCESSOR */
    941 	MUTEX_ABORT(mtx, "locking against myself");
    942 #endif	/* MULTIPROCESSOR */
    943 }
    944 #endif	/* defined(__HAVE_SPIN_MUTEX_STUBS) || defined(FULL) */
    945