xref: /freebsd/sys/kern/kern_mutex.c (revision d5b0e70f7e04d971691517ce1304d86a1e367e2e)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1998 Berkeley Software Design, Inc. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Berkeley Software Design Inc's name may not be used to endorse or
15  *    promote products derived from this software without specific prior
16  *    written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *	from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
31  *	and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
32  */
33 
34 /*
35  * Machine independent bits of mutex implementation.
36  */
37 
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include "opt_adaptive_mutexes.h"
42 #include "opt_ddb.h"
43 #include "opt_hwpmc_hooks.h"
44 #include "opt_sched.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/bus.h>
49 #include <sys/conf.h>
50 #include <sys/kdb.h>
51 #include <sys/kernel.h>
52 #include <sys/ktr.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/mutex.h>
56 #include <sys/proc.h>
57 #include <sys/resourcevar.h>
58 #include <sys/sched.h>
59 #include <sys/sbuf.h>
60 #include <sys/smp.h>
61 #include <sys/sysctl.h>
62 #include <sys/turnstile.h>
63 #include <sys/vmmeter.h>
64 #include <sys/lock_profile.h>
65 
66 #include <machine/atomic.h>
67 #include <machine/bus.h>
68 #include <machine/cpu.h>
69 
70 #include <ddb/ddb.h>
71 
72 #include <fs/devfs/devfs_int.h>
73 
74 #include <vm/vm.h>
75 #include <vm/vm_extern.h>
76 
77 #if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
78 #define	ADAPTIVE_MUTEXES
79 #endif
80 
81 #ifdef HWPMC_HOOKS
82 #include <sys/pmckern.h>
83 PMC_SOFT_DEFINE( , , lock, failed);
84 #endif
85 
86 /*
87  * Return the mutex address when the lock cookie address is provided.
88  * This functionality assumes that struct mtx* have a member named mtx_lock.
89  */
90 #define	mtxlock2mtx(c)	(__containerof(c, struct mtx, mtx_lock))
91 
92 /*
93  * Internal utility macros.
94  */
95 #define mtx_unowned(m)	((m)->mtx_lock == MTX_UNOWNED)
96 
97 #define	mtx_destroyed(m) ((m)->mtx_lock == MTX_DESTROYED)
98 
99 static void	assert_mtx(const struct lock_object *lock, int what);
100 #ifdef DDB
101 static void	db_show_mtx(const struct lock_object *lock);
102 #endif
103 static void	lock_mtx(struct lock_object *lock, uintptr_t how);
104 static void	lock_spin(struct lock_object *lock, uintptr_t how);
105 #ifdef KDTRACE_HOOKS
106 static int	owner_mtx(const struct lock_object *lock,
107 		    struct thread **owner);
108 #endif
109 static uintptr_t unlock_mtx(struct lock_object *lock);
110 static uintptr_t unlock_spin(struct lock_object *lock);
111 
112 /*
113  * Lock classes for sleep and spin mutexes.
114  */
115 struct lock_class lock_class_mtx_sleep = {
116 	.lc_name = "sleep mutex",
117 	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
118 	.lc_assert = assert_mtx,
119 #ifdef DDB
120 	.lc_ddb_show = db_show_mtx,
121 #endif
122 	.lc_lock = lock_mtx,
123 	.lc_unlock = unlock_mtx,
124 #ifdef KDTRACE_HOOKS
125 	.lc_owner = owner_mtx,
126 #endif
127 };
128 struct lock_class lock_class_mtx_spin = {
129 	.lc_name = "spin mutex",
130 	.lc_flags = LC_SPINLOCK | LC_RECURSABLE,
131 	.lc_assert = assert_mtx,
132 #ifdef DDB
133 	.lc_ddb_show = db_show_mtx,
134 #endif
135 	.lc_lock = lock_spin,
136 	.lc_unlock = unlock_spin,
137 #ifdef KDTRACE_HOOKS
138 	.lc_owner = owner_mtx,
139 #endif
140 };
141 
142 #ifdef ADAPTIVE_MUTEXES
143 #ifdef MUTEX_CUSTOM_BACKOFF
144 static SYSCTL_NODE(_debug, OID_AUTO, mtx, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
145     "mtx debugging");
146 
147 static struct lock_delay_config __read_frequently mtx_delay;
148 
149 SYSCTL_U16(_debug_mtx, OID_AUTO, delay_base, CTLFLAG_RW, &mtx_delay.base,
150     0, "");
151 SYSCTL_U16(_debug_mtx, OID_AUTO, delay_max, CTLFLAG_RW, &mtx_delay.max,
152     0, "");
153 
154 LOCK_DELAY_SYSINIT_DEFAULT(mtx_delay);
155 #else
156 #define mtx_delay	locks_delay
157 #endif
158 #endif
159 
160 #ifdef MUTEX_SPIN_CUSTOM_BACKOFF
161 static SYSCTL_NODE(_debug, OID_AUTO, mtx_spin,
162     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
163     "mtx spin debugging");
164 
165 static struct lock_delay_config __read_frequently mtx_spin_delay;
166 
167 SYSCTL_INT(_debug_mtx_spin, OID_AUTO, delay_base, CTLFLAG_RW,
168     &mtx_spin_delay.base, 0, "");
169 SYSCTL_INT(_debug_mtx_spin, OID_AUTO, delay_max, CTLFLAG_RW,
170     &mtx_spin_delay.max, 0, "");
171 
172 LOCK_DELAY_SYSINIT_DEFAULT(mtx_spin_delay);
173 #else
174 #define mtx_spin_delay	locks_delay
175 #endif
176 
177 /*
178  * System-wide mutexes
179  */
180 struct mtx blocked_lock;
181 struct mtx __exclusive_cache_line Giant;
182 
183 static void _mtx_lock_indefinite_check(struct mtx *, struct lock_delay_arg *);
184 
185 void
186 assert_mtx(const struct lock_object *lock, int what)
187 {
188 
189 	/*
190 	 * Treat LA_LOCKED as if LA_XLOCKED was asserted.
191 	 *
192 	 * Some callers of lc_assert uses LA_LOCKED to indicate that either
193 	 * a shared lock or write lock was held, while other callers uses
194 	 * the more strict LA_XLOCKED (used as MA_OWNED).
195 	 *
196 	 * Mutex is the only lock class that can not be shared, as a result,
197 	 * we can reasonably consider the caller really intends to assert
198 	 * LA_XLOCKED when they are asserting LA_LOCKED on a mutex object.
199 	 */
200 	if (what & LA_LOCKED) {
201 		what &= ~LA_LOCKED;
202 		what |= LA_XLOCKED;
203 	}
204 	mtx_assert((const struct mtx *)lock, what);
205 }
206 
207 void
208 lock_mtx(struct lock_object *lock, uintptr_t how)
209 {
210 
211 	mtx_lock((struct mtx *)lock);
212 }
213 
214 void
215 lock_spin(struct lock_object *lock, uintptr_t how)
216 {
217 
218 	mtx_lock_spin((struct mtx *)lock);
219 }
220 
221 uintptr_t
222 unlock_mtx(struct lock_object *lock)
223 {
224 	struct mtx *m;
225 
226 	m = (struct mtx *)lock;
227 	mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
228 	mtx_unlock(m);
229 	return (0);
230 }
231 
232 uintptr_t
233 unlock_spin(struct lock_object *lock)
234 {
235 	struct mtx *m;
236 
237 	m = (struct mtx *)lock;
238 	mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
239 	mtx_unlock_spin(m);
240 	return (0);
241 }
242 
243 #ifdef KDTRACE_HOOKS
244 int
245 owner_mtx(const struct lock_object *lock, struct thread **owner)
246 {
247 	const struct mtx *m;
248 	uintptr_t x;
249 
250 	m = (const struct mtx *)lock;
251 	x = m->mtx_lock;
252 	*owner = (struct thread *)(x & ~MTX_FLAGMASK);
253 	return (*owner != NULL);
254 }
255 #endif
256 
257 /*
258  * Function versions of the inlined __mtx_* macros.  These are used by
259  * modules and can also be called from assembly language if needed.
260  */
261 void
262 __mtx_lock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
263 {
264 	struct mtx *m;
265 	uintptr_t tid, v;
266 
267 	m = mtxlock2mtx(c);
268 
269 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
270 	    !TD_IS_IDLETHREAD(curthread),
271 	    ("mtx_lock() by idle thread %p on sleep mutex %s @ %s:%d",
272 	    curthread, m->lock_object.lo_name, file, line));
273 	KASSERT(m->mtx_lock != MTX_DESTROYED,
274 	    ("mtx_lock() of destroyed mutex @ %s:%d", file, line));
275 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
276 	    ("mtx_lock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
277 	    file, line));
278 	WITNESS_CHECKORDER(&m->lock_object, (opts & ~MTX_RECURSE) |
279 	    LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
280 
281 	tid = (uintptr_t)curthread;
282 	v = MTX_UNOWNED;
283 	if (!_mtx_obtain_lock_fetch(m, &v, tid))
284 		_mtx_lock_sleep(m, v, opts, file, line);
285 	else
286 		LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
287 		    m, 0, 0, file, line);
288 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
289 	    line);
290 	WITNESS_LOCK(&m->lock_object, (opts & ~MTX_RECURSE) | LOP_EXCLUSIVE,
291 	    file, line);
292 	TD_LOCKS_INC(curthread);
293 }
294 
295 void
296 __mtx_unlock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
297 {
298 	struct mtx *m;
299 
300 	m = mtxlock2mtx(c);
301 
302 	KASSERT(m->mtx_lock != MTX_DESTROYED,
303 	    ("mtx_unlock() of destroyed mutex @ %s:%d", file, line));
304 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
305 	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
306 	    file, line));
307 	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
308 	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
309 	    line);
310 	mtx_assert(m, MA_OWNED);
311 
312 #ifdef LOCK_PROFILING
313 	__mtx_unlock_sleep(c, (uintptr_t)curthread, opts, file, line);
314 #else
315 	__mtx_unlock(m, curthread, opts, file, line);
316 #endif
317 	TD_LOCKS_DEC(curthread);
318 }
319 
320 void
321 __mtx_lock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
322     int line)
323 {
324 	struct mtx *m;
325 #ifdef SMP
326 	uintptr_t tid, v;
327 #endif
328 
329 	m = mtxlock2mtx(c);
330 
331 	KASSERT(m->mtx_lock != MTX_DESTROYED,
332 	    ("mtx_lock_spin() of destroyed mutex @ %s:%d", file, line));
333 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
334 	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
335 	    m->lock_object.lo_name, file, line));
336 	if (mtx_owned(m))
337 		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
338 		    (opts & MTX_RECURSE) != 0,
339 	    ("mtx_lock_spin: recursed on non-recursive mutex %s @ %s:%d\n",
340 		    m->lock_object.lo_name, file, line));
341 	opts &= ~MTX_RECURSE;
342 	WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
343 	    file, line, NULL);
344 #ifdef SMP
345 	spinlock_enter();
346 	tid = (uintptr_t)curthread;
347 	v = MTX_UNOWNED;
348 	if (!_mtx_obtain_lock_fetch(m, &v, tid))
349 		_mtx_lock_spin(m, v, opts, file, line);
350 	else
351 		LOCKSTAT_PROFILE_OBTAIN_SPIN_LOCK_SUCCESS(spin__acquire,
352 		    m, 0, 0, file, line);
353 #else
354 	__mtx_lock_spin(m, curthread, opts, file, line);
355 #endif
356 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
357 	    line);
358 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
359 }
360 
361 int
362 __mtx_trylock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
363     int line)
364 {
365 	struct mtx *m;
366 
367 	if (SCHEDULER_STOPPED())
368 		return (1);
369 
370 	m = mtxlock2mtx(c);
371 
372 	KASSERT(m->mtx_lock != MTX_DESTROYED,
373 	    ("mtx_trylock_spin() of destroyed mutex @ %s:%d", file, line));
374 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
375 	    ("mtx_trylock_spin() of sleep mutex %s @ %s:%d",
376 	    m->lock_object.lo_name, file, line));
377 	KASSERT((opts & MTX_RECURSE) == 0,
378 	    ("mtx_trylock_spin: unsupp. opt MTX_RECURSE on mutex %s @ %s:%d\n",
379 	    m->lock_object.lo_name, file, line));
380 	if (__mtx_trylock_spin(m, curthread, opts, file, line)) {
381 		LOCK_LOG_TRY("LOCK", &m->lock_object, opts, 1, file, line);
382 		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
383 		return (1);
384 	}
385 	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, 0, file, line);
386 	return (0);
387 }
388 
389 void
390 __mtx_unlock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
391     int line)
392 {
393 	struct mtx *m;
394 
395 	m = mtxlock2mtx(c);
396 
397 	KASSERT(m->mtx_lock != MTX_DESTROYED,
398 	    ("mtx_unlock_spin() of destroyed mutex @ %s:%d", file, line));
399 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
400 	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
401 	    m->lock_object.lo_name, file, line));
402 	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
403 	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
404 	    line);
405 	mtx_assert(m, MA_OWNED);
406 
407 	__mtx_unlock_spin(m);
408 }
409 
410 /*
411  * The important part of mtx_trylock{,_flags}()
412  * Tries to acquire lock `m.'  If this function is called on a mutex that
413  * is already owned, it will recursively acquire the lock.
414  */
415 int
416 _mtx_trylock_flags_int(struct mtx *m, int opts LOCK_FILE_LINE_ARG_DEF)
417 {
418 	struct thread *td;
419 	uintptr_t tid, v;
420 #ifdef LOCK_PROFILING
421 	uint64_t waittime = 0;
422 	int contested = 0;
423 #endif
424 	int rval;
425 	bool recursed;
426 
427 	td = curthread;
428 	tid = (uintptr_t)td;
429 	if (SCHEDULER_STOPPED_TD(td))
430 		return (1);
431 
432 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
433 	    ("mtx_trylock() by idle thread %p on sleep mutex %s @ %s:%d",
434 	    curthread, m->lock_object.lo_name, file, line));
435 	KASSERT(m->mtx_lock != MTX_DESTROYED,
436 	    ("mtx_trylock() of destroyed mutex @ %s:%d", file, line));
437 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
438 	    ("mtx_trylock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
439 	    file, line));
440 
441 	rval = 1;
442 	recursed = false;
443 	v = MTX_UNOWNED;
444 	for (;;) {
445 		if (_mtx_obtain_lock_fetch(m, &v, tid))
446 			break;
447 		if (v == MTX_UNOWNED)
448 			continue;
449 		if (v == tid &&
450 		    ((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
451 		    (opts & MTX_RECURSE) != 0)) {
452 			m->mtx_recurse++;
453 			atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
454 			recursed = true;
455 			break;
456 		}
457 		rval = 0;
458 		break;
459 	}
460 
461 	opts &= ~MTX_RECURSE;
462 
463 	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, rval, file, line);
464 	if (rval) {
465 		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
466 		    file, line);
467 		TD_LOCKS_INC(curthread);
468 		if (!recursed)
469 			LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
470 			    m, contested, waittime, file, line);
471 	}
472 
473 	return (rval);
474 }
475 
476 int
477 _mtx_trylock_flags_(volatile uintptr_t *c, int opts, const char *file, int line)
478 {
479 	struct mtx *m;
480 
481 	m = mtxlock2mtx(c);
482 	return (_mtx_trylock_flags_int(m, opts LOCK_FILE_LINE_ARG));
483 }
484 
485 /*
486  * __mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
487  *
488  * We call this if the lock is either contested (i.e. we need to go to
489  * sleep waiting for it), or if we need to recurse on it.
490  */
491 #if LOCK_DEBUG > 0
492 void
493 __mtx_lock_sleep(volatile uintptr_t *c, uintptr_t v, int opts, const char *file,
494     int line)
495 #else
496 void
497 __mtx_lock_sleep(volatile uintptr_t *c, uintptr_t v)
498 #endif
499 {
500 	struct thread *td;
501 	struct mtx *m;
502 	struct turnstile *ts;
503 	uintptr_t tid;
504 	struct thread *owner;
505 #ifdef LOCK_PROFILING
506 	int contested = 0;
507 	uint64_t waittime = 0;
508 #endif
509 #if defined(ADAPTIVE_MUTEXES) || defined(KDTRACE_HOOKS)
510 	struct lock_delay_arg lda;
511 #endif
512 #ifdef KDTRACE_HOOKS
513 	u_int sleep_cnt = 0;
514 	int64_t sleep_time = 0;
515 	int64_t all_time = 0;
516 #endif
517 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
518 	int doing_lockprof = 0;
519 #endif
520 
521 	td = curthread;
522 	tid = (uintptr_t)td;
523 	m = mtxlock2mtx(c);
524 
525 #ifdef KDTRACE_HOOKS
526 	if (LOCKSTAT_PROFILE_ENABLED(adaptive__acquire)) {
527 		while (v == MTX_UNOWNED) {
528 			if (_mtx_obtain_lock_fetch(m, &v, tid))
529 				goto out_lockstat;
530 		}
531 		doing_lockprof = 1;
532 		all_time -= lockstat_nsecs(&m->lock_object);
533 	}
534 #endif
535 #ifdef LOCK_PROFILING
536 	doing_lockprof = 1;
537 #endif
538 
539 	if (SCHEDULER_STOPPED_TD(td))
540 		return;
541 
542 	if (__predict_false(v == MTX_UNOWNED))
543 		v = MTX_READ_VALUE(m);
544 
545 	if (__predict_false(lv_mtx_owner(v) == td)) {
546 		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
547 		    (opts & MTX_RECURSE) != 0,
548 	    ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
549 		    m->lock_object.lo_name, file, line));
550 #if LOCK_DEBUG > 0
551 		opts &= ~MTX_RECURSE;
552 #endif
553 		m->mtx_recurse++;
554 		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
555 		if (LOCK_LOG_TEST(&m->lock_object, opts))
556 			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
557 		return;
558 	}
559 #if LOCK_DEBUG > 0
560 	opts &= ~MTX_RECURSE;
561 #endif
562 
563 #if defined(ADAPTIVE_MUTEXES)
564 	lock_delay_arg_init(&lda, &mtx_delay);
565 #elif defined(KDTRACE_HOOKS)
566 	lock_delay_arg_init_noadapt(&lda);
567 #endif
568 
569 #ifdef HWPMC_HOOKS
570 	PMC_SOFT_CALL( , , lock, failed);
571 #endif
572 	lock_profile_obtain_lock_failed(&m->lock_object, false,
573 		    &contested, &waittime);
574 	if (LOCK_LOG_TEST(&m->lock_object, opts))
575 		CTR4(KTR_LOCK,
576 		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
577 		    m->lock_object.lo_name, (void *)m->mtx_lock, file, line);
578 
579 	for (;;) {
580 		if (v == MTX_UNOWNED) {
581 			if (_mtx_obtain_lock_fetch(m, &v, tid))
582 				break;
583 			continue;
584 		}
585 #ifdef KDTRACE_HOOKS
586 		lda.spin_cnt++;
587 #endif
588 #ifdef ADAPTIVE_MUTEXES
589 		/*
590 		 * If the owner is running on another CPU, spin until the
591 		 * owner stops running or the state of the lock changes.
592 		 */
593 		owner = lv_mtx_owner(v);
594 		if (TD_IS_RUNNING(owner)) {
595 			if (LOCK_LOG_TEST(&m->lock_object, 0))
596 				CTR3(KTR_LOCK,
597 				    "%s: spinning on %p held by %p",
598 				    __func__, m, owner);
599 			KTR_STATE1(KTR_SCHED, "thread",
600 			    sched_tdname((struct thread *)tid),
601 			    "spinning", "lockname:\"%s\"",
602 			    m->lock_object.lo_name);
603 			do {
604 				lock_delay(&lda);
605 				v = MTX_READ_VALUE(m);
606 				owner = lv_mtx_owner(v);
607 			} while (v != MTX_UNOWNED && TD_IS_RUNNING(owner));
608 			KTR_STATE0(KTR_SCHED, "thread",
609 			    sched_tdname((struct thread *)tid),
610 			    "running");
611 			continue;
612 		}
613 #endif
614 
615 		ts = turnstile_trywait(&m->lock_object);
616 		v = MTX_READ_VALUE(m);
617 retry_turnstile:
618 
619 		/*
620 		 * Check if the lock has been released while spinning for
621 		 * the turnstile chain lock.
622 		 */
623 		if (v == MTX_UNOWNED) {
624 			turnstile_cancel(ts);
625 			continue;
626 		}
627 
628 #ifdef ADAPTIVE_MUTEXES
629 		/*
630 		 * The current lock owner might have started executing
631 		 * on another CPU (or the lock could have changed
632 		 * owners) while we were waiting on the turnstile
633 		 * chain lock.  If so, drop the turnstile lock and try
634 		 * again.
635 		 */
636 		owner = lv_mtx_owner(v);
637 		if (TD_IS_RUNNING(owner)) {
638 			turnstile_cancel(ts);
639 			continue;
640 		}
641 #endif
642 
643 		/*
644 		 * If the mutex isn't already contested and a failure occurs
645 		 * setting the contested bit, the mutex was either released
646 		 * or the state of the MTX_RECURSED bit changed.
647 		 */
648 		if ((v & MTX_CONTESTED) == 0 &&
649 		    !atomic_fcmpset_ptr(&m->mtx_lock, &v, v | MTX_CONTESTED)) {
650 			goto retry_turnstile;
651 		}
652 
653 		/*
654 		 * We definitely must sleep for this lock.
655 		 */
656 		mtx_assert(m, MA_NOTOWNED);
657 
658 		/*
659 		 * Block on the turnstile.
660 		 */
661 #ifdef KDTRACE_HOOKS
662 		sleep_time -= lockstat_nsecs(&m->lock_object);
663 #endif
664 #ifndef ADAPTIVE_MUTEXES
665 		owner = mtx_owner(m);
666 #endif
667 		MPASS(owner == mtx_owner(m));
668 		turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
669 #ifdef KDTRACE_HOOKS
670 		sleep_time += lockstat_nsecs(&m->lock_object);
671 		sleep_cnt++;
672 #endif
673 		v = MTX_READ_VALUE(m);
674 	}
675 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
676 	if (__predict_true(!doing_lockprof))
677 		return;
678 #endif
679 #ifdef KDTRACE_HOOKS
680 	all_time += lockstat_nsecs(&m->lock_object);
681 	if (sleep_time)
682 		LOCKSTAT_RECORD1(adaptive__block, m, sleep_time);
683 
684 	/*
685 	 * Only record the loops spinning and not sleeping.
686 	 */
687 	if (lda.spin_cnt > sleep_cnt)
688 		LOCKSTAT_RECORD1(adaptive__spin, m, all_time - sleep_time);
689 out_lockstat:
690 #endif
691 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire, m, contested,
692 	    waittime, file, line);
693 }
694 
695 #ifdef SMP
696 /*
697  * _mtx_lock_spin_cookie: the tougher part of acquiring an MTX_SPIN lock.
698  *
699  * This is only called if we need to actually spin for the lock. Recursion
700  * is handled inline.
701  */
702 #if LOCK_DEBUG > 0
703 void
704 _mtx_lock_spin_cookie(volatile uintptr_t *c, uintptr_t v, int opts,
705     const char *file, int line)
706 #else
707 void
708 _mtx_lock_spin_cookie(volatile uintptr_t *c, uintptr_t v)
709 #endif
710 {
711 	struct mtx *m;
712 	struct lock_delay_arg lda;
713 	uintptr_t tid;
714 #ifdef LOCK_PROFILING
715 	int contested = 0;
716 	uint64_t waittime = 0;
717 #endif
718 #ifdef KDTRACE_HOOKS
719 	int64_t spin_time = 0;
720 #endif
721 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
722 	int doing_lockprof = 0;
723 #endif
724 
725 	tid = (uintptr_t)curthread;
726 	m = mtxlock2mtx(c);
727 
728 #ifdef KDTRACE_HOOKS
729 	if (LOCKSTAT_PROFILE_ENABLED(adaptive__acquire)) {
730 		while (v == MTX_UNOWNED) {
731 			if (_mtx_obtain_lock_fetch(m, &v, tid))
732 				goto out_lockstat;
733 		}
734 		doing_lockprof = 1;
735 		spin_time -= lockstat_nsecs(&m->lock_object);
736 	}
737 #endif
738 #ifdef LOCK_PROFILING
739 	doing_lockprof = 1;
740 #endif
741 
742 	if (__predict_false(v == MTX_UNOWNED))
743 		v = MTX_READ_VALUE(m);
744 
745 	if (__predict_false(v == tid)) {
746 		m->mtx_recurse++;
747 		return;
748 	}
749 
750 	if (SCHEDULER_STOPPED())
751 		return;
752 
753 	if (LOCK_LOG_TEST(&m->lock_object, opts))
754 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
755 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
756 	    "spinning", "lockname:\"%s\"", m->lock_object.lo_name);
757 
758 	lock_delay_arg_init(&lda, &mtx_spin_delay);
759 
760 #ifdef HWPMC_HOOKS
761 	PMC_SOFT_CALL( , , lock, failed);
762 #endif
763 	lock_profile_obtain_lock_failed(&m->lock_object, true, &contested, &waittime);
764 
765 	for (;;) {
766 		if (v == MTX_UNOWNED) {
767 			if (_mtx_obtain_lock_fetch(m, &v, tid))
768 				break;
769 			continue;
770 		}
771 		/* Give interrupts a chance while we spin. */
772 		spinlock_exit();
773 		do {
774 			if (__predict_true(lda.spin_cnt < 10000000)) {
775 				lock_delay(&lda);
776 			} else {
777 				_mtx_lock_indefinite_check(m, &lda);
778 			}
779 			v = MTX_READ_VALUE(m);
780 		} while (v != MTX_UNOWNED);
781 		spinlock_enter();
782 	}
783 
784 	if (LOCK_LOG_TEST(&m->lock_object, opts))
785 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
786 	KTR_STATE0(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
787 	    "running");
788 
789 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
790 	if (__predict_true(!doing_lockprof))
791 		return;
792 #endif
793 #ifdef KDTRACE_HOOKS
794 	spin_time += lockstat_nsecs(&m->lock_object);
795 	if (lda.spin_cnt != 0)
796 		LOCKSTAT_RECORD1(spin__spin, m, spin_time);
797 out_lockstat:
798 #endif
799 	LOCKSTAT_PROFILE_OBTAIN_SPIN_LOCK_SUCCESS(spin__acquire, m,
800 	    contested, waittime, file, line);
801 }
802 #endif /* SMP */
803 
804 #ifdef INVARIANTS
805 static void
806 thread_lock_validate(struct mtx *m, int opts, const char *file, int line)
807 {
808 
809 	KASSERT(m->mtx_lock != MTX_DESTROYED,
810 	    ("thread_lock() of destroyed mutex @ %s:%d", file, line));
811 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
812 	    ("thread_lock() of sleep mutex %s @ %s:%d",
813 	    m->lock_object.lo_name, file, line));
814 	KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) == 0,
815 	    ("thread_lock: got a recursive mutex %s @ %s:%d\n",
816 	    m->lock_object.lo_name, file, line));
817 	WITNESS_CHECKORDER(&m->lock_object,
818 	    opts | LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
819 }
820 #else
821 #define thread_lock_validate(m, opts, file, line) do { } while (0)
822 #endif
823 
824 #ifndef LOCK_PROFILING
825 #if LOCK_DEBUG > 0
826 void
827 _thread_lock(struct thread *td, int opts, const char *file, int line)
828 #else
829 void
830 _thread_lock(struct thread *td)
831 #endif
832 {
833 	struct mtx *m;
834 	uintptr_t tid;
835 
836 	tid = (uintptr_t)curthread;
837 
838 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(spin__acquire)))
839 		goto slowpath_noirq;
840 	spinlock_enter();
841 	m = td->td_lock;
842 	thread_lock_validate(m, 0, file, line);
843 	if (__predict_false(m == &blocked_lock))
844 		goto slowpath_unlocked;
845 	if (__predict_false(!_mtx_obtain_lock(m, tid)))
846 		goto slowpath_unlocked;
847 	if (__predict_true(m == td->td_lock)) {
848 		WITNESS_LOCK(&m->lock_object, LOP_EXCLUSIVE, file, line);
849 		return;
850 	}
851 	_mtx_release_lock_quick(m);
852 slowpath_unlocked:
853 	spinlock_exit();
854 slowpath_noirq:
855 #if LOCK_DEBUG > 0
856 	thread_lock_flags_(td, opts, file, line);
857 #else
858 	thread_lock_flags_(td, 0, 0, 0);
859 #endif
860 }
861 #endif
862 
863 void
864 thread_lock_flags_(struct thread *td, int opts, const char *file, int line)
865 {
866 	struct mtx *m;
867 	uintptr_t tid, v;
868 	struct lock_delay_arg lda;
869 #ifdef LOCK_PROFILING
870 	int contested = 0;
871 	uint64_t waittime = 0;
872 #endif
873 #ifdef KDTRACE_HOOKS
874 	int64_t spin_time = 0;
875 #endif
876 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
877 	int doing_lockprof = 1;
878 #endif
879 
880 	tid = (uintptr_t)curthread;
881 
882 	if (SCHEDULER_STOPPED()) {
883 		/*
884 		 * Ensure that spinlock sections are balanced even when the
885 		 * scheduler is stopped, since we may otherwise inadvertently
886 		 * re-enable interrupts while dumping core.
887 		 */
888 		spinlock_enter();
889 		return;
890 	}
891 
892 	lock_delay_arg_init(&lda, &mtx_spin_delay);
893 
894 #ifdef HWPMC_HOOKS
895 	PMC_SOFT_CALL( , , lock, failed);
896 #endif
897 
898 #ifdef LOCK_PROFILING
899 	doing_lockprof = 1;
900 #elif defined(KDTRACE_HOOKS)
901 	doing_lockprof = lockstat_enabled;
902 #endif
903 #ifdef KDTRACE_HOOKS
904 	if (__predict_false(doing_lockprof))
905 		spin_time -= lockstat_nsecs(&td->td_lock->lock_object);
906 #endif
907 	spinlock_enter();
908 
909 	for (;;) {
910 retry:
911 		m = td->td_lock;
912 		thread_lock_validate(m, opts, file, line);
913 		v = MTX_READ_VALUE(m);
914 		for (;;) {
915 			if (v == MTX_UNOWNED) {
916 				if (_mtx_obtain_lock_fetch(m, &v, tid))
917 					break;
918 				continue;
919 			}
920 			MPASS(v != tid);
921 			lock_profile_obtain_lock_failed(&m->lock_object, true,
922 			    &contested, &waittime);
923 			/* Give interrupts a chance while we spin. */
924 			spinlock_exit();
925 			do {
926 				if (__predict_true(lda.spin_cnt < 10000000)) {
927 					lock_delay(&lda);
928 				} else {
929 					_mtx_lock_indefinite_check(m, &lda);
930 				}
931 				if (m != td->td_lock) {
932 					spinlock_enter();
933 					goto retry;
934 				}
935 				v = MTX_READ_VALUE(m);
936 			} while (v != MTX_UNOWNED);
937 			spinlock_enter();
938 		}
939 		if (m == td->td_lock)
940 			break;
941 		_mtx_release_lock_quick(m);
942 	}
943 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
944 	    line);
945 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
946 
947 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
948 	if (__predict_true(!doing_lockprof))
949 		return;
950 #endif
951 #ifdef KDTRACE_HOOKS
952 	spin_time += lockstat_nsecs(&m->lock_object);
953 #endif
954 	LOCKSTAT_PROFILE_OBTAIN_SPIN_LOCK_SUCCESS(spin__acquire, m, contested,
955 	    waittime, file, line);
956 #ifdef KDTRACE_HOOKS
957 	if (lda.spin_cnt != 0)
958 		LOCKSTAT_RECORD1(thread__spin, m, spin_time);
959 #endif
960 }
961 
962 struct mtx *
963 thread_lock_block(struct thread *td)
964 {
965 	struct mtx *lock;
966 
967 	lock = td->td_lock;
968 	mtx_assert(lock, MA_OWNED);
969 	td->td_lock = &blocked_lock;
970 
971 	return (lock);
972 }
973 
974 void
975 thread_lock_unblock(struct thread *td, struct mtx *new)
976 {
977 
978 	mtx_assert(new, MA_OWNED);
979 	KASSERT(td->td_lock == &blocked_lock,
980 	    ("thread %p lock %p not blocked_lock %p",
981 	    td, td->td_lock, &blocked_lock));
982 	atomic_store_rel_ptr((volatile void *)&td->td_lock, (uintptr_t)new);
983 }
984 
985 void
986 thread_lock_block_wait(struct thread *td)
987 {
988 
989 	while (td->td_lock == &blocked_lock)
990 		cpu_spinwait();
991 
992 	/* Acquire fence to be certain that all thread state is visible. */
993 	atomic_thread_fence_acq();
994 }
995 
996 void
997 thread_lock_set(struct thread *td, struct mtx *new)
998 {
999 	struct mtx *lock;
1000 
1001 	mtx_assert(new, MA_OWNED);
1002 	lock = td->td_lock;
1003 	mtx_assert(lock, MA_OWNED);
1004 	td->td_lock = new;
1005 	mtx_unlock_spin(lock);
1006 }
1007 
1008 /*
1009  * __mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
1010  *
1011  * We are only called here if the lock is recursed, contested (i.e. we
1012  * need to wake up a blocked thread) or lockstat probe is active.
1013  */
1014 #if LOCK_DEBUG > 0
1015 void
1016 __mtx_unlock_sleep(volatile uintptr_t *c, uintptr_t v, int opts,
1017     const char *file, int line)
1018 #else
1019 void
1020 __mtx_unlock_sleep(volatile uintptr_t *c, uintptr_t v)
1021 #endif
1022 {
1023 	struct mtx *m;
1024 	struct turnstile *ts;
1025 	uintptr_t tid;
1026 
1027 	if (SCHEDULER_STOPPED())
1028 		return;
1029 
1030 	tid = (uintptr_t)curthread;
1031 	m = mtxlock2mtx(c);
1032 
1033 	if (__predict_false(v == tid))
1034 		v = MTX_READ_VALUE(m);
1035 
1036 	if (__predict_false(v & MTX_RECURSED)) {
1037 		if (--(m->mtx_recurse) == 0)
1038 			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
1039 		if (LOCK_LOG_TEST(&m->lock_object, opts))
1040 			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
1041 		return;
1042 	}
1043 
1044 	LOCKSTAT_PROFILE_RELEASE_LOCK(adaptive__release, m);
1045 	if (v == tid && _mtx_release_lock(m, tid))
1046 		return;
1047 
1048 	/*
1049 	 * We have to lock the chain before the turnstile so this turnstile
1050 	 * can be removed from the hash list if it is empty.
1051 	 */
1052 	turnstile_chain_lock(&m->lock_object);
1053 	_mtx_release_lock_quick(m);
1054 	ts = turnstile_lookup(&m->lock_object);
1055 	MPASS(ts != NULL);
1056 	if (LOCK_LOG_TEST(&m->lock_object, opts))
1057 		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
1058 	turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
1059 
1060 	/*
1061 	 * This turnstile is now no longer associated with the mutex.  We can
1062 	 * unlock the chain lock so a new turnstile may take it's place.
1063 	 */
1064 	turnstile_unpend(ts);
1065 	turnstile_chain_unlock(&m->lock_object);
1066 }
1067 
1068 /*
1069  * All the unlocking of MTX_SPIN locks is done inline.
1070  * See the __mtx_unlock_spin() macro for the details.
1071  */
1072 
1073 /*
1074  * The backing function for the INVARIANTS-enabled mtx_assert()
1075  */
1076 #ifdef INVARIANT_SUPPORT
1077 void
1078 __mtx_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1079 {
1080 	const struct mtx *m;
1081 
1082 	if (KERNEL_PANICKED() || dumping || SCHEDULER_STOPPED())
1083 		return;
1084 
1085 	m = mtxlock2mtx(c);
1086 
1087 	switch (what) {
1088 	case MA_OWNED:
1089 	case MA_OWNED | MA_RECURSED:
1090 	case MA_OWNED | MA_NOTRECURSED:
1091 		if (!mtx_owned(m))
1092 			panic("mutex %s not owned at %s:%d",
1093 			    m->lock_object.lo_name, file, line);
1094 		if (mtx_recursed(m)) {
1095 			if ((what & MA_NOTRECURSED) != 0)
1096 				panic("mutex %s recursed at %s:%d",
1097 				    m->lock_object.lo_name, file, line);
1098 		} else if ((what & MA_RECURSED) != 0) {
1099 			panic("mutex %s unrecursed at %s:%d",
1100 			    m->lock_object.lo_name, file, line);
1101 		}
1102 		break;
1103 	case MA_NOTOWNED:
1104 		if (mtx_owned(m))
1105 			panic("mutex %s owned at %s:%d",
1106 			    m->lock_object.lo_name, file, line);
1107 		break;
1108 	default:
1109 		panic("unknown mtx_assert at %s:%d", file, line);
1110 	}
1111 }
1112 #endif
1113 
1114 /*
1115  * General init routine used by the MTX_SYSINIT() macro.
1116  */
1117 void
1118 mtx_sysinit(void *arg)
1119 {
1120 	struct mtx_args *margs = arg;
1121 
1122 	mtx_init((struct mtx *)margs->ma_mtx, margs->ma_desc, NULL,
1123 	    margs->ma_opts);
1124 }
1125 
1126 /*
1127  * Mutex initialization routine; initialize lock `m' of type contained in
1128  * `opts' with options contained in `opts' and name `name.'  The optional
1129  * lock type `type' is used as a general lock category name for use with
1130  * witness.
1131  */
1132 void
1133 _mtx_init(volatile uintptr_t *c, const char *name, const char *type, int opts)
1134 {
1135 	struct mtx *m;
1136 	struct lock_class *class;
1137 	int flags;
1138 
1139 	m = mtxlock2mtx(c);
1140 
1141 	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
1142 	    MTX_NOWITNESS | MTX_DUPOK | MTX_NOPROFILE | MTX_NEW)) == 0);
1143 	ASSERT_ATOMIC_LOAD_PTR(m->mtx_lock,
1144 	    ("%s: mtx_lock not aligned for %s: %p", __func__, name,
1145 	    &m->mtx_lock));
1146 
1147 	/* Determine lock class and lock flags. */
1148 	if (opts & MTX_SPIN)
1149 		class = &lock_class_mtx_spin;
1150 	else
1151 		class = &lock_class_mtx_sleep;
1152 	flags = 0;
1153 	if (opts & MTX_QUIET)
1154 		flags |= LO_QUIET;
1155 	if (opts & MTX_RECURSE)
1156 		flags |= LO_RECURSABLE;
1157 	if ((opts & MTX_NOWITNESS) == 0)
1158 		flags |= LO_WITNESS;
1159 	if (opts & MTX_DUPOK)
1160 		flags |= LO_DUPOK;
1161 	if (opts & MTX_NOPROFILE)
1162 		flags |= LO_NOPROFILE;
1163 	if (opts & MTX_NEW)
1164 		flags |= LO_NEW;
1165 
1166 	/* Initialize mutex. */
1167 	lock_init(&m->lock_object, class, name, type, flags);
1168 
1169 	m->mtx_lock = MTX_UNOWNED;
1170 	m->mtx_recurse = 0;
1171 }
1172 
1173 /*
1174  * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
1175  * passed in as a flag here because if the corresponding mtx_init() was
1176  * called with MTX_QUIET set, then it will already be set in the mutex's
1177  * flags.
1178  */
1179 void
1180 _mtx_destroy(volatile uintptr_t *c)
1181 {
1182 	struct mtx *m;
1183 
1184 	m = mtxlock2mtx(c);
1185 
1186 	if (!mtx_owned(m))
1187 		MPASS(mtx_unowned(m));
1188 	else {
1189 		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
1190 
1191 		/* Perform the non-mtx related part of mtx_unlock_spin(). */
1192 		if (LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin) {
1193 			lock_profile_release_lock(&m->lock_object, true);
1194 			spinlock_exit();
1195 		} else {
1196 			TD_LOCKS_DEC(curthread);
1197 			lock_profile_release_lock(&m->lock_object, false);
1198 		}
1199 
1200 		/* Tell witness this isn't locked to make it happy. */
1201 		WITNESS_UNLOCK(&m->lock_object, LOP_EXCLUSIVE, __FILE__,
1202 		    __LINE__);
1203 	}
1204 
1205 	m->mtx_lock = MTX_DESTROYED;
1206 	lock_destroy(&m->lock_object);
1207 }
1208 
1209 /*
1210  * Intialize the mutex code and system mutexes.  This is called from the MD
1211  * startup code prior to mi_startup().  The per-CPU data space needs to be
1212  * setup before this is called.
1213  */
1214 void
1215 mutex_init(void)
1216 {
1217 
1218 	/* Setup turnstiles so that sleep mutexes work. */
1219 	init_turnstiles();
1220 
1221 	/*
1222 	 * Initialize mutexes.
1223 	 */
1224 	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
1225 	mtx_init(&blocked_lock, "blocked lock", NULL, MTX_SPIN);
1226 	blocked_lock.mtx_lock = 0xdeadc0de;	/* Always blocked. */
1227 	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
1228 	mtx_init(&proc0.p_slock, "process slock", NULL, MTX_SPIN);
1229 	mtx_init(&proc0.p_statmtx, "pstatl", NULL, MTX_SPIN);
1230 	mtx_init(&proc0.p_itimmtx, "pitiml", NULL, MTX_SPIN);
1231 	mtx_init(&proc0.p_profmtx, "pprofl", NULL, MTX_SPIN);
1232 	mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
1233 	mtx_lock(&Giant);
1234 }
1235 
1236 static void __noinline
1237 _mtx_lock_indefinite_check(struct mtx *m, struct lock_delay_arg *ldap)
1238 {
1239 	struct thread *td;
1240 
1241 	ldap->spin_cnt++;
1242 	if (ldap->spin_cnt < 60000000 || kdb_active || KERNEL_PANICKED())
1243 		cpu_lock_delay();
1244 	else {
1245 		td = mtx_owner(m);
1246 
1247 		/* If the mutex is unlocked, try again. */
1248 		if (td == NULL)
1249 			return;
1250 
1251 		printf( "spin lock %p (%s) held by %p (tid %d) too long\n",
1252 		    m, m->lock_object.lo_name, td, td->td_tid);
1253 #ifdef WITNESS
1254 		witness_display_spinlock(&m->lock_object, td, printf);
1255 #endif
1256 		panic("spin lock held too long");
1257 	}
1258 	cpu_spinwait();
1259 }
1260 
1261 void
1262 mtx_spin_wait_unlocked(struct mtx *m)
1263 {
1264 	struct lock_delay_arg lda;
1265 
1266 	KASSERT(m->mtx_lock != MTX_DESTROYED,
1267 	    ("%s() of destroyed mutex %p", __func__, m));
1268 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
1269 	    ("%s() of sleep mutex %p (%s)", __func__, m,
1270 	    m->lock_object.lo_name));
1271 	KASSERT(!mtx_owned(m), ("%s() waiting on myself on lock %p (%s)", __func__, m,
1272 	    m->lock_object.lo_name));
1273 
1274 	lda.spin_cnt = 0;
1275 
1276 	while (atomic_load_acq_ptr(&m->mtx_lock) != MTX_UNOWNED) {
1277 		if (__predict_true(lda.spin_cnt < 10000000)) {
1278 			cpu_spinwait();
1279 			lda.spin_cnt++;
1280 		} else {
1281 			_mtx_lock_indefinite_check(m, &lda);
1282 		}
1283 	}
1284 }
1285 
1286 void
1287 mtx_wait_unlocked(struct mtx *m)
1288 {
1289 	struct thread *owner;
1290 	uintptr_t v;
1291 
1292 	KASSERT(m->mtx_lock != MTX_DESTROYED,
1293 	    ("%s() of destroyed mutex %p", __func__, m));
1294 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
1295 	    ("%s() not a sleep mutex %p (%s)", __func__, m,
1296 	    m->lock_object.lo_name));
1297 	KASSERT(!mtx_owned(m), ("%s() waiting on myself on lock %p (%s)", __func__, m,
1298 	    m->lock_object.lo_name));
1299 
1300 	for (;;) {
1301 		v = atomic_load_acq_ptr(&m->mtx_lock);
1302 		if (v == MTX_UNOWNED) {
1303 			break;
1304 		}
1305 		owner = lv_mtx_owner(v);
1306 		if (!TD_IS_RUNNING(owner)) {
1307 			mtx_lock(m);
1308 			mtx_unlock(m);
1309 			break;
1310 		}
1311 		cpu_spinwait();
1312 	}
1313 }
1314 
1315 #ifdef DDB
1316 void
1317 db_show_mtx(const struct lock_object *lock)
1318 {
1319 	struct thread *td;
1320 	const struct mtx *m;
1321 
1322 	m = (const struct mtx *)lock;
1323 
1324 	db_printf(" flags: {");
1325 	if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
1326 		db_printf("SPIN");
1327 	else
1328 		db_printf("DEF");
1329 	if (m->lock_object.lo_flags & LO_RECURSABLE)
1330 		db_printf(", RECURSE");
1331 	if (m->lock_object.lo_flags & LO_DUPOK)
1332 		db_printf(", DUPOK");
1333 	db_printf("}\n");
1334 	db_printf(" state: {");
1335 	if (mtx_unowned(m))
1336 		db_printf("UNOWNED");
1337 	else if (mtx_destroyed(m))
1338 		db_printf("DESTROYED");
1339 	else {
1340 		db_printf("OWNED");
1341 		if (m->mtx_lock & MTX_CONTESTED)
1342 			db_printf(", CONTESTED");
1343 		if (m->mtx_lock & MTX_RECURSED)
1344 			db_printf(", RECURSED");
1345 	}
1346 	db_printf("}\n");
1347 	if (!mtx_unowned(m) && !mtx_destroyed(m)) {
1348 		td = mtx_owner(m);
1349 		db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
1350 		    td->td_tid, td->td_proc->p_pid, td->td_name);
1351 		if (mtx_recursed(m))
1352 			db_printf(" recursed: %d\n", m->mtx_recurse);
1353 	}
1354 }
1355 #endif
1356