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