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