xref: /freebsd/sys/kern/kern_mutex.c (revision a678f77962278b50da97a88aac8abe77c192a4f1)
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 __read_mostly 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 __read_mostly 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 	uintptr_t tid, v;
269 
270 	if (SCHEDULER_STOPPED())
271 		return;
272 
273 	m = mtxlock2mtx(c);
274 
275 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
276 	    ("mtx_lock() by idle thread %p on sleep mutex %s @ %s:%d",
277 	    curthread, m->lock_object.lo_name, file, line));
278 	KASSERT(m->mtx_lock != MTX_DESTROYED,
279 	    ("mtx_lock() of destroyed mutex @ %s:%d", file, line));
280 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
281 	    ("mtx_lock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
282 	    file, line));
283 	WITNESS_CHECKORDER(&m->lock_object, (opts & ~MTX_RECURSE) |
284 	    LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
285 
286 	tid = (uintptr_t)curthread;
287 	v = MTX_UNOWNED;
288 	if (!_mtx_obtain_lock_fetch(m, &v, tid))
289 		_mtx_lock_sleep(m, v, tid, opts, file, line);
290 	else
291 		LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
292 		    m, 0, 0, file, line);
293 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
294 	    line);
295 	WITNESS_LOCK(&m->lock_object, (opts & ~MTX_RECURSE) | LOP_EXCLUSIVE,
296 	    file, line);
297 	TD_LOCKS_INC(curthread);
298 }
299 
300 void
301 __mtx_unlock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
302 {
303 	struct mtx *m;
304 
305 	if (SCHEDULER_STOPPED())
306 		return;
307 
308 	m = mtxlock2mtx(c);
309 
310 	KASSERT(m->mtx_lock != MTX_DESTROYED,
311 	    ("mtx_unlock() of destroyed mutex @ %s:%d", file, line));
312 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
313 	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
314 	    file, line));
315 	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
316 	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
317 	    line);
318 	mtx_assert(m, MA_OWNED);
319 
320 	__mtx_unlock_sleep(c, opts, file, line);
321 	TD_LOCKS_DEC(curthread);
322 }
323 
324 void
325 __mtx_lock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
326     int line)
327 {
328 	struct mtx *m;
329 
330 	if (SCHEDULER_STOPPED())
331 		return;
332 
333 	m = mtxlock2mtx(c);
334 
335 	KASSERT(m->mtx_lock != MTX_DESTROYED,
336 	    ("mtx_lock_spin() of destroyed mutex @ %s:%d", file, line));
337 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
338 	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
339 	    m->lock_object.lo_name, file, line));
340 	if (mtx_owned(m))
341 		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
342 		    (opts & MTX_RECURSE) != 0,
343 	    ("mtx_lock_spin: recursed on non-recursive mutex %s @ %s:%d\n",
344 		    m->lock_object.lo_name, file, line));
345 	opts &= ~MTX_RECURSE;
346 	WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
347 	    file, line, NULL);
348 	__mtx_lock_spin(m, curthread, opts, file, line);
349 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
350 	    line);
351 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
352 }
353 
354 int
355 __mtx_trylock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
356     int line)
357 {
358 	struct mtx *m;
359 
360 	if (SCHEDULER_STOPPED())
361 		return (1);
362 
363 	m = mtxlock2mtx(c);
364 
365 	KASSERT(m->mtx_lock != MTX_DESTROYED,
366 	    ("mtx_trylock_spin() of destroyed mutex @ %s:%d", file, line));
367 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
368 	    ("mtx_trylock_spin() of sleep mutex %s @ %s:%d",
369 	    m->lock_object.lo_name, file, line));
370 	KASSERT((opts & MTX_RECURSE) == 0,
371 	    ("mtx_trylock_spin: unsupp. opt MTX_RECURSE on mutex %s @ %s:%d\n",
372 	    m->lock_object.lo_name, file, line));
373 	if (__mtx_trylock_spin(m, curthread, opts, file, line)) {
374 		LOCK_LOG_TRY("LOCK", &m->lock_object, opts, 1, file, line);
375 		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
376 		return (1);
377 	}
378 	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, 0, file, line);
379 	return (0);
380 }
381 
382 void
383 __mtx_unlock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
384     int line)
385 {
386 	struct mtx *m;
387 
388 	if (SCHEDULER_STOPPED())
389 		return;
390 
391 	m = mtxlock2mtx(c);
392 
393 	KASSERT(m->mtx_lock != MTX_DESTROYED,
394 	    ("mtx_unlock_spin() of destroyed mutex @ %s:%d", file, line));
395 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
396 	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
397 	    m->lock_object.lo_name, file, line));
398 	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
399 	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
400 	    line);
401 	mtx_assert(m, MA_OWNED);
402 
403 	__mtx_unlock_spin(m);
404 }
405 
406 /*
407  * The important part of mtx_trylock{,_flags}()
408  * Tries to acquire lock `m.'  If this function is called on a mutex that
409  * is already owned, it will recursively acquire the lock.
410  */
411 int
412 _mtx_trylock_flags_(volatile uintptr_t *c, int opts, const char *file, int line)
413 {
414 	struct mtx *m;
415 #ifdef LOCK_PROFILING
416 	uint64_t waittime = 0;
417 	int contested = 0;
418 #endif
419 	int rval;
420 
421 	if (SCHEDULER_STOPPED())
422 		return (1);
423 
424 	m = mtxlock2mtx(c);
425 
426 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
427 	    ("mtx_trylock() by idle thread %p on sleep mutex %s @ %s:%d",
428 	    curthread, m->lock_object.lo_name, file, line));
429 	KASSERT(m->mtx_lock != MTX_DESTROYED,
430 	    ("mtx_trylock() of destroyed mutex @ %s:%d", file, line));
431 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
432 	    ("mtx_trylock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
433 	    file, line));
434 
435 	if (mtx_owned(m) && ((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
436 	    (opts & MTX_RECURSE) != 0)) {
437 		m->mtx_recurse++;
438 		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
439 		rval = 1;
440 	} else
441 		rval = _mtx_obtain_lock(m, (uintptr_t)curthread);
442 	opts &= ~MTX_RECURSE;
443 
444 	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, rval, file, line);
445 	if (rval) {
446 		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
447 		    file, line);
448 		TD_LOCKS_INC(curthread);
449 		if (m->mtx_recurse == 0)
450 			LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
451 			    m, contested, waittime, file, line);
452 
453 	}
454 
455 	return (rval);
456 }
457 
458 /*
459  * __mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
460  *
461  * We call this if the lock is either contested (i.e. we need to go to
462  * sleep waiting for it), or if we need to recurse on it.
463  */
464 void
465 __mtx_lock_sleep(volatile uintptr_t *c, uintptr_t v, uintptr_t tid, int opts,
466     const char *file, int line)
467 {
468 	struct mtx *m;
469 	struct turnstile *ts;
470 #ifdef ADAPTIVE_MUTEXES
471 	volatile struct thread *owner;
472 #endif
473 #ifdef KTR
474 	int cont_logged = 0;
475 #endif
476 #ifdef LOCK_PROFILING
477 	int contested = 0;
478 	uint64_t waittime = 0;
479 #endif
480 #if defined(ADAPTIVE_MUTEXES) || defined(KDTRACE_HOOKS)
481 	struct lock_delay_arg lda;
482 #endif
483 #ifdef KDTRACE_HOOKS
484 	u_int sleep_cnt = 0;
485 	int64_t sleep_time = 0;
486 	int64_t all_time = 0;
487 #endif
488 
489 	if (SCHEDULER_STOPPED())
490 		return;
491 
492 #if defined(ADAPTIVE_MUTEXES)
493 	lock_delay_arg_init(&lda, &mtx_delay);
494 #elif defined(KDTRACE_HOOKS)
495 	lock_delay_arg_init(&lda, NULL);
496 #endif
497 	m = mtxlock2mtx(c);
498 	if (__predict_false(v == MTX_UNOWNED))
499 		v = MTX_READ_VALUE(m);
500 
501 	if (__predict_false(lv_mtx_owner(v) == (struct thread *)tid)) {
502 		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
503 		    (opts & MTX_RECURSE) != 0,
504 	    ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
505 		    m->lock_object.lo_name, file, line));
506 		opts &= ~MTX_RECURSE;
507 		m->mtx_recurse++;
508 		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
509 		if (LOCK_LOG_TEST(&m->lock_object, opts))
510 			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
511 		return;
512 	}
513 	opts &= ~MTX_RECURSE;
514 
515 #ifdef HWPMC_HOOKS
516 	PMC_SOFT_CALL( , , lock, failed);
517 #endif
518 	lock_profile_obtain_lock_failed(&m->lock_object,
519 		    &contested, &waittime);
520 	if (LOCK_LOG_TEST(&m->lock_object, opts))
521 		CTR4(KTR_LOCK,
522 		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
523 		    m->lock_object.lo_name, (void *)m->mtx_lock, file, line);
524 #ifdef KDTRACE_HOOKS
525 	all_time -= lockstat_nsecs(&m->lock_object);
526 #endif
527 
528 	for (;;) {
529 		if (v == MTX_UNOWNED) {
530 			if (_mtx_obtain_lock_fetch(m, &v, tid))
531 				break;
532 			continue;
533 		}
534 #ifdef KDTRACE_HOOKS
535 		lda.spin_cnt++;
536 #endif
537 #ifdef ADAPTIVE_MUTEXES
538 		/*
539 		 * If the owner is running on another CPU, spin until the
540 		 * owner stops running or the state of the lock changes.
541 		 */
542 		owner = lv_mtx_owner(v);
543 		if (TD_IS_RUNNING(owner)) {
544 			if (LOCK_LOG_TEST(&m->lock_object, 0))
545 				CTR3(KTR_LOCK,
546 				    "%s: spinning on %p held by %p",
547 				    __func__, m, owner);
548 			KTR_STATE1(KTR_SCHED, "thread",
549 			    sched_tdname((struct thread *)tid),
550 			    "spinning", "lockname:\"%s\"",
551 			    m->lock_object.lo_name);
552 			do {
553 				lock_delay(&lda);
554 				v = MTX_READ_VALUE(m);
555 				owner = lv_mtx_owner(v);
556 			} while (v != MTX_UNOWNED && TD_IS_RUNNING(owner));
557 			KTR_STATE0(KTR_SCHED, "thread",
558 			    sched_tdname((struct thread *)tid),
559 			    "running");
560 			continue;
561 		}
562 #endif
563 
564 		ts = turnstile_trywait(&m->lock_object);
565 		v = MTX_READ_VALUE(m);
566 
567 		/*
568 		 * Check if the lock has been released while spinning for
569 		 * the turnstile chain lock.
570 		 */
571 		if (v == MTX_UNOWNED) {
572 			turnstile_cancel(ts);
573 			continue;
574 		}
575 
576 #ifdef ADAPTIVE_MUTEXES
577 		/*
578 		 * The current lock owner might have started executing
579 		 * on another CPU (or the lock could have changed
580 		 * owners) while we were waiting on the turnstile
581 		 * chain lock.  If so, drop the turnstile lock and try
582 		 * again.
583 		 */
584 		owner = lv_mtx_owner(v);
585 		if (TD_IS_RUNNING(owner)) {
586 			turnstile_cancel(ts);
587 			continue;
588 		}
589 #endif
590 
591 		/*
592 		 * If the mutex isn't already contested and a failure occurs
593 		 * setting the contested bit, the mutex was either released
594 		 * or the state of the MTX_RECURSED bit changed.
595 		 */
596 		if ((v & MTX_CONTESTED) == 0 &&
597 		    !atomic_cmpset_ptr(&m->mtx_lock, v, v | MTX_CONTESTED)) {
598 			turnstile_cancel(ts);
599 			v = MTX_READ_VALUE(m);
600 			continue;
601 		}
602 
603 		/*
604 		 * We definitely must sleep for this lock.
605 		 */
606 		mtx_assert(m, MA_NOTOWNED);
607 
608 #ifdef KTR
609 		if (!cont_logged) {
610 			CTR6(KTR_CONTENTION,
611 			    "contention: %p at %s:%d wants %s, taken by %s:%d",
612 			    (void *)tid, file, line, m->lock_object.lo_name,
613 			    WITNESS_FILE(&m->lock_object),
614 			    WITNESS_LINE(&m->lock_object));
615 			cont_logged = 1;
616 		}
617 #endif
618 
619 		/*
620 		 * Block on the turnstile.
621 		 */
622 #ifdef KDTRACE_HOOKS
623 		sleep_time -= lockstat_nsecs(&m->lock_object);
624 #endif
625 		turnstile_wait(ts, mtx_owner(m), TS_EXCLUSIVE_QUEUE);
626 #ifdef KDTRACE_HOOKS
627 		sleep_time += lockstat_nsecs(&m->lock_object);
628 		sleep_cnt++;
629 #endif
630 		v = MTX_READ_VALUE(m);
631 	}
632 #ifdef KDTRACE_HOOKS
633 	all_time += lockstat_nsecs(&m->lock_object);
634 #endif
635 #ifdef KTR
636 	if (cont_logged) {
637 		CTR4(KTR_CONTENTION,
638 		    "contention end: %s acquired by %p at %s:%d",
639 		    m->lock_object.lo_name, (void *)tid, file, line);
640 	}
641 #endif
642 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire, m, contested,
643 	    waittime, file, line);
644 #ifdef KDTRACE_HOOKS
645 	if (sleep_time)
646 		LOCKSTAT_RECORD1(adaptive__block, m, sleep_time);
647 
648 	/*
649 	 * Only record the loops spinning and not sleeping.
650 	 */
651 	if (lda.spin_cnt > sleep_cnt)
652 		LOCKSTAT_RECORD1(adaptive__spin, m, all_time - sleep_time);
653 #endif
654 }
655 
656 static void
657 _mtx_lock_spin_failed(struct mtx *m)
658 {
659 	struct thread *td;
660 
661 	td = mtx_owner(m);
662 
663 	/* If the mutex is unlocked, try again. */
664 	if (td == NULL)
665 		return;
666 
667 	printf( "spin lock %p (%s) held by %p (tid %d) too long\n",
668 	    m, m->lock_object.lo_name, td, td->td_tid);
669 #ifdef WITNESS
670 	witness_display_spinlock(&m->lock_object, td, printf);
671 #endif
672 	panic("spin lock held too long");
673 }
674 
675 #ifdef SMP
676 /*
677  * _mtx_lock_spin_cookie: the tougher part of acquiring an MTX_SPIN lock.
678  *
679  * This is only called if we need to actually spin for the lock. Recursion
680  * is handled inline.
681  */
682 void
683 _mtx_lock_spin_cookie(volatile uintptr_t *c, uintptr_t v, uintptr_t tid,
684     int opts, const char *file, int line)
685 {
686 	struct mtx *m;
687 	struct lock_delay_arg lda;
688 #ifdef LOCK_PROFILING
689 	int contested = 0;
690 	uint64_t waittime = 0;
691 #endif
692 #ifdef KDTRACE_HOOKS
693 	int64_t spin_time = 0;
694 #endif
695 
696 	if (SCHEDULER_STOPPED())
697 		return;
698 
699 	lock_delay_arg_init(&lda, &mtx_spin_delay);
700 	m = mtxlock2mtx(c);
701 
702 	if (LOCK_LOG_TEST(&m->lock_object, opts))
703 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
704 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
705 	    "spinning", "lockname:\"%s\"", m->lock_object.lo_name);
706 
707 #ifdef HWPMC_HOOKS
708 	PMC_SOFT_CALL( , , lock, failed);
709 #endif
710 	lock_profile_obtain_lock_failed(&m->lock_object, &contested, &waittime);
711 #ifdef KDTRACE_HOOKS
712 	spin_time -= lockstat_nsecs(&m->lock_object);
713 #endif
714 	for (;;) {
715 		if (v == MTX_UNOWNED) {
716 			if (_mtx_obtain_lock_fetch(m, &v, tid))
717 				break;
718 			continue;
719 		}
720 		/* Give interrupts a chance while we spin. */
721 		spinlock_exit();
722 		do {
723 			if (lda.spin_cnt < 10000000) {
724 				lock_delay(&lda);
725 			} else {
726 				lda.spin_cnt++;
727 				if (lda.spin_cnt < 60000000 || kdb_active ||
728 				    panicstr != NULL)
729 					DELAY(1);
730 				else
731 					_mtx_lock_spin_failed(m);
732 				cpu_spinwait();
733 			}
734 			v = MTX_READ_VALUE(m);
735 		} while (v != MTX_UNOWNED);
736 		spinlock_enter();
737 	}
738 #ifdef KDTRACE_HOOKS
739 	spin_time += lockstat_nsecs(&m->lock_object);
740 #endif
741 
742 	if (LOCK_LOG_TEST(&m->lock_object, opts))
743 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
744 	KTR_STATE0(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
745 	    "running");
746 
747 #ifdef KDTRACE_HOOKS
748 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire, m,
749 	    contested, waittime, file, line);
750 	if (spin_time != 0)
751 		LOCKSTAT_RECORD1(spin__spin, m, spin_time);
752 #endif
753 }
754 #endif /* SMP */
755 
756 void
757 thread_lock_flags_(struct thread *td, int opts, const char *file, int line)
758 {
759 	struct mtx *m;
760 	uintptr_t tid, v;
761 	struct lock_delay_arg lda;
762 #ifdef LOCK_PROFILING
763 	int contested = 0;
764 	uint64_t waittime = 0;
765 #endif
766 #ifdef KDTRACE_HOOKS
767 	int64_t spin_time = 0;
768 #endif
769 
770 	tid = (uintptr_t)curthread;
771 
772 	if (SCHEDULER_STOPPED()) {
773 		/*
774 		 * Ensure that spinlock sections are balanced even when the
775 		 * scheduler is stopped, since we may otherwise inadvertently
776 		 * re-enable interrupts while dumping core.
777 		 */
778 		spinlock_enter();
779 		return;
780 	}
781 
782 	lock_delay_arg_init(&lda, &mtx_spin_delay);
783 
784 #ifdef KDTRACE_HOOKS
785 	spin_time -= lockstat_nsecs(&td->td_lock->lock_object);
786 #endif
787 	for (;;) {
788 retry:
789 		v = MTX_UNOWNED;
790 		spinlock_enter();
791 		m = td->td_lock;
792 		KASSERT(m->mtx_lock != MTX_DESTROYED,
793 		    ("thread_lock() of destroyed mutex @ %s:%d", file, line));
794 		KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
795 		    ("thread_lock() of sleep mutex %s @ %s:%d",
796 		    m->lock_object.lo_name, file, line));
797 		if (mtx_owned(m))
798 			KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0,
799 	    ("thread_lock: recursed on non-recursive mutex %s @ %s:%d\n",
800 			    m->lock_object.lo_name, file, line));
801 		WITNESS_CHECKORDER(&m->lock_object,
802 		    opts | LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
803 		for (;;) {
804 			if (_mtx_obtain_lock_fetch(m, &v, tid))
805 				break;
806 			if (v == MTX_UNOWNED)
807 				continue;
808 			if (v == tid) {
809 				m->mtx_recurse++;
810 				break;
811 			}
812 #ifdef HWPMC_HOOKS
813 			PMC_SOFT_CALL( , , lock, failed);
814 #endif
815 			lock_profile_obtain_lock_failed(&m->lock_object,
816 			    &contested, &waittime);
817 			/* Give interrupts a chance while we spin. */
818 			spinlock_exit();
819 			do {
820 				if (lda.spin_cnt < 10000000) {
821 					lock_delay(&lda);
822 				} else {
823 					lda.spin_cnt++;
824 					if (lda.spin_cnt < 60000000 ||
825 					    kdb_active || panicstr != NULL)
826 						DELAY(1);
827 					else
828 						_mtx_lock_spin_failed(m);
829 					cpu_spinwait();
830 				}
831 				if (m != td->td_lock)
832 					goto retry;
833 				v = MTX_READ_VALUE(m);
834 			} while (v != MTX_UNOWNED);
835 			spinlock_enter();
836 		}
837 		if (m == td->td_lock)
838 			break;
839 		__mtx_unlock_spin(m);	/* does spinlock_exit() */
840 	}
841 #ifdef KDTRACE_HOOKS
842 	spin_time += lockstat_nsecs(&m->lock_object);
843 #endif
844 	if (m->mtx_recurse == 0)
845 		LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire, m,
846 		    contested, waittime, file, line);
847 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
848 	    line);
849 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
850 #ifdef KDTRACE_HOOKS
851 	if (spin_time != 0)
852 		LOCKSTAT_RECORD1(thread__spin, m, spin_time);
853 #endif
854 }
855 
856 struct mtx *
857 thread_lock_block(struct thread *td)
858 {
859 	struct mtx *lock;
860 
861 	THREAD_LOCK_ASSERT(td, MA_OWNED);
862 	lock = td->td_lock;
863 	td->td_lock = &blocked_lock;
864 	mtx_unlock_spin(lock);
865 
866 	return (lock);
867 }
868 
869 void
870 thread_lock_unblock(struct thread *td, struct mtx *new)
871 {
872 	mtx_assert(new, MA_OWNED);
873 	MPASS(td->td_lock == &blocked_lock);
874 	atomic_store_rel_ptr((volatile void *)&td->td_lock, (uintptr_t)new);
875 }
876 
877 void
878 thread_lock_set(struct thread *td, struct mtx *new)
879 {
880 	struct mtx *lock;
881 
882 	mtx_assert(new, MA_OWNED);
883 	THREAD_LOCK_ASSERT(td, MA_OWNED);
884 	lock = td->td_lock;
885 	td->td_lock = new;
886 	mtx_unlock_spin(lock);
887 }
888 
889 /*
890  * __mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
891  *
892  * We are only called here if the lock is recursed or contested (i.e. we
893  * need to wake up a blocked thread).
894  */
895 void
896 __mtx_unlock_sleep(volatile uintptr_t *c, int opts, const char *file, int line)
897 {
898 	struct mtx *m;
899 	struct turnstile *ts;
900 
901 	if (SCHEDULER_STOPPED())
902 		return;
903 
904 	m = mtxlock2mtx(c);
905 
906 	if (!mtx_recursed(m)) {
907 		LOCKSTAT_PROFILE_RELEASE_LOCK(adaptive__release, m);
908 		if (_mtx_release_lock(m, (uintptr_t)curthread))
909 			return;
910 	} else {
911 		if (--(m->mtx_recurse) == 0)
912 			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
913 		if (LOCK_LOG_TEST(&m->lock_object, opts))
914 			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
915 		return;
916 	}
917 
918 	/*
919 	 * We have to lock the chain before the turnstile so this turnstile
920 	 * can be removed from the hash list if it is empty.
921 	 */
922 	turnstile_chain_lock(&m->lock_object);
923 	ts = turnstile_lookup(&m->lock_object);
924 	if (LOCK_LOG_TEST(&m->lock_object, opts))
925 		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
926 	MPASS(ts != NULL);
927 	turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
928 	_mtx_release_lock_quick(m);
929 
930 	/*
931 	 * This turnstile is now no longer associated with the mutex.  We can
932 	 * unlock the chain lock so a new turnstile may take it's place.
933 	 */
934 	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
935 	turnstile_chain_unlock(&m->lock_object);
936 }
937 
938 /*
939  * All the unlocking of MTX_SPIN locks is done inline.
940  * See the __mtx_unlock_spin() macro for the details.
941  */
942 
943 /*
944  * The backing function for the INVARIANTS-enabled mtx_assert()
945  */
946 #ifdef INVARIANT_SUPPORT
947 void
948 __mtx_assert(const volatile uintptr_t *c, int what, const char *file, int line)
949 {
950 	const struct mtx *m;
951 
952 	if (panicstr != NULL || dumping || SCHEDULER_STOPPED())
953 		return;
954 
955 	m = mtxlock2mtx(c);
956 
957 	switch (what) {
958 	case MA_OWNED:
959 	case MA_OWNED | MA_RECURSED:
960 	case MA_OWNED | MA_NOTRECURSED:
961 		if (!mtx_owned(m))
962 			panic("mutex %s not owned at %s:%d",
963 			    m->lock_object.lo_name, file, line);
964 		if (mtx_recursed(m)) {
965 			if ((what & MA_NOTRECURSED) != 0)
966 				panic("mutex %s recursed at %s:%d",
967 				    m->lock_object.lo_name, file, line);
968 		} else if ((what & MA_RECURSED) != 0) {
969 			panic("mutex %s unrecursed at %s:%d",
970 			    m->lock_object.lo_name, file, line);
971 		}
972 		break;
973 	case MA_NOTOWNED:
974 		if (mtx_owned(m))
975 			panic("mutex %s owned at %s:%d",
976 			    m->lock_object.lo_name, file, line);
977 		break;
978 	default:
979 		panic("unknown mtx_assert at %s:%d", file, line);
980 	}
981 }
982 #endif
983 
984 /*
985  * General init routine used by the MTX_SYSINIT() macro.
986  */
987 void
988 mtx_sysinit(void *arg)
989 {
990 	struct mtx_args *margs = arg;
991 
992 	mtx_init((struct mtx *)margs->ma_mtx, margs->ma_desc, NULL,
993 	    margs->ma_opts);
994 }
995 
996 /*
997  * Mutex initialization routine; initialize lock `m' of type contained in
998  * `opts' with options contained in `opts' and name `name.'  The optional
999  * lock type `type' is used as a general lock category name for use with
1000  * witness.
1001  */
1002 void
1003 _mtx_init(volatile uintptr_t *c, const char *name, const char *type, int opts)
1004 {
1005 	struct mtx *m;
1006 	struct lock_class *class;
1007 	int flags;
1008 
1009 	m = mtxlock2mtx(c);
1010 
1011 	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
1012 	    MTX_NOWITNESS | MTX_DUPOK | MTX_NOPROFILE | MTX_NEW)) == 0);
1013 	ASSERT_ATOMIC_LOAD_PTR(m->mtx_lock,
1014 	    ("%s: mtx_lock not aligned for %s: %p", __func__, name,
1015 	    &m->mtx_lock));
1016 
1017 	/* Determine lock class and lock flags. */
1018 	if (opts & MTX_SPIN)
1019 		class = &lock_class_mtx_spin;
1020 	else
1021 		class = &lock_class_mtx_sleep;
1022 	flags = 0;
1023 	if (opts & MTX_QUIET)
1024 		flags |= LO_QUIET;
1025 	if (opts & MTX_RECURSE)
1026 		flags |= LO_RECURSABLE;
1027 	if ((opts & MTX_NOWITNESS) == 0)
1028 		flags |= LO_WITNESS;
1029 	if (opts & MTX_DUPOK)
1030 		flags |= LO_DUPOK;
1031 	if (opts & MTX_NOPROFILE)
1032 		flags |= LO_NOPROFILE;
1033 	if (opts & MTX_NEW)
1034 		flags |= LO_NEW;
1035 
1036 	/* Initialize mutex. */
1037 	lock_init(&m->lock_object, class, name, type, flags);
1038 
1039 	m->mtx_lock = MTX_UNOWNED;
1040 	m->mtx_recurse = 0;
1041 }
1042 
1043 /*
1044  * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
1045  * passed in as a flag here because if the corresponding mtx_init() was
1046  * called with MTX_QUIET set, then it will already be set in the mutex's
1047  * flags.
1048  */
1049 void
1050 _mtx_destroy(volatile uintptr_t *c)
1051 {
1052 	struct mtx *m;
1053 
1054 	m = mtxlock2mtx(c);
1055 
1056 	if (!mtx_owned(m))
1057 		MPASS(mtx_unowned(m));
1058 	else {
1059 		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
1060 
1061 		/* Perform the non-mtx related part of mtx_unlock_spin(). */
1062 		if (LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin)
1063 			spinlock_exit();
1064 		else
1065 			TD_LOCKS_DEC(curthread);
1066 
1067 		lock_profile_release_lock(&m->lock_object);
1068 		/* Tell witness this isn't locked to make it happy. */
1069 		WITNESS_UNLOCK(&m->lock_object, LOP_EXCLUSIVE, __FILE__,
1070 		    __LINE__);
1071 	}
1072 
1073 	m->mtx_lock = MTX_DESTROYED;
1074 	lock_destroy(&m->lock_object);
1075 }
1076 
1077 /*
1078  * Intialize the mutex code and system mutexes.  This is called from the MD
1079  * startup code prior to mi_startup().  The per-CPU data space needs to be
1080  * setup before this is called.
1081  */
1082 void
1083 mutex_init(void)
1084 {
1085 
1086 	/* Setup turnstiles so that sleep mutexes work. */
1087 	init_turnstiles();
1088 
1089 	/*
1090 	 * Initialize mutexes.
1091 	 */
1092 	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
1093 	mtx_init(&blocked_lock, "blocked lock", NULL, MTX_SPIN);
1094 	blocked_lock.mtx_lock = 0xdeadc0de;	/* Always blocked. */
1095 	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
1096 	mtx_init(&proc0.p_slock, "process slock", NULL, MTX_SPIN);
1097 	mtx_init(&proc0.p_statmtx, "pstatl", NULL, MTX_SPIN);
1098 	mtx_init(&proc0.p_itimmtx, "pitiml", NULL, MTX_SPIN);
1099 	mtx_init(&proc0.p_profmtx, "pprofl", NULL, MTX_SPIN);
1100 	mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
1101 	mtx_lock(&Giant);
1102 }
1103 
1104 #ifdef DDB
1105 void
1106 db_show_mtx(const struct lock_object *lock)
1107 {
1108 	struct thread *td;
1109 	const struct mtx *m;
1110 
1111 	m = (const struct mtx *)lock;
1112 
1113 	db_printf(" flags: {");
1114 	if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
1115 		db_printf("SPIN");
1116 	else
1117 		db_printf("DEF");
1118 	if (m->lock_object.lo_flags & LO_RECURSABLE)
1119 		db_printf(", RECURSE");
1120 	if (m->lock_object.lo_flags & LO_DUPOK)
1121 		db_printf(", DUPOK");
1122 	db_printf("}\n");
1123 	db_printf(" state: {");
1124 	if (mtx_unowned(m))
1125 		db_printf("UNOWNED");
1126 	else if (mtx_destroyed(m))
1127 		db_printf("DESTROYED");
1128 	else {
1129 		db_printf("OWNED");
1130 		if (m->mtx_lock & MTX_CONTESTED)
1131 			db_printf(", CONTESTED");
1132 		if (m->mtx_lock & MTX_RECURSED)
1133 			db_printf(", RECURSED");
1134 	}
1135 	db_printf("}\n");
1136 	if (!mtx_unowned(m) && !mtx_destroyed(m)) {
1137 		td = mtx_owner(m);
1138 		db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
1139 		    td->td_tid, td->td_proc->p_pid, td->td_name);
1140 		if (mtx_recursed(m))
1141 			db_printf(" recursed: %d\n", m->mtx_recurse);
1142 	}
1143 }
1144 #endif
1145