xref: /freebsd/sys/kern/kern_mutex.c (revision bd66a0750f7ad8c13d4904fa976a03601a560cbf)
10384fff8SJason Evans /*-
28a36da99SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
38a36da99SPedro F. Giffuni  *
40384fff8SJason Evans  * Copyright (c) 1998 Berkeley Software Design, Inc. All rights reserved.
50384fff8SJason Evans  *
60384fff8SJason Evans  * Redistribution and use in source and binary forms, with or without
70384fff8SJason Evans  * modification, are permitted provided that the following conditions
80384fff8SJason Evans  * are met:
90384fff8SJason Evans  * 1. Redistributions of source code must retain the above copyright
100384fff8SJason Evans  *    notice, this list of conditions and the following disclaimer.
110384fff8SJason Evans  * 2. Redistributions in binary form must reproduce the above copyright
120384fff8SJason Evans  *    notice, this list of conditions and the following disclaimer in the
130384fff8SJason Evans  *    documentation and/or other materials provided with the distribution.
140384fff8SJason Evans  * 3. Berkeley Software Design Inc's name may not be used to endorse or
150384fff8SJason Evans  *    promote products derived from this software without specific prior
160384fff8SJason Evans  *    written permission.
170384fff8SJason Evans  *
180384fff8SJason Evans  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
190384fff8SJason Evans  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
200384fff8SJason Evans  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
210384fff8SJason Evans  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
220384fff8SJason Evans  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
230384fff8SJason Evans  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
240384fff8SJason Evans  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
250384fff8SJason Evans  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
260384fff8SJason Evans  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
270384fff8SJason Evans  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
280384fff8SJason Evans  * SUCH DAMAGE.
290384fff8SJason Evans  *
300384fff8SJason Evans  *	from BSDI $Id: mutex_witness.c,v 1.1.2.20 2000/04/27 03:10:27 cp Exp $
3136412d79SJohn Baldwin  *	and BSDI $Id: synch_machdep.c,v 2.3.2.39 2000/04/27 03:10:25 cp Exp $
320384fff8SJason Evans  */
330384fff8SJason Evans 
340384fff8SJason Evans /*
35ba48b69aSJohn Baldwin  * Machine independent bits of mutex implementation.
360384fff8SJason Evans  */
370384fff8SJason Evans 
38677b542eSDavid E. O'Brien #include <sys/cdefs.h>
39677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
40677b542eSDavid E. O'Brien 
412498cf8cSJohn Baldwin #include "opt_adaptive_mutexes.h"
429c36c934SJohn Baldwin #include "opt_ddb.h"
43f5f9340bSFabien Thomas #include "opt_hwpmc_hooks.h"
449923b511SScott Long #include "opt_sched.h"
45a5a96a19SJohn Baldwin 
460384fff8SJason Evans #include <sys/param.h>
476c35e809SDag-Erling Smørgrav #include <sys/systm.h>
4836412d79SJohn Baldwin #include <sys/bus.h>
491126349aSPaul Saab #include <sys/conf.h>
502d50560aSMarcel Moolenaar #include <sys/kdb.h>
5136412d79SJohn Baldwin #include <sys/kernel.h>
526c35e809SDag-Erling Smørgrav #include <sys/ktr.h>
5319284646SJohn Baldwin #include <sys/lock.h>
54fb919e4dSMark Murray #include <sys/malloc.h>
5519284646SJohn Baldwin #include <sys/mutex.h>
560384fff8SJason Evans #include <sys/proc.h>
57c4f7a187SJohn Baldwin #include <sys/resourcevar.h>
58b43179fbSJeff Roberson #include <sys/sched.h>
596c35e809SDag-Erling Smørgrav #include <sys/sbuf.h>
601ada9041SMateusz Guzik #include <sys/smp.h>
61a5a96a19SJohn Baldwin #include <sys/sysctl.h>
62961a7b24SJohn Baldwin #include <sys/turnstile.h>
6336412d79SJohn Baldwin #include <sys/vmmeter.h>
647c0435b9SKip Macy #include <sys/lock_profile.h>
650384fff8SJason Evans 
6636412d79SJohn Baldwin #include <machine/atomic.h>
6736412d79SJohn Baldwin #include <machine/bus.h>
680384fff8SJason Evans #include <machine/cpu.h>
6936412d79SJohn Baldwin 
709c36c934SJohn Baldwin #include <ddb/ddb.h>
719c36c934SJohn Baldwin 
728c4b6380SJohn Baldwin #include <fs/devfs/devfs_int.h>
738c4b6380SJohn Baldwin 
7436412d79SJohn Baldwin #include <vm/vm.h>
7536412d79SJohn Baldwin #include <vm/vm_extern.h>
7636412d79SJohn Baldwin 
77cd6e6e4eSJohn Baldwin #if defined(SMP) && !defined(NO_ADAPTIVE_MUTEXES)
78cd6e6e4eSJohn Baldwin #define	ADAPTIVE_MUTEXES
79cd6e6e4eSJohn Baldwin #endif
80cd6e6e4eSJohn Baldwin 
81f5f9340bSFabien Thomas #ifdef HWPMC_HOOKS
82f5f9340bSFabien Thomas #include <sys/pmckern.h>
83f5f9340bSFabien Thomas PMC_SOFT_DEFINE( , , lock, failed);
84f5f9340bSFabien Thomas #endif
85f5f9340bSFabien Thomas 
86b9a80acaSStephan Uphoff /*
877f44c618SAttilio Rao  * Return the mutex address when the lock cookie address is provided.
887f44c618SAttilio Rao  * This functionality assumes that struct mtx* have a member named mtx_lock.
897f44c618SAttilio Rao  */
907f44c618SAttilio Rao #define	mtxlock2mtx(c)	(__containerof(c, struct mtx, mtx_lock))
917f44c618SAttilio Rao 
927f44c618SAttilio Rao /*
939ed346baSBosko Milekic  * Internal utility macros.
940cde2e34SJason Evans  */
959ed346baSBosko Milekic #define mtx_unowned(m)	((m)->mtx_lock == MTX_UNOWNED)
960cde2e34SJason Evans 
97c0bfd703SJohn Baldwin #define	mtx_destroyed(m) ((m)->mtx_lock == MTX_DESTROYED)
98c0bfd703SJohn Baldwin 
99d576deedSPawel Jakub Dawidek static void	assert_mtx(const struct lock_object *lock, int what);
100d272fe53SJohn Baldwin #ifdef DDB
101d576deedSPawel Jakub Dawidek static void	db_show_mtx(const struct lock_object *lock);
102d272fe53SJohn Baldwin #endif
1037faf4d90SDavide Italiano static void	lock_mtx(struct lock_object *lock, uintptr_t how);
1047faf4d90SDavide Italiano static void	lock_spin(struct lock_object *lock, uintptr_t how);
105a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
106d576deedSPawel Jakub Dawidek static int	owner_mtx(const struct lock_object *lock,
107d576deedSPawel Jakub Dawidek 		    struct thread **owner);
108a5aedd68SStacey Son #endif
1097faf4d90SDavide Italiano static uintptr_t unlock_mtx(struct lock_object *lock);
1107faf4d90SDavide Italiano static uintptr_t unlock_spin(struct lock_object *lock);
111d272fe53SJohn Baldwin 
1120cde2e34SJason Evans /*
11319284646SJohn Baldwin  * Lock classes for sleep and spin mutexes.
1140cde2e34SJason Evans  */
11519284646SJohn Baldwin struct lock_class lock_class_mtx_sleep = {
116ae8dde30SJohn Baldwin 	.lc_name = "sleep mutex",
117ae8dde30SJohn Baldwin 	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
118f9721b43SAttilio Rao 	.lc_assert = assert_mtx,
119d272fe53SJohn Baldwin #ifdef DDB
120ae8dde30SJohn Baldwin 	.lc_ddb_show = db_show_mtx,
121d272fe53SJohn Baldwin #endif
1226e21afd4SJohn Baldwin 	.lc_lock = lock_mtx,
1236e21afd4SJohn Baldwin 	.lc_unlock = unlock_mtx,
124a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
125a5aedd68SStacey Son 	.lc_owner = owner_mtx,
126a5aedd68SStacey Son #endif
12719284646SJohn Baldwin };
12819284646SJohn Baldwin struct lock_class lock_class_mtx_spin = {
129ae8dde30SJohn Baldwin 	.lc_name = "spin mutex",
130ae8dde30SJohn Baldwin 	.lc_flags = LC_SPINLOCK | LC_RECURSABLE,
131f9721b43SAttilio Rao 	.lc_assert = assert_mtx,
132d272fe53SJohn Baldwin #ifdef DDB
133ae8dde30SJohn Baldwin 	.lc_ddb_show = db_show_mtx,
134d272fe53SJohn Baldwin #endif
1356e21afd4SJohn Baldwin 	.lc_lock = lock_spin,
1366e21afd4SJohn Baldwin 	.lc_unlock = unlock_spin,
137a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
138a5aedd68SStacey Son 	.lc_owner = owner_mtx,
139a5aedd68SStacey Son #endif
1408484de75SJohn Baldwin };
1418484de75SJohn Baldwin 
1421ada9041SMateusz Guzik #ifdef ADAPTIVE_MUTEXES
1432e77cad1SMateusz Guzik #ifdef MUTEX_CUSTOM_BACKOFF
1447029da5cSPawel Biernacki static SYSCTL_NODE(_debug, OID_AUTO, mtx, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
1457029da5cSPawel Biernacki     "mtx debugging");
1461ada9041SMateusz Guzik 
147574adb65SMateusz Guzik static struct lock_delay_config __read_frequently mtx_delay;
1481ada9041SMateusz Guzik 
1496b8dd26eSMateusz Guzik SYSCTL_U16(_debug_mtx, OID_AUTO, delay_base, CTLFLAG_RW, &mtx_delay.base,
1501ada9041SMateusz Guzik     0, "");
1516b8dd26eSMateusz Guzik SYSCTL_U16(_debug_mtx, OID_AUTO, delay_max, CTLFLAG_RW, &mtx_delay.max,
1521ada9041SMateusz Guzik     0, "");
1531ada9041SMateusz Guzik 
1548e5a3e9aSMateusz Guzik LOCK_DELAY_SYSINIT_DEFAULT(mtx_delay);
1552e77cad1SMateusz Guzik #else
1562e77cad1SMateusz Guzik #define mtx_delay	locks_delay
1572e77cad1SMateusz Guzik #endif
1581ada9041SMateusz Guzik #endif
1591ada9041SMateusz Guzik 
1602e77cad1SMateusz Guzik #ifdef MUTEX_SPIN_CUSTOM_BACKOFF
1617029da5cSPawel Biernacki static SYSCTL_NODE(_debug, OID_AUTO, mtx_spin,
1627029da5cSPawel Biernacki     CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
163a0d45f0fSMateusz Guzik     "mtx spin debugging");
164a0d45f0fSMateusz Guzik 
165574adb65SMateusz Guzik static struct lock_delay_config __read_frequently mtx_spin_delay;
166a0d45f0fSMateusz Guzik 
1678e5a3e9aSMateusz Guzik SYSCTL_INT(_debug_mtx_spin, OID_AUTO, delay_base, CTLFLAG_RW,
1688e5a3e9aSMateusz Guzik     &mtx_spin_delay.base, 0, "");
1698e5a3e9aSMateusz Guzik SYSCTL_INT(_debug_mtx_spin, OID_AUTO, delay_max, CTLFLAG_RW,
1708e5a3e9aSMateusz Guzik     &mtx_spin_delay.max, 0, "");
171a0d45f0fSMateusz Guzik 
1728e5a3e9aSMateusz Guzik LOCK_DELAY_SYSINIT_DEFAULT(mtx_spin_delay);
1732e77cad1SMateusz Guzik #else
1742e77cad1SMateusz Guzik #define mtx_spin_delay	locks_delay
1752e77cad1SMateusz Guzik #endif
176a0d45f0fSMateusz Guzik 
1779ed346baSBosko Milekic /*
178c53c013bSJohn Baldwin  * System-wide mutexes
179c53c013bSJohn Baldwin  */
1802502c107SJeff Roberson struct mtx blocked_lock;
1816a569d35SMateusz Guzik struct mtx __exclusive_cache_line Giant;
182c53c013bSJohn Baldwin 
18315140a8aSMateusz Guzik static void _mtx_lock_indefinite_check(struct mtx *, struct lock_delay_arg *);
18415140a8aSMateusz Guzik 
18567784314SPoul-Henning Kamp void
186d576deedSPawel Jakub Dawidek assert_mtx(const struct lock_object *lock, int what)
187f9721b43SAttilio Rao {
188f9721b43SAttilio Rao 
189a11bf9a4SXin LI 	/*
190a11bf9a4SXin LI 	 * Treat LA_LOCKED as if LA_XLOCKED was asserted.
191a11bf9a4SXin LI 	 *
192a11bf9a4SXin LI 	 * Some callers of lc_assert uses LA_LOCKED to indicate that either
193a11bf9a4SXin LI 	 * a shared lock or write lock was held, while other callers uses
194a11bf9a4SXin LI 	 * the more strict LA_XLOCKED (used as MA_OWNED).
195a11bf9a4SXin LI 	 *
196a11bf9a4SXin LI 	 * Mutex is the only lock class that can not be shared, as a result,
197a11bf9a4SXin LI 	 * we can reasonably consider the caller really intends to assert
198a11bf9a4SXin LI 	 * LA_XLOCKED when they are asserting LA_LOCKED on a mutex object.
199a11bf9a4SXin LI 	 */
200a11bf9a4SXin LI 	if (what & LA_LOCKED) {
201a11bf9a4SXin LI 		what &= ~LA_LOCKED;
202a11bf9a4SXin LI 		what |= LA_XLOCKED;
203a11bf9a4SXin LI 	}
204d576deedSPawel Jakub Dawidek 	mtx_assert((const struct mtx *)lock, what);
205f9721b43SAttilio Rao }
206f9721b43SAttilio Rao 
20767784314SPoul-Henning Kamp void
2087faf4d90SDavide Italiano lock_mtx(struct lock_object *lock, uintptr_t how)
2096e21afd4SJohn Baldwin {
2106e21afd4SJohn Baldwin 
2116e21afd4SJohn Baldwin 	mtx_lock((struct mtx *)lock);
2126e21afd4SJohn Baldwin }
2136e21afd4SJohn Baldwin 
21467784314SPoul-Henning Kamp void
2157faf4d90SDavide Italiano lock_spin(struct lock_object *lock, uintptr_t how)
2166e21afd4SJohn Baldwin {
2176e21afd4SJohn Baldwin 
2186e21afd4SJohn Baldwin 	panic("spin locks can only use msleep_spin");
2196e21afd4SJohn Baldwin }
2206e21afd4SJohn Baldwin 
2217faf4d90SDavide Italiano uintptr_t
2226e21afd4SJohn Baldwin unlock_mtx(struct lock_object *lock)
2236e21afd4SJohn Baldwin {
2246e21afd4SJohn Baldwin 	struct mtx *m;
2256e21afd4SJohn Baldwin 
2266e21afd4SJohn Baldwin 	m = (struct mtx *)lock;
2276e21afd4SJohn Baldwin 	mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
2286e21afd4SJohn Baldwin 	mtx_unlock(m);
2296e21afd4SJohn Baldwin 	return (0);
2306e21afd4SJohn Baldwin }
2316e21afd4SJohn Baldwin 
2327faf4d90SDavide Italiano uintptr_t
2336e21afd4SJohn Baldwin unlock_spin(struct lock_object *lock)
2346e21afd4SJohn Baldwin {
2356e21afd4SJohn Baldwin 
2366e21afd4SJohn Baldwin 	panic("spin locks can only use msleep_spin");
2376e21afd4SJohn Baldwin }
2386e21afd4SJohn Baldwin 
239a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
240a5aedd68SStacey Son int
241d576deedSPawel Jakub Dawidek owner_mtx(const struct lock_object *lock, struct thread **owner)
242a5aedd68SStacey Son {
24302315a67SMark Johnston 	const struct mtx *m;
24402315a67SMark Johnston 	uintptr_t x;
245a5aedd68SStacey Son 
24602315a67SMark Johnston 	m = (const struct mtx *)lock;
24702315a67SMark Johnston 	x = m->mtx_lock;
24802315a67SMark Johnston 	*owner = (struct thread *)(x & ~MTX_FLAGMASK);
249e280ce46SMateusz Guzik 	return (*owner != NULL);
250a5aedd68SStacey Son }
251a5aedd68SStacey Son #endif
252a5aedd68SStacey Son 
2530cde2e34SJason Evans /*
2546283b7d0SJohn Baldwin  * Function versions of the inlined __mtx_* macros.  These are used by
2556283b7d0SJohn Baldwin  * modules and can also be called from assembly language if needed.
2566283b7d0SJohn Baldwin  */
2576283b7d0SJohn Baldwin void
2587f44c618SAttilio Rao __mtx_lock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
2596283b7d0SJohn Baldwin {
2607f44c618SAttilio Rao 	struct mtx *m;
26108da2677SMateusz Guzik 	uintptr_t tid, v;
2626283b7d0SJohn Baldwin 
2637f44c618SAttilio Rao 	m = mtxlock2mtx(c);
2647f44c618SAttilio Rao 
265704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
266704cb42fSMark Johnston 	    !TD_IS_IDLETHREAD(curthread),
267e3ae0dfeSAttilio Rao 	    ("mtx_lock() by idle thread %p on sleep mutex %s @ %s:%d",
268e3ae0dfeSAttilio Rao 	    curthread, m->lock_object.lo_name, file, line));
269186abbd7SJohn Baldwin 	KASSERT(m->mtx_lock != MTX_DESTROYED,
270186abbd7SJohn Baldwin 	    ("mtx_lock() of destroyed mutex @ %s:%d", file, line));
271aa89d8cdSJohn Baldwin 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
272aa89d8cdSJohn Baldwin 	    ("mtx_lock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
2730d975d63SJohn Baldwin 	    file, line));
274ac6b769bSAttilio Rao 	WITNESS_CHECKORDER(&m->lock_object, (opts & ~MTX_RECURSE) |
275ac6b769bSAttilio Rao 	    LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
2767c0435b9SKip Macy 
27708da2677SMateusz Guzik 	tid = (uintptr_t)curthread;
27808da2677SMateusz Guzik 	v = MTX_UNOWNED;
27908da2677SMateusz Guzik 	if (!_mtx_obtain_lock_fetch(m, &v, tid))
2802f1ddb89SMateusz Guzik 		_mtx_lock_sleep(m, v, opts, file, line);
28108da2677SMateusz Guzik 	else
28208da2677SMateusz Guzik 		LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
28308da2677SMateusz Guzik 		    m, 0, 0, file, line);
284aa89d8cdSJohn Baldwin 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
285dde96c99SJohn Baldwin 	    line);
286ac6b769bSAttilio Rao 	WITNESS_LOCK(&m->lock_object, (opts & ~MTX_RECURSE) | LOP_EXCLUSIVE,
287ac6b769bSAttilio Rao 	    file, line);
288ce1c953eSMark Johnston 	TD_LOCKS_INC(curthread);
2896283b7d0SJohn Baldwin }
2906283b7d0SJohn Baldwin 
2916283b7d0SJohn Baldwin void
2927f44c618SAttilio Rao __mtx_unlock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
2936283b7d0SJohn Baldwin {
2947f44c618SAttilio Rao 	struct mtx *m;
29535370593SAndriy Gapon 
2967f44c618SAttilio Rao 	m = mtxlock2mtx(c);
2977f44c618SAttilio Rao 
298186abbd7SJohn Baldwin 	KASSERT(m->mtx_lock != MTX_DESTROYED,
299186abbd7SJohn Baldwin 	    ("mtx_unlock() of destroyed mutex @ %s:%d", file, line));
300aa89d8cdSJohn Baldwin 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
301aa89d8cdSJohn Baldwin 	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
3020d975d63SJohn Baldwin 	    file, line));
303aa89d8cdSJohn Baldwin 	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
304aa89d8cdSJohn Baldwin 	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
3050d975d63SJohn Baldwin 	    line);
30621377ce0SJohn Baldwin 	mtx_assert(m, MA_OWNED);
307c66d7606SKip Macy 
308ffd5c94cSMateusz Guzik #ifdef LOCK_PROFILING
309b584eb2eSMateusz Guzik 	__mtx_unlock_sleep(c, (uintptr_t)curthread, opts, file, line);
310ffd5c94cSMateusz Guzik #else
311ffd5c94cSMateusz Guzik 	__mtx_unlock(m, curthread, opts, file, line);
312ffd5c94cSMateusz Guzik #endif
313ce1c953eSMark Johnston 	TD_LOCKS_DEC(curthread);
3146283b7d0SJohn Baldwin }
3156283b7d0SJohn Baldwin 
3166283b7d0SJohn Baldwin void
3177f44c618SAttilio Rao __mtx_lock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
3187f44c618SAttilio Rao     int line)
3196283b7d0SJohn Baldwin {
3207f44c618SAttilio Rao 	struct mtx *m;
32162bf13cbSMateusz Guzik #ifdef SMP
3220d74fe26SMateusz Guzik 	uintptr_t tid, v;
32362bf13cbSMateusz Guzik #endif
3246283b7d0SJohn Baldwin 
3257f44c618SAttilio Rao 	m = mtxlock2mtx(c);
3267f44c618SAttilio Rao 
327186abbd7SJohn Baldwin 	KASSERT(m->mtx_lock != MTX_DESTROYED,
328186abbd7SJohn Baldwin 	    ("mtx_lock_spin() of destroyed mutex @ %s:%d", file, line));
329aa89d8cdSJohn Baldwin 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
3300d975d63SJohn Baldwin 	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
331aa89d8cdSJohn Baldwin 	    m->lock_object.lo_name, file, line));
332ad69e26bSJohn Baldwin 	if (mtx_owned(m))
333ac6b769bSAttilio Rao 		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
334ac6b769bSAttilio Rao 		    (opts & MTX_RECURSE) != 0,
335ad69e26bSJohn Baldwin 	    ("mtx_lock_spin: recursed on non-recursive mutex %s @ %s:%d\n",
336ad69e26bSJohn Baldwin 		    m->lock_object.lo_name, file, line));
337ac6b769bSAttilio Rao 	opts &= ~MTX_RECURSE;
338aa89d8cdSJohn Baldwin 	WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
33941313430SJohn Baldwin 	    file, line, NULL);
34062bf13cbSMateusz Guzik #ifdef SMP
3410d74fe26SMateusz Guzik 	spinlock_enter();
3420d74fe26SMateusz Guzik 	tid = (uintptr_t)curthread;
3430d74fe26SMateusz Guzik 	v = MTX_UNOWNED;
3440d74fe26SMateusz Guzik 	if (!_mtx_obtain_lock_fetch(m, &v, tid))
3450d74fe26SMateusz Guzik 		_mtx_lock_spin(m, v, opts, file, line);
3460d74fe26SMateusz Guzik 	else
3470d74fe26SMateusz Guzik 		LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire,
3480d74fe26SMateusz Guzik 		    m, 0, 0, file, line);
34962bf13cbSMateusz Guzik #else
35062bf13cbSMateusz Guzik 	__mtx_lock_spin(m, curthread, opts, file, line);
35162bf13cbSMateusz Guzik #endif
352aa89d8cdSJohn Baldwin 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
353dde96c99SJohn Baldwin 	    line);
354aa89d8cdSJohn Baldwin 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
3556283b7d0SJohn Baldwin }
3566283b7d0SJohn Baldwin 
35790b581f2SKonstantin Belousov int
35890b581f2SKonstantin Belousov __mtx_trylock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
35990b581f2SKonstantin Belousov     int line)
36090b581f2SKonstantin Belousov {
36190b581f2SKonstantin Belousov 	struct mtx *m;
36290b581f2SKonstantin Belousov 
36390b581f2SKonstantin Belousov 	if (SCHEDULER_STOPPED())
36490b581f2SKonstantin Belousov 		return (1);
36590b581f2SKonstantin Belousov 
36690b581f2SKonstantin Belousov 	m = mtxlock2mtx(c);
36790b581f2SKonstantin Belousov 
36890b581f2SKonstantin Belousov 	KASSERT(m->mtx_lock != MTX_DESTROYED,
36990b581f2SKonstantin Belousov 	    ("mtx_trylock_spin() of destroyed mutex @ %s:%d", file, line));
37090b581f2SKonstantin Belousov 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
37190b581f2SKonstantin Belousov 	    ("mtx_trylock_spin() of sleep mutex %s @ %s:%d",
37290b581f2SKonstantin Belousov 	    m->lock_object.lo_name, file, line));
37390b581f2SKonstantin Belousov 	KASSERT((opts & MTX_RECURSE) == 0,
37490b581f2SKonstantin Belousov 	    ("mtx_trylock_spin: unsupp. opt MTX_RECURSE on mutex %s @ %s:%d\n",
37590b581f2SKonstantin Belousov 	    m->lock_object.lo_name, file, line));
37690b581f2SKonstantin Belousov 	if (__mtx_trylock_spin(m, curthread, opts, file, line)) {
37790b581f2SKonstantin Belousov 		LOCK_LOG_TRY("LOCK", &m->lock_object, opts, 1, file, line);
37890b581f2SKonstantin Belousov 		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
37990b581f2SKonstantin Belousov 		return (1);
38090b581f2SKonstantin Belousov 	}
38190b581f2SKonstantin Belousov 	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, 0, file, line);
38290b581f2SKonstantin Belousov 	return (0);
38390b581f2SKonstantin Belousov }
38490b581f2SKonstantin Belousov 
3856283b7d0SJohn Baldwin void
3867f44c618SAttilio Rao __mtx_unlock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
3877f44c618SAttilio Rao     int line)
3886283b7d0SJohn Baldwin {
3897f44c618SAttilio Rao 	struct mtx *m;
390c66d7606SKip Macy 
3917f44c618SAttilio Rao 	m = mtxlock2mtx(c);
3927f44c618SAttilio Rao 
393186abbd7SJohn Baldwin 	KASSERT(m->mtx_lock != MTX_DESTROYED,
394186abbd7SJohn Baldwin 	    ("mtx_unlock_spin() of destroyed mutex @ %s:%d", file, line));
395aa89d8cdSJohn Baldwin 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
3960d975d63SJohn Baldwin 	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
397aa89d8cdSJohn Baldwin 	    m->lock_object.lo_name, file, line));
398aa89d8cdSJohn Baldwin 	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
399aa89d8cdSJohn Baldwin 	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
400dde96c99SJohn Baldwin 	    line);
4010d975d63SJohn Baldwin 	mtx_assert(m, MA_OWNED);
402c66d7606SKip Macy 
403961135eaSJohn Baldwin 	__mtx_unlock_spin(m);
4046283b7d0SJohn Baldwin }
4056283b7d0SJohn Baldwin 
4066283b7d0SJohn Baldwin /*
4079ed346baSBosko Milekic  * The important part of mtx_trylock{,_flags}()
408eac09796SJohn Baldwin  * Tries to acquire lock `m.'  If this function is called on a mutex that
409eac09796SJohn Baldwin  * is already owned, it will recursively acquire the lock.
4100cde2e34SJason Evans  */
4110cde2e34SJason Evans int
412013c0b49SMateusz Guzik _mtx_trylock_flags_int(struct mtx *m, int opts LOCK_FILE_LINE_ARG_DEF)
4130cde2e34SJason Evans {
4145c5df0d9SMateusz Guzik 	struct thread *td;
4155c5df0d9SMateusz Guzik 	uintptr_t tid, v;
4161723a064SJeff Roberson #ifdef LOCK_PROFILING
4177c0435b9SKip Macy 	uint64_t waittime = 0;
4181723a064SJeff Roberson 	int contested = 0;
4191723a064SJeff Roberson #endif
4201723a064SJeff Roberson 	int rval;
4215c5df0d9SMateusz Guzik 	bool recursed;
4220cde2e34SJason Evans 
4235c5df0d9SMateusz Guzik 	td = curthread;
4245c5df0d9SMateusz Guzik 	tid = (uintptr_t)td;
4255c5df0d9SMateusz Guzik 	if (SCHEDULER_STOPPED_TD(td))
42635370593SAndriy Gapon 		return (1);
42735370593SAndriy Gapon 
428704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
429e3ae0dfeSAttilio Rao 	    ("mtx_trylock() by idle thread %p on sleep mutex %s @ %s:%d",
430e3ae0dfeSAttilio Rao 	    curthread, m->lock_object.lo_name, file, line));
431186abbd7SJohn Baldwin 	KASSERT(m->mtx_lock != MTX_DESTROYED,
432186abbd7SJohn Baldwin 	    ("mtx_trylock() of destroyed mutex @ %s:%d", file, line));
433aa89d8cdSJohn Baldwin 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
434aa89d8cdSJohn Baldwin 	    ("mtx_trylock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
43583cece6fSJohn Baldwin 	    file, line));
4369ed346baSBosko Milekic 
4375c5df0d9SMateusz Guzik 	rval = 1;
4385c5df0d9SMateusz Guzik 	recursed = false;
4395c5df0d9SMateusz Guzik 	v = MTX_UNOWNED;
440b247fd39SMateusz Guzik 	for (;;) {
441b247fd39SMateusz Guzik 		if (_mtx_obtain_lock_fetch(m, &v, tid))
442b247fd39SMateusz Guzik 			break;
443b247fd39SMateusz Guzik 		if (v == MTX_UNOWNED)
444b247fd39SMateusz Guzik 			continue;
4455c5df0d9SMateusz Guzik 		if (v == tid &&
4465c5df0d9SMateusz Guzik 		    ((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
447ac6b769bSAttilio Rao 		    (opts & MTX_RECURSE) != 0)) {
448eac09796SJohn Baldwin 			m->mtx_recurse++;
449eac09796SJohn Baldwin 			atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
4505c5df0d9SMateusz Guzik 			recursed = true;
451b247fd39SMateusz Guzik 			break;
4525c5df0d9SMateusz Guzik 		}
453b247fd39SMateusz Guzik 		rval = 0;
454b247fd39SMateusz Guzik 		break;
4555c5df0d9SMateusz Guzik 	}
4565c5df0d9SMateusz Guzik 
457ac6b769bSAttilio Rao 	opts &= ~MTX_RECURSE;
4589ed346baSBosko Milekic 
459aa89d8cdSJohn Baldwin 	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, rval, file, line);
460764e4d54SJohn Baldwin 	if (rval) {
461aa89d8cdSJohn Baldwin 		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
4622d96f0b1SJohn Baldwin 		    file, line);
463ce1c953eSMark Johnston 		TD_LOCKS_INC(curthread);
4645c5df0d9SMateusz Guzik 		if (!recursed)
46532cd0147SMark Johnston 			LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
466a5aedd68SStacey Son 			    m, contested, waittime, file, line);
467764e4d54SJohn Baldwin 	}
4689ed346baSBosko Milekic 
46919284646SJohn Baldwin 	return (rval);
4700cde2e34SJason Evans }
4710cde2e34SJason Evans 
472013c0b49SMateusz Guzik int
473013c0b49SMateusz Guzik _mtx_trylock_flags_(volatile uintptr_t *c, int opts, const char *file, int line)
474013c0b49SMateusz Guzik {
475013c0b49SMateusz Guzik 	struct mtx *m;
476013c0b49SMateusz Guzik 
477013c0b49SMateusz Guzik 	m = mtxlock2mtx(c);
478013c0b49SMateusz Guzik 	return (_mtx_trylock_flags_int(m, opts LOCK_FILE_LINE_ARG));
479013c0b49SMateusz Guzik }
480013c0b49SMateusz Guzik 
4810cde2e34SJason Evans /*
4827f44c618SAttilio Rao  * __mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
4839ed346baSBosko Milekic  *
4849ed346baSBosko Milekic  * We call this if the lock is either contested (i.e. we need to go to
4859ed346baSBosko Milekic  * sleep waiting for it), or if we need to recurse on it.
4860cde2e34SJason Evans  */
48709f1319aSMateusz Guzik #if LOCK_DEBUG > 0
4880cde2e34SJason Evans void
4892f1ddb89SMateusz Guzik __mtx_lock_sleep(volatile uintptr_t *c, uintptr_t v, int opts, const char *file,
4902f1ddb89SMateusz Guzik     int line)
49109f1319aSMateusz Guzik #else
49209f1319aSMateusz Guzik void
4932f1ddb89SMateusz Guzik __mtx_lock_sleep(volatile uintptr_t *c, uintptr_t v)
49409f1319aSMateusz Guzik #endif
49536412d79SJohn Baldwin {
4962f1ddb89SMateusz Guzik 	struct thread *td;
4977f44c618SAttilio Rao 	struct mtx *m;
4982502c107SJeff Roberson 	struct turnstile *ts;
4992f1ddb89SMateusz Guzik 	uintptr_t tid;
5002ccee9ccSMateusz Guzik 	struct thread *owner;
5011723a064SJeff Roberson #ifdef LOCK_PROFILING
50270fe8436SKip Macy 	int contested = 0;
50370fe8436SKip Macy 	uint64_t waittime = 0;
5041723a064SJeff Roberson #endif
5051ada9041SMateusz Guzik #if defined(ADAPTIVE_MUTEXES) || defined(KDTRACE_HOOKS)
5061ada9041SMateusz Guzik 	struct lock_delay_arg lda;
5071ada9041SMateusz Guzik #endif
508a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
50961852185SMateusz Guzik 	u_int sleep_cnt = 0;
510a5aedd68SStacey Son 	int64_t sleep_time = 0;
511076dd8ebSAndriy Gapon 	int64_t all_time = 0;
512dfaa7859SMateusz Guzik #endif
513dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
514f183fb16SMateusz Guzik 	int doing_lockprof = 0;
515a5aedd68SStacey Son #endif
51609bdec20SMateusz Guzik 
5172f1ddb89SMateusz Guzik 	td = curthread;
5182f1ddb89SMateusz Guzik 	tid = (uintptr_t)td;
51909bdec20SMateusz Guzik 	m = mtxlock2mtx(c);
52009bdec20SMateusz Guzik 
52109bdec20SMateusz Guzik #ifdef KDTRACE_HOOKS
52209bdec20SMateusz Guzik 	if (LOCKSTAT_PROFILE_ENABLED(adaptive__acquire)) {
52309bdec20SMateusz Guzik 		while (v == MTX_UNOWNED) {
52409bdec20SMateusz Guzik 			if (_mtx_obtain_lock_fetch(m, &v, tid))
52509bdec20SMateusz Guzik 				goto out_lockstat;
52609bdec20SMateusz Guzik 		}
52709bdec20SMateusz Guzik 		doing_lockprof = 1;
52809bdec20SMateusz Guzik 		all_time -= lockstat_nsecs(&m->lock_object);
52909bdec20SMateusz Guzik 	}
53009bdec20SMateusz Guzik #endif
53109bdec20SMateusz Guzik #ifdef LOCK_PROFILING
53209bdec20SMateusz Guzik 	doing_lockprof = 1;
53309bdec20SMateusz Guzik #endif
53409bdec20SMateusz Guzik 
5352f1ddb89SMateusz Guzik 	if (SCHEDULER_STOPPED_TD(td))
53635370593SAndriy Gapon 		return;
53735370593SAndriy Gapon 
538fa5000a4SMateusz Guzik #if defined(ADAPTIVE_MUTEXES)
5391ada9041SMateusz Guzik 	lock_delay_arg_init(&lda, &mtx_delay);
540fa5000a4SMateusz Guzik #elif defined(KDTRACE_HOOKS)
541c795344fSMateusz Guzik 	lock_delay_arg_init_noadapt(&lda);
5421ada9041SMateusz Guzik #endif
54309bdec20SMateusz Guzik 
544c1aaf63cSMateusz Guzik 	if (__predict_false(v == MTX_UNOWNED))
545c1aaf63cSMateusz Guzik 		v = MTX_READ_VALUE(m);
5467f44c618SAttilio Rao 
5472f1ddb89SMateusz Guzik 	if (__predict_false(lv_mtx_owner(v) == td)) {
548ac6b769bSAttilio Rao 		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
549ac6b769bSAttilio Rao 		    (opts & MTX_RECURSE) != 0,
550eac09796SJohn Baldwin 	    ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
551aa89d8cdSJohn Baldwin 		    m->lock_object.lo_name, file, line));
552a24c8eb8SMateusz Guzik #if LOCK_DEBUG > 0
553ac6b769bSAttilio Rao 		opts &= ~MTX_RECURSE;
554a24c8eb8SMateusz Guzik #endif
55536412d79SJohn Baldwin 		m->mtx_recurse++;
55608812b39SBosko Milekic 		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
557aa89d8cdSJohn Baldwin 		if (LOCK_LOG_TEST(&m->lock_object, opts))
5585746a1d8SBosko Milekic 			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
55936412d79SJohn Baldwin 		return;
56036412d79SJohn Baldwin 	}
561a24c8eb8SMateusz Guzik #if LOCK_DEBUG > 0
562ac6b769bSAttilio Rao 	opts &= ~MTX_RECURSE;
563a24c8eb8SMateusz Guzik #endif
5649ed346baSBosko Milekic 
565f5f9340bSFabien Thomas #ifdef HWPMC_HOOKS
566f5f9340bSFabien Thomas 	PMC_SOFT_CALL( , , lock, failed);
567f5f9340bSFabien Thomas #endif
56870fe8436SKip Macy 	lock_profile_obtain_lock_failed(&m->lock_object,
56970fe8436SKip Macy 		    &contested, &waittime);
570aa89d8cdSJohn Baldwin 	if (LOCK_LOG_TEST(&m->lock_object, opts))
57115ec816aSJohn Baldwin 		CTR4(KTR_LOCK,
57215ec816aSJohn Baldwin 		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
573aa89d8cdSJohn Baldwin 		    m->lock_object.lo_name, (void *)m->mtx_lock, file, line);
5741bd0eefbSJohn Baldwin 
575fc4f686dSMateusz Guzik 	for (;;) {
5762604eb9eSMateusz Guzik 		if (v == MTX_UNOWNED) {
57790836c32SMateusz Guzik 			if (_mtx_obtain_lock_fetch(m, &v, tid))
578fc4f686dSMateusz Guzik 				break;
5792604eb9eSMateusz Guzik 			continue;
5802604eb9eSMateusz Guzik 		}
581a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
5821ada9041SMateusz Guzik 		lda.spin_cnt++;
583a5aedd68SStacey Son #endif
58449aead8aSAttilio Rao #ifdef ADAPTIVE_MUTEXES
58549aead8aSAttilio Rao 		/*
58649aead8aSAttilio Rao 		 * If the owner is running on another CPU, spin until the
58749aead8aSAttilio Rao 		 * owner stops running or the state of the lock changes.
58849aead8aSAttilio Rao 		 */
5892604eb9eSMateusz Guzik 		owner = lv_mtx_owner(v);
59049aead8aSAttilio Rao 		if (TD_IS_RUNNING(owner)) {
59149aead8aSAttilio Rao 			if (LOCK_LOG_TEST(&m->lock_object, 0))
59249aead8aSAttilio Rao 				CTR3(KTR_LOCK,
59349aead8aSAttilio Rao 				    "%s: spinning on %p held by %p",
59449aead8aSAttilio Rao 				    __func__, m, owner);
5952cba8dd3SJohn Baldwin 			KTR_STATE1(KTR_SCHED, "thread",
5962cba8dd3SJohn Baldwin 			    sched_tdname((struct thread *)tid),
5972cba8dd3SJohn Baldwin 			    "spinning", "lockname:\"%s\"",
5982cba8dd3SJohn Baldwin 			    m->lock_object.lo_name);
5992604eb9eSMateusz Guzik 			do {
6001ada9041SMateusz Guzik 				lock_delay(&lda);
601391df78aSMateusz Guzik 				v = MTX_READ_VALUE(m);
6022604eb9eSMateusz Guzik 				owner = lv_mtx_owner(v);
6032604eb9eSMateusz Guzik 			} while (v != MTX_UNOWNED && TD_IS_RUNNING(owner));
6042cba8dd3SJohn Baldwin 			KTR_STATE0(KTR_SCHED, "thread",
6052cba8dd3SJohn Baldwin 			    sched_tdname((struct thread *)tid),
6062cba8dd3SJohn Baldwin 			    "running");
60749aead8aSAttilio Rao 			continue;
60849aead8aSAttilio Rao 		}
60949aead8aSAttilio Rao #endif
61049aead8aSAttilio Rao 
6112502c107SJeff Roberson 		ts = turnstile_trywait(&m->lock_object);
6122604eb9eSMateusz Guzik 		v = MTX_READ_VALUE(m);
613310f24d7SMateusz Guzik retry_turnstile:
6145fa8dd90SJohn Baldwin 
61536412d79SJohn Baldwin 		/*
6169ed346baSBosko Milekic 		 * Check if the lock has been released while spinning for
617961a7b24SJohn Baldwin 		 * the turnstile chain lock.
61836412d79SJohn Baldwin 		 */
6195fa8dd90SJohn Baldwin 		if (v == MTX_UNOWNED) {
6202502c107SJeff Roberson 			turnstile_cancel(ts);
62136412d79SJohn Baldwin 			continue;
62236412d79SJohn Baldwin 		}
6239ed346baSBosko Milekic 
62449aead8aSAttilio Rao #ifdef ADAPTIVE_MUTEXES
62549aead8aSAttilio Rao 		/*
626fa29f023SJohn Baldwin 		 * The current lock owner might have started executing
627fa29f023SJohn Baldwin 		 * on another CPU (or the lock could have changed
628fa29f023SJohn Baldwin 		 * owners) while we were waiting on the turnstile
629fa29f023SJohn Baldwin 		 * chain lock.  If so, drop the turnstile lock and try
630fa29f023SJohn Baldwin 		 * again.
63149aead8aSAttilio Rao 		 */
6322604eb9eSMateusz Guzik 		owner = lv_mtx_owner(v);
63349aead8aSAttilio Rao 		if (TD_IS_RUNNING(owner)) {
63449aead8aSAttilio Rao 			turnstile_cancel(ts);
63549aead8aSAttilio Rao 			continue;
63649aead8aSAttilio Rao 		}
63749aead8aSAttilio Rao #endif
63849aead8aSAttilio Rao 
63936412d79SJohn Baldwin 		/*
6409ed346baSBosko Milekic 		 * If the mutex isn't already contested and a failure occurs
6419ed346baSBosko Milekic 		 * setting the contested bit, the mutex was either released
6429ed346baSBosko Milekic 		 * or the state of the MTX_RECURSED bit changed.
64336412d79SJohn Baldwin 		 */
64436412d79SJohn Baldwin 		if ((v & MTX_CONTESTED) == 0 &&
645310f24d7SMateusz Guzik 		    !atomic_fcmpset_ptr(&m->mtx_lock, &v, v | MTX_CONTESTED)) {
646310f24d7SMateusz Guzik 			goto retry_turnstile;
64736412d79SJohn Baldwin 		}
64836412d79SJohn Baldwin 
6499ed346baSBosko Milekic 		/*
6507feefcd6SJohn Baldwin 		 * We definitely must sleep for this lock.
6519ed346baSBosko Milekic 		 */
65236412d79SJohn Baldwin 		mtx_assert(m, MA_NOTOWNED);
65336412d79SJohn Baldwin 
6549ed346baSBosko Milekic 		/*
655961a7b24SJohn Baldwin 		 * Block on the turnstile.
6569ed346baSBosko Milekic 		 */
657a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
658e2b25737SMark Johnston 		sleep_time -= lockstat_nsecs(&m->lock_object);
659a5aedd68SStacey Son #endif
660284194f1SMateusz Guzik #ifndef ADAPTIVE_MUTEXES
661284194f1SMateusz Guzik 		owner = mtx_owner(m);
662284194f1SMateusz Guzik #endif
6638448e020SMateusz Guzik 		MPASS(owner == mtx_owner(m));
6648448e020SMateusz Guzik 		turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
665a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
666e2b25737SMark Johnston 		sleep_time += lockstat_nsecs(&m->lock_object);
667a5aedd68SStacey Son 		sleep_cnt++;
668a5aedd68SStacey Son #endif
6692604eb9eSMateusz Guzik 		v = MTX_READ_VALUE(m);
67036412d79SJohn Baldwin 	}
671dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
672dfaa7859SMateusz Guzik 	if (__predict_true(!doing_lockprof))
6737640beb9SMateusz Guzik 		return;
674dfaa7859SMateusz Guzik #endif
675dfaa7859SMateusz Guzik #ifdef KDTRACE_HOOKS
6767640beb9SMateusz Guzik 	all_time += lockstat_nsecs(&m->lock_object);
677a5aedd68SStacey Son 	if (sleep_time)
67832cd0147SMark Johnston 		LOCKSTAT_RECORD1(adaptive__block, m, sleep_time);
679a5aedd68SStacey Son 
680a5aedd68SStacey Son 	/*
681a5aedd68SStacey Son 	 * Only record the loops spinning and not sleeping.
682a5aedd68SStacey Son 	 */
6831ada9041SMateusz Guzik 	if (lda.spin_cnt > sleep_cnt)
68432cd0147SMark Johnston 		LOCKSTAT_RECORD1(adaptive__spin, m, all_time - sleep_time);
68509bdec20SMateusz Guzik out_lockstat:
686a5aedd68SStacey Son #endif
68709bdec20SMateusz Guzik 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire, m, contested,
68809bdec20SMateusz Guzik 	    waittime, file, line);
6899ed346baSBosko Milekic }
6909ed346baSBosko Milekic 
691b95b98b0SKonstantin Belousov #ifdef SMP
6929ed346baSBosko Milekic /*
6937f44c618SAttilio Rao  * _mtx_lock_spin_cookie: the tougher part of acquiring an MTX_SPIN lock.
6949ed346baSBosko Milekic  *
6959ed346baSBosko Milekic  * This is only called if we need to actually spin for the lock. Recursion
6969ed346baSBosko Milekic  * is handled inline.
6979ed346baSBosko Milekic  */
6980d74fe26SMateusz Guzik #if LOCK_DEBUG > 0
6999ed346baSBosko Milekic void
7000d74fe26SMateusz Guzik _mtx_lock_spin_cookie(volatile uintptr_t *c, uintptr_t v, int opts,
7010d74fe26SMateusz Guzik     const char *file, int line)
7020d74fe26SMateusz Guzik #else
7030d74fe26SMateusz Guzik void
7040d74fe26SMateusz Guzik _mtx_lock_spin_cookie(volatile uintptr_t *c, uintptr_t v)
7050d74fe26SMateusz Guzik #endif
70636412d79SJohn Baldwin {
7077f44c618SAttilio Rao 	struct mtx *m;
708a0d45f0fSMateusz Guzik 	struct lock_delay_arg lda;
7090d74fe26SMateusz Guzik 	uintptr_t tid;
7101723a064SJeff Roberson #ifdef LOCK_PROFILING
7111723a064SJeff Roberson 	int contested = 0;
71270fe8436SKip Macy 	uint64_t waittime = 0;
7131723a064SJeff Roberson #endif
714076dd8ebSAndriy Gapon #ifdef KDTRACE_HOOKS
715076dd8ebSAndriy Gapon 	int64_t spin_time = 0;
716076dd8ebSAndriy Gapon #endif
717dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
718f183fb16SMateusz Guzik 	int doing_lockprof = 0;
719dfaa7859SMateusz Guzik #endif
72036412d79SJohn Baldwin 
7210d74fe26SMateusz Guzik 	tid = (uintptr_t)curthread;
7227f44c618SAttilio Rao 	m = mtxlock2mtx(c);
7237f44c618SAttilio Rao 
72409bdec20SMateusz Guzik #ifdef KDTRACE_HOOKS
72509bdec20SMateusz Guzik 	if (LOCKSTAT_PROFILE_ENABLED(adaptive__acquire)) {
72609bdec20SMateusz Guzik 		while (v == MTX_UNOWNED) {
72709bdec20SMateusz Guzik 			if (_mtx_obtain_lock_fetch(m, &v, tid))
72809bdec20SMateusz Guzik 				goto out_lockstat;
72909bdec20SMateusz Guzik 		}
73009bdec20SMateusz Guzik 		doing_lockprof = 1;
73109bdec20SMateusz Guzik 		spin_time -= lockstat_nsecs(&m->lock_object);
73209bdec20SMateusz Guzik 	}
73309bdec20SMateusz Guzik #endif
73409bdec20SMateusz Guzik #ifdef LOCK_PROFILING
73509bdec20SMateusz Guzik 	doing_lockprof = 1;
73609bdec20SMateusz Guzik #endif
73709bdec20SMateusz Guzik 
73813d2ef0fSMateusz Guzik 	if (__predict_false(v == MTX_UNOWNED))
73913d2ef0fSMateusz Guzik 		v = MTX_READ_VALUE(m);
74013d2ef0fSMateusz Guzik 
74113d2ef0fSMateusz Guzik 	if (__predict_false(v == tid)) {
74213d2ef0fSMateusz Guzik 		m->mtx_recurse++;
74313d2ef0fSMateusz Guzik 		return;
74413d2ef0fSMateusz Guzik 	}
74513d2ef0fSMateusz Guzik 
7460d74fe26SMateusz Guzik 	if (SCHEDULER_STOPPED())
7470d74fe26SMateusz Guzik 		return;
7480d74fe26SMateusz Guzik 
7490d74fe26SMateusz Guzik 	lock_delay_arg_init(&lda, &mtx_spin_delay);
7500d74fe26SMateusz Guzik 
751aa89d8cdSJohn Baldwin 	if (LOCK_LOG_TEST(&m->lock_object, opts))
7525746a1d8SBosko Milekic 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
7532cba8dd3SJohn Baldwin 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
7542cba8dd3SJohn Baldwin 	    "spinning", "lockname:\"%s\"", m->lock_object.lo_name);
7559ed346baSBosko Milekic 
756f5f9340bSFabien Thomas #ifdef HWPMC_HOOKS
757f5f9340bSFabien Thomas 	PMC_SOFT_CALL( , , lock, failed);
758f5f9340bSFabien Thomas #endif
75970fe8436SKip Macy 	lock_profile_obtain_lock_failed(&m->lock_object, &contested, &waittime);
76009bdec20SMateusz Guzik 
761fc4f686dSMateusz Guzik 	for (;;) {
7622604eb9eSMateusz Guzik 		if (v == MTX_UNOWNED) {
76390836c32SMateusz Guzik 			if (_mtx_obtain_lock_fetch(m, &v, tid))
764fc4f686dSMateusz Guzik 				break;
76536412d79SJohn Baldwin 			continue;
766703fc290SJohn Baldwin 		}
7672604eb9eSMateusz Guzik 		/* Give interrupts a chance while we spin. */
7682604eb9eSMateusz Guzik 		spinlock_exit();
7692604eb9eSMateusz Guzik 		do {
77015140a8aSMateusz Guzik 			if (__predict_true(lda.spin_cnt < 10000000)) {
7712604eb9eSMateusz Guzik 				lock_delay(&lda);
7722604eb9eSMateusz Guzik 			} else {
77315140a8aSMateusz Guzik 				_mtx_lock_indefinite_check(m, &lda);
77436412d79SJohn Baldwin 			}
7752604eb9eSMateusz Guzik 			v = MTX_READ_VALUE(m);
7762604eb9eSMateusz Guzik 		} while (v != MTX_UNOWNED);
777c6a37e84SJohn Baldwin 		spinlock_enter();
77836412d79SJohn Baldwin 	}
77936412d79SJohn Baldwin 
780aa89d8cdSJohn Baldwin 	if (LOCK_LOG_TEST(&m->lock_object, opts))
7819ed346baSBosko Milekic 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
7822cba8dd3SJohn Baldwin 	KTR_STATE0(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
7832cba8dd3SJohn Baldwin 	    "running");
7849ed346baSBosko Milekic 
785dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
786dfaa7859SMateusz Guzik 	if (__predict_true(!doing_lockprof))
787dfaa7859SMateusz Guzik 		return;
788dfaa7859SMateusz Guzik #endif
789c6d48c87SMark Johnston #ifdef KDTRACE_HOOKS
790dfaa7859SMateusz Guzik 	spin_time += lockstat_nsecs(&m->lock_object);
79109bdec20SMateusz Guzik 	if (lda.spin_cnt != 0)
79209bdec20SMateusz Guzik 		LOCKSTAT_RECORD1(spin__spin, m, spin_time);
79309bdec20SMateusz Guzik out_lockstat:
794dfaa7859SMateusz Guzik #endif
79532cd0147SMark Johnston 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire, m,
79632cd0147SMark Johnston 	    contested, waittime, file, line);
79736412d79SJohn Baldwin }
79833fb8a38SJohn Baldwin #endif /* SMP */
79936412d79SJohn Baldwin 
800be49509eSMateusz Guzik #ifdef INVARIANTS
801be49509eSMateusz Guzik static void
802be49509eSMateusz Guzik thread_lock_validate(struct mtx *m, int opts, const char *file, int line)
803be49509eSMateusz Guzik {
804be49509eSMateusz Guzik 
805be49509eSMateusz Guzik 	KASSERT(m->mtx_lock != MTX_DESTROYED,
806be49509eSMateusz Guzik 	    ("thread_lock() of destroyed mutex @ %s:%d", file, line));
807be49509eSMateusz Guzik 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
808be49509eSMateusz Guzik 	    ("thread_lock() of sleep mutex %s @ %s:%d",
809be49509eSMateusz Guzik 	    m->lock_object.lo_name, file, line));
8103fd19ce7SMateusz Guzik 	KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) == 0,
8113fd19ce7SMateusz Guzik 	    ("thread_lock: got a recursive mutex %s @ %s:%d\n",
812be49509eSMateusz Guzik 	    m->lock_object.lo_name, file, line));
813be49509eSMateusz Guzik 	WITNESS_CHECKORDER(&m->lock_object,
814be49509eSMateusz Guzik 	    opts | LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
815be49509eSMateusz Guzik }
816be49509eSMateusz Guzik #else
817be49509eSMateusz Guzik #define thread_lock_validate(m, opts, file, line) do { } while (0)
818be49509eSMateusz Guzik #endif
819be49509eSMateusz Guzik 
820be49509eSMateusz Guzik #ifndef LOCK_PROFILING
821be49509eSMateusz Guzik #if LOCK_DEBUG > 0
822be49509eSMateusz Guzik void
823be49509eSMateusz Guzik _thread_lock(struct thread *td, int opts, const char *file, int line)
824be49509eSMateusz Guzik #else
825be49509eSMateusz Guzik void
826be49509eSMateusz Guzik _thread_lock(struct thread *td)
827be49509eSMateusz Guzik #endif
828be49509eSMateusz Guzik {
829be49509eSMateusz Guzik 	struct mtx *m;
8303fd19ce7SMateusz Guzik 	uintptr_t tid;
831be49509eSMateusz Guzik 
832be49509eSMateusz Guzik 	tid = (uintptr_t)curthread;
833be49509eSMateusz Guzik 
8342c50bafeSMateusz Guzik 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(spin__acquire)))
8352c50bafeSMateusz Guzik 		goto slowpath_noirq;
836be49509eSMateusz Guzik 	spinlock_enter();
837be49509eSMateusz Guzik 	m = td->td_lock;
838be49509eSMateusz Guzik 	thread_lock_validate(m, 0, file, line);
8393fd19ce7SMateusz Guzik 	if (__predict_false(m == &blocked_lock))
840be49509eSMateusz Guzik 		goto slowpath_unlocked;
8413fd19ce7SMateusz Guzik 	if (__predict_false(!_mtx_obtain_lock(m, tid)))
842be49509eSMateusz Guzik 		goto slowpath_unlocked;
843be49509eSMateusz Guzik 	if (__predict_true(m == td->td_lock)) {
844be49509eSMateusz Guzik 		WITNESS_LOCK(&m->lock_object, LOP_EXCLUSIVE, file, line);
845be49509eSMateusz Guzik 		return;
846be49509eSMateusz Guzik 	}
847be49509eSMateusz Guzik 	_mtx_release_lock_quick(m);
848be49509eSMateusz Guzik slowpath_unlocked:
849be49509eSMateusz Guzik 	spinlock_exit();
8502c50bafeSMateusz Guzik slowpath_noirq:
8512c50bafeSMateusz Guzik #if LOCK_DEBUG > 0
8522c50bafeSMateusz Guzik 	thread_lock_flags_(td, opts, file, line);
8532c50bafeSMateusz Guzik #else
854be49509eSMateusz Guzik 	thread_lock_flags_(td, 0, 0, 0);
8552c50bafeSMateusz Guzik #endif
856be49509eSMateusz Guzik }
857be49509eSMateusz Guzik #endif
858be49509eSMateusz Guzik 
8592502c107SJeff Roberson void
860ccdf2333SAttilio Rao thread_lock_flags_(struct thread *td, int opts, const char *file, int line)
8612502c107SJeff Roberson {
8622502c107SJeff Roberson 	struct mtx *m;
8635e5ad162SMateusz Guzik 	uintptr_t tid, v;
864a0d45f0fSMateusz Guzik 	struct lock_delay_arg lda;
8651723a064SJeff Roberson #ifdef LOCK_PROFILING
8661723a064SJeff Roberson 	int contested = 0;
8671723a064SJeff Roberson 	uint64_t waittime = 0;
8681723a064SJeff Roberson #endif
869a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
870076dd8ebSAndriy Gapon 	int64_t spin_time = 0;
871a5aedd68SStacey Son #endif
872dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
873dfaa7859SMateusz Guzik 	int doing_lockprof = 1;
874dfaa7859SMateusz Guzik #endif
8752502c107SJeff Roberson 
8762502c107SJeff Roberson 	tid = (uintptr_t)curthread;
87735370593SAndriy Gapon 
878f61d6c5aSMark Johnston 	if (SCHEDULER_STOPPED()) {
879f61d6c5aSMark Johnston 		/*
880f61d6c5aSMark Johnston 		 * Ensure that spinlock sections are balanced even when the
881f61d6c5aSMark Johnston 		 * scheduler is stopped, since we may otherwise inadvertently
882f61d6c5aSMark Johnston 		 * re-enable interrupts while dumping core.
883f61d6c5aSMark Johnston 		 */
884f61d6c5aSMark Johnston 		spinlock_enter();
88535370593SAndriy Gapon 		return;
886f61d6c5aSMark Johnston 	}
88735370593SAndriy Gapon 
888a0d45f0fSMateusz Guzik 	lock_delay_arg_init(&lda, &mtx_spin_delay);
889a0d45f0fSMateusz Guzik 
8901f4d28c7SMateusz Guzik #ifdef HWPMC_HOOKS
8911f4d28c7SMateusz Guzik 	PMC_SOFT_CALL( , , lock, failed);
8921f4d28c7SMateusz Guzik #endif
8931f4d28c7SMateusz Guzik 
894dfaa7859SMateusz Guzik #ifdef LOCK_PROFILING
895dfaa7859SMateusz Guzik 	doing_lockprof = 1;
896df1c30f6SWarner Losh #elif defined(KDTRACE_HOOKS)
897dfaa7859SMateusz Guzik 	doing_lockprof = lockstat_enabled;
898dfaa7859SMateusz Guzik 	if (__predict_false(doing_lockprof))
899e2b25737SMark Johnston 		spin_time -= lockstat_nsecs(&td->td_lock->lock_object);
900076dd8ebSAndriy Gapon #endif
9019f4e008dSMateusz Guzik 	spinlock_enter();
9029f4e008dSMateusz Guzik 
9032502c107SJeff Roberson 	for (;;) {
9042502c107SJeff Roberson retry:
905710eacdcSJeff Roberson 		m = td->td_lock;
906be49509eSMateusz Guzik 		thread_lock_validate(m, opts, file, line);
9071f4d28c7SMateusz Guzik 		v = MTX_READ_VALUE(m);
908fc4f686dSMateusz Guzik 		for (;;) {
9091f4d28c7SMateusz Guzik 			if (v == MTX_UNOWNED) {
91090836c32SMateusz Guzik 				if (_mtx_obtain_lock_fetch(m, &v, tid))
911fc4f686dSMateusz Guzik 					break;
9125e5ad162SMateusz Guzik 				continue;
9131f4d28c7SMateusz Guzik 			}
9143fd19ce7SMateusz Guzik 			MPASS(v != tid);
915eea4f254SJeff Roberson 			lock_profile_obtain_lock_failed(&m->lock_object,
916eea4f254SJeff Roberson 			    &contested, &waittime);
9172502c107SJeff Roberson 			/* Give interrupts a chance while we spin. */
9182502c107SJeff Roberson 			spinlock_exit();
9195e5ad162SMateusz Guzik 			do {
92015140a8aSMateusz Guzik 				if (__predict_true(lda.spin_cnt < 10000000)) {
921a0d45f0fSMateusz Guzik 					lock_delay(&lda);
922a0d45f0fSMateusz Guzik 				} else {
92315140a8aSMateusz Guzik 					_mtx_lock_indefinite_check(m, &lda);
924a0d45f0fSMateusz Guzik 				}
9259f4e008dSMateusz Guzik 				if (m != td->td_lock) {
9269f4e008dSMateusz Guzik 					spinlock_enter();
9272502c107SJeff Roberson 					goto retry;
9289f4e008dSMateusz Guzik 				}
9295e5ad162SMateusz Guzik 				v = MTX_READ_VALUE(m);
9305e5ad162SMateusz Guzik 			} while (v != MTX_UNOWNED);
9312502c107SJeff Roberson 			spinlock_enter();
9322502c107SJeff Roberson 		}
9332502c107SJeff Roberson 		if (m == td->td_lock)
9342502c107SJeff Roberson 			break;
9359f4e008dSMateusz Guzik 		_mtx_release_lock_quick(m);
9362502c107SJeff Roberson 	}
937dfaa7859SMateusz Guzik 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
938dfaa7859SMateusz Guzik 	    line);
939dfaa7859SMateusz Guzik 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
940dfaa7859SMateusz Guzik 
941dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
942dfaa7859SMateusz Guzik 	if (__predict_true(!doing_lockprof))
943dfaa7859SMateusz Guzik 		return;
944dfaa7859SMateusz Guzik #endif
945076dd8ebSAndriy Gapon #ifdef KDTRACE_HOOKS
946e2b25737SMark Johnston 	spin_time += lockstat_nsecs(&m->lock_object);
947076dd8ebSAndriy Gapon #endif
9483fd19ce7SMateusz Guzik 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire, m, contested,
9493fd19ce7SMateusz Guzik 	    waittime, file, line);
9505002e195SMark Johnston #ifdef KDTRACE_HOOKS
951d0f68f91SMark Johnston 	if (lda.spin_cnt != 0)
95232cd0147SMark Johnston 		LOCKSTAT_RECORD1(thread__spin, m, spin_time);
9535002e195SMark Johnston #endif
9542502c107SJeff Roberson }
9552502c107SJeff Roberson 
9562502c107SJeff Roberson struct mtx *
9572502c107SJeff Roberson thread_lock_block(struct thread *td)
9582502c107SJeff Roberson {
9592502c107SJeff Roberson 	struct mtx *lock;
9602502c107SJeff Roberson 
961710eacdcSJeff Roberson 	lock = td->td_lock;
96261a74c5cSJeff Roberson 	mtx_assert(lock, MA_OWNED);
9632502c107SJeff Roberson 	td->td_lock = &blocked_lock;
9642502c107SJeff Roberson 
9652502c107SJeff Roberson 	return (lock);
9662502c107SJeff Roberson }
9672502c107SJeff Roberson 
9682502c107SJeff Roberson void
9692502c107SJeff Roberson thread_lock_unblock(struct thread *td, struct mtx *new)
9702502c107SJeff Roberson {
97161a74c5cSJeff Roberson 
9722502c107SJeff Roberson 	mtx_assert(new, MA_OWNED);
97361a74c5cSJeff Roberson 	KASSERT(td->td_lock == &blocked_lock,
97461a74c5cSJeff Roberson 	    ("thread %p lock %p not blocked_lock %p",
97561a74c5cSJeff Roberson 	    td, td->td_lock, &blocked_lock));
97665d32cd8SMatt Jacob 	atomic_store_rel_ptr((volatile void *)&td->td_lock, (uintptr_t)new);
9772502c107SJeff Roberson }
9782502c107SJeff Roberson 
9792502c107SJeff Roberson void
98061a74c5cSJeff Roberson thread_lock_block_wait(struct thread *td)
98161a74c5cSJeff Roberson {
98261a74c5cSJeff Roberson 
98361a74c5cSJeff Roberson 	while (td->td_lock == &blocked_lock)
98461a74c5cSJeff Roberson 		cpu_spinwait();
98561a74c5cSJeff Roberson 
98661a74c5cSJeff Roberson 	/* Acquire fence to be certain that all thread state is visible. */
98761a74c5cSJeff Roberson 	atomic_thread_fence_acq();
98861a74c5cSJeff Roberson }
98961a74c5cSJeff Roberson 
99061a74c5cSJeff Roberson void
9912502c107SJeff Roberson thread_lock_set(struct thread *td, struct mtx *new)
9922502c107SJeff Roberson {
9932502c107SJeff Roberson 	struct mtx *lock;
9942502c107SJeff Roberson 
9952502c107SJeff Roberson 	mtx_assert(new, MA_OWNED);
996710eacdcSJeff Roberson 	lock = td->td_lock;
99761a74c5cSJeff Roberson 	mtx_assert(lock, MA_OWNED);
9982502c107SJeff Roberson 	td->td_lock = new;
9992502c107SJeff Roberson 	mtx_unlock_spin(lock);
10002502c107SJeff Roberson }
10012502c107SJeff Roberson 
10029ed346baSBosko Milekic /*
10037f44c618SAttilio Rao  * __mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
10049ed346baSBosko Milekic  *
10053b3cf014SMateusz Guzik  * We are only called here if the lock is recursed, contested (i.e. we
10063b3cf014SMateusz Guzik  * need to wake up a blocked thread) or lockstat probe is active.
10079ed346baSBosko Milekic  */
100809f1319aSMateusz Guzik #if LOCK_DEBUG > 0
100936412d79SJohn Baldwin void
1010b584eb2eSMateusz Guzik __mtx_unlock_sleep(volatile uintptr_t *c, uintptr_t v, int opts,
1011b584eb2eSMateusz Guzik     const char *file, int line)
101209f1319aSMateusz Guzik #else
101309f1319aSMateusz Guzik void
1014b584eb2eSMateusz Guzik __mtx_unlock_sleep(volatile uintptr_t *c, uintptr_t v)
101509f1319aSMateusz Guzik #endif
101636412d79SJohn Baldwin {
10177f44c618SAttilio Rao 	struct mtx *m;
1018961a7b24SJohn Baldwin 	struct turnstile *ts;
1019b584eb2eSMateusz Guzik 	uintptr_t tid;
10209ed346baSBosko Milekic 
102135370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
102235370593SAndriy Gapon 		return;
102335370593SAndriy Gapon 
10243b3cf014SMateusz Guzik 	tid = (uintptr_t)curthread;
10257f44c618SAttilio Rao 	m = mtxlock2mtx(c);
1026b584eb2eSMateusz Guzik 
1027b584eb2eSMateusz Guzik 	if (__predict_false(v == tid))
10283b3cf014SMateusz Guzik 		v = MTX_READ_VALUE(m);
102990836c32SMateusz Guzik 
1030b584eb2eSMateusz Guzik 	if (__predict_false(v & MTX_RECURSED)) {
103136412d79SJohn Baldwin 		if (--(m->mtx_recurse) == 0)
103208812b39SBosko Milekic 			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
1033aa89d8cdSJohn Baldwin 		if (LOCK_LOG_TEST(&m->lock_object, opts))
10349ed346baSBosko Milekic 			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
103536412d79SJohn Baldwin 		return;
103636412d79SJohn Baldwin 	}
10379ed346baSBosko Milekic 
10383b3cf014SMateusz Guzik 	LOCKSTAT_PROFILE_RELEASE_LOCK(adaptive__release, m);
10393b3cf014SMateusz Guzik 	if (v == tid && _mtx_release_lock(m, tid))
10403b3cf014SMateusz Guzik 		return;
10413b3cf014SMateusz Guzik 
10422502c107SJeff Roberson 	/*
10432502c107SJeff Roberson 	 * We have to lock the chain before the turnstile so this turnstile
10442502c107SJeff Roberson 	 * can be removed from the hash list if it is empty.
10452502c107SJeff Roberson 	 */
10462502c107SJeff Roberson 	turnstile_chain_lock(&m->lock_object);
10478448e020SMateusz Guzik 	_mtx_release_lock_quick(m);
1048aa89d8cdSJohn Baldwin 	ts = turnstile_lookup(&m->lock_object);
10498448e020SMateusz Guzik 	MPASS(ts != NULL);
1050aa89d8cdSJohn Baldwin 	if (LOCK_LOG_TEST(&m->lock_object, opts))
10519ed346baSBosko Milekic 		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
10527aa4f685SJohn Baldwin 	turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
1053bf9c6c31SJohn Baldwin 
10542502c107SJeff Roberson 	/*
10552502c107SJeff Roberson 	 * This turnstile is now no longer associated with the mutex.  We can
10562502c107SJeff Roberson 	 * unlock the chain lock so a new turnstile may take it's place.
10572502c107SJeff Roberson 	 */
1058d0a22279SMateusz Guzik 	turnstile_unpend(ts);
10592502c107SJeff Roberson 	turnstile_chain_unlock(&m->lock_object);
10609ed346baSBosko Milekic }
10619ed346baSBosko Milekic 
10629ed346baSBosko Milekic /*
10639ed346baSBosko Milekic  * All the unlocking of MTX_SPIN locks is done inline.
1064961135eaSJohn Baldwin  * See the __mtx_unlock_spin() macro for the details.
10659ed346baSBosko Milekic  */
10669ed346baSBosko Milekic 
10679ed346baSBosko Milekic /*
106815ec816aSJohn Baldwin  * The backing function for the INVARIANTS-enabled mtx_assert()
10699ed346baSBosko Milekic  */
10701103f3b0SJohn Baldwin #ifdef INVARIANT_SUPPORT
10710cde2e34SJason Evans void
10727f44c618SAttilio Rao __mtx_assert(const volatile uintptr_t *c, int what, const char *file, int line)
10730cde2e34SJason Evans {
10747f44c618SAttilio Rao 	const struct mtx *m;
10755cb0fbe4SJohn Baldwin 
1076879e0604SMateusz Guzik 	if (KERNEL_PANICKED() || dumping || SCHEDULER_STOPPED())
10775cb0fbe4SJohn Baldwin 		return;
10787f44c618SAttilio Rao 
10797f44c618SAttilio Rao 	m = mtxlock2mtx(c);
10807f44c618SAttilio Rao 
1081a10f4966SJake Burkholder 	switch (what) {
10820cde2e34SJason Evans 	case MA_OWNED:
10830cde2e34SJason Evans 	case MA_OWNED | MA_RECURSED:
10840cde2e34SJason Evans 	case MA_OWNED | MA_NOTRECURSED:
1085a10f4966SJake Burkholder 		if (!mtx_owned(m))
10860cde2e34SJason Evans 			panic("mutex %s not owned at %s:%d",
1087aa89d8cdSJohn Baldwin 			    m->lock_object.lo_name, file, line);
1088a10f4966SJake Burkholder 		if (mtx_recursed(m)) {
1089a10f4966SJake Burkholder 			if ((what & MA_NOTRECURSED) != 0)
10900cde2e34SJason Evans 				panic("mutex %s recursed at %s:%d",
1091aa89d8cdSJohn Baldwin 				    m->lock_object.lo_name, file, line);
1092a10f4966SJake Burkholder 		} else if ((what & MA_RECURSED) != 0) {
10930cde2e34SJason Evans 			panic("mutex %s unrecursed at %s:%d",
1094aa89d8cdSJohn Baldwin 			    m->lock_object.lo_name, file, line);
10950cde2e34SJason Evans 		}
10960cde2e34SJason Evans 		break;
10970cde2e34SJason Evans 	case MA_NOTOWNED:
1098a10f4966SJake Burkholder 		if (mtx_owned(m))
10990cde2e34SJason Evans 			panic("mutex %s owned at %s:%d",
1100aa89d8cdSJohn Baldwin 			    m->lock_object.lo_name, file, line);
11010cde2e34SJason Evans 		break;
11020cde2e34SJason Evans 	default:
110356771ca7SJason Evans 		panic("unknown mtx_assert at %s:%d", file, line);
11040cde2e34SJason Evans 	}
11050cde2e34SJason Evans }
11060cde2e34SJason Evans #endif
11070cde2e34SJason Evans 
11089ed346baSBosko Milekic /*
1109c27b5699SAndrew R. Reiter  * General init routine used by the MTX_SYSINIT() macro.
1110c27b5699SAndrew R. Reiter  */
1111c27b5699SAndrew R. Reiter void
1112c27b5699SAndrew R. Reiter mtx_sysinit(void *arg)
1113c27b5699SAndrew R. Reiter {
1114c27b5699SAndrew R. Reiter 	struct mtx_args *margs = arg;
1115c27b5699SAndrew R. Reiter 
11167f44c618SAttilio Rao 	mtx_init((struct mtx *)margs->ma_mtx, margs->ma_desc, NULL,
11177f44c618SAttilio Rao 	    margs->ma_opts);
1118c27b5699SAndrew R. Reiter }
1119c27b5699SAndrew R. Reiter 
1120c27b5699SAndrew R. Reiter /*
11219ed346baSBosko Milekic  * Mutex initialization routine; initialize lock `m' of type contained in
11220c88508aSJohn Baldwin  * `opts' with options contained in `opts' and name `name.'  The optional
11230c88508aSJohn Baldwin  * lock type `type' is used as a general lock category name for use with
11240c88508aSJohn Baldwin  * witness.
11259ed346baSBosko Milekic  */
112636412d79SJohn Baldwin void
11277f44c618SAttilio Rao _mtx_init(volatile uintptr_t *c, const char *name, const char *type, int opts)
112836412d79SJohn Baldwin {
11297f44c618SAttilio Rao 	struct mtx *m;
113083a81bcbSJohn Baldwin 	struct lock_class *class;
113183a81bcbSJohn Baldwin 	int flags;
11329ed346baSBosko Milekic 
11337f44c618SAttilio Rao 	m = mtxlock2mtx(c);
11347f44c618SAttilio Rao 
113519284646SJohn Baldwin 	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
1136fd07ddcfSDmitry Chagin 	    MTX_NOWITNESS | MTX_DUPOK | MTX_NOPROFILE | MTX_NEW)) == 0);
1137353998acSAttilio Rao 	ASSERT_ATOMIC_LOAD_PTR(m->mtx_lock,
1138353998acSAttilio Rao 	    ("%s: mtx_lock not aligned for %s: %p", __func__, name,
1139353998acSAttilio Rao 	    &m->mtx_lock));
11409ed346baSBosko Milekic 
114183a81bcbSJohn Baldwin 	/* Determine lock class and lock flags. */
114219284646SJohn Baldwin 	if (opts & MTX_SPIN)
114383a81bcbSJohn Baldwin 		class = &lock_class_mtx_spin;
114419284646SJohn Baldwin 	else
114583a81bcbSJohn Baldwin 		class = &lock_class_mtx_sleep;
114683a81bcbSJohn Baldwin 	flags = 0;
114719284646SJohn Baldwin 	if (opts & MTX_QUIET)
114883a81bcbSJohn Baldwin 		flags |= LO_QUIET;
114919284646SJohn Baldwin 	if (opts & MTX_RECURSE)
115083a81bcbSJohn Baldwin 		flags |= LO_RECURSABLE;
115119284646SJohn Baldwin 	if ((opts & MTX_NOWITNESS) == 0)
115283a81bcbSJohn Baldwin 		flags |= LO_WITNESS;
1153f22a4b62SJeff Roberson 	if (opts & MTX_DUPOK)
115483a81bcbSJohn Baldwin 		flags |= LO_DUPOK;
11557c0435b9SKip Macy 	if (opts & MTX_NOPROFILE)
11567c0435b9SKip Macy 		flags |= LO_NOPROFILE;
1157fd07ddcfSDmitry Chagin 	if (opts & MTX_NEW)
1158fd07ddcfSDmitry Chagin 		flags |= LO_NEW;
115919284646SJohn Baldwin 
116083a81bcbSJohn Baldwin 	/* Initialize mutex. */
1161b5fb43e5SJohn Baldwin 	lock_init(&m->lock_object, class, name, type, flags);
1162b5fb43e5SJohn Baldwin 
116319284646SJohn Baldwin 	m->mtx_lock = MTX_UNOWNED;
116483a81bcbSJohn Baldwin 	m->mtx_recurse = 0;
116536412d79SJohn Baldwin }
116636412d79SJohn Baldwin 
11679ed346baSBosko Milekic /*
116819284646SJohn Baldwin  * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
116919284646SJohn Baldwin  * passed in as a flag here because if the corresponding mtx_init() was
117019284646SJohn Baldwin  * called with MTX_QUIET set, then it will already be set in the mutex's
117119284646SJohn Baldwin  * flags.
11729ed346baSBosko Milekic  */
117336412d79SJohn Baldwin void
11747f44c618SAttilio Rao _mtx_destroy(volatile uintptr_t *c)
117536412d79SJohn Baldwin {
11767f44c618SAttilio Rao 	struct mtx *m;
11777f44c618SAttilio Rao 
11787f44c618SAttilio Rao 	m = mtxlock2mtx(c);
117936412d79SJohn Baldwin 
118019284646SJohn Baldwin 	if (!mtx_owned(m))
118119284646SJohn Baldwin 		MPASS(mtx_unowned(m));
118219284646SJohn Baldwin 	else {
118308812b39SBosko Milekic 		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
11849ed346baSBosko Milekic 
1185861a2308SScott Long 		/* Perform the non-mtx related part of mtx_unlock_spin(). */
1186aa89d8cdSJohn Baldwin 		if (LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin)
1187861a2308SScott Long 			spinlock_exit();
1188764e4d54SJohn Baldwin 		else
1189ce1c953eSMark Johnston 			TD_LOCKS_DEC(curthread);
1190861a2308SScott Long 
1191d3df4af3SJeff Roberson 		lock_profile_release_lock(&m->lock_object);
119219284646SJohn Baldwin 		/* Tell witness this isn't locked to make it happy. */
1193aa89d8cdSJohn Baldwin 		WITNESS_UNLOCK(&m->lock_object, LOP_EXCLUSIVE, __FILE__,
1194c86b6ff5SJohn Baldwin 		    __LINE__);
119536412d79SJohn Baldwin 	}
11960384fff8SJason Evans 
1197186abbd7SJohn Baldwin 	m->mtx_lock = MTX_DESTROYED;
1198aa89d8cdSJohn Baldwin 	lock_destroy(&m->lock_object);
11990384fff8SJason Evans }
1200d23f5958SMatthew Dillon 
1201d23f5958SMatthew Dillon /*
1202c53c013bSJohn Baldwin  * Intialize the mutex code and system mutexes.  This is called from the MD
1203c53c013bSJohn Baldwin  * startup code prior to mi_startup().  The per-CPU data space needs to be
1204c53c013bSJohn Baldwin  * setup before this is called.
1205c53c013bSJohn Baldwin  */
1206c53c013bSJohn Baldwin void
1207c53c013bSJohn Baldwin mutex_init(void)
1208c53c013bSJohn Baldwin {
1209c53c013bSJohn Baldwin 
1210961a7b24SJohn Baldwin 	/* Setup turnstiles so that sleep mutexes work. */
1211961a7b24SJohn Baldwin 	init_turnstiles();
1212961a7b24SJohn Baldwin 
1213c53c013bSJohn Baldwin 	/*
1214c53c013bSJohn Baldwin 	 * Initialize mutexes.
1215c53c013bSJohn Baldwin 	 */
12160c88508aSJohn Baldwin 	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
12172502c107SJeff Roberson 	mtx_init(&blocked_lock, "blocked lock", NULL, MTX_SPIN);
12182502c107SJeff Roberson 	blocked_lock.mtx_lock = 0xdeadc0de;	/* Always blocked. */
12190c88508aSJohn Baldwin 	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
12206afb32fcSKonstantin Belousov 	mtx_init(&proc0.p_slock, "process slock", NULL, MTX_SPIN);
12215c7bebf9SKonstantin Belousov 	mtx_init(&proc0.p_statmtx, "pstatl", NULL, MTX_SPIN);
12225c7bebf9SKonstantin Belousov 	mtx_init(&proc0.p_itimmtx, "pitiml", NULL, MTX_SPIN);
12235c7bebf9SKonstantin Belousov 	mtx_init(&proc0.p_profmtx, "pprofl", NULL, MTX_SPIN);
12248c4b6380SJohn Baldwin 	mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
1225c53c013bSJohn Baldwin 	mtx_lock(&Giant);
1226c53c013bSJohn Baldwin }
1227d272fe53SJohn Baldwin 
122815140a8aSMateusz Guzik static void __noinline
122915140a8aSMateusz Guzik _mtx_lock_indefinite_check(struct mtx *m, struct lock_delay_arg *ldap)
123015140a8aSMateusz Guzik {
123115140a8aSMateusz Guzik 	struct thread *td;
123215140a8aSMateusz Guzik 
123315140a8aSMateusz Guzik 	ldap->spin_cnt++;
1234879e0604SMateusz Guzik 	if (ldap->spin_cnt < 60000000 || kdb_active || KERNEL_PANICKED())
12354cbbb748SJohn Baldwin 		cpu_lock_delay();
123615140a8aSMateusz Guzik 	else {
123715140a8aSMateusz Guzik 		td = mtx_owner(m);
123815140a8aSMateusz Guzik 
123915140a8aSMateusz Guzik 		/* If the mutex is unlocked, try again. */
124015140a8aSMateusz Guzik 		if (td == NULL)
124115140a8aSMateusz Guzik 			return;
124215140a8aSMateusz Guzik 
124315140a8aSMateusz Guzik 		printf( "spin lock %p (%s) held by %p (tid %d) too long\n",
124415140a8aSMateusz Guzik 		    m, m->lock_object.lo_name, td, td->td_tid);
124515140a8aSMateusz Guzik #ifdef WITNESS
124615140a8aSMateusz Guzik 		witness_display_spinlock(&m->lock_object, td, printf);
124715140a8aSMateusz Guzik #endif
124815140a8aSMateusz Guzik 		panic("spin lock held too long");
124915140a8aSMateusz Guzik 	}
125015140a8aSMateusz Guzik 	cpu_spinwait();
125115140a8aSMateusz Guzik }
125215140a8aSMateusz Guzik 
1253d2576988SMateusz Guzik void
1254d2576988SMateusz Guzik mtx_spin_wait_unlocked(struct mtx *m)
1255d2576988SMateusz Guzik {
1256d2576988SMateusz Guzik 	struct lock_delay_arg lda;
1257d2576988SMateusz Guzik 
1258500ca73dSMateusz Guzik 	KASSERT(m->mtx_lock != MTX_DESTROYED,
1259500ca73dSMateusz Guzik 	    ("%s() of destroyed mutex %p", __func__, m));
1260500ca73dSMateusz Guzik 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
1261500ca73dSMateusz Guzik 	    ("%s() of sleep mutex %p (%s)", __func__, m,
1262500ca73dSMateusz Guzik 	    m->lock_object.lo_name));
1263500ca73dSMateusz Guzik 	KASSERT(!mtx_owned(m), ("%s() waiting on myself on lock %p (%s)", __func__, m,
1264500ca73dSMateusz Guzik 	    m->lock_object.lo_name));
1265500ca73dSMateusz Guzik 
1266d2576988SMateusz Guzik 	lda.spin_cnt = 0;
1267d2576988SMateusz Guzik 
1268d2576988SMateusz Guzik 	while (atomic_load_acq_ptr(&m->mtx_lock) != MTX_UNOWNED) {
1269d2576988SMateusz Guzik 		if (__predict_true(lda.spin_cnt < 10000000)) {
1270d2576988SMateusz Guzik 			cpu_spinwait();
1271d2576988SMateusz Guzik 			lda.spin_cnt++;
1272d2576988SMateusz Guzik 		} else {
1273d2576988SMateusz Guzik 			_mtx_lock_indefinite_check(m, &lda);
1274d2576988SMateusz Guzik 		}
1275d2576988SMateusz Guzik 	}
1276d2576988SMateusz Guzik }
1277d2576988SMateusz Guzik 
1278*bd66a075SMateusz Guzik void
1279*bd66a075SMateusz Guzik mtx_wait_unlocked(struct mtx *m)
1280*bd66a075SMateusz Guzik {
1281*bd66a075SMateusz Guzik 	struct thread *owner;
1282*bd66a075SMateusz Guzik 	uintptr_t v;
1283*bd66a075SMateusz Guzik 
1284*bd66a075SMateusz Guzik 	KASSERT(m->mtx_lock != MTX_DESTROYED,
1285*bd66a075SMateusz Guzik 	    ("%s() of destroyed mutex %p", __func__, m));
1286*bd66a075SMateusz Guzik 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
1287*bd66a075SMateusz Guzik 	    ("%s() not a sleep mutex %p (%s)", __func__, m,
1288*bd66a075SMateusz Guzik 	    m->lock_object.lo_name));
1289*bd66a075SMateusz Guzik 	KASSERT(!mtx_owned(m), ("%s() waiting on myself on lock %p (%s)", __func__, m,
1290*bd66a075SMateusz Guzik 	    m->lock_object.lo_name));
1291*bd66a075SMateusz Guzik 
1292*bd66a075SMateusz Guzik 	for (;;) {
1293*bd66a075SMateusz Guzik 		v = atomic_load_acq_ptr(&m->mtx_lock);
1294*bd66a075SMateusz Guzik 		if (v == MTX_UNOWNED) {
1295*bd66a075SMateusz Guzik 			break;
1296*bd66a075SMateusz Guzik 		}
1297*bd66a075SMateusz Guzik 		owner = lv_mtx_owner(v);
1298*bd66a075SMateusz Guzik 		if (!TD_IS_RUNNING(owner)) {
1299*bd66a075SMateusz Guzik 			mtx_lock(m);
1300*bd66a075SMateusz Guzik 			mtx_unlock(m);
1301*bd66a075SMateusz Guzik 			break;
1302*bd66a075SMateusz Guzik 		}
1303*bd66a075SMateusz Guzik 		cpu_spinwait();
1304*bd66a075SMateusz Guzik 	}
1305*bd66a075SMateusz Guzik }
1306*bd66a075SMateusz Guzik 
1307d272fe53SJohn Baldwin #ifdef DDB
1308d272fe53SJohn Baldwin void
1309d576deedSPawel Jakub Dawidek db_show_mtx(const struct lock_object *lock)
1310d272fe53SJohn Baldwin {
1311d272fe53SJohn Baldwin 	struct thread *td;
1312d576deedSPawel Jakub Dawidek 	const struct mtx *m;
1313d272fe53SJohn Baldwin 
1314d576deedSPawel Jakub Dawidek 	m = (const struct mtx *)lock;
1315d272fe53SJohn Baldwin 
1316d272fe53SJohn Baldwin 	db_printf(" flags: {");
131783a81bcbSJohn Baldwin 	if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
1318d272fe53SJohn Baldwin 		db_printf("SPIN");
1319d272fe53SJohn Baldwin 	else
1320d272fe53SJohn Baldwin 		db_printf("DEF");
1321aa89d8cdSJohn Baldwin 	if (m->lock_object.lo_flags & LO_RECURSABLE)
1322d272fe53SJohn Baldwin 		db_printf(", RECURSE");
1323aa89d8cdSJohn Baldwin 	if (m->lock_object.lo_flags & LO_DUPOK)
1324d272fe53SJohn Baldwin 		db_printf(", DUPOK");
1325d272fe53SJohn Baldwin 	db_printf("}\n");
1326d272fe53SJohn Baldwin 	db_printf(" state: {");
1327d272fe53SJohn Baldwin 	if (mtx_unowned(m))
1328d272fe53SJohn Baldwin 		db_printf("UNOWNED");
1329c0bfd703SJohn Baldwin 	else if (mtx_destroyed(m))
1330c0bfd703SJohn Baldwin 		db_printf("DESTROYED");
1331d272fe53SJohn Baldwin 	else {
1332d272fe53SJohn Baldwin 		db_printf("OWNED");
1333d272fe53SJohn Baldwin 		if (m->mtx_lock & MTX_CONTESTED)
1334d272fe53SJohn Baldwin 			db_printf(", CONTESTED");
1335d272fe53SJohn Baldwin 		if (m->mtx_lock & MTX_RECURSED)
1336d272fe53SJohn Baldwin 			db_printf(", RECURSED");
1337d272fe53SJohn Baldwin 	}
1338d272fe53SJohn Baldwin 	db_printf("}\n");
1339c0bfd703SJohn Baldwin 	if (!mtx_unowned(m) && !mtx_destroyed(m)) {
1340d272fe53SJohn Baldwin 		td = mtx_owner(m);
1341d272fe53SJohn Baldwin 		db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
1342431f8906SJulian Elischer 		    td->td_tid, td->td_proc->p_pid, td->td_name);
1343d272fe53SJohn Baldwin 		if (mtx_recursed(m))
1344d272fe53SJohn Baldwin 			db_printf(" recursed: %d\n", m->mtx_recurse);
1345d272fe53SJohn Baldwin 	}
1346d272fe53SJohn Baldwin }
1347d272fe53SJohn Baldwin #endif
1348