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