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