xref: /freebsd/sys/kern/kern_mutex.c (revision 677b542ea243380af64822b30e4ef5f7a6d978ee)
10384fff8SJason Evans /*-
20384fff8SJason Evans  * Copyright (c) 1998 Berkeley Software Design, Inc. All rights reserved.
30384fff8SJason Evans  *
40384fff8SJason Evans  * Redistribution and use in source and binary forms, with or without
50384fff8SJason Evans  * modification, are permitted provided that the following conditions
60384fff8SJason Evans  * are met:
70384fff8SJason Evans  * 1. Redistributions of source code must retain the above copyright
80384fff8SJason Evans  *    notice, this list of conditions and the following disclaimer.
90384fff8SJason Evans  * 2. Redistributions in binary form must reproduce the above copyright
100384fff8SJason Evans  *    notice, this list of conditions and the following disclaimer in the
110384fff8SJason Evans  *    documentation and/or other materials provided with the distribution.
120384fff8SJason Evans  * 3. Berkeley Software Design Inc's name may not be used to endorse or
130384fff8SJason Evans  *    promote products derived from this software without specific prior
140384fff8SJason Evans  *    written permission.
150384fff8SJason Evans  *
160384fff8SJason Evans  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
170384fff8SJason Evans  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
180384fff8SJason Evans  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
190384fff8SJason Evans  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
200384fff8SJason Evans  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
210384fff8SJason Evans  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
220384fff8SJason Evans  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
230384fff8SJason Evans  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
240384fff8SJason Evans  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
250384fff8SJason Evans  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
260384fff8SJason Evans  * SUCH DAMAGE.
270384fff8SJason Evans  *
280384fff8SJason Evans  *	from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
2936412d79SJohn Baldwin  *	and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
300384fff8SJason Evans  */
310384fff8SJason Evans 
320384fff8SJason Evans /*
33ba48b69aSJohn Baldwin  * Machine independent bits of mutex implementation.
340384fff8SJason Evans  */
350384fff8SJason Evans 
36677b542eSDavid E. O'Brien #include <sys/cdefs.h>
37677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
38677b542eSDavid E. O'Brien 
392498cf8cSJohn Baldwin #include "opt_adaptive_mutexes.h"
409c36c934SJohn Baldwin #include "opt_ddb.h"
41a5a96a19SJohn Baldwin 
420384fff8SJason Evans #include <sys/param.h>
436c35e809SDag-Erling Smørgrav #include <sys/systm.h>
4436412d79SJohn Baldwin #include <sys/bus.h>
4536412d79SJohn Baldwin #include <sys/kernel.h>
466c35e809SDag-Erling Smørgrav #include <sys/ktr.h>
4719284646SJohn Baldwin #include <sys/lock.h>
48fb919e4dSMark Murray #include <sys/malloc.h>
4919284646SJohn Baldwin #include <sys/mutex.h>
500384fff8SJason Evans #include <sys/proc.h>
51c4f7a187SJohn Baldwin #include <sys/resourcevar.h>
52b43179fbSJeff Roberson #include <sys/sched.h>
536c35e809SDag-Erling Smørgrav #include <sys/sbuf.h>
54a5a96a19SJohn Baldwin #include <sys/sysctl.h>
5536412d79SJohn Baldwin #include <sys/vmmeter.h>
560384fff8SJason Evans 
5736412d79SJohn Baldwin #include <machine/atomic.h>
5836412d79SJohn Baldwin #include <machine/bus.h>
5936412d79SJohn Baldwin #include <machine/clock.h>
600384fff8SJason Evans #include <machine/cpu.h>
6136412d79SJohn Baldwin 
629c36c934SJohn Baldwin #include <ddb/ddb.h>
639c36c934SJohn Baldwin 
6436412d79SJohn Baldwin #include <vm/vm.h>
6536412d79SJohn Baldwin #include <vm/vm_extern.h>
6636412d79SJohn Baldwin 
670cde2e34SJason Evans /*
689ed346baSBosko Milekic  * Internal utility macros.
690cde2e34SJason Evans  */
709ed346baSBosko Milekic #define mtx_unowned(m)	((m)->mtx_lock == MTX_UNOWNED)
710cde2e34SJason Evans 
729ed346baSBosko Milekic #define mtx_owner(m)	(mtx_unowned((m)) ? NULL \
73b40ce416SJulian Elischer 	: (struct thread *)((m)->mtx_lock & MTX_FLAGMASK))
749ed346baSBosko Milekic 
750cde2e34SJason Evans /*
7619284646SJohn Baldwin  * Lock classes for sleep and spin mutexes.
770cde2e34SJason Evans  */
7819284646SJohn Baldwin struct lock_class lock_class_mtx_sleep = {
7919284646SJohn Baldwin 	"sleep mutex",
8019284646SJohn Baldwin 	LC_SLEEPLOCK | LC_RECURSABLE
8119284646SJohn Baldwin };
8219284646SJohn Baldwin struct lock_class lock_class_mtx_spin = {
8319284646SJohn Baldwin 	"spin mutex",
8419284646SJohn Baldwin 	LC_SPINLOCK | LC_RECURSABLE
858484de75SJohn Baldwin };
868484de75SJohn Baldwin 
879ed346baSBosko Milekic /*
88c53c013bSJohn Baldwin  * System-wide mutexes
89c53c013bSJohn Baldwin  */
90c53c013bSJohn Baldwin struct mtx sched_lock;
91c53c013bSJohn Baldwin struct mtx Giant;
92c53c013bSJohn Baldwin 
93c53c013bSJohn Baldwin /*
949ed346baSBosko Milekic  * Prototypes for non-exported routines.
959ed346baSBosko Milekic  */
96b40ce416SJulian Elischer static void	propagate_priority(struct thread *);
9736412d79SJohn Baldwin 
9836412d79SJohn Baldwin static void
99b40ce416SJulian Elischer propagate_priority(struct thread *td)
10036412d79SJohn Baldwin {
1012c100766SJulian Elischer 	int pri = td->td_priority;
102b40ce416SJulian Elischer 	struct mtx *m = td->td_blocked;
10336412d79SJohn Baldwin 
1041bd0eefbSJohn Baldwin 	mtx_assert(&sched_lock, MA_OWNED);
10536412d79SJohn Baldwin 	for (;;) {
106b40ce416SJulian Elischer 		struct thread *td1;
10736412d79SJohn Baldwin 
108b40ce416SJulian Elischer 		td = mtx_owner(m);
10936412d79SJohn Baldwin 
110b40ce416SJulian Elischer 		if (td == NULL) {
11136412d79SJohn Baldwin 			/*
11236412d79SJohn Baldwin 			 * This really isn't quite right. Really
113b40ce416SJulian Elischer 			 * ought to bump priority of thread that
11436412d79SJohn Baldwin 			 * next acquires the mutex.
11536412d79SJohn Baldwin 			 */
11636412d79SJohn Baldwin 			MPASS(m->mtx_lock == MTX_CONTESTED);
11736412d79SJohn Baldwin 			return;
11836412d79SJohn Baldwin 		}
1199ed346baSBosko Milekic 
120e602ba25SJulian Elischer 		MPASS(td->td_proc != NULL);
121b40ce416SJulian Elischer 		MPASS(td->td_proc->p_magic == P_MAGIC);
12271fad9fdSJulian Elischer 		KASSERT(!TD_IS_SLEEPING(td), ("sleeping thread owns a mutex"));
1232c100766SJulian Elischer 		if (td->td_priority <= pri) /* lower is higher priority */
12436412d79SJohn Baldwin 			return;
1251bd0eefbSJohn Baldwin 
1261bd0eefbSJohn Baldwin 
12736412d79SJohn Baldwin 		/*
12836412d79SJohn Baldwin 		 * If lock holder is actually running, just bump priority.
12936412d79SJohn Baldwin 		 */
13071fad9fdSJulian Elischer 		if (TD_IS_RUNNING(td)) {
131e602ba25SJulian Elischer 			td->td_priority = pri;
13236412d79SJohn Baldwin 			return;
13336412d79SJohn Baldwin 		}
134d5a08a60SJake Burkholder 
1351b43703bSJohn Baldwin #ifndef SMP
1361b43703bSJohn Baldwin 		/*
137b40ce416SJulian Elischer 		 * For UP, we check to see if td is curthread (this shouldn't
1381b43703bSJohn Baldwin 		 * ever happen however as it would mean we are in a deadlock.)
1391b43703bSJohn Baldwin 		 */
140b40ce416SJulian Elischer 		KASSERT(td != curthread, ("Deadlock detected"));
1411b43703bSJohn Baldwin #endif
1421b43703bSJohn Baldwin 
14336412d79SJohn Baldwin 		/*
144b40ce416SJulian Elischer 		 * If on run queue move to new run queue, and quit.
145b40ce416SJulian Elischer 		 * XXXKSE this gets a lot more complicated under threads
146b40ce416SJulian Elischer 		 * but try anyhow.
14736412d79SJohn Baldwin 		 */
14871fad9fdSJulian Elischer 		if (TD_ON_RUNQ(td)) {
149b40ce416SJulian Elischer 			MPASS(td->td_blocked == NULL);
150b43179fbSJeff Roberson 			sched_prio(td, pri);
15136412d79SJohn Baldwin 			return;
15236412d79SJohn Baldwin 		}
153e602ba25SJulian Elischer 		/*
154e602ba25SJulian Elischer 		 * Adjust for any other cases.
155e602ba25SJulian Elischer 		 */
156e602ba25SJulian Elischer 		td->td_priority = pri;
15736412d79SJohn Baldwin 
15836412d79SJohn Baldwin 		/*
1591bd0eefbSJohn Baldwin 		 * If we aren't blocked on a mutex, we should be.
16036412d79SJohn Baldwin 		 */
161551cf4e1SJohn Baldwin 		KASSERT(TD_ON_LOCK(td), (
1621bd0eefbSJohn Baldwin 		    "process %d(%s):%d holds %s but isn't blocked on a mutex\n",
163e602ba25SJulian Elischer 		    td->td_proc->p_pid, td->td_proc->p_comm, td->td_state,
16419284646SJohn Baldwin 		    m->mtx_object.lo_name));
16536412d79SJohn Baldwin 
16636412d79SJohn Baldwin 		/*
167b40ce416SJulian Elischer 		 * Pick up the mutex that td is blocked on.
16836412d79SJohn Baldwin 		 */
169b40ce416SJulian Elischer 		m = td->td_blocked;
17036412d79SJohn Baldwin 		MPASS(m != NULL);
17136412d79SJohn Baldwin 
17236412d79SJohn Baldwin 		/*
173b40ce416SJulian Elischer 		 * Check if the thread needs to be moved up on
17436412d79SJohn Baldwin 		 * the blocked chain
17536412d79SJohn Baldwin 		 */
176b40ce416SJulian Elischer 		if (td == TAILQ_FIRST(&m->mtx_blocked)) {
1771bd0eefbSJohn Baldwin 			continue;
1781bd0eefbSJohn Baldwin 		}
1799ed346baSBosko Milekic 
180551cf4e1SJohn Baldwin 		td1 = TAILQ_PREV(td, threadqueue, td_lockq);
1812c100766SJulian Elischer 		if (td1->td_priority <= pri) {
18236412d79SJohn Baldwin 			continue;
18336412d79SJohn Baldwin 		}
18436412d79SJohn Baldwin 
18536412d79SJohn Baldwin 		/*
186b40ce416SJulian Elischer 		 * Remove thread from blocked chain and determine where
187b40ce416SJulian Elischer 		 * it should be moved up to.  Since we know that td1 has
188b40ce416SJulian Elischer 		 * a lower priority than td, we know that at least one
189b40ce416SJulian Elischer 		 * thread in the chain has a lower priority and that
190b40ce416SJulian Elischer 		 * td1 will thus not be NULL after the loop.
19136412d79SJohn Baldwin 		 */
192551cf4e1SJohn Baldwin 		TAILQ_REMOVE(&m->mtx_blocked, td, td_lockq);
193551cf4e1SJohn Baldwin 		TAILQ_FOREACH(td1, &m->mtx_blocked, td_lockq) {
194b40ce416SJulian Elischer 			MPASS(td1->td_proc->p_magic == P_MAGIC);
1952c100766SJulian Elischer 			if (td1->td_priority > pri)
19636412d79SJohn Baldwin 				break;
19736412d79SJohn Baldwin 		}
1989ed346baSBosko Milekic 
199b40ce416SJulian Elischer 		MPASS(td1 != NULL);
200551cf4e1SJohn Baldwin 		TAILQ_INSERT_BEFORE(td1, td, td_lockq);
20136412d79SJohn Baldwin 		CTR4(KTR_LOCK,
2028484de75SJohn Baldwin 		    "propagate_priority: p %p moved before %p on [%p] %s",
203b40ce416SJulian Elischer 		    td, td1, m, m->mtx_object.lo_name);
20436412d79SJohn Baldwin 	}
20536412d79SJohn Baldwin }
20636412d79SJohn Baldwin 
2076c35e809SDag-Erling Smørgrav #ifdef MUTEX_PROFILING
2086c35e809SDag-Erling Smørgrav SYSCTL_NODE(_debug, OID_AUTO, mutex, CTLFLAG_RD, NULL, "mutex debugging");
2096c35e809SDag-Erling Smørgrav SYSCTL_NODE(_debug_mutex, OID_AUTO, prof, CTLFLAG_RD, NULL, "mutex profiling");
2106c35e809SDag-Erling Smørgrav static int mutex_prof_enable = 0;
2116c35e809SDag-Erling Smørgrav SYSCTL_INT(_debug_mutex_prof, OID_AUTO, enable, CTLFLAG_RW,
2126c35e809SDag-Erling Smørgrav     &mutex_prof_enable, 0, "Enable tracing of mutex holdtime");
2136c35e809SDag-Erling Smørgrav 
2146c35e809SDag-Erling Smørgrav struct mutex_prof {
2156c35e809SDag-Erling Smørgrav 	const char	*name;
2166c35e809SDag-Erling Smørgrav 	const char	*file;
2176c35e809SDag-Erling Smørgrav 	int		line;
218ecf031c9SDag-Erling Smørgrav 	uintmax_t	cnt_max;
219ecf031c9SDag-Erling Smørgrav 	uintmax_t	cnt_tot;
220ecf031c9SDag-Erling Smørgrav 	uintmax_t	cnt_cur;
221e6330704SDag-Erling Smørgrav 	struct mutex_prof *next;
2226c35e809SDag-Erling Smørgrav };
2236c35e809SDag-Erling Smørgrav 
2246c35e809SDag-Erling Smørgrav /*
2256c35e809SDag-Erling Smørgrav  * mprof_buf is a static pool of profiling records to avoid possible
2266c35e809SDag-Erling Smørgrav  * reentrance of the memory allocation functions.
2276c35e809SDag-Erling Smørgrav  *
2286c35e809SDag-Erling Smørgrav  * Note: NUM_MPROF_BUFFERS must be smaller than MPROF_HASH_SIZE.
2296c35e809SDag-Erling Smørgrav  */
230e6330704SDag-Erling Smørgrav #define	NUM_MPROF_BUFFERS	1000
2316c35e809SDag-Erling Smørgrav static struct mutex_prof mprof_buf[NUM_MPROF_BUFFERS];
2326c35e809SDag-Erling Smørgrav static int first_free_mprof_buf;
233e6330704SDag-Erling Smørgrav #define	MPROF_HASH_SIZE		1009
2346c35e809SDag-Erling Smørgrav static struct mutex_prof *mprof_hash[MPROF_HASH_SIZE];
2350bd5f797SMike Makonnen /* SWAG: sbuf size = avg stat. line size * number of locks */
2360bd5f797SMike Makonnen #define MPROF_SBUF_SIZE		256 * 400
2376c35e809SDag-Erling Smørgrav 
2386c35e809SDag-Erling Smørgrav static int mutex_prof_acquisitions;
2396c35e809SDag-Erling Smørgrav SYSCTL_INT(_debug_mutex_prof, OID_AUTO, acquisitions, CTLFLAG_RD,
2406c35e809SDag-Erling Smørgrav     &mutex_prof_acquisitions, 0, "Number of mutex acquistions recorded");
2416c35e809SDag-Erling Smørgrav static int mutex_prof_records;
2426c35e809SDag-Erling Smørgrav SYSCTL_INT(_debug_mutex_prof, OID_AUTO, records, CTLFLAG_RD,
2436c35e809SDag-Erling Smørgrav     &mutex_prof_records, 0, "Number of profiling records");
2446c35e809SDag-Erling Smørgrav static int mutex_prof_maxrecords = NUM_MPROF_BUFFERS;
2456c35e809SDag-Erling Smørgrav SYSCTL_INT(_debug_mutex_prof, OID_AUTO, maxrecords, CTLFLAG_RD,
2466c35e809SDag-Erling Smørgrav     &mutex_prof_maxrecords, 0, "Maximum number of profiling records");
2476c35e809SDag-Erling Smørgrav static int mutex_prof_rejected;
2486c35e809SDag-Erling Smørgrav SYSCTL_INT(_debug_mutex_prof, OID_AUTO, rejected, CTLFLAG_RD,
2496c35e809SDag-Erling Smørgrav     &mutex_prof_rejected, 0, "Number of rejected profiling records");
2506c35e809SDag-Erling Smørgrav static int mutex_prof_hashsize = MPROF_HASH_SIZE;
2516c35e809SDag-Erling Smørgrav SYSCTL_INT(_debug_mutex_prof, OID_AUTO, hashsize, CTLFLAG_RD,
2526c35e809SDag-Erling Smørgrav     &mutex_prof_hashsize, 0, "Hash size");
2536c35e809SDag-Erling Smørgrav static int mutex_prof_collisions = 0;
2546c35e809SDag-Erling Smørgrav SYSCTL_INT(_debug_mutex_prof, OID_AUTO, collisions, CTLFLAG_RD,
2556c35e809SDag-Erling Smørgrav     &mutex_prof_collisions, 0, "Number of hash collisions");
2566c35e809SDag-Erling Smørgrav 
2576c35e809SDag-Erling Smørgrav /*
2586c35e809SDag-Erling Smørgrav  * mprof_mtx protects the profiling buffers and the hash.
2596c35e809SDag-Erling Smørgrav  */
2606c35e809SDag-Erling Smørgrav static struct mtx mprof_mtx;
261e6330704SDag-Erling Smørgrav MTX_SYSINIT(mprof, &mprof_mtx, "mutex profiling lock", MTX_SPIN | MTX_QUIET);
2626c35e809SDag-Erling Smørgrav 
263b784ffe9SDag-Erling Smørgrav static u_int64_t
264b784ffe9SDag-Erling Smørgrav nanoseconds(void)
265b784ffe9SDag-Erling Smørgrav {
266b784ffe9SDag-Erling Smørgrav 	struct timespec tv;
267b784ffe9SDag-Erling Smørgrav 
268b784ffe9SDag-Erling Smørgrav 	nanotime(&tv);
269b784ffe9SDag-Erling Smørgrav 	return (tv.tv_sec * (u_int64_t)1000000000 + tv.tv_nsec);
270b784ffe9SDag-Erling Smørgrav }
271b784ffe9SDag-Erling Smørgrav 
2726c35e809SDag-Erling Smørgrav static int
2736c35e809SDag-Erling Smørgrav dump_mutex_prof_stats(SYSCTL_HANDLER_ARGS)
2746c35e809SDag-Erling Smørgrav {
2756c35e809SDag-Erling Smørgrav 	struct sbuf *sb;
2766c35e809SDag-Erling Smørgrav 	int error, i;
2770bd5f797SMike Makonnen 	static int multiplier = 1;
2786c35e809SDag-Erling Smørgrav 
2796c35e809SDag-Erling Smørgrav 	if (first_free_mprof_buf == 0)
2806d036900SDag-Erling Smørgrav 		return (SYSCTL_OUT(req, "No locking recorded",
2816d036900SDag-Erling Smørgrav 		    sizeof("No locking recorded")));
2826c35e809SDag-Erling Smørgrav 
2830bd5f797SMike Makonnen retry_sbufops:
2840bd5f797SMike Makonnen 	sb = sbuf_new(NULL, NULL, MPROF_SBUF_SIZE * multiplier, SBUF_FIXEDLEN);
2856d036900SDag-Erling Smørgrav 	sbuf_printf(sb, "%6s %12s %11s %5s %s\n",
2866d036900SDag-Erling Smørgrav 	    "max", "total", "count", "avg", "name");
2876d036900SDag-Erling Smørgrav 	/*
2886d036900SDag-Erling Smørgrav 	 * XXX this spinlock seems to be by far the largest perpetrator
2896d036900SDag-Erling Smørgrav 	 * of spinlock latency (1.6 msec on an Athlon1600 was recorded
2906d036900SDag-Erling Smørgrav 	 * even before I pessimized it further by moving the average
2916d036900SDag-Erling Smørgrav 	 * computation here).
2926d036900SDag-Erling Smørgrav 	 */
2936c35e809SDag-Erling Smørgrav 	mtx_lock_spin(&mprof_mtx);
2940bd5f797SMike Makonnen 	for (i = 0; i < first_free_mprof_buf; ++i) {
2956d036900SDag-Erling Smørgrav 		sbuf_printf(sb, "%6ju %12ju %11ju %5ju %s:%d (%s)\n",
296ecf031c9SDag-Erling Smørgrav 		    mprof_buf[i].cnt_max / 1000,
297ecf031c9SDag-Erling Smørgrav 		    mprof_buf[i].cnt_tot / 1000,
298ecf031c9SDag-Erling Smørgrav 		    mprof_buf[i].cnt_cur,
299ecf031c9SDag-Erling Smørgrav 		    mprof_buf[i].cnt_cur == 0 ? (uintmax_t)0 :
300ecf031c9SDag-Erling Smørgrav 			mprof_buf[i].cnt_tot / (mprof_buf[i].cnt_cur * 1000),
3016c35e809SDag-Erling Smørgrav 		    mprof_buf[i].file, mprof_buf[i].line, mprof_buf[i].name);
3020bd5f797SMike Makonnen 		if (sbuf_overflowed(sb)) {
3030bd5f797SMike Makonnen 			mtx_unlock_spin(&mprof_mtx);
3040bd5f797SMike Makonnen 			sbuf_delete(sb);
3050bd5f797SMike Makonnen 			multiplier++;
3060bd5f797SMike Makonnen 			goto retry_sbufops;
3070bd5f797SMike Makonnen 		}
3080bd5f797SMike Makonnen 	}
3096c35e809SDag-Erling Smørgrav 	mtx_unlock_spin(&mprof_mtx);
3106c35e809SDag-Erling Smørgrav 	sbuf_finish(sb);
3116c35e809SDag-Erling Smørgrav 	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
3126c35e809SDag-Erling Smørgrav 	sbuf_delete(sb);
3136c35e809SDag-Erling Smørgrav 	return (error);
3146c35e809SDag-Erling Smørgrav }
3156c35e809SDag-Erling Smørgrav SYSCTL_PROC(_debug_mutex_prof, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD,
3166c35e809SDag-Erling Smørgrav     NULL, 0, dump_mutex_prof_stats, "A", "Mutex profiling statistics");
3176c35e809SDag-Erling Smørgrav #endif
3186c35e809SDag-Erling Smørgrav 
3190cde2e34SJason Evans /*
3206283b7d0SJohn Baldwin  * Function versions of the inlined __mtx_* macros.  These are used by
3216283b7d0SJohn Baldwin  * modules and can also be called from assembly language if needed.
3226283b7d0SJohn Baldwin  */
3236283b7d0SJohn Baldwin void
3246283b7d0SJohn Baldwin _mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
3256283b7d0SJohn Baldwin {
3266283b7d0SJohn Baldwin 
327dde96c99SJohn Baldwin 	MPASS(curthread != NULL);
3280d975d63SJohn Baldwin 	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_sleep,
3290d975d63SJohn Baldwin 	    ("mtx_lock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
3300d975d63SJohn Baldwin 	    file, line));
331dde96c99SJohn Baldwin 	_get_sleep_lock(m, curthread, opts, file, line);
332dde96c99SJohn Baldwin 	LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
333dde96c99SJohn Baldwin 	    line);
334dde96c99SJohn Baldwin 	WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
3356c35e809SDag-Erling Smørgrav #ifdef MUTEX_PROFILING
3366c35e809SDag-Erling Smørgrav 	/* don't reset the timer when/if recursing */
337b61860adSDag-Erling Smørgrav 	if (m->mtx_acqtime == 0) {
338b61860adSDag-Erling Smørgrav 		m->mtx_filename = file;
339b61860adSDag-Erling Smørgrav 		m->mtx_lineno = line;
340b61860adSDag-Erling Smørgrav 		m->mtx_acqtime = mutex_prof_enable ? nanoseconds() : 0;
3416c35e809SDag-Erling Smørgrav 		++mutex_prof_acquisitions;
3426c35e809SDag-Erling Smørgrav 	}
3436c35e809SDag-Erling Smørgrav #endif
3446283b7d0SJohn Baldwin }
3456283b7d0SJohn Baldwin 
3466283b7d0SJohn Baldwin void
3476283b7d0SJohn Baldwin _mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
3486283b7d0SJohn Baldwin {
3496283b7d0SJohn Baldwin 
350dde96c99SJohn Baldwin 	MPASS(curthread != NULL);
3510d975d63SJohn Baldwin 	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_sleep,
3520d975d63SJohn Baldwin 	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->mtx_object.lo_name,
3530d975d63SJohn Baldwin 	    file, line));
3540d975d63SJohn Baldwin 	WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
3550d975d63SJohn Baldwin 	LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
3560d975d63SJohn Baldwin 	    line);
35721377ce0SJohn Baldwin 	mtx_assert(m, MA_OWNED);
3586c35e809SDag-Erling Smørgrav #ifdef MUTEX_PROFILING
359b61860adSDag-Erling Smørgrav 	if (m->mtx_acqtime != 0) {
3606c35e809SDag-Erling Smørgrav 		static const char *unknown = "(unknown)";
3616c35e809SDag-Erling Smørgrav 		struct mutex_prof *mpp;
362b784ffe9SDag-Erling Smørgrav 		u_int64_t acqtime, now;
3636c35e809SDag-Erling Smørgrav 		const char *p, *q;
364e6330704SDag-Erling Smørgrav 		volatile u_int hash;
3656c35e809SDag-Erling Smørgrav 
366b784ffe9SDag-Erling Smørgrav 		now = nanoseconds();
367b61860adSDag-Erling Smørgrav 		acqtime = m->mtx_acqtime;
368b61860adSDag-Erling Smørgrav 		m->mtx_acqtime = 0;
369b784ffe9SDag-Erling Smørgrav 		if (now <= acqtime)
3706c35e809SDag-Erling Smørgrav 			goto out;
3710bd5f797SMike Makonnen 		for (p = m->mtx_filename;
3720bd5f797SMike Makonnen 		    p != NULL && strncmp(p, "../", 3) == 0; p += 3)
3736c35e809SDag-Erling Smørgrav 			/* nothing */ ;
3746c35e809SDag-Erling Smørgrav 		if (p == NULL || *p == '\0')
3756c35e809SDag-Erling Smørgrav 			p = unknown;
376b61860adSDag-Erling Smørgrav 		for (hash = m->mtx_lineno, q = p; *q != '\0'; ++q)
3776c35e809SDag-Erling Smørgrav 			hash = (hash * 2 + *q) % MPROF_HASH_SIZE;
3786c35e809SDag-Erling Smørgrav 		mtx_lock_spin(&mprof_mtx);
379e6330704SDag-Erling Smørgrav 		for (mpp = mprof_hash[hash]; mpp != NULL; mpp = mpp->next)
380b61860adSDag-Erling Smørgrav 			if (mpp->line == m->mtx_lineno &&
381b61860adSDag-Erling Smørgrav 			    strcmp(mpp->file, p) == 0)
3826c35e809SDag-Erling Smørgrav 				break;
3836c35e809SDag-Erling Smørgrav 		if (mpp == NULL) {
3846c35e809SDag-Erling Smørgrav 			/* Just exit if we cannot get a trace buffer */
3856c35e809SDag-Erling Smørgrav 			if (first_free_mprof_buf >= NUM_MPROF_BUFFERS) {
3866c35e809SDag-Erling Smørgrav 				++mutex_prof_rejected;
3876c35e809SDag-Erling Smørgrav 				goto unlock;
3886c35e809SDag-Erling Smørgrav 			}
3896c35e809SDag-Erling Smørgrav 			mpp = &mprof_buf[first_free_mprof_buf++];
3906c35e809SDag-Erling Smørgrav 			mpp->name = mtx_name(m);
3916c35e809SDag-Erling Smørgrav 			mpp->file = p;
392b61860adSDag-Erling Smørgrav 			mpp->line = m->mtx_lineno;
393e6330704SDag-Erling Smørgrav 			mpp->next = mprof_hash[hash];
394e6330704SDag-Erling Smørgrav 			if (mprof_hash[hash] != NULL)
395e6330704SDag-Erling Smørgrav 				++mutex_prof_collisions;
3966c35e809SDag-Erling Smørgrav 			mprof_hash[hash] = mpp;
397e6330704SDag-Erling Smørgrav 			++mutex_prof_records;
3986c35e809SDag-Erling Smørgrav 		}
3996c35e809SDag-Erling Smørgrav 		/*
4006c35e809SDag-Erling Smørgrav 		 * Record if the mutex has been held longer now than ever
4016d036900SDag-Erling Smørgrav 		 * before.
4026c35e809SDag-Erling Smørgrav 		 */
403ecf031c9SDag-Erling Smørgrav 		if (now - acqtime > mpp->cnt_max)
404ecf031c9SDag-Erling Smørgrav 			mpp->cnt_max = now - acqtime;
405ecf031c9SDag-Erling Smørgrav 		mpp->cnt_tot += now - acqtime;
406ecf031c9SDag-Erling Smørgrav 		mpp->cnt_cur++;
4076c35e809SDag-Erling Smørgrav unlock:
4086c35e809SDag-Erling Smørgrav 		mtx_unlock_spin(&mprof_mtx);
4096c35e809SDag-Erling Smørgrav 	}
4106c35e809SDag-Erling Smørgrav out:
4116c35e809SDag-Erling Smørgrav #endif
412dde96c99SJohn Baldwin 	_rel_sleep_lock(m, curthread, opts, file, line);
4136283b7d0SJohn Baldwin }
4146283b7d0SJohn Baldwin 
4156283b7d0SJohn Baldwin void
4166283b7d0SJohn Baldwin _mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
4176283b7d0SJohn Baldwin {
4186283b7d0SJohn Baldwin 
419dde96c99SJohn Baldwin 	MPASS(curthread != NULL);
4200d975d63SJohn Baldwin 	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_spin,
4210d975d63SJohn Baldwin 	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
4220d975d63SJohn Baldwin 	    m->mtx_object.lo_name, file, line));
423ce39e722SJohn Baldwin #if defined(SMP) || LOCK_DEBUG > 0 || 1
424dde96c99SJohn Baldwin 	_get_spin_lock(m, curthread, opts, file, line);
425e8fdcfb5SJohn Baldwin #else
426e8fdcfb5SJohn Baldwin 	critical_enter();
427e8fdcfb5SJohn Baldwin #endif
428dde96c99SJohn Baldwin 	LOCK_LOG_LOCK("LOCK", &m->mtx_object, opts, m->mtx_recurse, file,
429dde96c99SJohn Baldwin 	    line);
430dde96c99SJohn Baldwin 	WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
4316283b7d0SJohn Baldwin }
4326283b7d0SJohn Baldwin 
4336283b7d0SJohn Baldwin void
4346283b7d0SJohn Baldwin _mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
4356283b7d0SJohn Baldwin {
4366283b7d0SJohn Baldwin 
437dde96c99SJohn Baldwin 	MPASS(curthread != NULL);
4380d975d63SJohn Baldwin 	KASSERT(m->mtx_object.lo_class == &lock_class_mtx_spin,
4390d975d63SJohn Baldwin 	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
4400d975d63SJohn Baldwin 	    m->mtx_object.lo_name, file, line));
441dde96c99SJohn Baldwin 	WITNESS_UNLOCK(&m->mtx_object, opts | LOP_EXCLUSIVE, file, line);
442dde96c99SJohn Baldwin 	LOCK_LOG_LOCK("UNLOCK", &m->mtx_object, opts, m->mtx_recurse, file,
443dde96c99SJohn Baldwin 	    line);
4440d975d63SJohn Baldwin 	mtx_assert(m, MA_OWNED);
445ce39e722SJohn Baldwin #if defined(SMP) || LOCK_DEBUG > 0 || 1
446dde96c99SJohn Baldwin 	_rel_spin_lock(m);
447e8fdcfb5SJohn Baldwin #else
448e8fdcfb5SJohn Baldwin 	critical_exit();
449e8fdcfb5SJohn Baldwin #endif
4506283b7d0SJohn Baldwin }
4516283b7d0SJohn Baldwin 
4526283b7d0SJohn Baldwin /*
4539ed346baSBosko Milekic  * The important part of mtx_trylock{,_flags}()
4541106937dSJohn Baldwin  * Tries to acquire lock `m.' We do NOT handle recursion here.  If this
4551106937dSJohn Baldwin  * function is called on a recursed mutex, it will return failure and
4561106937dSJohn Baldwin  * will not recursively acquire the lock.  You are expected to know what
4571106937dSJohn Baldwin  * you are doing.
4580cde2e34SJason Evans  */
4590cde2e34SJason Evans int
4609ed346baSBosko Milekic _mtx_trylock(struct mtx *m, int opts, const char *file, int line)
4610cde2e34SJason Evans {
4620cde2e34SJason Evans 	int rval;
4630cde2e34SJason Evans 
464b40ce416SJulian Elischer 	MPASS(curthread != NULL);
4659ed346baSBosko Milekic 
466b40ce416SJulian Elischer 	rval = _obtain_lock(m, curthread);
4679ed346baSBosko Milekic 
46819284646SJohn Baldwin 	LOCK_LOG_TRY("LOCK", &m->mtx_object, opts, rval, file, line);
4696b869595SJohn Baldwin 	if (rval)
4702d96f0b1SJohn Baldwin 		WITNESS_LOCK(&m->mtx_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
4712d96f0b1SJohn Baldwin 		    file, line);
4729ed346baSBosko Milekic 
47319284646SJohn Baldwin 	return (rval);
4740cde2e34SJason Evans }
4750cde2e34SJason Evans 
4760cde2e34SJason Evans /*
4779ed346baSBosko Milekic  * _mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
4789ed346baSBosko Milekic  *
4799ed346baSBosko Milekic  * We call this if the lock is either contested (i.e. we need to go to
4809ed346baSBosko Milekic  * sleep waiting for it), or if we need to recurse on it.
4810cde2e34SJason Evans  */
4820cde2e34SJason Evans void
4839ed346baSBosko Milekic _mtx_lock_sleep(struct mtx *m, int opts, const char *file, int line)
48436412d79SJohn Baldwin {
485b40ce416SJulian Elischer 	struct thread *td = curthread;
4865fa8dd90SJohn Baldwin 	struct thread *td1;
4872498cf8cSJohn Baldwin #if defined(SMP) && defined(ADAPTIVE_MUTEXES)
4882498cf8cSJohn Baldwin 	struct thread *owner;
4892498cf8cSJohn Baldwin #endif
4905fa8dd90SJohn Baldwin 	uintptr_t v;
49102bd1bcdSIan Dowse #ifdef KTR
49202bd1bcdSIan Dowse 	int cont_logged = 0;
49302bd1bcdSIan Dowse #endif
49436412d79SJohn Baldwin 
4955fa8dd90SJohn Baldwin 	if (mtx_owned(m)) {
49636412d79SJohn Baldwin 		m->mtx_recurse++;
49708812b39SBosko Milekic 		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
49819284646SJohn Baldwin 		if (LOCK_LOG_TEST(&m->mtx_object, opts))
4995746a1d8SBosko Milekic 			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
50036412d79SJohn Baldwin 		return;
50136412d79SJohn Baldwin 	}
5029ed346baSBosko Milekic 
50319284646SJohn Baldwin 	if (LOCK_LOG_TEST(&m->mtx_object, opts))
50415ec816aSJohn Baldwin 		CTR4(KTR_LOCK,
50515ec816aSJohn Baldwin 		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
50619284646SJohn Baldwin 		    m->mtx_object.lo_name, (void *)m->mtx_lock, file, line);
5071bd0eefbSJohn Baldwin 
508b40ce416SJulian Elischer 	while (!_obtain_lock(m, td)) {
50936412d79SJohn Baldwin 
5109ed346baSBosko Milekic 		mtx_lock_spin(&sched_lock);
5115fa8dd90SJohn Baldwin 		v = m->mtx_lock;
5125fa8dd90SJohn Baldwin 
51336412d79SJohn Baldwin 		/*
5149ed346baSBosko Milekic 		 * Check if the lock has been released while spinning for
5159ed346baSBosko Milekic 		 * the sched_lock.
51636412d79SJohn Baldwin 		 */
5175fa8dd90SJohn Baldwin 		if (v == MTX_UNOWNED) {
5189ed346baSBosko Milekic 			mtx_unlock_spin(&sched_lock);
519703fc290SJohn Baldwin #ifdef __i386__
5206b8c6989SJohn Baldwin 			ia32_pause();
521703fc290SJohn Baldwin #endif
52236412d79SJohn Baldwin 			continue;
52336412d79SJohn Baldwin 		}
5249ed346baSBosko Milekic 
52536412d79SJohn Baldwin 		/*
5269ed346baSBosko Milekic 		 * The mutex was marked contested on release. This means that
527b40ce416SJulian Elischer 		 * there are threads blocked on it.
52836412d79SJohn Baldwin 		 */
52936412d79SJohn Baldwin 		if (v == MTX_CONTESTED) {
530b40ce416SJulian Elischer 			td1 = TAILQ_FIRST(&m->mtx_blocked);
531b40ce416SJulian Elischer 			MPASS(td1 != NULL);
532b40ce416SJulian Elischer 			m->mtx_lock = (uintptr_t)td | MTX_CONTESTED;
5339ed346baSBosko Milekic 
5342c100766SJulian Elischer 			if (td1->td_priority < td->td_priority)
5352c100766SJulian Elischer 				td->td_priority = td1->td_priority;
5369ed346baSBosko Milekic 			mtx_unlock_spin(&sched_lock);
53736412d79SJohn Baldwin 			return;
53836412d79SJohn Baldwin 		}
5399ed346baSBosko Milekic 
54036412d79SJohn Baldwin 		/*
5419ed346baSBosko Milekic 		 * If the mutex isn't already contested and a failure occurs
5429ed346baSBosko Milekic 		 * setting the contested bit, the mutex was either released
5439ed346baSBosko Milekic 		 * or the state of the MTX_RECURSED bit changed.
54436412d79SJohn Baldwin 		 */
54536412d79SJohn Baldwin 		if ((v & MTX_CONTESTED) == 0 &&
54636412d79SJohn Baldwin 		    !atomic_cmpset_ptr(&m->mtx_lock, (void *)v,
54736412d79SJohn Baldwin 			(void *)(v | MTX_CONTESTED))) {
5489ed346baSBosko Milekic 			mtx_unlock_spin(&sched_lock);
549703fc290SJohn Baldwin #ifdef __i386__
5506b8c6989SJohn Baldwin 			ia32_pause();
551703fc290SJohn Baldwin #endif
55236412d79SJohn Baldwin 			continue;
55336412d79SJohn Baldwin 		}
55436412d79SJohn Baldwin 
5552498cf8cSJohn Baldwin #if defined(SMP) && defined(ADAPTIVE_MUTEXES)
5562498cf8cSJohn Baldwin 		/*
5572498cf8cSJohn Baldwin 		 * If the current owner of the lock is executing on another
5582498cf8cSJohn Baldwin 		 * CPU, spin instead of blocking.
5592498cf8cSJohn Baldwin 		 */
5602498cf8cSJohn Baldwin 		owner = (struct thread *)(v & MTX_FLAGMASK);
56127dad03cSJohn Baldwin 		if (m != &Giant && TD_IS_RUNNING(owner)) {
5622498cf8cSJohn Baldwin 			mtx_unlock_spin(&sched_lock);
56327dad03cSJohn Baldwin 			while (mtx_owner(m) == owner && TD_IS_RUNNING(owner)) {
564703fc290SJohn Baldwin #ifdef __i386__
5656b8c6989SJohn Baldwin 				ia32_pause();
566703fc290SJohn Baldwin #endif
5677fcca609SJohn Baldwin 			}
5682498cf8cSJohn Baldwin 			continue;
5692498cf8cSJohn Baldwin 		}
5702498cf8cSJohn Baldwin #endif	/* SMP && ADAPTIVE_MUTEXES */
5712498cf8cSJohn Baldwin 
5729ed346baSBosko Milekic 		/*
5737feefcd6SJohn Baldwin 		 * We definitely must sleep for this lock.
5749ed346baSBosko Milekic 		 */
57536412d79SJohn Baldwin 		mtx_assert(m, MA_NOTOWNED);
57636412d79SJohn Baldwin 
57736412d79SJohn Baldwin #ifdef notyet
57836412d79SJohn Baldwin 		/*
5799ed346baSBosko Milekic 		 * If we're borrowing an interrupted thread's VM context, we
5809ed346baSBosko Milekic 		 * must clean up before going to sleep.
58136412d79SJohn Baldwin 		 */
582b40ce416SJulian Elischer 		if (td->td_ithd != NULL) {
583b40ce416SJulian Elischer 			struct ithd *it = td->td_ithd;
58436412d79SJohn Baldwin 
58536412d79SJohn Baldwin 			if (it->it_interrupted) {
58619284646SJohn Baldwin 				if (LOCK_LOG_TEST(&m->mtx_object, opts))
58736412d79SJohn Baldwin 					CTR2(KTR_LOCK,
58815ec816aSJohn Baldwin 				    "_mtx_lock_sleep: %p interrupted %p",
58936412d79SJohn Baldwin 					    it, it->it_interrupted);
59036412d79SJohn Baldwin 				intr_thd_fixup(it);
59136412d79SJohn Baldwin 			}
59236412d79SJohn Baldwin 		}
59336412d79SJohn Baldwin #endif
59436412d79SJohn Baldwin 
5959ed346baSBosko Milekic 		/*
5969ed346baSBosko Milekic 		 * Put us on the list of threads blocked on this mutex.
5979ed346baSBosko Milekic 		 */
59836412d79SJohn Baldwin 		if (TAILQ_EMPTY(&m->mtx_blocked)) {
59918fc2ba9SJohn Baldwin 			td1 = mtx_owner(m);
600b40ce416SJulian Elischer 			LIST_INSERT_HEAD(&td1->td_contested, m, mtx_contested);
601551cf4e1SJohn Baldwin 			TAILQ_INSERT_TAIL(&m->mtx_blocked, td, td_lockq);
60236412d79SJohn Baldwin 		} else {
603551cf4e1SJohn Baldwin 			TAILQ_FOREACH(td1, &m->mtx_blocked, td_lockq)
6042c100766SJulian Elischer 				if (td1->td_priority > td->td_priority)
60536412d79SJohn Baldwin 					break;
606b40ce416SJulian Elischer 			if (td1)
607551cf4e1SJohn Baldwin 				TAILQ_INSERT_BEFORE(td1, td, td_lockq);
60836412d79SJohn Baldwin 			else
609551cf4e1SJohn Baldwin 				TAILQ_INSERT_TAIL(&m->mtx_blocked, td, td_lockq);
61036412d79SJohn Baldwin 		}
61102bd1bcdSIan Dowse #ifdef KTR
61202bd1bcdSIan Dowse 		if (!cont_logged) {
61302bd1bcdSIan Dowse 			CTR6(KTR_CONTENTION,
61402bd1bcdSIan Dowse 			    "contention: %p at %s:%d wants %s, taken by %s:%d",
61502bd1bcdSIan Dowse 			    td, file, line, m->mtx_object.lo_name,
61602bd1bcdSIan Dowse 			    WITNESS_FILE(&m->mtx_object),
61702bd1bcdSIan Dowse 			    WITNESS_LINE(&m->mtx_object));
61802bd1bcdSIan Dowse 			cont_logged = 1;
61902bd1bcdSIan Dowse 		}
62002bd1bcdSIan Dowse #endif
62136412d79SJohn Baldwin 
6229ed346baSBosko Milekic 		/*
6239ed346baSBosko Milekic 		 * Save who we're blocked on.
6249ed346baSBosko Milekic 		 */
625b40ce416SJulian Elischer 		td->td_blocked = m;
626551cf4e1SJohn Baldwin 		td->td_lockname = m->mtx_object.lo_name;
627551cf4e1SJohn Baldwin 		TD_SET_LOCK(td);
628b40ce416SJulian Elischer 		propagate_priority(td);
6299ed346baSBosko Milekic 
63019284646SJohn Baldwin 		if (LOCK_LOG_TEST(&m->mtx_object, opts))
631562e4ffeSJohn Baldwin 			CTR3(KTR_LOCK,
632b40ce416SJulian Elischer 			    "_mtx_lock_sleep: p %p blocked on [%p] %s", td, m,
63319284646SJohn Baldwin 			    m->mtx_object.lo_name);
6349ed346baSBosko Milekic 
635b40ce416SJulian Elischer 		td->td_proc->p_stats->p_ru.ru_nvcsw++;
63620cdcc5bSJohn Baldwin 		mi_switch();
6379ed346baSBosko Milekic 
63819284646SJohn Baldwin 		if (LOCK_LOG_TEST(&m->mtx_object, opts))
63936412d79SJohn Baldwin 			CTR3(KTR_LOCK,
6409ed346baSBosko Milekic 			  "_mtx_lock_sleep: p %p free from blocked on [%p] %s",
641b40ce416SJulian Elischer 			  td, m, m->mtx_object.lo_name);
6429ed346baSBosko Milekic 
6439ed346baSBosko Milekic 		mtx_unlock_spin(&sched_lock);
64436412d79SJohn Baldwin 	}
6459ed346baSBosko Milekic 
64602bd1bcdSIan Dowse #ifdef KTR
64702bd1bcdSIan Dowse 	if (cont_logged) {
64802bd1bcdSIan Dowse 		CTR4(KTR_CONTENTION,
64902bd1bcdSIan Dowse 		    "contention end: %s acquired by %p at %s:%d",
65002bd1bcdSIan Dowse 		    m->mtx_object.lo_name, td, file, line);
65102bd1bcdSIan Dowse 	}
65202bd1bcdSIan Dowse #endif
65336412d79SJohn Baldwin 	return;
6549ed346baSBosko Milekic }
6559ed346baSBosko Milekic 
6569ed346baSBosko Milekic /*
6579ed346baSBosko Milekic  * _mtx_lock_spin: the tougher part of acquiring an MTX_SPIN lock.
6589ed346baSBosko Milekic  *
6599ed346baSBosko Milekic  * This is only called if we need to actually spin for the lock. Recursion
6609ed346baSBosko Milekic  * is handled inline.
6619ed346baSBosko Milekic  */
6629ed346baSBosko Milekic void
6637e1f6dfeSJohn Baldwin _mtx_lock_spin(struct mtx *m, int opts, const char *file, int line)
66436412d79SJohn Baldwin {
66536412d79SJohn Baldwin 	int i = 0;
66636412d79SJohn Baldwin 
66719284646SJohn Baldwin 	if (LOCK_LOG_TEST(&m->mtx_object, opts))
6685746a1d8SBosko Milekic 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
6699ed346baSBosko Milekic 
67036412d79SJohn Baldwin 	for (;;) {
671b40ce416SJulian Elischer 		if (_obtain_lock(m, curthread))
67236412d79SJohn Baldwin 			break;
6739ed346baSBosko Milekic 
6747141f2adSJohn Baldwin 		/* Give interrupts a chance while we spin. */
6757e1f6dfeSJohn Baldwin 		critical_exit();
67636412d79SJohn Baldwin 		while (m->mtx_lock != MTX_UNOWNED) {
677703fc290SJohn Baldwin 			if (i++ < 10000000) {
678703fc290SJohn Baldwin #ifdef __i386__
6796b8c6989SJohn Baldwin 				ia32_pause();
680703fc290SJohn Baldwin #endif
68136412d79SJohn Baldwin 				continue;
682703fc290SJohn Baldwin 			}
6830e54ddadSJohn Baldwin 			if (i < 60000000)
68436412d79SJohn Baldwin 				DELAY(1);
68536412d79SJohn Baldwin #ifdef DDB
68636412d79SJohn Baldwin 			else if (!db_active)
68736412d79SJohn Baldwin #else
68836412d79SJohn Baldwin 			else
68936412d79SJohn Baldwin #endif
6909ed346baSBosko Milekic 				panic("spin lock %s held by %p for > 5 seconds",
69119284646SJohn Baldwin 				    m->mtx_object.lo_name, (void *)m->mtx_lock);
692703fc290SJohn Baldwin #ifdef __i386__
6936b8c6989SJohn Baldwin 			ia32_pause();
694703fc290SJohn Baldwin #endif
69536412d79SJohn Baldwin 		}
6967e1f6dfeSJohn Baldwin 		critical_enter();
69736412d79SJohn Baldwin 	}
69836412d79SJohn Baldwin 
69919284646SJohn Baldwin 	if (LOCK_LOG_TEST(&m->mtx_object, opts))
7009ed346baSBosko Milekic 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
7019ed346baSBosko Milekic 
70236412d79SJohn Baldwin 	return;
70336412d79SJohn Baldwin }
70436412d79SJohn Baldwin 
7059ed346baSBosko Milekic /*
7069ed346baSBosko Milekic  * _mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
7079ed346baSBosko Milekic  *
7089ed346baSBosko Milekic  * We are only called here if the lock is recursed or contested (i.e. we
7099ed346baSBosko Milekic  * need to wake up a blocked thread).
7109ed346baSBosko Milekic  */
71136412d79SJohn Baldwin void
7129ed346baSBosko Milekic _mtx_unlock_sleep(struct mtx *m, int opts, const char *file, int line)
71336412d79SJohn Baldwin {
714b40ce416SJulian Elischer 	struct thread *td, *td1;
71536412d79SJohn Baldwin 	struct mtx *m1;
71636412d79SJohn Baldwin 	int pri;
71736412d79SJohn Baldwin 
718b40ce416SJulian Elischer 	td = curthread;
7199ed346baSBosko Milekic 
72008812b39SBosko Milekic 	if (mtx_recursed(m)) {
72136412d79SJohn Baldwin 		if (--(m->mtx_recurse) == 0)
72208812b39SBosko Milekic 			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
72319284646SJohn Baldwin 		if (LOCK_LOG_TEST(&m->mtx_object, opts))
7249ed346baSBosko Milekic 			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
72536412d79SJohn Baldwin 		return;
72636412d79SJohn Baldwin 	}
7279ed346baSBosko Milekic 
7289ed346baSBosko Milekic 	mtx_lock_spin(&sched_lock);
72919284646SJohn Baldwin 	if (LOCK_LOG_TEST(&m->mtx_object, opts))
7309ed346baSBosko Milekic 		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
7319ed346baSBosko Milekic 
732b40ce416SJulian Elischer 	td1 = TAILQ_FIRST(&m->mtx_blocked);
7332498cf8cSJohn Baldwin #if defined(SMP) && defined(ADAPTIVE_MUTEXES)
7342498cf8cSJohn Baldwin 	if (td1 == NULL) {
7352498cf8cSJohn Baldwin 		_release_lock_quick(m);
7362498cf8cSJohn Baldwin 		if (LOCK_LOG_TEST(&m->mtx_object, opts))
7372498cf8cSJohn Baldwin 			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p no sleepers", m);
7382498cf8cSJohn Baldwin 		mtx_unlock_spin(&sched_lock);
7392498cf8cSJohn Baldwin 		return;
7402498cf8cSJohn Baldwin 	}
7412498cf8cSJohn Baldwin #endif
742b40ce416SJulian Elischer 	MPASS(td->td_proc->p_magic == P_MAGIC);
743b40ce416SJulian Elischer 	MPASS(td1->td_proc->p_magic == P_MAGIC);
7449ed346baSBosko Milekic 
745551cf4e1SJohn Baldwin 	TAILQ_REMOVE(&m->mtx_blocked, td1, td_lockq);
7469ed346baSBosko Milekic 
74736412d79SJohn Baldwin 	if (TAILQ_EMPTY(&m->mtx_blocked)) {
74836412d79SJohn Baldwin 		LIST_REMOVE(m, mtx_contested);
74936412d79SJohn Baldwin 		_release_lock_quick(m);
75019284646SJohn Baldwin 		if (LOCK_LOG_TEST(&m->mtx_object, opts))
7519ed346baSBosko Milekic 			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p not held", m);
75236412d79SJohn Baldwin 	} else
7539ed346baSBosko Milekic 		atomic_store_rel_ptr(&m->mtx_lock, (void *)MTX_CONTESTED);
7549ed346baSBosko Milekic 
755d5a08a60SJake Burkholder 	pri = PRI_MAX;
756b40ce416SJulian Elischer 	LIST_FOREACH(m1, &td->td_contested, mtx_contested) {
7572c100766SJulian Elischer 		int cp = TAILQ_FIRST(&m1->mtx_blocked)->td_priority;
75836412d79SJohn Baldwin 		if (cp < pri)
75936412d79SJohn Baldwin 			pri = cp;
76036412d79SJohn Baldwin 	}
7619ed346baSBosko Milekic 
7622c100766SJulian Elischer 	if (pri > td->td_base_pri)
7632c100766SJulian Elischer 		pri = td->td_base_pri;
7642c100766SJulian Elischer 	td->td_priority = pri;
7659ed346baSBosko Milekic 
76619284646SJohn Baldwin 	if (LOCK_LOG_TEST(&m->mtx_object, opts))
7679ed346baSBosko Milekic 		CTR2(KTR_LOCK, "_mtx_unlock_sleep: %p contested setrunqueue %p",
768b40ce416SJulian Elischer 		    m, td1);
7699ed346baSBosko Milekic 
770b40ce416SJulian Elischer 	td1->td_blocked = NULL;
771551cf4e1SJohn Baldwin 	TD_CLR_LOCK(td1);
772e0817317SJulian Elischer 	if (!TD_CAN_RUN(td1)) {
773e0817317SJulian Elischer 		mtx_unlock_spin(&sched_lock);
774e0817317SJulian Elischer 		return;
775e0817317SJulian Elischer 	}
77627354830SJulian Elischer 	setrunqueue(td1);
7779ed346baSBosko Milekic 
7782c100766SJulian Elischer 	if (td->td_critnest == 1 && td1->td_priority < pri) {
77936412d79SJohn Baldwin #ifdef notyet
780b40ce416SJulian Elischer 		if (td->td_ithd != NULL) {
781b40ce416SJulian Elischer 			struct ithd *it = td->td_ithd;
78236412d79SJohn Baldwin 
78336412d79SJohn Baldwin 			if (it->it_interrupted) {
78419284646SJohn Baldwin 				if (LOCK_LOG_TEST(&m->mtx_object, opts))
78536412d79SJohn Baldwin 					CTR2(KTR_LOCK,
78615ec816aSJohn Baldwin 				    "_mtx_unlock_sleep: %p interrupted %p",
78736412d79SJohn Baldwin 					    it, it->it_interrupted);
78836412d79SJohn Baldwin 				intr_thd_fixup(it);
78936412d79SJohn Baldwin 			}
79036412d79SJohn Baldwin 		}
79136412d79SJohn Baldwin #endif
79219284646SJohn Baldwin 		if (LOCK_LOG_TEST(&m->mtx_object, opts))
793562e4ffeSJohn Baldwin 			CTR2(KTR_LOCK,
7949ed346baSBosko Milekic 			    "_mtx_unlock_sleep: %p switching out lock=%p", m,
7959ed346baSBosko Milekic 			    (void *)m->mtx_lock);
7969ed346baSBosko Milekic 
797b40ce416SJulian Elischer 		td->td_proc->p_stats->p_ru.ru_nivcsw++;
79836412d79SJohn Baldwin 		mi_switch();
79919284646SJohn Baldwin 		if (LOCK_LOG_TEST(&m->mtx_object, opts))
8009ed346baSBosko Milekic 			CTR2(KTR_LOCK, "_mtx_unlock_sleep: %p resuming lock=%p",
80131271627SJohn Baldwin 			    m, (void *)m->mtx_lock);
80236412d79SJohn Baldwin 	}
80336412d79SJohn Baldwin 
8049ed346baSBosko Milekic 	mtx_unlock_spin(&sched_lock);
8059ed346baSBosko Milekic 
8069ed346baSBosko Milekic 	return;
8079ed346baSBosko Milekic }
8089ed346baSBosko Milekic 
8099ed346baSBosko Milekic /*
8109ed346baSBosko Milekic  * All the unlocking of MTX_SPIN locks is done inline.
8119ed346baSBosko Milekic  * See the _rel_spin_lock() macro for the details.
8129ed346baSBosko Milekic  */
8139ed346baSBosko Milekic 
8149ed346baSBosko Milekic /*
81515ec816aSJohn Baldwin  * The backing function for the INVARIANTS-enabled mtx_assert()
8169ed346baSBosko Milekic  */
8171103f3b0SJohn Baldwin #ifdef INVARIANT_SUPPORT
8180cde2e34SJason Evans void
81956771ca7SJason Evans _mtx_assert(struct mtx *m, int what, const char *file, int line)
8200cde2e34SJason Evans {
8215cb0fbe4SJohn Baldwin 
8225cb0fbe4SJohn Baldwin 	if (panicstr != NULL)
8235cb0fbe4SJohn Baldwin 		return;
824a10f4966SJake Burkholder 	switch (what) {
8250cde2e34SJason Evans 	case MA_OWNED:
8260cde2e34SJason Evans 	case MA_OWNED | MA_RECURSED:
8270cde2e34SJason Evans 	case MA_OWNED | MA_NOTRECURSED:
828a10f4966SJake Burkholder 		if (!mtx_owned(m))
8290cde2e34SJason Evans 			panic("mutex %s not owned at %s:%d",
83019284646SJohn Baldwin 			    m->mtx_object.lo_name, file, line);
831a10f4966SJake Burkholder 		if (mtx_recursed(m)) {
832a10f4966SJake Burkholder 			if ((what & MA_NOTRECURSED) != 0)
8330cde2e34SJason Evans 				panic("mutex %s recursed at %s:%d",
83419284646SJohn Baldwin 				    m->mtx_object.lo_name, file, line);
835a10f4966SJake Burkholder 		} else if ((what & MA_RECURSED) != 0) {
8360cde2e34SJason Evans 			panic("mutex %s unrecursed at %s:%d",
83719284646SJohn Baldwin 			    m->mtx_object.lo_name, file, line);
8380cde2e34SJason Evans 		}
8390cde2e34SJason Evans 		break;
8400cde2e34SJason Evans 	case MA_NOTOWNED:
841a10f4966SJake Burkholder 		if (mtx_owned(m))
8420cde2e34SJason Evans 			panic("mutex %s owned at %s:%d",
84319284646SJohn Baldwin 			    m->mtx_object.lo_name, file, line);
8440cde2e34SJason Evans 		break;
8450cde2e34SJason Evans 	default:
84656771ca7SJason Evans 		panic("unknown mtx_assert at %s:%d", file, line);
8470cde2e34SJason Evans 	}
8480cde2e34SJason Evans }
8490cde2e34SJason Evans #endif
8500cde2e34SJason Evans 
8519ed346baSBosko Milekic /*
8529ed346baSBosko Milekic  * The MUTEX_DEBUG-enabled mtx_validate()
85319284646SJohn Baldwin  *
85419284646SJohn Baldwin  * Most of these checks have been moved off into the LO_INITIALIZED flag
85519284646SJohn Baldwin  * maintained by the witness code.
8569ed346baSBosko Milekic  */
85736412d79SJohn Baldwin #ifdef MUTEX_DEBUG
85836412d79SJohn Baldwin 
8594d77a549SAlfred Perlstein void	mtx_validate(struct mtx *);
86036412d79SJohn Baldwin 
86119284646SJohn Baldwin void
86219284646SJohn Baldwin mtx_validate(struct mtx *m)
86336412d79SJohn Baldwin {
86436412d79SJohn Baldwin 
86536412d79SJohn Baldwin /*
866fa669ab7SPoul-Henning Kamp  * XXX: When kernacc() does not require Giant we can reenable this check
867fa669ab7SPoul-Henning Kamp  */
868fa669ab7SPoul-Henning Kamp #ifdef notyet
869fa669ab7SPoul-Henning Kamp /*
87036412d79SJohn Baldwin  * XXX - When kernacc() is fixed on the alpha to handle K0_SEG memory properly
87136412d79SJohn Baldwin  * we can re-enable the kernacc() checks.
87236412d79SJohn Baldwin  */
87336412d79SJohn Baldwin #ifndef __alpha__
87476dcbd6fSBosko Milekic 	/*
87576dcbd6fSBosko Milekic 	 * Can't call kernacc() from early init386(), especially when
87676dcbd6fSBosko Milekic 	 * initializing Giant mutex, because some stuff in kernacc()
87776dcbd6fSBosko Milekic 	 * requires Giant itself.
87876dcbd6fSBosko Milekic 	 */
879ab07087eSBosko Milekic 	if (!cold)
880ab07087eSBosko Milekic 		if (!kernacc((caddr_t)m, sizeof(m),
881ab07087eSBosko Milekic 		    VM_PROT_READ | VM_PROT_WRITE))
88219284646SJohn Baldwin 			panic("Can't read and write to mutex %p", m);
88336412d79SJohn Baldwin #endif
884fa669ab7SPoul-Henning Kamp #endif
88536412d79SJohn Baldwin }
88636412d79SJohn Baldwin #endif
88736412d79SJohn Baldwin 
8889ed346baSBosko Milekic /*
889c27b5699SAndrew R. Reiter  * General init routine used by the MTX_SYSINIT() macro.
890c27b5699SAndrew R. Reiter  */
891c27b5699SAndrew R. Reiter void
892c27b5699SAndrew R. Reiter mtx_sysinit(void *arg)
893c27b5699SAndrew R. Reiter {
894c27b5699SAndrew R. Reiter 	struct mtx_args *margs = arg;
895c27b5699SAndrew R. Reiter 
8960c88508aSJohn Baldwin 	mtx_init(margs->ma_mtx, margs->ma_desc, NULL, margs->ma_opts);
897c27b5699SAndrew R. Reiter }
898c27b5699SAndrew R. Reiter 
899c27b5699SAndrew R. Reiter /*
9009ed346baSBosko Milekic  * Mutex initialization routine; initialize lock `m' of type contained in
9010c88508aSJohn Baldwin  * `opts' with options contained in `opts' and name `name.'  The optional
9020c88508aSJohn Baldwin  * lock type `type' is used as a general lock category name for use with
9030c88508aSJohn Baldwin  * witness.
9049ed346baSBosko Milekic  */
90536412d79SJohn Baldwin void
9060c88508aSJohn Baldwin mtx_init(struct mtx *m, const char *name, const char *type, int opts)
90736412d79SJohn Baldwin {
90819284646SJohn Baldwin 	struct lock_object *lock;
9099ed346baSBosko Milekic 
91019284646SJohn Baldwin 	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
91175d468eeSJohn Baldwin 	    MTX_NOWITNESS | MTX_DUPOK)) == 0);
9129ed346baSBosko Milekic 
91336412d79SJohn Baldwin #ifdef MUTEX_DEBUG
9149ed346baSBosko Milekic 	/* Diagnostic and error correction */
91519284646SJohn Baldwin 	mtx_validate(m);
9166936206eSJohn Baldwin #endif
91736412d79SJohn Baldwin 
91819284646SJohn Baldwin 	lock = &m->mtx_object;
9197ada5876SJohn Baldwin 	KASSERT((lock->lo_flags & LO_INITIALIZED) == 0,
920b82af320SPoul-Henning Kamp 	    ("mutex \"%s\" %p already initialized", name, m));
9217ada5876SJohn Baldwin 	bzero(m, sizeof(*m));
92219284646SJohn Baldwin 	if (opts & MTX_SPIN)
92319284646SJohn Baldwin 		lock->lo_class = &lock_class_mtx_spin;
92419284646SJohn Baldwin 	else
92519284646SJohn Baldwin 		lock->lo_class = &lock_class_mtx_sleep;
9260c88508aSJohn Baldwin 	lock->lo_name = name;
9270c88508aSJohn Baldwin 	lock->lo_type = type != NULL ? type : name;
92819284646SJohn Baldwin 	if (opts & MTX_QUIET)
92919284646SJohn Baldwin 		lock->lo_flags = LO_QUIET;
93019284646SJohn Baldwin 	if (opts & MTX_RECURSE)
93119284646SJohn Baldwin 		lock->lo_flags |= LO_RECURSABLE;
93219284646SJohn Baldwin 	if ((opts & MTX_NOWITNESS) == 0)
93319284646SJohn Baldwin 		lock->lo_flags |= LO_WITNESS;
934f22a4b62SJeff Roberson 	if (opts & MTX_DUPOK)
935f22a4b62SJeff Roberson 		lock->lo_flags |= LO_DUPOK;
93619284646SJohn Baldwin 
93719284646SJohn Baldwin 	m->mtx_lock = MTX_UNOWNED;
93836412d79SJohn Baldwin 	TAILQ_INIT(&m->mtx_blocked);
9399ed346baSBosko Milekic 
94019284646SJohn Baldwin 	LOCK_LOG_INIT(lock, opts);
941d1c1b841SJason Evans 
94219284646SJohn Baldwin 	WITNESS_INIT(lock);
94336412d79SJohn Baldwin }
94436412d79SJohn Baldwin 
9459ed346baSBosko Milekic /*
94619284646SJohn Baldwin  * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
94719284646SJohn Baldwin  * passed in as a flag here because if the corresponding mtx_init() was
94819284646SJohn Baldwin  * called with MTX_QUIET set, then it will already be set in the mutex's
94919284646SJohn Baldwin  * flags.
9509ed346baSBosko Milekic  */
95136412d79SJohn Baldwin void
95236412d79SJohn Baldwin mtx_destroy(struct mtx *m)
95336412d79SJohn Baldwin {
95436412d79SJohn Baldwin 
95519284646SJohn Baldwin 	LOCK_LOG_DESTROY(&m->mtx_object, 0);
9569ed346baSBosko Milekic 
95719284646SJohn Baldwin 	if (!mtx_owned(m))
95819284646SJohn Baldwin 		MPASS(mtx_unowned(m));
95919284646SJohn Baldwin 	else {
96008812b39SBosko Milekic 		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
9619ed346baSBosko Milekic 
96219284646SJohn Baldwin 		/* Tell witness this isn't locked to make it happy. */
963c86b6ff5SJohn Baldwin 		WITNESS_UNLOCK(&m->mtx_object, LOP_EXCLUSIVE, __FILE__,
964c86b6ff5SJohn Baldwin 		    __LINE__);
96536412d79SJohn Baldwin 	}
9660384fff8SJason Evans 
96719284646SJohn Baldwin 	WITNESS_DESTROY(&m->mtx_object);
9680384fff8SJason Evans }
969d23f5958SMatthew Dillon 
970d23f5958SMatthew Dillon /*
971c53c013bSJohn Baldwin  * Intialize the mutex code and system mutexes.  This is called from the MD
972c53c013bSJohn Baldwin  * startup code prior to mi_startup().  The per-CPU data space needs to be
973c53c013bSJohn Baldwin  * setup before this is called.
974c53c013bSJohn Baldwin  */
975c53c013bSJohn Baldwin void
976c53c013bSJohn Baldwin mutex_init(void)
977c53c013bSJohn Baldwin {
978c53c013bSJohn Baldwin 
979c53c013bSJohn Baldwin 	/* Setup thread0 so that mutexes work. */
980c53c013bSJohn Baldwin 	LIST_INIT(&thread0.td_contested);
981c53c013bSJohn Baldwin 
982c53c013bSJohn Baldwin 	/*
983c53c013bSJohn Baldwin 	 * Initialize mutexes.
984c53c013bSJohn Baldwin 	 */
9850c88508aSJohn Baldwin 	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
9860c88508aSJohn Baldwin 	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
9870c88508aSJohn Baldwin 	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
988c53c013bSJohn Baldwin 	mtx_lock(&Giant);
989c53c013bSJohn Baldwin }
990