xref: /netbsd-src/sys/kern/kern_mutex.c (revision 2de962bd804263c16657f586aa00f1704045df8e)
1 /*	$NetBSD: kern_mutex.c,v 1.41 2008/05/19 17:06:02 ad Exp $	*/
2 
3 /*-
4  * Copyright (c) 2002, 2006, 2007, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe and Andrew Doran.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Kernel mutex implementation, modeled after those found in Solaris,
34  * a description of which can be found in:
35  *
36  *	Solaris Internals: Core Kernel Architecture, Jim Mauro and
37  *	    Richard McDougall.
38  */
39 
40 #define	__MUTEX_PRIVATE
41 
42 #include <sys/cdefs.h>
43 __KERNEL_RCSID(0, "$NetBSD: kern_mutex.c,v 1.41 2008/05/19 17:06:02 ad Exp $");
44 
45 #include <sys/param.h>
46 #include <sys/proc.h>
47 #include <sys/mutex.h>
48 #include <sys/sched.h>
49 #include <sys/sleepq.h>
50 #include <sys/systm.h>
51 #include <sys/lockdebug.h>
52 #include <sys/kernel.h>
53 #include <sys/atomic.h>
54 #include <sys/intr.h>
55 #include <sys/lock.h>
56 #include <sys/pool.h>
57 
58 #include <dev/lockstat.h>
59 
60 #include <machine/lock.h>
61 
62 /*
63  * When not running a debug kernel, spin mutexes are not much
64  * more than an splraiseipl() and splx() pair.
65  */
66 
67 #if defined(DIAGNOSTIC) || defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
68 #define	FULL
69 #endif
70 
71 /*
72  * Debugging support.
73  */
74 
75 #define	MUTEX_WANTLOCK(mtx)					\
76     LOCKDEBUG_WANTLOCK(MUTEX_DEBUG_P(mtx), (mtx),		\
77         (uintptr_t)__builtin_return_address(0), false, false)
78 #define	MUTEX_LOCKED(mtx)					\
79     LOCKDEBUG_LOCKED(MUTEX_DEBUG_P(mtx), (mtx),			\
80         (uintptr_t)__builtin_return_address(0), 0)
81 #define	MUTEX_UNLOCKED(mtx)					\
82     LOCKDEBUG_UNLOCKED(MUTEX_DEBUG_P(mtx), (mtx),		\
83         (uintptr_t)__builtin_return_address(0), 0)
84 #define	MUTEX_ABORT(mtx, msg)					\
85     mutex_abort(mtx, __func__, msg)
86 
87 #if defined(LOCKDEBUG)
88 
89 #define	MUTEX_DASSERT(mtx, cond)				\
90 do {								\
91 	if (!(cond))						\
92 		MUTEX_ABORT(mtx, "assertion failed: " #cond);	\
93 } while (/* CONSTCOND */ 0);
94 
95 #else	/* LOCKDEBUG */
96 
97 #define	MUTEX_DASSERT(mtx, cond)	/* nothing */
98 
99 #endif /* LOCKDEBUG */
100 
101 #if defined(DIAGNOSTIC)
102 
103 #define	MUTEX_ASSERT(mtx, cond)					\
104 do {								\
105 	if (!(cond))						\
106 		MUTEX_ABORT(mtx, "assertion failed: " #cond);	\
107 } while (/* CONSTCOND */ 0)
108 
109 #else	/* DIAGNOSTIC */
110 
111 #define	MUTEX_ASSERT(mtx, cond)	/* nothing */
112 
113 #endif	/* DIAGNOSTIC */
114 
115 /*
116  * Spin mutex SPL save / restore.
117  */
118 #ifndef MUTEX_COUNT_BIAS
119 #define	MUTEX_COUNT_BIAS	0
120 #endif
121 
122 #define	MUTEX_SPIN_SPLRAISE(mtx)					\
123 do {									\
124 	struct cpu_info *x__ci;						\
125 	int x__cnt, s;							\
126 	s = splraiseipl(mtx->mtx_ipl);					\
127 	x__ci = curcpu();						\
128 	x__cnt = x__ci->ci_mtx_count--;					\
129 	__insn_barrier();						\
130 	if (x__cnt == MUTEX_COUNT_BIAS)					\
131 		x__ci->ci_mtx_oldspl = (s);				\
132 } while (/* CONSTCOND */ 0)
133 
134 #define	MUTEX_SPIN_SPLRESTORE(mtx)					\
135 do {									\
136 	struct cpu_info *x__ci = curcpu();				\
137 	int s = x__ci->ci_mtx_oldspl;					\
138 	__insn_barrier();						\
139 	if (++(x__ci->ci_mtx_count) == MUTEX_COUNT_BIAS)		\
140 		splx(s);						\
141 } while (/* CONSTCOND */ 0)
142 
143 /*
144  * For architectures that provide 'simple' mutexes: they provide a
145  * CAS function that is either MP-safe, or does not need to be MP
146  * safe.  Adaptive mutexes on these architectures do not require an
147  * additional interlock.
148  */
149 
150 #ifdef __HAVE_SIMPLE_MUTEXES
151 
152 #define	MUTEX_OWNER(owner)						\
153 	(owner & MUTEX_THREAD)
154 #define	MUTEX_HAS_WAITERS(mtx)						\
155 	(((int)(mtx)->mtx_owner & MUTEX_BIT_WAITERS) != 0)
156 
157 #define	MUTEX_INITIALIZE_ADAPTIVE(mtx, dodebug)				\
158 do {									\
159 	if (dodebug)							\
160 		(mtx)->mtx_owner |= MUTEX_BIT_DEBUG;			\
161 } while (/* CONSTCOND */ 0);
162 
163 #define	MUTEX_INITIALIZE_SPIN(mtx, dodebug, ipl)			\
164 do {									\
165 	(mtx)->mtx_owner = MUTEX_BIT_SPIN;				\
166 	if (dodebug)							\
167 		(mtx)->mtx_owner |= MUTEX_BIT_DEBUG;			\
168 	(mtx)->mtx_ipl = makeiplcookie((ipl));				\
169 	__cpu_simple_lock_init(&(mtx)->mtx_lock);			\
170 } while (/* CONSTCOND */ 0)
171 
172 #define	MUTEX_DESTROY(mtx)						\
173 do {									\
174 	(mtx)->mtx_owner = MUTEX_THREAD;				\
175 } while (/* CONSTCOND */ 0);
176 
177 #define	MUTEX_SPIN_P(mtx)		\
178     (((mtx)->mtx_owner & MUTEX_BIT_SPIN) != 0)
179 #define	MUTEX_ADAPTIVE_P(mtx)		\
180     (((mtx)->mtx_owner & MUTEX_BIT_SPIN) == 0)
181 
182 #define	MUTEX_DEBUG_P(mtx)	(((mtx)->mtx_owner & MUTEX_BIT_DEBUG) != 0)
183 #if defined(LOCKDEBUG)
184 #define	MUTEX_OWNED(owner)		(((owner) & ~MUTEX_BIT_DEBUG) != 0)
185 #define	MUTEX_INHERITDEBUG(new, old)	(new) |= (old) & MUTEX_BIT_DEBUG
186 #else /* defined(LOCKDEBUG) */
187 #define	MUTEX_OWNED(owner)		((owner) != 0)
188 #define	MUTEX_INHERITDEBUG(new, old)	/* nothing */
189 #endif /* defined(LOCKDEBUG) */
190 
191 static inline int
192 MUTEX_ACQUIRE(kmutex_t *mtx, uintptr_t curthread)
193 {
194 	int rv;
195 	uintptr_t old = 0;
196 	uintptr_t new = curthread;
197 
198 	MUTEX_INHERITDEBUG(old, mtx->mtx_owner);
199 	MUTEX_INHERITDEBUG(new, old);
200 	rv = MUTEX_CAS(&mtx->mtx_owner, old, new);
201 	MUTEX_RECEIVE(mtx);
202 	return rv;
203 }
204 
205 static inline int
206 MUTEX_SET_WAITERS(kmutex_t *mtx, uintptr_t owner)
207 {
208 	int rv;
209 	rv = MUTEX_CAS(&mtx->mtx_owner, owner, owner | MUTEX_BIT_WAITERS);
210 	MUTEX_RECEIVE(mtx);
211 	return rv;
212 }
213 
214 static inline void
215 MUTEX_RELEASE(kmutex_t *mtx)
216 {
217 	uintptr_t new;
218 
219 	MUTEX_GIVE(mtx);
220 	new = 0;
221 	MUTEX_INHERITDEBUG(new, mtx->mtx_owner);
222 	mtx->mtx_owner = new;
223 }
224 
225 static inline void
226 MUTEX_CLEAR_WAITERS(kmutex_t *mtx)
227 {
228 	/* nothing */
229 }
230 #endif	/* __HAVE_SIMPLE_MUTEXES */
231 
232 /*
233  * Patch in stubs via strong alias where they are not available.
234  */
235 
236 #if defined(LOCKDEBUG)
237 #undef	__HAVE_MUTEX_STUBS
238 #undef	__HAVE_SPIN_MUTEX_STUBS
239 #endif
240 
241 #ifndef __HAVE_MUTEX_STUBS
242 __strong_alias(mutex_enter,mutex_vector_enter);
243 __strong_alias(mutex_exit,mutex_vector_exit);
244 #endif
245 
246 #ifndef __HAVE_SPIN_MUTEX_STUBS
247 __strong_alias(mutex_spin_enter,mutex_vector_enter);
248 __strong_alias(mutex_spin_exit,mutex_vector_exit);
249 #endif
250 
251 void	mutex_abort(kmutex_t *, const char *, const char *);
252 void	mutex_dump(volatile void *);
253 int	mutex_onproc(uintptr_t, struct cpu_info **);
254 
255 lockops_t mutex_spin_lockops = {
256 	"Mutex",
257 	0,
258 	mutex_dump
259 };
260 
261 lockops_t mutex_adaptive_lockops = {
262 	"Mutex",
263 	1,
264 	mutex_dump
265 };
266 
267 syncobj_t mutex_syncobj = {
268 	SOBJ_SLEEPQ_SORTED,
269 	turnstile_unsleep,
270 	turnstile_changepri,
271 	sleepq_lendpri,
272 	(void *)mutex_owner,
273 };
274 
275 /* Mutex cache */
276 #define	MUTEX_OBJ_MAGIC	0x5aa3c85d
277 struct kmutexobj {
278 	kmutex_t	mo_lock;
279 	u_int		mo_magic;
280 	u_int		mo_refcnt;
281 };
282 
283 static int	mutex_obj_ctor(void *, void *, int);
284 
285 static pool_cache_t	mutex_obj_cache;
286 
287 /*
288  * mutex_dump:
289  *
290  *	Dump the contents of a mutex structure.
291  */
292 void
293 mutex_dump(volatile void *cookie)
294 {
295 	volatile kmutex_t *mtx = cookie;
296 
297 	printf_nolog("owner field  : %#018lx wait/spin: %16d/%d\n",
298 	    (long)MUTEX_OWNER(mtx->mtx_owner), MUTEX_HAS_WAITERS(mtx),
299 	    MUTEX_SPIN_P(mtx));
300 }
301 
302 /*
303  * mutex_abort:
304  *
305  *	Dump information about an error and panic the system.  This
306  *	generates a lot of machine code in the DIAGNOSTIC case, so
307  *	we ask the compiler to not inline it.
308  */
309 
310 #if __GNUC_PREREQ__(3, 0)
311 __attribute ((noinline)) __attribute ((noreturn))
312 #endif
313 void
314 mutex_abort(kmutex_t *mtx, const char *func, const char *msg)
315 {
316 
317 	LOCKDEBUG_ABORT(mtx, (MUTEX_SPIN_P(mtx) ?
318 	    &mutex_spin_lockops : &mutex_adaptive_lockops), func, msg);
319 	/* NOTREACHED */
320 }
321 
322 /*
323  * mutex_init:
324  *
325  *	Initialize a mutex for use.  Note that adaptive mutexes are in
326  *	essence spin mutexes that can sleep to avoid deadlock and wasting
327  *	CPU time.  We can't easily provide a type of mutex that always
328  *	sleeps - see comments in mutex_vector_enter() about releasing
329  *	mutexes unlocked.
330  */
331 void
332 mutex_init(kmutex_t *mtx, kmutex_type_t type, int ipl)
333 {
334 	bool dodebug;
335 
336 	memset(mtx, 0, sizeof(*mtx));
337 
338 	switch (type) {
339 	case MUTEX_ADAPTIVE:
340 		KASSERT(ipl == IPL_NONE);
341 		break;
342 	case MUTEX_DEFAULT:
343 	case MUTEX_DRIVER:
344 		if (ipl == IPL_NONE || ipl == IPL_SOFTCLOCK ||
345 		    ipl == IPL_SOFTBIO || ipl == IPL_SOFTNET ||
346 		    ipl == IPL_SOFTSERIAL) {
347 			type = MUTEX_ADAPTIVE;
348 		} else {
349 			type = MUTEX_SPIN;
350 		}
351 		break;
352 	default:
353 		break;
354 	}
355 
356 	switch (type) {
357 	case MUTEX_NODEBUG:
358 		dodebug = LOCKDEBUG_ALLOC(mtx, NULL,
359 		    (uintptr_t)__builtin_return_address(0));
360 		MUTEX_INITIALIZE_SPIN(mtx, dodebug, ipl);
361 		break;
362 	case MUTEX_ADAPTIVE:
363 		dodebug = LOCKDEBUG_ALLOC(mtx, &mutex_adaptive_lockops,
364 		    (uintptr_t)__builtin_return_address(0));
365 		MUTEX_INITIALIZE_ADAPTIVE(mtx, dodebug);
366 		break;
367 	case MUTEX_SPIN:
368 		dodebug = LOCKDEBUG_ALLOC(mtx, &mutex_spin_lockops,
369 		    (uintptr_t)__builtin_return_address(0));
370 		MUTEX_INITIALIZE_SPIN(mtx, dodebug, ipl);
371 		break;
372 	default:
373 		panic("mutex_init: impossible type");
374 		break;
375 	}
376 }
377 
378 /*
379  * mutex_destroy:
380  *
381  *	Tear down a mutex.
382  */
383 void
384 mutex_destroy(kmutex_t *mtx)
385 {
386 
387 	if (MUTEX_ADAPTIVE_P(mtx)) {
388 		MUTEX_ASSERT(mtx, !MUTEX_OWNED(mtx->mtx_owner) &&
389 		    !MUTEX_HAS_WAITERS(mtx));
390 	} else {
391 		MUTEX_ASSERT(mtx, !__SIMPLELOCK_LOCKED_P(&mtx->mtx_lock));
392 	}
393 
394 	LOCKDEBUG_FREE(MUTEX_DEBUG_P(mtx), mtx);
395 	MUTEX_DESTROY(mtx);
396 }
397 
398 /*
399  * mutex_onproc:
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  *	Note that we can't use the mutex owner field as an LWP pointer.  We
406  *	don't have full control over the timing of our execution, and so the
407  *	pointer could be completely invalid by the time we dereference it.
408  */
409 #ifdef MULTIPROCESSOR
410 int
411 mutex_onproc(uintptr_t owner, struct cpu_info **cip)
412 {
413 	CPU_INFO_ITERATOR cii;
414 	struct cpu_info *ci;
415 	struct lwp *l;
416 
417 	if (!MUTEX_OWNED(owner))
418 		return 0;
419 	l = (struct lwp *)MUTEX_OWNER(owner);
420 
421 	/* See if the target is running on a CPU somewhere. */
422 	if ((ci = *cip) != NULL && ci->ci_curlwp == l)
423 		goto run;
424 	for (CPU_INFO_FOREACH(cii, ci))
425 		if (ci->ci_curlwp == l)
426 			goto run;
427 
428 	/* No: it may be safe to block now. */
429 	*cip = NULL;
430 	return 0;
431 
432  run:
433  	/* Target is running; do we need to block? */
434  	*cip = ci;
435 	return ci->ci_biglock_wanted != l;
436 }
437 #endif	/* MULTIPROCESSOR */
438 
439 /*
440  * mutex_vector_enter:
441  *
442  *	Support routine for mutex_enter() that must handles all cases.  In
443  *	the LOCKDEBUG case, mutex_enter() is always aliased here, even if
444  *	fast-path stubs are available.  If an mutex_spin_enter() stub is
445  *	not available, then it is also aliased directly here.
446  */
447 void
448 mutex_vector_enter(kmutex_t *mtx)
449 {
450 	uintptr_t owner, curthread;
451 	turnstile_t *ts;
452 #ifdef MULTIPROCESSOR
453 	struct cpu_info *ci = NULL;
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 	if (MUTEX_SPIN_P(mtx)) {
466 #if defined(LOCKDEBUG) && defined(MULTIPROCESSOR)
467 		u_int spins = 0;
468 #endif
469 		MUTEX_SPIN_SPLRAISE(mtx);
470 		MUTEX_WANTLOCK(mtx);
471 #ifdef FULL
472 		if (__cpu_simple_lock_try(&mtx->mtx_lock)) {
473 			MUTEX_LOCKED(mtx);
474 			return;
475 		}
476 #if !defined(MULTIPROCESSOR)
477 		MUTEX_ABORT(mtx, "locking against myself");
478 #else /* !MULTIPROCESSOR */
479 
480 		LOCKSTAT_ENTER(lsflag);
481 		LOCKSTAT_START_TIMER(lsflag, spintime);
482 		count = SPINLOCK_BACKOFF_MIN;
483 
484 		/*
485 		 * Spin testing the lock word and do exponential backoff
486 		 * to reduce cache line ping-ponging between CPUs.
487 		 */
488 		do {
489 			if (panicstr != NULL)
490 				break;
491 			while (__SIMPLELOCK_LOCKED_P(&mtx->mtx_lock)) {
492 				SPINLOCK_BACKOFF(count);
493 #ifdef LOCKDEBUG
494 				if (SPINLOCK_SPINOUT(spins))
495 					MUTEX_ABORT(mtx, "spinout");
496 #endif	/* LOCKDEBUG */
497 			}
498 		} while (!__cpu_simple_lock_try(&mtx->mtx_lock));
499 
500 		if (count != SPINLOCK_BACKOFF_MIN) {
501 			LOCKSTAT_STOP_TIMER(lsflag, spintime);
502 			LOCKSTAT_EVENT(lsflag, mtx,
503 			    LB_SPIN_MUTEX | LB_SPIN, 1, spintime);
504 		}
505 		LOCKSTAT_EXIT(lsflag);
506 #endif	/* !MULTIPROCESSOR */
507 #endif	/* FULL */
508 		MUTEX_LOCKED(mtx);
509 		return;
510 	}
511 
512 	curthread = (uintptr_t)curlwp;
513 
514 	MUTEX_DASSERT(mtx, MUTEX_ADAPTIVE_P(mtx));
515 	MUTEX_ASSERT(mtx, curthread != 0);
516 	MUTEX_WANTLOCK(mtx);
517 
518 	if (panicstr == NULL) {
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 (owner = mtx->mtx_owner;;) {
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 
546 		if (panicstr != NULL)
547 			return;
548 		if (MUTEX_OWNER(owner) == curthread)
549 			MUTEX_ABORT(mtx, "locking against myself");
550 
551 #ifdef MULTIPROCESSOR
552 		/*
553 		 * Check to see if the owner is running on a processor.
554 		 * If so, then we should just spin, as the owner will
555 		 * likely release the lock very soon.
556 		 */
557 		if (mutex_onproc(owner, &ci)) {
558 			LOCKSTAT_START_TIMER(lsflag, spintime);
559 			count = SPINLOCK_BACKOFF_MIN;
560 			for (;;) {
561 				SPINLOCK_BACKOFF(count);
562 				owner = mtx->mtx_owner;
563 				if (!mutex_onproc(owner, &ci))
564 					break;
565 			}
566 			LOCKSTAT_STOP_TIMER(lsflag, spintime);
567 			LOCKSTAT_COUNT(spincnt, 1);
568 			if (!MUTEX_OWNED(owner))
569 				continue;
570 		}
571 #endif
572 
573 		ts = turnstile_lookup(mtx);
574 
575 		/*
576 		 * Once we have the turnstile chain interlock, mark the
577 		 * mutex has having waiters.  If that fails, spin again:
578 		 * chances are that the mutex has been released.
579 		 */
580 		if (!MUTEX_SET_WAITERS(mtx, owner)) {
581 			turnstile_exit(mtx);
582 			owner = mtx->mtx_owner;
583 			continue;
584 		}
585 
586 #ifdef MULTIPROCESSOR
587 		/*
588 		 * mutex_exit() is permitted to release the mutex without
589 		 * any interlocking instructions, and the following can
590 		 * occur as a result:
591 		 *
592 		 *  CPU 1: MUTEX_SET_WAITERS()      CPU2: mutex_exit()
593 		 * ---------------------------- ----------------------------
594 		 *		..		    acquire cache line
595 		 *		..                   test for waiters
596 		 *	acquire cache line    <-      lose cache line
597 		 *	 lock cache line	           ..
598 		 *     verify mutex is held                ..
599 		 *	    set waiters  	           ..
600 		 *	 unlock cache line		   ..
601 		 *	  lose cache line     ->    acquire cache line
602 		 *		..	          clear lock word, waiters
603 		 *	  return success
604 		 *
605 		 * There is a another race that can occur: a third CPU could
606 		 * acquire the mutex as soon as it is released.  Since
607 		 * adaptive mutexes are primarily spin mutexes, this is not
608 		 * something that we need to worry about too much.  What we
609 		 * do need to ensure is that the waiters bit gets set.
610 		 *
611 		 * To allow the unlocked release, we need to make some
612 		 * assumptions here:
613 		 *
614 		 * o Release is the only non-atomic/unlocked operation
615 		 *   that can be performed on the mutex.  (It must still
616 		 *   be atomic on the local CPU, e.g. in case interrupted
617 		 *   or preempted).
618 		 *
619 		 * o At any given time, MUTEX_SET_WAITERS() can only ever
620 		 *   be in progress on one CPU in the system - guaranteed
621 		 *   by the turnstile chain lock.
622 		 *
623 		 * o No other operations other than MUTEX_SET_WAITERS()
624 		 *   and release can modify a mutex with a non-zero
625 		 *   owner field.
626 		 *
627 		 * o The result of a successful MUTEX_SET_WAITERS() call
628 		 *   is an unbuffered write that is immediately visible
629 		 *   to all other processors in the system.
630 		 *
631 		 * o If the holding LWP switches away, it posts a store
632 		 *   fence before changing curlwp, ensuring that any
633 		 *   overwrite of the mutex waiters flag by mutex_exit()
634 		 *   completes before the modification of curlwp becomes
635 		 *   visible to this CPU.
636 		 *
637 		 * o mi_switch() posts a store fence before setting curlwp
638 		 *   and before resuming execution of an LWP.
639 		 *
640 		 * o _kernel_lock() posts a store fence before setting
641 		 *   curcpu()->ci_biglock_wanted, and after clearing it.
642 		 *   This ensures that any overwrite of the mutex waiters
643 		 *   flag by mutex_exit() completes before the modification
644 		 *   of ci_biglock_wanted becomes visible.
645 		 *
646 		 * We now post a read memory barrier (after setting the
647 		 * waiters field) and check the lock holder's status again.
648 		 * Some of the possible outcomes (not an exhaustive list):
649 		 *
650 		 * 1. The onproc check returns true: the holding LWP is
651 		 *    running again.  The lock may be released soon and
652 		 *    we should spin.  Importantly, we can't trust the
653 		 *    value of the waiters flag.
654 		 *
655 		 * 2. The onproc check returns false: the holding LWP is
656 		 *    not running.  We now have the opportunity to check
657 		 *    if mutex_exit() has blatted the modifications made
658 		 *    by MUTEX_SET_WAITERS().
659 		 *
660 		 * 3. The onproc check returns false: the holding LWP may
661 		 *    or may not be running.  It has context switched at
662 		 *    some point during our check.  Again, we have the
663 		 *    chance to see if the waiters bit is still set or
664 		 *    has been overwritten.
665 		 *
666 		 * 4. The onproc check returns false: the holding LWP is
667 		 *    running on a CPU, but wants the big lock.  It's OK
668 		 *    to check the waiters field in this case.
669 		 *
670 		 * 5. The has-waiters check fails: the mutex has been
671 		 *    released, the waiters flag cleared and another LWP
672 		 *    now owns the mutex.
673 		 *
674 		 * 6. The has-waiters check fails: the mutex has been
675 		 *    released.
676 		 *
677 		 * If the waiters bit is not set it's unsafe to go asleep,
678 		 * as we might never be awoken.
679 		 */
680 		if ((membar_consumer(), mutex_onproc(owner, &ci)) ||
681 		    (membar_consumer(), !MUTEX_HAS_WAITERS(mtx))) {
682 			turnstile_exit(mtx);
683 			owner = mtx->mtx_owner;
684 			continue;
685 		}
686 #endif	/* MULTIPROCESSOR */
687 
688 		LOCKSTAT_START_TIMER(lsflag, slptime);
689 
690 		turnstile_block(ts, TS_WRITER_Q, mtx, &mutex_syncobj);
691 
692 		LOCKSTAT_STOP_TIMER(lsflag, slptime);
693 		LOCKSTAT_COUNT(slpcnt, 1);
694 
695 		owner = mtx->mtx_owner;
696 	}
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)) {
720 #ifdef FULL
721 		if (__predict_false(!__SIMPLELOCK_LOCKED_P(&mtx->mtx_lock))) {
722 			if (panicstr != NULL)
723 				return;
724 			MUTEX_ABORT(mtx, "exiting unheld spin mutex");
725 		}
726 		MUTEX_UNLOCKED(mtx);
727 		__cpu_simple_unlock(&mtx->mtx_lock);
728 #endif
729 		MUTEX_SPIN_SPLRESTORE(mtx);
730 		return;
731 	}
732 
733 	if (__predict_false((uintptr_t)panicstr | cold)) {
734 		MUTEX_UNLOCKED(mtx);
735 		MUTEX_RELEASE(mtx);
736 		return;
737 	}
738 
739 	curthread = (uintptr_t)curlwp;
740 	MUTEX_DASSERT(mtx, curthread != 0);
741 	MUTEX_ASSERT(mtx, MUTEX_OWNER(mtx->mtx_owner) == curthread);
742 	MUTEX_UNLOCKED(mtx);
743 
744 #ifdef LOCKDEBUG
745 	/*
746 	 * Avoid having to take the turnstile chain lock every time
747 	 * around.  Raise the priority level to splhigh() in order
748 	 * to disable preemption and so make the following atomic.
749 	 */
750 	{
751 		int s = splhigh();
752 		if (!MUTEX_HAS_WAITERS(mtx)) {
753 			MUTEX_RELEASE(mtx);
754 			splx(s);
755 			return;
756 		}
757 		splx(s);
758 	}
759 #endif
760 
761 	/*
762 	 * Get this lock's turnstile.  This gets the interlock on
763 	 * the sleep queue.  Once we have that, we can clear the
764 	 * lock.  If there was no turnstile for the lock, there
765 	 * were no waiters remaining.
766 	 */
767 	ts = turnstile_lookup(mtx);
768 
769 	if (ts == NULL) {
770 		MUTEX_RELEASE(mtx);
771 		turnstile_exit(mtx);
772 	} else {
773 		MUTEX_RELEASE(mtx);
774 		turnstile_wakeup(ts, TS_WRITER_Q,
775 		    TS_WAITERS(ts, TS_WRITER_Q), NULL);
776 	}
777 }
778 
779 #ifndef __HAVE_SIMPLE_MUTEXES
780 /*
781  * mutex_wakeup:
782  *
783  *	Support routine for mutex_exit() that wakes up all waiters.
784  *	We assume that the mutex has been released, but it need not
785  *	be.
786  */
787 void
788 mutex_wakeup(kmutex_t *mtx)
789 {
790 	turnstile_t *ts;
791 
792 	ts = turnstile_lookup(mtx);
793 	if (ts == NULL) {
794 		turnstile_exit(mtx);
795 		return;
796 	}
797 	MUTEX_CLEAR_WAITERS(mtx);
798 	turnstile_wakeup(ts, TS_WRITER_Q, TS_WAITERS(ts, TS_WRITER_Q), NULL);
799 }
800 #endif	/* !__HAVE_SIMPLE_MUTEXES */
801 
802 /*
803  * mutex_owned:
804  *
805  *	Return true if the current LWP (adaptive) or CPU (spin)
806  *	holds the mutex.
807  */
808 int
809 mutex_owned(kmutex_t *mtx)
810 {
811 
812 	if (mtx == NULL)
813 		return 0;
814 	if (MUTEX_ADAPTIVE_P(mtx))
815 		return MUTEX_OWNER(mtx->mtx_owner) == (uintptr_t)curlwp;
816 #ifdef FULL
817 	return __SIMPLELOCK_LOCKED_P(&mtx->mtx_lock);
818 #else
819 	return 1;
820 #endif
821 }
822 
823 /*
824  * mutex_owner:
825  *
826  *	Return the current owner of an adaptive mutex.  Used for
827  *	priority inheritance.
828  */
829 lwp_t *
830 mutex_owner(kmutex_t *mtx)
831 {
832 
833 	MUTEX_ASSERT(mtx, MUTEX_ADAPTIVE_P(mtx));
834 	return (struct lwp *)MUTEX_OWNER(mtx->mtx_owner);
835 }
836 
837 /*
838  * mutex_tryenter:
839  *
840  *	Try to acquire the mutex; return non-zero if we did.
841  */
842 int
843 mutex_tryenter(kmutex_t *mtx)
844 {
845 	uintptr_t curthread;
846 
847 	/*
848 	 * Handle spin mutexes.
849 	 */
850 	if (MUTEX_SPIN_P(mtx)) {
851 		MUTEX_SPIN_SPLRAISE(mtx);
852 #ifdef FULL
853 		if (__cpu_simple_lock_try(&mtx->mtx_lock)) {
854 			MUTEX_WANTLOCK(mtx);
855 			MUTEX_LOCKED(mtx);
856 			return 1;
857 		}
858 		MUTEX_SPIN_SPLRESTORE(mtx);
859 #else
860 		MUTEX_WANTLOCK(mtx);
861 		MUTEX_LOCKED(mtx);
862 		return 1;
863 #endif
864 	} else {
865 		curthread = (uintptr_t)curlwp;
866 		MUTEX_ASSERT(mtx, curthread != 0);
867 		if (MUTEX_ACQUIRE(mtx, curthread)) {
868 			MUTEX_WANTLOCK(mtx);
869 			MUTEX_LOCKED(mtx);
870 			MUTEX_DASSERT(mtx,
871 			    MUTEX_OWNER(mtx->mtx_owner) == curthread);
872 			return 1;
873 		}
874 	}
875 
876 	return 0;
877 }
878 
879 #if defined(__HAVE_SPIN_MUTEX_STUBS) || defined(FULL)
880 /*
881  * mutex_spin_retry:
882  *
883  *	Support routine for mutex_spin_enter().  Assumes that the caller
884  *	has already raised the SPL, and adjusted counters.
885  */
886 void
887 mutex_spin_retry(kmutex_t *mtx)
888 {
889 #ifdef MULTIPROCESSOR
890 	u_int count;
891 	LOCKSTAT_TIMER(spintime);
892 	LOCKSTAT_FLAG(lsflag);
893 #ifdef LOCKDEBUG
894 	u_int spins = 0;
895 #endif	/* LOCKDEBUG */
896 
897 	MUTEX_WANTLOCK(mtx);
898 
899 	LOCKSTAT_ENTER(lsflag);
900 	LOCKSTAT_START_TIMER(lsflag, spintime);
901 	count = SPINLOCK_BACKOFF_MIN;
902 
903 	/*
904 	 * Spin testing the lock word and do exponential backoff
905 	 * to reduce cache line ping-ponging between CPUs.
906 	 */
907 	do {
908 		if (panicstr != NULL)
909 			break;
910 		while (__SIMPLELOCK_LOCKED_P(&mtx->mtx_lock)) {
911 			SPINLOCK_BACKOFF(count);
912 #ifdef LOCKDEBUG
913 			if (SPINLOCK_SPINOUT(spins))
914 				MUTEX_ABORT(mtx, "spinout");
915 #endif	/* LOCKDEBUG */
916 		}
917 	} while (!__cpu_simple_lock_try(&mtx->mtx_lock));
918 
919 	LOCKSTAT_STOP_TIMER(lsflag, spintime);
920 	LOCKSTAT_EVENT(lsflag, mtx, LB_SPIN_MUTEX | LB_SPIN, 1, spintime);
921 	LOCKSTAT_EXIT(lsflag);
922 
923 	MUTEX_LOCKED(mtx);
924 #else	/* MULTIPROCESSOR */
925 	MUTEX_ABORT(mtx, "locking against myself");
926 #endif	/* MULTIPROCESSOR */
927 }
928 #endif	/* defined(__HAVE_SPIN_MUTEX_STUBS) || defined(FULL) */
929 
930 /*
931  * mutex_obj_init:
932  *
933  *	Initialize the mutex object store.
934  */
935 void
936 mutex_obj_init(void)
937 {
938 
939 	mutex_obj_cache = pool_cache_init(sizeof(struct kmutexobj),
940 	    coherency_unit, 0, 0, "mutex", NULL, IPL_NONE, mutex_obj_ctor,
941 	    NULL, NULL);
942 }
943 
944 /*
945  * mutex_obj_ctor:
946  *
947  *	Initialize a new lock for the cache.
948  */
949 static int
950 mutex_obj_ctor(void *arg, void *obj, int flags)
951 {
952 	struct kmutexobj * mo = obj;
953 
954 	mo->mo_magic = MUTEX_OBJ_MAGIC;
955 
956 	return 0;
957 }
958 
959 /*
960  * mutex_obj_alloc:
961  *
962  *	Allocate a single lock object.
963  */
964 kmutex_t *
965 mutex_obj_alloc(kmutex_type_t type, int ipl)
966 {
967 	struct kmutexobj *mo;
968 
969 	mo = pool_cache_get(mutex_obj_cache, PR_WAITOK);
970 	mutex_init(&mo->mo_lock, type, ipl);
971 	mo->mo_refcnt = 1;
972 
973 	return (kmutex_t *)mo;
974 }
975 
976 /*
977  * mutex_obj_hold:
978  *
979  *	Add a single reference to a lock object.  A reference to the object
980  *	must already be held, and must be held across this call.
981  */
982 void
983 mutex_obj_hold(kmutex_t *lock)
984 {
985 	struct kmutexobj *mo = (struct kmutexobj *)lock;
986 
987 	KASSERT(mo->mo_magic == MUTEX_OBJ_MAGIC);
988 	KASSERT(mo->mo_refcnt > 0);
989 
990 	atomic_inc_uint(&mo->mo_refcnt);
991 }
992 
993 /*
994  * mutex_obj_free:
995  *
996  *	Drop a reference from a lock object.  If the last reference is being
997  *	dropped, free the object and return true.  Otherwise, return false.
998  */
999 bool
1000 mutex_obj_free(kmutex_t *lock)
1001 {
1002 	struct kmutexobj *mo = (struct kmutexobj *)lock;
1003 
1004 	KASSERT(mo->mo_magic == MUTEX_OBJ_MAGIC);
1005 	KASSERT(mo->mo_refcnt > 0);
1006 
1007 	if (atomic_dec_uint_nv(&mo->mo_refcnt) > 0) {
1008 		return false;
1009 	}
1010 	mutex_destroy(&mo->mo_lock);
1011 	pool_cache_put(mutex_obj_cache, mo);
1012 	return true;
1013 }
1014