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