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