xref: /freebsd/sys/kern/kern_mutex.c (revision 35a04710d7286aa9538917fd7f8e417dbee95b82)
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_global.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 /*
79  * Internal utility macros.
80  */
81 #define mtx_unowned(m)	((m)->mtx_lock == MTX_UNOWNED)
82 
83 #define	mtx_destroyed(m) ((m)->mtx_lock == MTX_DESTROYED)
84 
85 #define	mtx_owner(m)	((struct thread *)((m)->mtx_lock & ~MTX_FLAGMASK))
86 
87 static void	assert_mtx(struct lock_object *lock, int what);
88 #ifdef DDB
89 static void	db_show_mtx(struct lock_object *lock);
90 #endif
91 static void	lock_mtx(struct lock_object *lock, int how);
92 static void	lock_spin(struct lock_object *lock, int how);
93 static int	unlock_mtx(struct lock_object *lock);
94 static int	unlock_spin(struct lock_object *lock);
95 
96 /*
97  * Lock classes for sleep and spin mutexes.
98  */
99 struct lock_class lock_class_mtx_sleep = {
100 	.lc_name = "sleep mutex",
101 	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
102 	.lc_assert = assert_mtx,
103 #ifdef DDB
104 	.lc_ddb_show = db_show_mtx,
105 #endif
106 	.lc_lock = lock_mtx,
107 	.lc_unlock = unlock_mtx,
108 };
109 struct lock_class lock_class_mtx_spin = {
110 	.lc_name = "spin mutex",
111 	.lc_flags = LC_SPINLOCK | LC_RECURSABLE,
112 	.lc_assert = assert_mtx,
113 #ifdef DDB
114 	.lc_ddb_show = db_show_mtx,
115 #endif
116 	.lc_lock = lock_spin,
117 	.lc_unlock = unlock_spin,
118 };
119 
120 /*
121  * System-wide mutexes
122  */
123 struct mtx blocked_lock;
124 struct mtx Giant;
125 
126 #ifdef LOCK_PROFILING
127 static inline void lock_profile_init(void)
128 {
129         int i;
130         /* Initialize the mutex profiling locks */
131         for (i = 0; i < LPROF_LOCK_SIZE; i++) {
132                 mtx_init(&lprof_locks[i], "mprof lock",
133                     NULL, MTX_SPIN|MTX_QUIET|MTX_NOPROFILE);
134         }
135 }
136 #else
137 static inline void lock_profile_init(void) {;}
138 #endif
139 
140 void
141 assert_mtx(struct lock_object *lock, int what)
142 {
143 
144 	mtx_assert((struct mtx *)lock, what);
145 }
146 
147 void
148 lock_mtx(struct lock_object *lock, int how)
149 {
150 
151 	mtx_lock((struct mtx *)lock);
152 }
153 
154 void
155 lock_spin(struct lock_object *lock, int how)
156 {
157 
158 	panic("spin locks can only use msleep_spin");
159 }
160 
161 int
162 unlock_mtx(struct lock_object *lock)
163 {
164 	struct mtx *m;
165 
166 	m = (struct mtx *)lock;
167 	mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
168 	mtx_unlock(m);
169 	return (0);
170 }
171 
172 int
173 unlock_spin(struct lock_object *lock)
174 {
175 
176 	panic("spin locks can only use msleep_spin");
177 }
178 
179 /*
180  * Function versions of the inlined __mtx_* macros.  These are used by
181  * modules and can also be called from assembly language if needed.
182  */
183 void
184 _mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
185 {
186 
187 	MPASS(curthread != NULL);
188 	KASSERT(m->mtx_lock != MTX_DESTROYED,
189 	    ("mtx_lock() of destroyed mutex @ %s:%d", file, line));
190 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
191 	    ("mtx_lock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
192 	    file, line));
193 	WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
194 	    file, line);
195 
196 	_get_sleep_lock(m, curthread, opts, file, line);
197 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
198 	    line);
199 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
200 	curthread->td_locks++;
201 }
202 
203 void
204 _mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
205 {
206 	MPASS(curthread != NULL);
207 	KASSERT(m->mtx_lock != MTX_DESTROYED,
208 	    ("mtx_unlock() of destroyed mutex @ %s:%d", file, line));
209 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
210 	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
211 	    file, line));
212 	curthread->td_locks--;
213 	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
214 	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
215 	    line);
216 	mtx_assert(m, MA_OWNED);
217 
218 	if (m->mtx_recurse == 0)
219 		lock_profile_release_lock(&m->lock_object);
220 	_rel_sleep_lock(m, curthread, opts, file, line);
221 }
222 
223 void
224 _mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
225 {
226 
227 	MPASS(curthread != NULL);
228 	KASSERT(m->mtx_lock != MTX_DESTROYED,
229 	    ("mtx_lock_spin() of destroyed mutex @ %s:%d", file, line));
230 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
231 	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
232 	    m->lock_object.lo_name, file, line));
233 	WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
234 	    file, line);
235 	_get_spin_lock(m, curthread, opts, file, line);
236 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
237 	    line);
238 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
239 }
240 
241 void
242 _mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
243 {
244 
245 	MPASS(curthread != NULL);
246 	KASSERT(m->mtx_lock != MTX_DESTROYED,
247 	    ("mtx_unlock_spin() of destroyed mutex @ %s:%d", file, line));
248 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
249 	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
250 	    m->lock_object.lo_name, file, line));
251 	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
252 	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
253 	    line);
254 	mtx_assert(m, MA_OWNED);
255 
256 	_rel_spin_lock(m);
257 }
258 
259 /*
260  * The important part of mtx_trylock{,_flags}()
261  * Tries to acquire lock `m.'  If this function is called on a mutex that
262  * is already owned, it will recursively acquire the lock.
263  */
264 int
265 _mtx_trylock(struct mtx *m, int opts, const char *file, int line)
266 {
267 	int rval, contested = 0;
268 	uint64_t waittime = 0;
269 
270 	MPASS(curthread != NULL);
271 	KASSERT(m->mtx_lock != MTX_DESTROYED,
272 	    ("mtx_trylock() of destroyed mutex @ %s:%d", file, line));
273 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
274 	    ("mtx_trylock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
275 	    file, line));
276 
277 	if (mtx_owned(m) && (m->lock_object.lo_flags & LO_RECURSABLE) != 0) {
278 		m->mtx_recurse++;
279 		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
280 		rval = 1;
281 	} else
282 		rval = _obtain_lock(m, (uintptr_t)curthread);
283 
284 	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, rval, file, line);
285 	if (rval) {
286 		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
287 		    file, line);
288 		curthread->td_locks++;
289 		if (m->mtx_recurse == 0)
290 			lock_profile_obtain_lock_success(&m->lock_object, contested,
291 			    waittime, file, line);
292 
293 	}
294 
295 	return (rval);
296 }
297 
298 /*
299  * _mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
300  *
301  * We call this if the lock is either contested (i.e. we need to go to
302  * sleep waiting for it), or if we need to recurse on it.
303  */
304 void
305 _mtx_lock_sleep(struct mtx *m, uintptr_t tid, int opts, const char *file,
306     int line)
307 {
308 	struct turnstile *ts;
309 #ifdef ADAPTIVE_MUTEXES
310 	volatile struct thread *owner;
311 #endif
312 #ifdef KTR
313 	int cont_logged = 0;
314 #endif
315 	int contested = 0;
316 	uint64_t waittime = 0;
317 	uintptr_t v;
318 
319 	if (mtx_owned(m)) {
320 		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0,
321 	    ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
322 		    m->lock_object.lo_name, file, line));
323 		m->mtx_recurse++;
324 		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
325 		if (LOCK_LOG_TEST(&m->lock_object, opts))
326 			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
327 		return;
328 	}
329 
330 	lock_profile_obtain_lock_failed(&m->lock_object,
331 		    &contested, &waittime);
332 	if (LOCK_LOG_TEST(&m->lock_object, opts))
333 		CTR4(KTR_LOCK,
334 		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
335 		    m->lock_object.lo_name, (void *)m->mtx_lock, file, line);
336 
337 	while (!_obtain_lock(m, tid)) {
338 #ifdef ADAPTIVE_MUTEXES
339 		/*
340 		 * If the owner is running on another CPU, spin until the
341 		 * owner stops running or the state of the lock changes.
342 		 */
343 		v = m->mtx_lock;
344 		if (v != MTX_UNOWNED) {
345 			owner = (struct thread *)(v & ~MTX_FLAGMASK);
346 			if (TD_IS_RUNNING(owner)) {
347 				if (LOCK_LOG_TEST(&m->lock_object, 0))
348 					CTR3(KTR_LOCK,
349 					    "%s: spinning on %p held by %p",
350 					    __func__, m, owner);
351 				while (mtx_owner(m) == owner &&
352 				    TD_IS_RUNNING(owner))
353 					cpu_spinwait();
354 				continue;
355 			}
356 		}
357 #endif
358 
359 		ts = turnstile_trywait(&m->lock_object);
360 		v = m->mtx_lock;
361 
362 		/*
363 		 * Check if the lock has been released while spinning for
364 		 * the turnstile chain lock.
365 		 */
366 		if (v == MTX_UNOWNED) {
367 			turnstile_cancel(ts);
368 			cpu_spinwait();
369 			continue;
370 		}
371 
372 		MPASS(v != MTX_CONTESTED);
373 
374 #ifdef ADAPTIVE_MUTEXES
375 		/*
376 		 * If the current owner of the lock is executing on another
377 		 * CPU quit the hard path and try to spin.
378 		 */
379 		owner = (struct thread *)(v & ~MTX_FLAGMASK);
380 		if (TD_IS_RUNNING(owner)) {
381 			turnstile_cancel(ts);
382 			cpu_spinwait();
383 			continue;
384 		}
385 #endif
386 
387 		/*
388 		 * If the mutex isn't already contested and a failure occurs
389 		 * setting the contested bit, the mutex was either released
390 		 * or the state of the MTX_RECURSED bit changed.
391 		 */
392 		if ((v & MTX_CONTESTED) == 0 &&
393 		    !atomic_cmpset_ptr(&m->mtx_lock, v, v | MTX_CONTESTED)) {
394 			turnstile_cancel(ts);
395 			cpu_spinwait();
396 			continue;
397 		}
398 
399 		/*
400 		 * We definitely must sleep for this lock.
401 		 */
402 		mtx_assert(m, MA_NOTOWNED);
403 
404 #ifdef KTR
405 		if (!cont_logged) {
406 			CTR6(KTR_CONTENTION,
407 			    "contention: %p at %s:%d wants %s, taken by %s:%d",
408 			    (void *)tid, file, line, m->lock_object.lo_name,
409 			    WITNESS_FILE(&m->lock_object),
410 			    WITNESS_LINE(&m->lock_object));
411 			cont_logged = 1;
412 		}
413 #endif
414 
415 		/*
416 		 * Block on the turnstile.
417 		 */
418 		turnstile_wait(ts, mtx_owner(m), TS_EXCLUSIVE_QUEUE);
419 	}
420 #ifdef KTR
421 	if (cont_logged) {
422 		CTR4(KTR_CONTENTION,
423 		    "contention end: %s acquired by %p at %s:%d",
424 		    m->lock_object.lo_name, (void *)tid, file, line);
425 	}
426 #endif
427 	lock_profile_obtain_lock_success(&m->lock_object, contested,
428 	    waittime, (file), (line));
429 }
430 
431 static void
432 _mtx_lock_spin_failed(struct mtx *m)
433 {
434 	struct thread *td;
435 
436 	td = mtx_owner(m);
437 
438 	/* If the mutex is unlocked, try again. */
439 	if (td == NULL)
440 		return;
441 
442 	printf( "spin lock %p (%s) held by %p (tid %d) too long\n",
443 	    m, m->lock_object.lo_name, td, td->td_tid);
444 #ifdef WITNESS
445 	witness_display_spinlock(&m->lock_object, td);
446 #endif
447 	panic("spin lock held too long");
448 }
449 
450 #ifdef SMP
451 /*
452  * _mtx_lock_spin: the tougher part of acquiring an MTX_SPIN lock.
453  *
454  * This is only called if we need to actually spin for the lock. Recursion
455  * is handled inline.
456  */
457 void
458 _mtx_lock_spin(struct mtx *m, uintptr_t tid, int opts, const char *file,
459     int line)
460 {
461 	int i = 0, contested = 0;
462 	uint64_t waittime = 0;
463 
464 	if (LOCK_LOG_TEST(&m->lock_object, opts))
465 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
466 
467 	lock_profile_obtain_lock_failed(&m->lock_object, &contested, &waittime);
468 	while (!_obtain_lock(m, tid)) {
469 
470 		/* Give interrupts a chance while we spin. */
471 		spinlock_exit();
472 		while (m->mtx_lock != MTX_UNOWNED) {
473 			if (i++ < 10000000) {
474 				cpu_spinwait();
475 				continue;
476 			}
477 			if (i < 60000000 || kdb_active || panicstr != NULL)
478 				DELAY(1);
479 			else
480 				_mtx_lock_spin_failed(m);
481 			cpu_spinwait();
482 		}
483 		spinlock_enter();
484 	}
485 
486 	if (LOCK_LOG_TEST(&m->lock_object, opts))
487 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
488 
489 	lock_profile_obtain_lock_success(&m->lock_object, contested,
490 	    waittime, (file), (line));
491 }
492 #endif /* SMP */
493 
494 void
495 _thread_lock_flags(struct thread *td, int opts, const char *file, int line)
496 {
497 	struct mtx *m;
498 	uintptr_t tid;
499 	int i, contested;
500 	uint64_t waittime;
501 
502 
503 	contested = i = 0;
504 	waittime = 0;
505 	tid = (uintptr_t)curthread;
506 	for (;;) {
507 retry:
508 		spinlock_enter();
509 		m = td->td_lock;
510 		WITNESS_CHECKORDER(&m->lock_object,
511 		    opts | LOP_NEWORDER | LOP_EXCLUSIVE, file, line);
512 		while (!_obtain_lock(m, tid)) {
513 			if (m->mtx_lock == tid) {
514 				m->mtx_recurse++;
515 				break;
516 			}
517 			lock_profile_obtain_lock_failed(&m->lock_object, &contested, &waittime);
518 			/* Give interrupts a chance while we spin. */
519 			spinlock_exit();
520 			while (m->mtx_lock != MTX_UNOWNED) {
521 				if (i++ < 10000000)
522 					cpu_spinwait();
523 				else if (i < 60000000 ||
524 				    kdb_active || panicstr != NULL)
525 					DELAY(1);
526 				else
527 					_mtx_lock_spin_failed(m);
528 				cpu_spinwait();
529 				if (m != td->td_lock)
530 					goto retry;
531 			}
532 			spinlock_enter();
533 		}
534 		if (m == td->td_lock)
535 			break;
536 		_rel_spin_lock(m);	/* does spinlock_exit() */
537 	}
538 	lock_profile_obtain_lock_success(&m->lock_object, contested,
539 	    waittime, (file), (line));
540 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
541 }
542 
543 struct mtx *
544 thread_lock_block(struct thread *td)
545 {
546 	struct mtx *lock;
547 
548 	spinlock_enter();
549 	THREAD_LOCK_ASSERT(td, MA_OWNED);
550 	lock = td->td_lock;
551 	td->td_lock = &blocked_lock;
552 	mtx_unlock_spin(lock);
553 
554 	return (lock);
555 }
556 
557 void
558 thread_lock_unblock(struct thread *td, struct mtx *new)
559 {
560 	mtx_assert(new, MA_OWNED);
561 	MPASS(td->td_lock == &blocked_lock);
562 	atomic_store_rel_ptr((volatile void *)&td->td_lock, (uintptr_t)new);
563 	spinlock_exit();
564 }
565 
566 void
567 thread_lock_set(struct thread *td, struct mtx *new)
568 {
569 	struct mtx *lock;
570 
571 	mtx_assert(new, MA_OWNED);
572 	THREAD_LOCK_ASSERT(td, MA_OWNED);
573 	lock = td->td_lock;
574 	td->td_lock = new;
575 	mtx_unlock_spin(lock);
576 }
577 
578 /*
579  * _mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
580  *
581  * We are only called here if the lock is recursed or contested (i.e. we
582  * need to wake up a blocked thread).
583  */
584 void
585 _mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line)
586 {
587 	struct turnstile *ts;
588 
589 	if (mtx_recursed(m)) {
590 		if (--(m->mtx_recurse) == 0)
591 			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
592 		if (LOCK_LOG_TEST(&m->lock_object, opts))
593 			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
594 		return;
595 	}
596 
597 	/*
598 	 * We have to lock the chain before the turnstile so this turnstile
599 	 * can be removed from the hash list if it is empty.
600 	 */
601 	turnstile_chain_lock(&m->lock_object);
602 	ts = turnstile_lookup(&m->lock_object);
603 	if (LOCK_LOG_TEST(&m->lock_object, opts))
604 		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
605 
606 	MPASS(ts != NULL);
607 	turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
608 	_release_lock_quick(m);
609 	/*
610 	 * This turnstile is now no longer associated with the mutex.  We can
611 	 * unlock the chain lock so a new turnstile may take it's place.
612 	 */
613 	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
614 	turnstile_chain_unlock(&m->lock_object);
615 }
616 
617 /*
618  * All the unlocking of MTX_SPIN locks is done inline.
619  * See the _rel_spin_lock() macro for the details.
620  */
621 
622 /*
623  * The backing function for the INVARIANTS-enabled mtx_assert()
624  */
625 #ifdef INVARIANT_SUPPORT
626 void
627 _mtx_assert(struct mtx *m, int what, const char *file, int line)
628 {
629 
630 	if (panicstr != NULL || dumping)
631 		return;
632 	switch (what) {
633 	case MA_OWNED:
634 	case MA_OWNED | MA_RECURSED:
635 	case MA_OWNED | MA_NOTRECURSED:
636 		if (!mtx_owned(m))
637 			panic("mutex %s not owned at %s:%d",
638 			    m->lock_object.lo_name, file, line);
639 		if (mtx_recursed(m)) {
640 			if ((what & MA_NOTRECURSED) != 0)
641 				panic("mutex %s recursed at %s:%d",
642 				    m->lock_object.lo_name, file, line);
643 		} else if ((what & MA_RECURSED) != 0) {
644 			panic("mutex %s unrecursed at %s:%d",
645 			    m->lock_object.lo_name, file, line);
646 		}
647 		break;
648 	case MA_NOTOWNED:
649 		if (mtx_owned(m))
650 			panic("mutex %s owned at %s:%d",
651 			    m->lock_object.lo_name, file, line);
652 		break;
653 	default:
654 		panic("unknown mtx_assert at %s:%d", file, line);
655 	}
656 }
657 #endif
658 
659 /*
660  * The MUTEX_DEBUG-enabled mtx_validate()
661  *
662  * Most of these checks have been moved off into the LO_INITIALIZED flag
663  * maintained by the witness code.
664  */
665 #ifdef MUTEX_DEBUG
666 
667 void	mtx_validate(struct mtx *);
668 
669 void
670 mtx_validate(struct mtx *m)
671 {
672 
673 /*
674  * XXX: When kernacc() does not require Giant we can reenable this check
675  */
676 #ifdef notyet
677 	/*
678 	 * Can't call kernacc() from early init386(), especially when
679 	 * initializing Giant mutex, because some stuff in kernacc()
680 	 * requires Giant itself.
681 	 */
682 	if (!cold)
683 		if (!kernacc((caddr_t)m, sizeof(m),
684 		    VM_PROT_READ | VM_PROT_WRITE))
685 			panic("Can't read and write to mutex %p", m);
686 #endif
687 }
688 #endif
689 
690 /*
691  * General init routine used by the MTX_SYSINIT() macro.
692  */
693 void
694 mtx_sysinit(void *arg)
695 {
696 	struct mtx_args *margs = arg;
697 
698 	mtx_init(margs->ma_mtx, margs->ma_desc, NULL, margs->ma_opts);
699 }
700 
701 /*
702  * Mutex initialization routine; initialize lock `m' of type contained in
703  * `opts' with options contained in `opts' and name `name.'  The optional
704  * lock type `type' is used as a general lock category name for use with
705  * witness.
706  */
707 void
708 mtx_init(struct mtx *m, const char *name, const char *type, int opts)
709 {
710 	struct lock_class *class;
711 	int flags;
712 
713 	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
714 		MTX_NOWITNESS | MTX_DUPOK | MTX_NOPROFILE)) == 0);
715 
716 #ifdef MUTEX_DEBUG
717 	/* Diagnostic and error correction */
718 	mtx_validate(m);
719 #endif
720 
721 	/* Determine lock class and lock flags. */
722 	if (opts & MTX_SPIN)
723 		class = &lock_class_mtx_spin;
724 	else
725 		class = &lock_class_mtx_sleep;
726 	flags = 0;
727 	if (opts & MTX_QUIET)
728 		flags |= LO_QUIET;
729 	if (opts & MTX_RECURSE)
730 		flags |= LO_RECURSABLE;
731 	if ((opts & MTX_NOWITNESS) == 0)
732 		flags |= LO_WITNESS;
733 	if (opts & MTX_DUPOK)
734 		flags |= LO_DUPOK;
735 	if (opts & MTX_NOPROFILE)
736 		flags |= LO_NOPROFILE;
737 
738 	/* Initialize mutex. */
739 	m->mtx_lock = MTX_UNOWNED;
740 	m->mtx_recurse = 0;
741 
742 	lock_init(&m->lock_object, class, name, type, flags);
743 }
744 
745 /*
746  * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
747  * passed in as a flag here because if the corresponding mtx_init() was
748  * called with MTX_QUIET set, then it will already be set in the mutex's
749  * flags.
750  */
751 void
752 mtx_destroy(struct mtx *m)
753 {
754 
755 	if (!mtx_owned(m))
756 		MPASS(mtx_unowned(m));
757 	else {
758 		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
759 
760 		/* Perform the non-mtx related part of mtx_unlock_spin(). */
761 		if (LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin)
762 			spinlock_exit();
763 		else
764 			curthread->td_locks--;
765 
766 		/* Tell witness this isn't locked to make it happy. */
767 		WITNESS_UNLOCK(&m->lock_object, LOP_EXCLUSIVE, __FILE__,
768 		    __LINE__);
769 	}
770 
771 	m->mtx_lock = MTX_DESTROYED;
772 	lock_destroy(&m->lock_object);
773 }
774 
775 /*
776  * Intialize the mutex code and system mutexes.  This is called from the MD
777  * startup code prior to mi_startup().  The per-CPU data space needs to be
778  * setup before this is called.
779  */
780 void
781 mutex_init(void)
782 {
783 
784 	/* Setup turnstiles so that sleep mutexes work. */
785 	init_turnstiles();
786 
787 	/*
788 	 * Initialize mutexes.
789 	 */
790 	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
791 	mtx_init(&blocked_lock, "blocked lock", NULL, MTX_SPIN);
792 	blocked_lock.mtx_lock = 0xdeadc0de;	/* Always blocked. */
793 	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
794 	mtx_init(&proc0.p_slock, "process slock", NULL, MTX_SPIN | MTX_RECURSE);
795 	mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
796 	mtx_lock(&Giant);
797 
798 	lock_profile_init();
799 }
800 
801 #ifdef DDB
802 void
803 db_show_mtx(struct lock_object *lock)
804 {
805 	struct thread *td;
806 	struct mtx *m;
807 
808 	m = (struct mtx *)lock;
809 
810 	db_printf(" flags: {");
811 	if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
812 		db_printf("SPIN");
813 	else
814 		db_printf("DEF");
815 	if (m->lock_object.lo_flags & LO_RECURSABLE)
816 		db_printf(", RECURSE");
817 	if (m->lock_object.lo_flags & LO_DUPOK)
818 		db_printf(", DUPOK");
819 	db_printf("}\n");
820 	db_printf(" state: {");
821 	if (mtx_unowned(m))
822 		db_printf("UNOWNED");
823 	else if (mtx_destroyed(m))
824 		db_printf("DESTROYED");
825 	else {
826 		db_printf("OWNED");
827 		if (m->mtx_lock & MTX_CONTESTED)
828 			db_printf(", CONTESTED");
829 		if (m->mtx_lock & MTX_RECURSED)
830 			db_printf(", RECURSED");
831 	}
832 	db_printf("}\n");
833 	if (!mtx_unowned(m) && !mtx_destroyed(m)) {
834 		td = mtx_owner(m);
835 		db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
836 		    td->td_tid, td->td_proc->p_pid, td->td_name);
837 		if (mtx_recursed(m))
838 			db_printf(" recursed: %d\n", m->mtx_recurse);
839 	}
840 }
841 #endif
842