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