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