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