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