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