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