kern_mutex.c revision 170339
1193242Ssam/*-
2193242Ssam * Copyright (c) 1998 Berkeley Software Design, Inc. All rights reserved.
3193242Ssam *
4193242Ssam * Redistribution and use in source and binary forms, with or without
5193242Ssam * modification, are permitted provided that the following conditions
6193242Ssam * are met:
7193242Ssam * 1. Redistributions of source code must retain the above copyright
8193242Ssam *    notice, this list of conditions and the following disclaimer.
9193242Ssam * 2. Redistributions in binary form must reproduce the above copyright
10193242Ssam *    notice, this list of conditions and the following disclaimer in the
11193242Ssam *    documentation and/or other materials provided with the distribution.
12193242Ssam * 3. Berkeley Software Design Inc's name may not be used to endorse or
13193242Ssam *    promote products derived from this software without specific prior
14193242Ssam *    written permission.
15193242Ssam *
16193242Ssam * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
17193242Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18193242Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19193242Ssam * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
20193242Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21193242Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22193242Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23193242Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24193242Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25193242Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26193242Ssam * SUCH DAMAGE.
27193242Ssam *
28193242Ssam *	from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
29193242Ssam *	and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
30193242Ssam */
31193242Ssam
32193242Ssam/*
33193242Ssam * Machine independent bits of mutex implementation.
34193242Ssam */
35193242Ssam
36193242Ssam#include <sys/cdefs.h>
37193242Ssam__FBSDID("$FreeBSD: head/sys/kern/kern_mutex.c 170339 2007-06-05 18:57:09Z attilio $");
38193242Ssam
39193242Ssam#include "opt_adaptive_mutexes.h"
40193242Ssam#include "opt_ddb.h"
41193242Ssam#include "opt_global.h"
42193242Ssam#include "opt_mutex_wake_all.h"
43193242Ssam#include "opt_sched.h"
44193242Ssam
45193242Ssam#include <sys/param.h>
46193242Ssam#include <sys/systm.h>
47193242Ssam#include <sys/bus.h>
48193242Ssam#include <sys/conf.h>
49193242Ssam#include <sys/kdb.h>
50193242Ssam#include <sys/kernel.h>
51193242Ssam#include <sys/ktr.h>
52193242Ssam#include <sys/lock.h>
53193242Ssam#include <sys/malloc.h>
54193242Ssam#include <sys/mutex.h>
55193242Ssam#include <sys/proc.h>
56193242Ssam#include <sys/resourcevar.h>
57193242Ssam#include <sys/sched.h>
58193242Ssam#include <sys/sbuf.h>
59193242Ssam#include <sys/sysctl.h>
60193242Ssam#include <sys/turnstile.h>
61193242Ssam#include <sys/vmmeter.h>
62193242Ssam#include <sys/lock_profile.h>
63193242Ssam
64193242Ssam#include <machine/atomic.h>
65193242Ssam#include <machine/bus.h>
66193242Ssam#include <machine/cpu.h>
67193242Ssam
68193242Ssam#include <ddb/ddb.h>
69193242Ssam
70193242Ssam#include <fs/devfs/devfs_int.h>
71193242Ssam
72193242Ssam#include <vm/vm.h>
73193242Ssam#include <vm/vm_extern.h>
74193242Ssam
75193242Ssam/*
76193242Ssam * Force MUTEX_WAKE_ALL for now.
77193242Ssam * single thread wakeup needs fixes to avoid race conditions with
78193242Ssam * priority inheritance.
79193242Ssam */
80193242Ssam#ifndef MUTEX_WAKE_ALL
81193242Ssam#define MUTEX_WAKE_ALL
82193242Ssam#endif
83193242Ssam
84193242Ssam#if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
85193242Ssam#define	ADAPTIVE_MUTEXES
86193242Ssam#endif
87193242Ssam
88193242Ssam/*
89193242Ssam * Internal utility macros.
90193242Ssam */
91193242Ssam#define mtx_unowned(m)	((m)->mtx_lock == MTX_UNOWNED)
92193242Ssam
93193242Ssam#define	mtx_destroyed(m) ((m)->mtx_lock == MTX_DESTROYED)
94193242Ssam
95193242Ssam#define	mtx_owner(m)	((struct thread *)((m)->mtx_lock & ~MTX_FLAGMASK))
96193242Ssam
97193242Ssam#ifdef DDB
98193242Ssamstatic void	db_show_mtx(struct lock_object *lock);
99193242Ssam#endif
100193242Ssamstatic void	lock_mtx(struct lock_object *lock, int how);
101193242Ssamstatic void	lock_spin(struct lock_object *lock, int how);
102193242Ssamstatic int	unlock_mtx(struct lock_object *lock);
103193242Ssamstatic int	unlock_spin(struct lock_object *lock);
104193242Ssam
105193242Ssam/*
106193242Ssam * Lock classes for sleep and spin mutexes.
107193242Ssam */
108193242Ssamstruct lock_class lock_class_mtx_sleep = {
109193242Ssam	.lc_name = "sleep mutex",
110193242Ssam	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
111193242Ssam#ifdef DDB
112193242Ssam	.lc_ddb_show = db_show_mtx,
113193242Ssam#endif
114193242Ssam	.lc_lock = lock_mtx,
115193242Ssam	.lc_unlock = unlock_mtx,
116193242Ssam};
117193242Ssamstruct lock_class lock_class_mtx_spin = {
118193242Ssam	.lc_name = "spin mutex",
119193242Ssam	.lc_flags = LC_SPINLOCK | LC_RECURSABLE,
120193242Ssam#ifdef DDB
121193242Ssam	.lc_ddb_show = db_show_mtx,
122193242Ssam#endif
123193242Ssam	.lc_lock = lock_spin,
124193242Ssam	.lc_unlock = unlock_spin,
125193242Ssam};
126193242Ssam
127193242Ssam/*
128193242Ssam * System-wide mutexes
129 */
130struct mtx blocked_lock;
131struct mtx sched_lock;
132struct mtx Giant;
133
134#ifdef LOCK_PROFILING
135static inline void lock_profile_init(void)
136{
137        int i;
138        /* Initialize the mutex profiling locks */
139        for (i = 0; i < LPROF_LOCK_SIZE; i++) {
140                mtx_init(&lprof_locks[i], "mprof lock",
141                    NULL, MTX_SPIN|MTX_QUIET|MTX_NOPROFILE);
142        }
143}
144#else
145static inline void lock_profile_init(void) {;}
146#endif
147
148void
149lock_mtx(struct lock_object *lock, int how)
150{
151
152	mtx_lock((struct mtx *)lock);
153}
154
155void
156lock_spin(struct lock_object *lock, int how)
157{
158
159	panic("spin locks can only use msleep_spin");
160}
161
162int
163unlock_mtx(struct lock_object *lock)
164{
165	struct mtx *m;
166
167	m = (struct mtx *)lock;
168	mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
169	mtx_unlock(m);
170	return (0);
171}
172
173int
174unlock_spin(struct lock_object *lock)
175{
176
177	panic("spin locks can only use msleep_spin");
178}
179
180/*
181 * Function versions of the inlined __mtx_* macros.  These are used by
182 * modules and can also be called from assembly language if needed.
183 */
184void
185_mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
186{
187
188	MPASS(curthread != NULL);
189	KASSERT(m->mtx_lock != MTX_DESTROYED,
190	    ("mtx_lock() of destroyed mutex @ %s:%d", file, line));
191	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
192	    ("mtx_lock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
193	    file, line));
194	WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
195	    file, line);
196
197	_get_sleep_lock(m, curthread, opts, file, line);
198	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
199	    line);
200	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
201	curthread->td_locks++;
202}
203
204void
205_mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
206{
207	MPASS(curthread != NULL);
208	KASSERT(m->mtx_lock != MTX_DESTROYED,
209	    ("mtx_unlock() of destroyed mutex @ %s:%d", file, line));
210	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
211	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
212	    file, line));
213	curthread->td_locks--;
214	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
215	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
216	    line);
217	mtx_assert(m, MA_OWNED);
218
219	if (m->mtx_recurse == 0)
220		lock_profile_release_lock(&m->lock_object);
221	_rel_sleep_lock(m, curthread, opts, file, line);
222}
223
224void
225_mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
226{
227
228	MPASS(curthread != NULL);
229	KASSERT(m->mtx_lock != MTX_DESTROYED,
230	    ("mtx_lock_spin() of destroyed mutex @ %s:%d", file, line));
231	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
232	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
233	    m->lock_object.lo_name, file, line));
234	WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
235	    file, line);
236	_get_spin_lock(m, curthread, opts, file, line);
237	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
238	    line);
239	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
240}
241
242void
243_mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
244{
245
246	MPASS(curthread != NULL);
247	KASSERT(m->mtx_lock != MTX_DESTROYED,
248	    ("mtx_unlock_spin() of destroyed mutex @ %s:%d", file, line));
249	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
250	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
251	    m->lock_object.lo_name, file, line));
252	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
253	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
254	    line);
255	mtx_assert(m, MA_OWNED);
256
257	_rel_spin_lock(m);
258}
259
260/*
261 * The important part of mtx_trylock{,_flags}()
262 * Tries to acquire lock `m.'  If this function is called on a mutex that
263 * is already owned, it will recursively acquire the lock.
264 */
265int
266_mtx_trylock(struct mtx *m, int opts, const char *file, int line)
267{
268	int rval, contested = 0;
269	uint64_t waittime = 0;
270
271	MPASS(curthread != NULL);
272	KASSERT(m->mtx_lock != MTX_DESTROYED,
273	    ("mtx_trylock() of destroyed mutex @ %s:%d", file, line));
274	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
275	    ("mtx_trylock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
276	    file, line));
277
278	if (mtx_owned(m) && (m->lock_object.lo_flags & LO_RECURSABLE) != 0) {
279		m->mtx_recurse++;
280		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
281		rval = 1;
282	} else
283		rval = _obtain_lock(m, (uintptr_t)curthread);
284
285	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, rval, file, line);
286	if (rval) {
287		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
288		    file, line);
289		curthread->td_locks++;
290		if (m->mtx_recurse == 0)
291			lock_profile_obtain_lock_success(&m->lock_object, contested,
292			    waittime, file, line);
293
294	}
295
296	return (rval);
297}
298
299/*
300 * _mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
301 *
302 * We call this if the lock is either contested (i.e. we need to go to
303 * sleep waiting for it), or if we need to recurse on it.
304 */
305void
306_mtx_lock_sleep(struct mtx *m, uintptr_t tid, int opts, const char *file,
307    int line)
308{
309	struct turnstile *ts;
310#ifdef ADAPTIVE_MUTEXES
311	volatile struct thread *owner;
312#endif
313#ifdef KTR
314	int cont_logged = 0;
315#endif
316	int contested = 0;
317	uint64_t waittime = 0;
318	uintptr_t v;
319
320	if (mtx_owned(m)) {
321		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0,
322	    ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
323		    m->lock_object.lo_name, file, line));
324		m->mtx_recurse++;
325		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
326		if (LOCK_LOG_TEST(&m->lock_object, opts))
327			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
328		return;
329	}
330
331	lock_profile_obtain_lock_failed(&m->lock_object,
332		    &contested, &waittime);
333	if (LOCK_LOG_TEST(&m->lock_object, opts))
334		CTR4(KTR_LOCK,
335		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
336		    m->lock_object.lo_name, (void *)m->mtx_lock, file, line);
337
338	while (!_obtain_lock(m, tid)) {
339		ts = turnstile_trywait(&m->lock_object);
340		v = m->mtx_lock;
341
342		/*
343		 * Check if the lock has been released while spinning for
344		 * the turnstile chain lock.
345		 */
346		if (v == MTX_UNOWNED) {
347			turnstile_cancel(ts);
348			cpu_spinwait();
349			continue;
350		}
351
352#ifdef MUTEX_WAKE_ALL
353		MPASS(v != MTX_CONTESTED);
354#else
355		/*
356		 * The mutex was marked contested on release. This means that
357		 * there are other threads blocked on it.  Grab ownership of
358		 * it and propagate its priority to the current thread if
359		 * necessary.
360		 */
361		if (v == MTX_CONTESTED) {
362			m->mtx_lock = tid | MTX_CONTESTED;
363			turnstile_claim(ts);
364			break;
365		}
366#endif
367
368		/*
369		 * If the mutex isn't already contested and a failure occurs
370		 * setting the contested bit, the mutex was either released
371		 * or the state of the MTX_RECURSED bit changed.
372		 */
373		if ((v & MTX_CONTESTED) == 0 &&
374		    !atomic_cmpset_ptr(&m->mtx_lock, v, v | MTX_CONTESTED)) {
375			turnstile_cancel(ts);
376			cpu_spinwait();
377			continue;
378		}
379
380#ifdef ADAPTIVE_MUTEXES
381		/*
382		 * If the current owner of the lock is executing on another
383		 * CPU, spin instead of blocking.
384		 */
385		owner = (struct thread *)(v & ~MTX_FLAGMASK);
386#ifdef ADAPTIVE_GIANT
387		if (TD_IS_RUNNING(owner))
388#else
389		if (m != &Giant && TD_IS_RUNNING(owner))
390#endif
391		{
392			turnstile_cancel(ts);
393			while (mtx_owner(m) == owner && TD_IS_RUNNING(owner)) {
394				cpu_spinwait();
395			}
396			continue;
397		}
398#endif	/* ADAPTIVE_MUTEXES */
399
400		/*
401		 * We definitely must sleep for this lock.
402		 */
403		mtx_assert(m, MA_NOTOWNED);
404
405#ifdef KTR
406		if (!cont_logged) {
407			CTR6(KTR_CONTENTION,
408			    "contention: %p at %s:%d wants %s, taken by %s:%d",
409			    (void *)tid, file, line, m->lock_object.lo_name,
410			    WITNESS_FILE(&m->lock_object),
411			    WITNESS_LINE(&m->lock_object));
412			cont_logged = 1;
413		}
414#endif
415
416		/*
417		 * Block on the turnstile.
418		 */
419		turnstile_wait(ts, mtx_owner(m), TS_EXCLUSIVE_QUEUE);
420	}
421#ifdef KTR
422	if (cont_logged) {
423		CTR4(KTR_CONTENTION,
424		    "contention end: %s acquired by %p at %s:%d",
425		    m->lock_object.lo_name, (void *)tid, file, line);
426	}
427#endif
428	lock_profile_obtain_lock_success(&m->lock_object, contested,
429	    waittime, (file), (line));
430}
431
432static void
433_mtx_lock_spin_failed(struct mtx *m)
434{
435	struct thread *td;
436
437	td = mtx_owner(m);
438
439	/* If the mutex is unlocked, try again. */
440	if (td == NULL)
441		return;
442
443	printf( "spin lock %p (%s) held by %p (tid %d) too long\n",
444	    m, m->lock_object.lo_name, td, td->td_tid);
445#ifdef WITNESS
446	witness_display_spinlock(&m->lock_object, td);
447#endif
448	panic("spin lock held too long");
449}
450
451#ifdef SMP
452/*
453 * _mtx_lock_spin: the tougher part of acquiring an MTX_SPIN lock.
454 *
455 * This is only called if we need to actually spin for the lock. Recursion
456 * is handled inline.
457 */
458void
459_mtx_lock_spin(struct mtx *m, uintptr_t tid, int opts, const char *file,
460    int line)
461{
462	int i = 0, contested = 0;
463	uint64_t waittime = 0;
464
465	if (LOCK_LOG_TEST(&m->lock_object, opts))
466		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
467
468	lock_profile_obtain_lock_failed(&m->lock_object, &contested, &waittime);
469	while (!_obtain_lock(m, tid)) {
470
471		/* Give interrupts a chance while we spin. */
472		spinlock_exit();
473		while (m->mtx_lock != MTX_UNOWNED) {
474			if (i++ < 10000000) {
475				cpu_spinwait();
476				continue;
477			}
478			if (i < 60000000 || kdb_active || panicstr != NULL)
479				DELAY(1);
480			else
481				_mtx_lock_spin_failed(m);
482			cpu_spinwait();
483		}
484		spinlock_enter();
485	}
486
487	if (LOCK_LOG_TEST(&m->lock_object, opts))
488		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
489
490	lock_profile_obtain_lock_success(&m->lock_object, contested,
491	    waittime, (file), (line));
492}
493#endif /* SMP */
494
495void
496_thread_lock_flags(struct thread *td, int opts, const char *file, int line)
497{
498	struct mtx *m;
499	uintptr_t tid;
500	int i;
501
502	i = 0;
503	tid = (uintptr_t)curthread;
504	for (;;) {
505retry:
506		spinlock_enter();
507		m = __DEVOLATILE(struct mtx *, td->td_lock);
508		WITNESS_CHECKORDER(&m->lock_object,
509		    opts | LOP_NEWORDER | LOP_EXCLUSIVE, file, line);
510		while (!_obtain_lock(m, tid)) {
511			if (m->mtx_lock == tid) {
512				m->mtx_recurse++;
513				break;
514			}
515			/* Give interrupts a chance while we spin. */
516			spinlock_exit();
517			while (m->mtx_lock != MTX_UNOWNED) {
518				if (i++ < 10000000)
519					cpu_spinwait();
520				else if (i < 60000000 ||
521				    kdb_active || panicstr != NULL)
522					DELAY(1);
523				else
524					_mtx_lock_spin_failed(m);
525				cpu_spinwait();
526				if (m != td->td_lock)
527					goto retry;
528			}
529			spinlock_enter();
530		}
531		if (m == td->td_lock)
532			break;
533		_rel_spin_lock(m);	/* does spinlock_exit() */
534	}
535	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
536}
537
538struct mtx *
539thread_lock_block(struct thread *td)
540{
541	struct mtx *lock;
542
543	spinlock_enter();
544	THREAD_LOCK_ASSERT(td, MA_OWNED);
545	lock = __DEVOLATILE(struct mtx *, td->td_lock);
546	td->td_lock = &blocked_lock;
547	mtx_unlock_spin(lock);
548
549	return (lock);
550}
551
552void
553thread_lock_unblock(struct thread *td, struct mtx *new)
554{
555	mtx_assert(new, MA_OWNED);
556	MPASS(td->td_lock == &blocked_lock);
557	atomic_store_rel_ptr((void *)&td->td_lock, (uintptr_t)new);
558	spinlock_exit();
559}
560
561void
562thread_lock_set(struct thread *td, struct mtx *new)
563{
564	struct mtx *lock;
565
566	mtx_assert(new, MA_OWNED);
567	THREAD_LOCK_ASSERT(td, MA_OWNED);
568	lock = __DEVOLATILE(struct mtx *, td->td_lock);
569	td->td_lock = new;
570	mtx_unlock_spin(lock);
571}
572
573/*
574 * _mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
575 *
576 * We are only called here if the lock is recursed or contested (i.e. we
577 * need to wake up a blocked thread).
578 */
579void
580_mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line)
581{
582	struct turnstile *ts;
583
584	if (mtx_recursed(m)) {
585		if (--(m->mtx_recurse) == 0)
586			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
587		if (LOCK_LOG_TEST(&m->lock_object, opts))
588			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
589		return;
590	}
591
592	/*
593	 * We have to lock the chain before the turnstile so this turnstile
594	 * can be removed from the hash list if it is empty.
595	 */
596	turnstile_chain_lock(&m->lock_object);
597	ts = turnstile_lookup(&m->lock_object);
598	if (LOCK_LOG_TEST(&m->lock_object, opts))
599		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
600
601#ifdef ADAPTIVE_MUTEXES
602	if (ts == NULL) {
603		_release_lock_quick(m);
604		if (LOCK_LOG_TEST(&m->lock_object, opts))
605			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p no sleepers", m);
606		turnstile_chain_unlock(&m->lock_object);
607		return;
608	}
609#else
610	MPASS(ts != NULL);
611#endif
612#ifdef MUTEX_WAKE_ALL
613	turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
614	_release_lock_quick(m);
615#else
616	if (turnstile_signal(ts, TS_EXCLUSIVE_QUEUE)) {
617		_release_lock_quick(m);
618		if (LOCK_LOG_TEST(&m->lock_object, opts))
619			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p not held", m);
620	} else {
621		m->mtx_lock = MTX_CONTESTED;
622		if (LOCK_LOG_TEST(&m->lock_object, opts))
623			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p still contested",
624			    m);
625	}
626#endif
627	/*
628	 * This turnstile is now no longer associated with the mutex.  We can
629	 * unlock the chain lock so a new turnstile may take it's place.
630	 */
631	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
632	turnstile_chain_unlock(&m->lock_object);
633}
634
635/*
636 * All the unlocking of MTX_SPIN locks is done inline.
637 * See the _rel_spin_lock() macro for the details.
638 */
639
640/*
641 * The backing function for the INVARIANTS-enabled mtx_assert()
642 */
643#ifdef INVARIANT_SUPPORT
644void
645_mtx_assert(struct mtx *m, int what, const char *file, int line)
646{
647
648	if (panicstr != NULL || dumping)
649		return;
650	switch (what) {
651	case MA_OWNED:
652	case MA_OWNED | MA_RECURSED:
653	case MA_OWNED | MA_NOTRECURSED:
654		if (!mtx_owned(m))
655			panic("mutex %s not owned at %s:%d",
656			    m->lock_object.lo_name, file, line);
657		if (mtx_recursed(m)) {
658			if ((what & MA_NOTRECURSED) != 0)
659				panic("mutex %s recursed at %s:%d",
660				    m->lock_object.lo_name, file, line);
661		} else if ((what & MA_RECURSED) != 0) {
662			panic("mutex %s unrecursed at %s:%d",
663			    m->lock_object.lo_name, file, line);
664		}
665		break;
666	case MA_NOTOWNED:
667		if (mtx_owned(m))
668			panic("mutex %s owned at %s:%d",
669			    m->lock_object.lo_name, file, line);
670		break;
671	default:
672		panic("unknown mtx_assert at %s:%d", file, line);
673	}
674}
675#endif
676
677/*
678 * The MUTEX_DEBUG-enabled mtx_validate()
679 *
680 * Most of these checks have been moved off into the LO_INITIALIZED flag
681 * maintained by the witness code.
682 */
683#ifdef MUTEX_DEBUG
684
685void	mtx_validate(struct mtx *);
686
687void
688mtx_validate(struct mtx *m)
689{
690
691/*
692 * XXX: When kernacc() does not require Giant we can reenable this check
693 */
694#ifdef notyet
695	/*
696	 * Can't call kernacc() from early init386(), especially when
697	 * initializing Giant mutex, because some stuff in kernacc()
698	 * requires Giant itself.
699	 */
700	if (!cold)
701		if (!kernacc((caddr_t)m, sizeof(m),
702		    VM_PROT_READ | VM_PROT_WRITE))
703			panic("Can't read and write to mutex %p", m);
704#endif
705}
706#endif
707
708/*
709 * General init routine used by the MTX_SYSINIT() macro.
710 */
711void
712mtx_sysinit(void *arg)
713{
714	struct mtx_args *margs = arg;
715
716	mtx_init(margs->ma_mtx, margs->ma_desc, NULL, margs->ma_opts);
717}
718
719/*
720 * Mutex initialization routine; initialize lock `m' of type contained in
721 * `opts' with options contained in `opts' and name `name.'  The optional
722 * lock type `type' is used as a general lock category name for use with
723 * witness.
724 */
725void
726mtx_init(struct mtx *m, const char *name, const char *type, int opts)
727{
728	struct lock_class *class;
729	int flags;
730
731	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
732		MTX_NOWITNESS | MTX_DUPOK | MTX_NOPROFILE)) == 0);
733
734#ifdef MUTEX_DEBUG
735	/* Diagnostic and error correction */
736	mtx_validate(m);
737#endif
738
739	/* Determine lock class and lock flags. */
740	if (opts & MTX_SPIN)
741		class = &lock_class_mtx_spin;
742	else
743		class = &lock_class_mtx_sleep;
744	flags = 0;
745	if (opts & MTX_QUIET)
746		flags |= LO_QUIET;
747	if (opts & MTX_RECURSE)
748		flags |= LO_RECURSABLE;
749	if ((opts & MTX_NOWITNESS) == 0)
750		flags |= LO_WITNESS;
751	if (opts & MTX_DUPOK)
752		flags |= LO_DUPOK;
753	if (opts & MTX_NOPROFILE)
754		flags |= LO_NOPROFILE;
755
756	/* Initialize mutex. */
757	m->mtx_lock = MTX_UNOWNED;
758	m->mtx_recurse = 0;
759
760	lock_init(&m->lock_object, class, name, type, flags);
761}
762
763/*
764 * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
765 * passed in as a flag here because if the corresponding mtx_init() was
766 * called with MTX_QUIET set, then it will already be set in the mutex's
767 * flags.
768 */
769void
770mtx_destroy(struct mtx *m)
771{
772
773	if (!mtx_owned(m))
774		MPASS(mtx_unowned(m));
775	else {
776		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
777
778		/* Perform the non-mtx related part of mtx_unlock_spin(). */
779		if (LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin)
780			spinlock_exit();
781		else
782			curthread->td_locks--;
783
784		/* Tell witness this isn't locked to make it happy. */
785		WITNESS_UNLOCK(&m->lock_object, LOP_EXCLUSIVE, __FILE__,
786		    __LINE__);
787	}
788
789	m->mtx_lock = MTX_DESTROYED;
790	lock_destroy(&m->lock_object);
791}
792
793/*
794 * Intialize the mutex code and system mutexes.  This is called from the MD
795 * startup code prior to mi_startup().  The per-CPU data space needs to be
796 * setup before this is called.
797 */
798void
799mutex_init(void)
800{
801
802	/* Setup turnstiles so that sleep mutexes work. */
803	init_turnstiles();
804
805	/*
806	 * Initialize mutexes.
807	 */
808	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
809	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
810	mtx_init(&blocked_lock, "blocked lock", NULL, MTX_SPIN);
811	blocked_lock.mtx_lock = 0xdeadc0de;	/* Always blocked. */
812	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
813	mtx_init(&proc0.p_slock, "process slock", NULL, MTX_SPIN | MTX_RECURSE);
814	mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
815	mtx_lock(&Giant);
816
817	lock_profile_init();
818}
819
820#ifdef DDB
821void
822db_show_mtx(struct lock_object *lock)
823{
824	struct thread *td;
825	struct mtx *m;
826
827	m = (struct mtx *)lock;
828
829	db_printf(" flags: {");
830	if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
831		db_printf("SPIN");
832	else
833		db_printf("DEF");
834	if (m->lock_object.lo_flags & LO_RECURSABLE)
835		db_printf(", RECURSE");
836	if (m->lock_object.lo_flags & LO_DUPOK)
837		db_printf(", DUPOK");
838	db_printf("}\n");
839	db_printf(" state: {");
840	if (mtx_unowned(m))
841		db_printf("UNOWNED");
842	else if (mtx_destroyed(m))
843		db_printf("DESTROYED");
844	else {
845		db_printf("OWNED");
846		if (m->mtx_lock & MTX_CONTESTED)
847			db_printf(", CONTESTED");
848		if (m->mtx_lock & MTX_RECURSED)
849			db_printf(", RECURSED");
850	}
851	db_printf("}\n");
852	if (!mtx_unowned(m) && !mtx_destroyed(m)) {
853		td = mtx_owner(m);
854		db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
855		    td->td_tid, td->td_proc->p_pid, td->td_proc->p_comm);
856		if (mtx_recursed(m))
857			db_printf(" recursed: %d\n", m->mtx_recurse);
858	}
859}
860#endif
861