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