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