xref: /freebsd/sys/kern/kern_mutex.c (revision 879e0604ee6ac0ded87f6754141e7af25f4b7d5a)
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
1441ada9041SMateusz Guzik static SYSCTL_NODE(_debug, OID_AUTO, mtx, CTLFLAG_RD, NULL, "mtx debugging");
1451ada9041SMateusz Guzik 
146574adb65SMateusz Guzik static struct lock_delay_config __read_frequently mtx_delay;
1471ada9041SMateusz Guzik 
1486b8dd26eSMateusz Guzik SYSCTL_U16(_debug_mtx, OID_AUTO, delay_base, CTLFLAG_RW, &mtx_delay.base,
1491ada9041SMateusz Guzik     0, "");
1506b8dd26eSMateusz Guzik SYSCTL_U16(_debug_mtx, OID_AUTO, delay_max, CTLFLAG_RW, &mtx_delay.max,
1511ada9041SMateusz Guzik     0, "");
1521ada9041SMateusz Guzik 
1538e5a3e9aSMateusz Guzik LOCK_DELAY_SYSINIT_DEFAULT(mtx_delay);
1542e77cad1SMateusz Guzik #else
1552e77cad1SMateusz Guzik #define mtx_delay	locks_delay
1562e77cad1SMateusz Guzik #endif
1571ada9041SMateusz Guzik #endif
1581ada9041SMateusz Guzik 
1592e77cad1SMateusz Guzik #ifdef MUTEX_SPIN_CUSTOM_BACKOFF
160a0d45f0fSMateusz Guzik static SYSCTL_NODE(_debug, OID_AUTO, mtx_spin, CTLFLAG_RD, NULL,
161a0d45f0fSMateusz Guzik     "mtx spin debugging");
162a0d45f0fSMateusz Guzik 
163574adb65SMateusz Guzik static struct lock_delay_config __read_frequently mtx_spin_delay;
164a0d45f0fSMateusz Guzik 
1658e5a3e9aSMateusz Guzik SYSCTL_INT(_debug_mtx_spin, OID_AUTO, delay_base, CTLFLAG_RW,
1668e5a3e9aSMateusz Guzik     &mtx_spin_delay.base, 0, "");
1678e5a3e9aSMateusz Guzik SYSCTL_INT(_debug_mtx_spin, OID_AUTO, delay_max, CTLFLAG_RW,
1688e5a3e9aSMateusz Guzik     &mtx_spin_delay.max, 0, "");
169a0d45f0fSMateusz Guzik 
1708e5a3e9aSMateusz Guzik LOCK_DELAY_SYSINIT_DEFAULT(mtx_spin_delay);
1712e77cad1SMateusz Guzik #else
1722e77cad1SMateusz Guzik #define mtx_spin_delay	locks_delay
1732e77cad1SMateusz Guzik #endif
174a0d45f0fSMateusz Guzik 
1759ed346baSBosko Milekic /*
176c53c013bSJohn Baldwin  * System-wide mutexes
177c53c013bSJohn Baldwin  */
1782502c107SJeff Roberson struct mtx blocked_lock;
1796a569d35SMateusz Guzik struct mtx __exclusive_cache_line Giant;
180c53c013bSJohn Baldwin 
18115140a8aSMateusz Guzik static void _mtx_lock_indefinite_check(struct mtx *, struct lock_delay_arg *);
18215140a8aSMateusz Guzik 
18367784314SPoul-Henning Kamp void
184d576deedSPawel Jakub Dawidek assert_mtx(const struct lock_object *lock, int what)
185f9721b43SAttilio Rao {
186f9721b43SAttilio Rao 
187a11bf9a4SXin LI 	/*
188a11bf9a4SXin LI 	 * Treat LA_LOCKED as if LA_XLOCKED was asserted.
189a11bf9a4SXin LI 	 *
190a11bf9a4SXin LI 	 * Some callers of lc_assert uses LA_LOCKED to indicate that either
191a11bf9a4SXin LI 	 * a shared lock or write lock was held, while other callers uses
192a11bf9a4SXin LI 	 * the more strict LA_XLOCKED (used as MA_OWNED).
193a11bf9a4SXin LI 	 *
194a11bf9a4SXin LI 	 * Mutex is the only lock class that can not be shared, as a result,
195a11bf9a4SXin LI 	 * we can reasonably consider the caller really intends to assert
196a11bf9a4SXin LI 	 * LA_XLOCKED when they are asserting LA_LOCKED on a mutex object.
197a11bf9a4SXin LI 	 */
198a11bf9a4SXin LI 	if (what & LA_LOCKED) {
199a11bf9a4SXin LI 		what &= ~LA_LOCKED;
200a11bf9a4SXin LI 		what |= LA_XLOCKED;
201a11bf9a4SXin LI 	}
202d576deedSPawel Jakub Dawidek 	mtx_assert((const struct mtx *)lock, what);
203f9721b43SAttilio Rao }
204f9721b43SAttilio Rao 
20567784314SPoul-Henning Kamp void
2067faf4d90SDavide Italiano lock_mtx(struct lock_object *lock, uintptr_t how)
2076e21afd4SJohn Baldwin {
2086e21afd4SJohn Baldwin 
2096e21afd4SJohn Baldwin 	mtx_lock((struct mtx *)lock);
2106e21afd4SJohn Baldwin }
2116e21afd4SJohn Baldwin 
21267784314SPoul-Henning Kamp void
2137faf4d90SDavide Italiano lock_spin(struct lock_object *lock, uintptr_t how)
2146e21afd4SJohn Baldwin {
2156e21afd4SJohn Baldwin 
2166e21afd4SJohn Baldwin 	panic("spin locks can only use msleep_spin");
2176e21afd4SJohn Baldwin }
2186e21afd4SJohn Baldwin 
2197faf4d90SDavide Italiano uintptr_t
2206e21afd4SJohn Baldwin unlock_mtx(struct lock_object *lock)
2216e21afd4SJohn Baldwin {
2226e21afd4SJohn Baldwin 	struct mtx *m;
2236e21afd4SJohn Baldwin 
2246e21afd4SJohn Baldwin 	m = (struct mtx *)lock;
2256e21afd4SJohn Baldwin 	mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
2266e21afd4SJohn Baldwin 	mtx_unlock(m);
2276e21afd4SJohn Baldwin 	return (0);
2286e21afd4SJohn Baldwin }
2296e21afd4SJohn Baldwin 
2307faf4d90SDavide Italiano uintptr_t
2316e21afd4SJohn Baldwin unlock_spin(struct lock_object *lock)
2326e21afd4SJohn Baldwin {
2336e21afd4SJohn Baldwin 
2346e21afd4SJohn Baldwin 	panic("spin locks can only use msleep_spin");
2356e21afd4SJohn Baldwin }
2366e21afd4SJohn Baldwin 
237a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
238a5aedd68SStacey Son int
239d576deedSPawel Jakub Dawidek owner_mtx(const struct lock_object *lock, struct thread **owner)
240a5aedd68SStacey Son {
24102315a67SMark Johnston 	const struct mtx *m;
24202315a67SMark Johnston 	uintptr_t x;
243a5aedd68SStacey Son 
24402315a67SMark Johnston 	m = (const struct mtx *)lock;
24502315a67SMark Johnston 	x = m->mtx_lock;
24602315a67SMark Johnston 	*owner = (struct thread *)(x & ~MTX_FLAGMASK);
247e280ce46SMateusz Guzik 	return (*owner != NULL);
248a5aedd68SStacey Son }
249a5aedd68SStacey Son #endif
250a5aedd68SStacey Son 
2510cde2e34SJason Evans /*
2526283b7d0SJohn Baldwin  * Function versions of the inlined __mtx_* macros.  These are used by
2536283b7d0SJohn Baldwin  * modules and can also be called from assembly language if needed.
2546283b7d0SJohn Baldwin  */
2556283b7d0SJohn Baldwin void
2567f44c618SAttilio Rao __mtx_lock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
2576283b7d0SJohn Baldwin {
2587f44c618SAttilio Rao 	struct mtx *m;
25908da2677SMateusz Guzik 	uintptr_t tid, v;
2606283b7d0SJohn Baldwin 
2617f44c618SAttilio Rao 	m = mtxlock2mtx(c);
2627f44c618SAttilio Rao 
263704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
264704cb42fSMark Johnston 	    !TD_IS_IDLETHREAD(curthread),
265e3ae0dfeSAttilio Rao 	    ("mtx_lock() by idle thread %p on sleep mutex %s @ %s:%d",
266e3ae0dfeSAttilio Rao 	    curthread, m->lock_object.lo_name, file, line));
267186abbd7SJohn Baldwin 	KASSERT(m->mtx_lock != MTX_DESTROYED,
268186abbd7SJohn Baldwin 	    ("mtx_lock() of destroyed mutex @ %s:%d", file, line));
269aa89d8cdSJohn Baldwin 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
270aa89d8cdSJohn Baldwin 	    ("mtx_lock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
2710d975d63SJohn Baldwin 	    file, line));
272ac6b769bSAttilio Rao 	WITNESS_CHECKORDER(&m->lock_object, (opts & ~MTX_RECURSE) |
273ac6b769bSAttilio Rao 	    LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
2747c0435b9SKip Macy 
27508da2677SMateusz Guzik 	tid = (uintptr_t)curthread;
27608da2677SMateusz Guzik 	v = MTX_UNOWNED;
27708da2677SMateusz Guzik 	if (!_mtx_obtain_lock_fetch(m, &v, tid))
2782f1ddb89SMateusz Guzik 		_mtx_lock_sleep(m, v, opts, file, line);
27908da2677SMateusz Guzik 	else
28008da2677SMateusz Guzik 		LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
28108da2677SMateusz Guzik 		    m, 0, 0, file, line);
282aa89d8cdSJohn Baldwin 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
283dde96c99SJohn Baldwin 	    line);
284ac6b769bSAttilio Rao 	WITNESS_LOCK(&m->lock_object, (opts & ~MTX_RECURSE) | LOP_EXCLUSIVE,
285ac6b769bSAttilio Rao 	    file, line);
286ce1c953eSMark Johnston 	TD_LOCKS_INC(curthread);
2876283b7d0SJohn Baldwin }
2886283b7d0SJohn Baldwin 
2896283b7d0SJohn Baldwin void
2907f44c618SAttilio Rao __mtx_unlock_flags(volatile uintptr_t *c, int opts, const char *file, int line)
2916283b7d0SJohn Baldwin {
2927f44c618SAttilio Rao 	struct mtx *m;
29335370593SAndriy Gapon 
2947f44c618SAttilio Rao 	m = mtxlock2mtx(c);
2957f44c618SAttilio Rao 
296186abbd7SJohn Baldwin 	KASSERT(m->mtx_lock != MTX_DESTROYED,
297186abbd7SJohn Baldwin 	    ("mtx_unlock() of destroyed mutex @ %s:%d", file, line));
298aa89d8cdSJohn Baldwin 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
299aa89d8cdSJohn Baldwin 	    ("mtx_unlock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
3000d975d63SJohn Baldwin 	    file, line));
301aa89d8cdSJohn Baldwin 	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
302aa89d8cdSJohn Baldwin 	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
3030d975d63SJohn Baldwin 	    line);
30421377ce0SJohn Baldwin 	mtx_assert(m, MA_OWNED);
305c66d7606SKip Macy 
306ffd5c94cSMateusz Guzik #ifdef LOCK_PROFILING
307b584eb2eSMateusz Guzik 	__mtx_unlock_sleep(c, (uintptr_t)curthread, opts, file, line);
308ffd5c94cSMateusz Guzik #else
309ffd5c94cSMateusz Guzik 	__mtx_unlock(m, curthread, opts, file, line);
310ffd5c94cSMateusz Guzik #endif
311ce1c953eSMark Johnston 	TD_LOCKS_DEC(curthread);
3126283b7d0SJohn Baldwin }
3136283b7d0SJohn Baldwin 
3146283b7d0SJohn Baldwin void
3157f44c618SAttilio Rao __mtx_lock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
3167f44c618SAttilio Rao     int line)
3176283b7d0SJohn Baldwin {
3187f44c618SAttilio Rao 	struct mtx *m;
31962bf13cbSMateusz Guzik #ifdef SMP
3200d74fe26SMateusz Guzik 	uintptr_t tid, v;
32162bf13cbSMateusz Guzik #endif
3226283b7d0SJohn Baldwin 
3237f44c618SAttilio Rao 	m = mtxlock2mtx(c);
3247f44c618SAttilio Rao 
325186abbd7SJohn Baldwin 	KASSERT(m->mtx_lock != MTX_DESTROYED,
326186abbd7SJohn Baldwin 	    ("mtx_lock_spin() of destroyed mutex @ %s:%d", file, line));
327aa89d8cdSJohn Baldwin 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
3280d975d63SJohn Baldwin 	    ("mtx_lock_spin() of sleep mutex %s @ %s:%d",
329aa89d8cdSJohn Baldwin 	    m->lock_object.lo_name, file, line));
330ad69e26bSJohn Baldwin 	if (mtx_owned(m))
331ac6b769bSAttilio Rao 		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
332ac6b769bSAttilio Rao 		    (opts & MTX_RECURSE) != 0,
333ad69e26bSJohn Baldwin 	    ("mtx_lock_spin: recursed on non-recursive mutex %s @ %s:%d\n",
334ad69e26bSJohn Baldwin 		    m->lock_object.lo_name, file, line));
335ac6b769bSAttilio Rao 	opts &= ~MTX_RECURSE;
336aa89d8cdSJohn Baldwin 	WITNESS_CHECKORDER(&m->lock_object, opts | LOP_NEWORDER | LOP_EXCLUSIVE,
33741313430SJohn Baldwin 	    file, line, NULL);
33862bf13cbSMateusz Guzik #ifdef SMP
3390d74fe26SMateusz Guzik 	spinlock_enter();
3400d74fe26SMateusz Guzik 	tid = (uintptr_t)curthread;
3410d74fe26SMateusz Guzik 	v = MTX_UNOWNED;
3420d74fe26SMateusz Guzik 	if (!_mtx_obtain_lock_fetch(m, &v, tid))
3430d74fe26SMateusz Guzik 		_mtx_lock_spin(m, v, opts, file, line);
3440d74fe26SMateusz Guzik 	else
3450d74fe26SMateusz Guzik 		LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire,
3460d74fe26SMateusz Guzik 		    m, 0, 0, file, line);
34762bf13cbSMateusz Guzik #else
34862bf13cbSMateusz Guzik 	__mtx_lock_spin(m, curthread, opts, file, line);
34962bf13cbSMateusz Guzik #endif
350aa89d8cdSJohn Baldwin 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
351dde96c99SJohn Baldwin 	    line);
352aa89d8cdSJohn Baldwin 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
3536283b7d0SJohn Baldwin }
3546283b7d0SJohn Baldwin 
35590b581f2SKonstantin Belousov int
35690b581f2SKonstantin Belousov __mtx_trylock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
35790b581f2SKonstantin Belousov     int line)
35890b581f2SKonstantin Belousov {
35990b581f2SKonstantin Belousov 	struct mtx *m;
36090b581f2SKonstantin Belousov 
36190b581f2SKonstantin Belousov 	if (SCHEDULER_STOPPED())
36290b581f2SKonstantin Belousov 		return (1);
36390b581f2SKonstantin Belousov 
36490b581f2SKonstantin Belousov 	m = mtxlock2mtx(c);
36590b581f2SKonstantin Belousov 
36690b581f2SKonstantin Belousov 	KASSERT(m->mtx_lock != MTX_DESTROYED,
36790b581f2SKonstantin Belousov 	    ("mtx_trylock_spin() of destroyed mutex @ %s:%d", file, line));
36890b581f2SKonstantin Belousov 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
36990b581f2SKonstantin Belousov 	    ("mtx_trylock_spin() of sleep mutex %s @ %s:%d",
37090b581f2SKonstantin Belousov 	    m->lock_object.lo_name, file, line));
37190b581f2SKonstantin Belousov 	KASSERT((opts & MTX_RECURSE) == 0,
37290b581f2SKonstantin Belousov 	    ("mtx_trylock_spin: unsupp. opt MTX_RECURSE on mutex %s @ %s:%d\n",
37390b581f2SKonstantin Belousov 	    m->lock_object.lo_name, file, line));
37490b581f2SKonstantin Belousov 	if (__mtx_trylock_spin(m, curthread, opts, file, line)) {
37590b581f2SKonstantin Belousov 		LOCK_LOG_TRY("LOCK", &m->lock_object, opts, 1, file, line);
37690b581f2SKonstantin Belousov 		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
37790b581f2SKonstantin Belousov 		return (1);
37890b581f2SKonstantin Belousov 	}
37990b581f2SKonstantin Belousov 	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, 0, file, line);
38090b581f2SKonstantin Belousov 	return (0);
38190b581f2SKonstantin Belousov }
38290b581f2SKonstantin Belousov 
3836283b7d0SJohn Baldwin void
3847f44c618SAttilio Rao __mtx_unlock_spin_flags(volatile uintptr_t *c, int opts, const char *file,
3857f44c618SAttilio Rao     int line)
3866283b7d0SJohn Baldwin {
3877f44c618SAttilio Rao 	struct mtx *m;
388c66d7606SKip Macy 
3897f44c618SAttilio Rao 	m = mtxlock2mtx(c);
3907f44c618SAttilio Rao 
391186abbd7SJohn Baldwin 	KASSERT(m->mtx_lock != MTX_DESTROYED,
392186abbd7SJohn Baldwin 	    ("mtx_unlock_spin() of destroyed mutex @ %s:%d", file, line));
393aa89d8cdSJohn Baldwin 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
3940d975d63SJohn Baldwin 	    ("mtx_unlock_spin() of sleep mutex %s @ %s:%d",
395aa89d8cdSJohn Baldwin 	    m->lock_object.lo_name, file, line));
396aa89d8cdSJohn Baldwin 	WITNESS_UNLOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
397aa89d8cdSJohn Baldwin 	LOCK_LOG_LOCK("UNLOCK", &m->lock_object, opts, m->mtx_recurse, file,
398dde96c99SJohn Baldwin 	    line);
3990d975d63SJohn Baldwin 	mtx_assert(m, MA_OWNED);
400c66d7606SKip Macy 
401961135eaSJohn Baldwin 	__mtx_unlock_spin(m);
4026283b7d0SJohn Baldwin }
4036283b7d0SJohn Baldwin 
4046283b7d0SJohn Baldwin /*
4059ed346baSBosko Milekic  * The important part of mtx_trylock{,_flags}()
406eac09796SJohn Baldwin  * Tries to acquire lock `m.'  If this function is called on a mutex that
407eac09796SJohn Baldwin  * is already owned, it will recursively acquire the lock.
4080cde2e34SJason Evans  */
4090cde2e34SJason Evans int
410013c0b49SMateusz Guzik _mtx_trylock_flags_int(struct mtx *m, int opts LOCK_FILE_LINE_ARG_DEF)
4110cde2e34SJason Evans {
4125c5df0d9SMateusz Guzik 	struct thread *td;
4135c5df0d9SMateusz Guzik 	uintptr_t tid, v;
4141723a064SJeff Roberson #ifdef LOCK_PROFILING
4157c0435b9SKip Macy 	uint64_t waittime = 0;
4161723a064SJeff Roberson 	int contested = 0;
4171723a064SJeff Roberson #endif
4181723a064SJeff Roberson 	int rval;
4195c5df0d9SMateusz Guzik 	bool recursed;
4200cde2e34SJason Evans 
4215c5df0d9SMateusz Guzik 	td = curthread;
4225c5df0d9SMateusz Guzik 	tid = (uintptr_t)td;
4235c5df0d9SMateusz Guzik 	if (SCHEDULER_STOPPED_TD(td))
42435370593SAndriy Gapon 		return (1);
42535370593SAndriy Gapon 
426704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
427e3ae0dfeSAttilio Rao 	    ("mtx_trylock() by idle thread %p on sleep mutex %s @ %s:%d",
428e3ae0dfeSAttilio Rao 	    curthread, m->lock_object.lo_name, file, line));
429186abbd7SJohn Baldwin 	KASSERT(m->mtx_lock != MTX_DESTROYED,
430186abbd7SJohn Baldwin 	    ("mtx_trylock() of destroyed mutex @ %s:%d", file, line));
431aa89d8cdSJohn Baldwin 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_sleep,
432aa89d8cdSJohn Baldwin 	    ("mtx_trylock() of spin mutex %s @ %s:%d", m->lock_object.lo_name,
43383cece6fSJohn Baldwin 	    file, line));
4349ed346baSBosko Milekic 
4355c5df0d9SMateusz Guzik 	rval = 1;
4365c5df0d9SMateusz Guzik 	recursed = false;
4375c5df0d9SMateusz Guzik 	v = MTX_UNOWNED;
438b247fd39SMateusz Guzik 	for (;;) {
439b247fd39SMateusz Guzik 		if (_mtx_obtain_lock_fetch(m, &v, tid))
440b247fd39SMateusz Guzik 			break;
441b247fd39SMateusz Guzik 		if (v == MTX_UNOWNED)
442b247fd39SMateusz Guzik 			continue;
4435c5df0d9SMateusz Guzik 		if (v == tid &&
4445c5df0d9SMateusz Guzik 		    ((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
445ac6b769bSAttilio Rao 		    (opts & MTX_RECURSE) != 0)) {
446eac09796SJohn Baldwin 			m->mtx_recurse++;
447eac09796SJohn Baldwin 			atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
4485c5df0d9SMateusz Guzik 			recursed = true;
449b247fd39SMateusz Guzik 			break;
4505c5df0d9SMateusz Guzik 		}
451b247fd39SMateusz Guzik 		rval = 0;
452b247fd39SMateusz Guzik 		break;
4535c5df0d9SMateusz Guzik 	}
4545c5df0d9SMateusz Guzik 
455ac6b769bSAttilio Rao 	opts &= ~MTX_RECURSE;
4569ed346baSBosko Milekic 
457aa89d8cdSJohn Baldwin 	LOCK_LOG_TRY("LOCK", &m->lock_object, opts, rval, file, line);
458764e4d54SJohn Baldwin 	if (rval) {
459aa89d8cdSJohn Baldwin 		WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE | LOP_TRYLOCK,
4602d96f0b1SJohn Baldwin 		    file, line);
461ce1c953eSMark Johnston 		TD_LOCKS_INC(curthread);
4625c5df0d9SMateusz Guzik 		if (!recursed)
46332cd0147SMark Johnston 			LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire,
464a5aedd68SStacey Son 			    m, contested, waittime, file, line);
465764e4d54SJohn Baldwin 	}
4669ed346baSBosko Milekic 
46719284646SJohn Baldwin 	return (rval);
4680cde2e34SJason Evans }
4690cde2e34SJason Evans 
470013c0b49SMateusz Guzik int
471013c0b49SMateusz Guzik _mtx_trylock_flags_(volatile uintptr_t *c, int opts, const char *file, int line)
472013c0b49SMateusz Guzik {
473013c0b49SMateusz Guzik 	struct mtx *m;
474013c0b49SMateusz Guzik 
475013c0b49SMateusz Guzik 	m = mtxlock2mtx(c);
476013c0b49SMateusz Guzik 	return (_mtx_trylock_flags_int(m, opts LOCK_FILE_LINE_ARG));
477013c0b49SMateusz Guzik }
478013c0b49SMateusz Guzik 
4790cde2e34SJason Evans /*
4807f44c618SAttilio Rao  * __mtx_lock_sleep: the tougher part of acquiring an MTX_DEF lock.
4819ed346baSBosko Milekic  *
4829ed346baSBosko Milekic  * We call this if the lock is either contested (i.e. we need to go to
4839ed346baSBosko Milekic  * sleep waiting for it), or if we need to recurse on it.
4840cde2e34SJason Evans  */
48509f1319aSMateusz Guzik #if LOCK_DEBUG > 0
4860cde2e34SJason Evans void
4872f1ddb89SMateusz Guzik __mtx_lock_sleep(volatile uintptr_t *c, uintptr_t v, int opts, const char *file,
4882f1ddb89SMateusz Guzik     int line)
48909f1319aSMateusz Guzik #else
49009f1319aSMateusz Guzik void
4912f1ddb89SMateusz Guzik __mtx_lock_sleep(volatile uintptr_t *c, uintptr_t v)
49209f1319aSMateusz Guzik #endif
49336412d79SJohn Baldwin {
4942f1ddb89SMateusz Guzik 	struct thread *td;
4957f44c618SAttilio Rao 	struct mtx *m;
4962502c107SJeff Roberson 	struct turnstile *ts;
4972f1ddb89SMateusz Guzik 	uintptr_t tid;
4982ccee9ccSMateusz Guzik 	struct thread *owner;
4991723a064SJeff Roberson #ifdef LOCK_PROFILING
50070fe8436SKip Macy 	int contested = 0;
50170fe8436SKip Macy 	uint64_t waittime = 0;
5021723a064SJeff Roberson #endif
5031ada9041SMateusz Guzik #if defined(ADAPTIVE_MUTEXES) || defined(KDTRACE_HOOKS)
5041ada9041SMateusz Guzik 	struct lock_delay_arg lda;
5051ada9041SMateusz Guzik #endif
506a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
50761852185SMateusz Guzik 	u_int sleep_cnt = 0;
508a5aedd68SStacey Son 	int64_t sleep_time = 0;
509076dd8ebSAndriy Gapon 	int64_t all_time = 0;
510dfaa7859SMateusz Guzik #endif
511dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
512f183fb16SMateusz Guzik 	int doing_lockprof = 0;
513a5aedd68SStacey Son #endif
51409bdec20SMateusz Guzik 
5152f1ddb89SMateusz Guzik 	td = curthread;
5162f1ddb89SMateusz Guzik 	tid = (uintptr_t)td;
51709bdec20SMateusz Guzik 	m = mtxlock2mtx(c);
51809bdec20SMateusz Guzik 
51909bdec20SMateusz Guzik #ifdef KDTRACE_HOOKS
52009bdec20SMateusz Guzik 	if (LOCKSTAT_PROFILE_ENABLED(adaptive__acquire)) {
52109bdec20SMateusz Guzik 		while (v == MTX_UNOWNED) {
52209bdec20SMateusz Guzik 			if (_mtx_obtain_lock_fetch(m, &v, tid))
52309bdec20SMateusz Guzik 				goto out_lockstat;
52409bdec20SMateusz Guzik 		}
52509bdec20SMateusz Guzik 		doing_lockprof = 1;
52609bdec20SMateusz Guzik 		all_time -= lockstat_nsecs(&m->lock_object);
52709bdec20SMateusz Guzik 	}
52809bdec20SMateusz Guzik #endif
52909bdec20SMateusz Guzik #ifdef LOCK_PROFILING
53009bdec20SMateusz Guzik 	doing_lockprof = 1;
53109bdec20SMateusz Guzik #endif
53209bdec20SMateusz Guzik 
5332f1ddb89SMateusz Guzik 	if (SCHEDULER_STOPPED_TD(td))
53435370593SAndriy Gapon 		return;
53535370593SAndriy Gapon 
536fa5000a4SMateusz Guzik #if defined(ADAPTIVE_MUTEXES)
5371ada9041SMateusz Guzik 	lock_delay_arg_init(&lda, &mtx_delay);
538fa5000a4SMateusz Guzik #elif defined(KDTRACE_HOOKS)
539fa5000a4SMateusz Guzik 	lock_delay_arg_init(&lda, NULL);
5401ada9041SMateusz Guzik #endif
54109bdec20SMateusz Guzik 
542c1aaf63cSMateusz Guzik 	if (__predict_false(v == MTX_UNOWNED))
543c1aaf63cSMateusz Guzik 		v = MTX_READ_VALUE(m);
5447f44c618SAttilio Rao 
5452f1ddb89SMateusz Guzik 	if (__predict_false(lv_mtx_owner(v) == td)) {
546ac6b769bSAttilio Rao 		KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) != 0 ||
547ac6b769bSAttilio Rao 		    (opts & MTX_RECURSE) != 0,
548eac09796SJohn Baldwin 	    ("_mtx_lock_sleep: recursed on non-recursive mutex %s @ %s:%d\n",
549aa89d8cdSJohn Baldwin 		    m->lock_object.lo_name, file, line));
550a24c8eb8SMateusz Guzik #if LOCK_DEBUG > 0
551ac6b769bSAttilio Rao 		opts &= ~MTX_RECURSE;
552a24c8eb8SMateusz Guzik #endif
55336412d79SJohn Baldwin 		m->mtx_recurse++;
55408812b39SBosko Milekic 		atomic_set_ptr(&m->mtx_lock, MTX_RECURSED);
555aa89d8cdSJohn Baldwin 		if (LOCK_LOG_TEST(&m->lock_object, opts))
5565746a1d8SBosko Milekic 			CTR1(KTR_LOCK, "_mtx_lock_sleep: %p recursing", m);
55736412d79SJohn Baldwin 		return;
55836412d79SJohn Baldwin 	}
559a24c8eb8SMateusz Guzik #if LOCK_DEBUG > 0
560ac6b769bSAttilio Rao 	opts &= ~MTX_RECURSE;
561a24c8eb8SMateusz Guzik #endif
5629ed346baSBosko Milekic 
563f5f9340bSFabien Thomas #ifdef HWPMC_HOOKS
564f5f9340bSFabien Thomas 	PMC_SOFT_CALL( , , lock, failed);
565f5f9340bSFabien Thomas #endif
56670fe8436SKip Macy 	lock_profile_obtain_lock_failed(&m->lock_object,
56770fe8436SKip Macy 		    &contested, &waittime);
568aa89d8cdSJohn Baldwin 	if (LOCK_LOG_TEST(&m->lock_object, opts))
56915ec816aSJohn Baldwin 		CTR4(KTR_LOCK,
57015ec816aSJohn Baldwin 		    "_mtx_lock_sleep: %s contested (lock=%p) at %s:%d",
571aa89d8cdSJohn Baldwin 		    m->lock_object.lo_name, (void *)m->mtx_lock, file, line);
5721bd0eefbSJohn Baldwin 
573fc4f686dSMateusz Guzik 	for (;;) {
5742604eb9eSMateusz Guzik 		if (v == MTX_UNOWNED) {
57590836c32SMateusz Guzik 			if (_mtx_obtain_lock_fetch(m, &v, tid))
576fc4f686dSMateusz Guzik 				break;
5772604eb9eSMateusz Guzik 			continue;
5782604eb9eSMateusz Guzik 		}
579a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
5801ada9041SMateusz Guzik 		lda.spin_cnt++;
581a5aedd68SStacey Son #endif
58249aead8aSAttilio Rao #ifdef ADAPTIVE_MUTEXES
58349aead8aSAttilio Rao 		/*
58449aead8aSAttilio Rao 		 * If the owner is running on another CPU, spin until the
58549aead8aSAttilio Rao 		 * owner stops running or the state of the lock changes.
58649aead8aSAttilio Rao 		 */
5872604eb9eSMateusz Guzik 		owner = lv_mtx_owner(v);
58849aead8aSAttilio Rao 		if (TD_IS_RUNNING(owner)) {
58949aead8aSAttilio Rao 			if (LOCK_LOG_TEST(&m->lock_object, 0))
59049aead8aSAttilio Rao 				CTR3(KTR_LOCK,
59149aead8aSAttilio Rao 				    "%s: spinning on %p held by %p",
59249aead8aSAttilio Rao 				    __func__, m, owner);
5932cba8dd3SJohn Baldwin 			KTR_STATE1(KTR_SCHED, "thread",
5942cba8dd3SJohn Baldwin 			    sched_tdname((struct thread *)tid),
5952cba8dd3SJohn Baldwin 			    "spinning", "lockname:\"%s\"",
5962cba8dd3SJohn Baldwin 			    m->lock_object.lo_name);
5972604eb9eSMateusz Guzik 			do {
5981ada9041SMateusz Guzik 				lock_delay(&lda);
599391df78aSMateusz Guzik 				v = MTX_READ_VALUE(m);
6002604eb9eSMateusz Guzik 				owner = lv_mtx_owner(v);
6012604eb9eSMateusz Guzik 			} while (v != MTX_UNOWNED && TD_IS_RUNNING(owner));
6022cba8dd3SJohn Baldwin 			KTR_STATE0(KTR_SCHED, "thread",
6032cba8dd3SJohn Baldwin 			    sched_tdname((struct thread *)tid),
6042cba8dd3SJohn Baldwin 			    "running");
60549aead8aSAttilio Rao 			continue;
60649aead8aSAttilio Rao 		}
60749aead8aSAttilio Rao #endif
60849aead8aSAttilio Rao 
6092502c107SJeff Roberson 		ts = turnstile_trywait(&m->lock_object);
6102604eb9eSMateusz Guzik 		v = MTX_READ_VALUE(m);
611310f24d7SMateusz Guzik retry_turnstile:
6125fa8dd90SJohn Baldwin 
61336412d79SJohn Baldwin 		/*
6149ed346baSBosko Milekic 		 * Check if the lock has been released while spinning for
615961a7b24SJohn Baldwin 		 * the turnstile chain lock.
61636412d79SJohn Baldwin 		 */
6175fa8dd90SJohn Baldwin 		if (v == MTX_UNOWNED) {
6182502c107SJeff Roberson 			turnstile_cancel(ts);
61936412d79SJohn Baldwin 			continue;
62036412d79SJohn Baldwin 		}
6219ed346baSBosko Milekic 
62249aead8aSAttilio Rao #ifdef ADAPTIVE_MUTEXES
62349aead8aSAttilio Rao 		/*
624fa29f023SJohn Baldwin 		 * The current lock owner might have started executing
625fa29f023SJohn Baldwin 		 * on another CPU (or the lock could have changed
626fa29f023SJohn Baldwin 		 * owners) while we were waiting on the turnstile
627fa29f023SJohn Baldwin 		 * chain lock.  If so, drop the turnstile lock and try
628fa29f023SJohn Baldwin 		 * again.
62949aead8aSAttilio Rao 		 */
6302604eb9eSMateusz Guzik 		owner = lv_mtx_owner(v);
63149aead8aSAttilio Rao 		if (TD_IS_RUNNING(owner)) {
63249aead8aSAttilio Rao 			turnstile_cancel(ts);
63349aead8aSAttilio Rao 			continue;
63449aead8aSAttilio Rao 		}
63549aead8aSAttilio Rao #endif
63649aead8aSAttilio Rao 
63736412d79SJohn Baldwin 		/*
6389ed346baSBosko Milekic 		 * If the mutex isn't already contested and a failure occurs
6399ed346baSBosko Milekic 		 * setting the contested bit, the mutex was either released
6409ed346baSBosko Milekic 		 * or the state of the MTX_RECURSED bit changed.
64136412d79SJohn Baldwin 		 */
64236412d79SJohn Baldwin 		if ((v & MTX_CONTESTED) == 0 &&
643310f24d7SMateusz Guzik 		    !atomic_fcmpset_ptr(&m->mtx_lock, &v, v | MTX_CONTESTED)) {
644310f24d7SMateusz Guzik 			goto retry_turnstile;
64536412d79SJohn Baldwin 		}
64636412d79SJohn Baldwin 
6479ed346baSBosko Milekic 		/*
6487feefcd6SJohn Baldwin 		 * We definitely must sleep for this lock.
6499ed346baSBosko Milekic 		 */
65036412d79SJohn Baldwin 		mtx_assert(m, MA_NOTOWNED);
65136412d79SJohn Baldwin 
6529ed346baSBosko Milekic 		/*
653961a7b24SJohn Baldwin 		 * Block on the turnstile.
6549ed346baSBosko Milekic 		 */
655a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
656e2b25737SMark Johnston 		sleep_time -= lockstat_nsecs(&m->lock_object);
657a5aedd68SStacey Son #endif
658284194f1SMateusz Guzik #ifndef ADAPTIVE_MUTEXES
659284194f1SMateusz Guzik 		owner = mtx_owner(m);
660284194f1SMateusz Guzik #endif
6618448e020SMateusz Guzik 		MPASS(owner == mtx_owner(m));
6628448e020SMateusz Guzik 		turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
663a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
664e2b25737SMark Johnston 		sleep_time += lockstat_nsecs(&m->lock_object);
665a5aedd68SStacey Son 		sleep_cnt++;
666a5aedd68SStacey Son #endif
6672604eb9eSMateusz Guzik 		v = MTX_READ_VALUE(m);
66836412d79SJohn Baldwin 	}
669dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
670dfaa7859SMateusz Guzik 	if (__predict_true(!doing_lockprof))
6717640beb9SMateusz Guzik 		return;
672dfaa7859SMateusz Guzik #endif
673dfaa7859SMateusz Guzik #ifdef KDTRACE_HOOKS
6747640beb9SMateusz Guzik 	all_time += lockstat_nsecs(&m->lock_object);
675a5aedd68SStacey Son 	if (sleep_time)
67632cd0147SMark Johnston 		LOCKSTAT_RECORD1(adaptive__block, m, sleep_time);
677a5aedd68SStacey Son 
678a5aedd68SStacey Son 	/*
679a5aedd68SStacey Son 	 * Only record the loops spinning and not sleeping.
680a5aedd68SStacey Son 	 */
6811ada9041SMateusz Guzik 	if (lda.spin_cnt > sleep_cnt)
68232cd0147SMark Johnston 		LOCKSTAT_RECORD1(adaptive__spin, m, all_time - sleep_time);
68309bdec20SMateusz Guzik out_lockstat:
684a5aedd68SStacey Son #endif
68509bdec20SMateusz Guzik 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(adaptive__acquire, m, contested,
68609bdec20SMateusz Guzik 	    waittime, file, line);
6879ed346baSBosko Milekic }
6889ed346baSBosko Milekic 
689b95b98b0SKonstantin Belousov #ifdef SMP
6909ed346baSBosko Milekic /*
6917f44c618SAttilio Rao  * _mtx_lock_spin_cookie: the tougher part of acquiring an MTX_SPIN lock.
6929ed346baSBosko Milekic  *
6939ed346baSBosko Milekic  * This is only called if we need to actually spin for the lock. Recursion
6949ed346baSBosko Milekic  * is handled inline.
6959ed346baSBosko Milekic  */
6960d74fe26SMateusz Guzik #if LOCK_DEBUG > 0
6979ed346baSBosko Milekic void
6980d74fe26SMateusz Guzik _mtx_lock_spin_cookie(volatile uintptr_t *c, uintptr_t v, int opts,
6990d74fe26SMateusz Guzik     const char *file, int line)
7000d74fe26SMateusz Guzik #else
7010d74fe26SMateusz Guzik void
7020d74fe26SMateusz Guzik _mtx_lock_spin_cookie(volatile uintptr_t *c, uintptr_t v)
7030d74fe26SMateusz Guzik #endif
70436412d79SJohn Baldwin {
7057f44c618SAttilio Rao 	struct mtx *m;
706a0d45f0fSMateusz Guzik 	struct lock_delay_arg lda;
7070d74fe26SMateusz Guzik 	uintptr_t tid;
7081723a064SJeff Roberson #ifdef LOCK_PROFILING
7091723a064SJeff Roberson 	int contested = 0;
71070fe8436SKip Macy 	uint64_t waittime = 0;
7111723a064SJeff Roberson #endif
712076dd8ebSAndriy Gapon #ifdef KDTRACE_HOOKS
713076dd8ebSAndriy Gapon 	int64_t spin_time = 0;
714076dd8ebSAndriy Gapon #endif
715dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
716f183fb16SMateusz Guzik 	int doing_lockprof = 0;
717dfaa7859SMateusz Guzik #endif
71836412d79SJohn Baldwin 
7190d74fe26SMateusz Guzik 	tid = (uintptr_t)curthread;
7207f44c618SAttilio Rao 	m = mtxlock2mtx(c);
7217f44c618SAttilio Rao 
72209bdec20SMateusz Guzik #ifdef KDTRACE_HOOKS
72309bdec20SMateusz Guzik 	if (LOCKSTAT_PROFILE_ENABLED(adaptive__acquire)) {
72409bdec20SMateusz Guzik 		while (v == MTX_UNOWNED) {
72509bdec20SMateusz Guzik 			if (_mtx_obtain_lock_fetch(m, &v, tid))
72609bdec20SMateusz Guzik 				goto out_lockstat;
72709bdec20SMateusz Guzik 		}
72809bdec20SMateusz Guzik 		doing_lockprof = 1;
72909bdec20SMateusz Guzik 		spin_time -= lockstat_nsecs(&m->lock_object);
73009bdec20SMateusz Guzik 	}
73109bdec20SMateusz Guzik #endif
73209bdec20SMateusz Guzik #ifdef LOCK_PROFILING
73309bdec20SMateusz Guzik 	doing_lockprof = 1;
73409bdec20SMateusz Guzik #endif
73509bdec20SMateusz Guzik 
73613d2ef0fSMateusz Guzik 	if (__predict_false(v == MTX_UNOWNED))
73713d2ef0fSMateusz Guzik 		v = MTX_READ_VALUE(m);
73813d2ef0fSMateusz Guzik 
73913d2ef0fSMateusz Guzik 	if (__predict_false(v == tid)) {
74013d2ef0fSMateusz Guzik 		m->mtx_recurse++;
74113d2ef0fSMateusz Guzik 		return;
74213d2ef0fSMateusz Guzik 	}
74313d2ef0fSMateusz Guzik 
7440d74fe26SMateusz Guzik 	if (SCHEDULER_STOPPED())
7450d74fe26SMateusz Guzik 		return;
7460d74fe26SMateusz Guzik 
7470d74fe26SMateusz Guzik 	lock_delay_arg_init(&lda, &mtx_spin_delay);
7480d74fe26SMateusz Guzik 
749aa89d8cdSJohn Baldwin 	if (LOCK_LOG_TEST(&m->lock_object, opts))
7505746a1d8SBosko Milekic 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
7512cba8dd3SJohn Baldwin 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
7522cba8dd3SJohn Baldwin 	    "spinning", "lockname:\"%s\"", m->lock_object.lo_name);
7539ed346baSBosko Milekic 
754f5f9340bSFabien Thomas #ifdef HWPMC_HOOKS
755f5f9340bSFabien Thomas 	PMC_SOFT_CALL( , , lock, failed);
756f5f9340bSFabien Thomas #endif
75770fe8436SKip Macy 	lock_profile_obtain_lock_failed(&m->lock_object, &contested, &waittime);
75809bdec20SMateusz Guzik 
759fc4f686dSMateusz Guzik 	for (;;) {
7602604eb9eSMateusz Guzik 		if (v == MTX_UNOWNED) {
76190836c32SMateusz Guzik 			if (_mtx_obtain_lock_fetch(m, &v, tid))
762fc4f686dSMateusz Guzik 				break;
76336412d79SJohn Baldwin 			continue;
764703fc290SJohn Baldwin 		}
7652604eb9eSMateusz Guzik 		/* Give interrupts a chance while we spin. */
7662604eb9eSMateusz Guzik 		spinlock_exit();
7672604eb9eSMateusz Guzik 		do {
76815140a8aSMateusz Guzik 			if (__predict_true(lda.spin_cnt < 10000000)) {
7692604eb9eSMateusz Guzik 				lock_delay(&lda);
7702604eb9eSMateusz Guzik 			} else {
77115140a8aSMateusz Guzik 				_mtx_lock_indefinite_check(m, &lda);
77236412d79SJohn Baldwin 			}
7732604eb9eSMateusz Guzik 			v = MTX_READ_VALUE(m);
7742604eb9eSMateusz Guzik 		} while (v != MTX_UNOWNED);
775c6a37e84SJohn Baldwin 		spinlock_enter();
77636412d79SJohn Baldwin 	}
77736412d79SJohn Baldwin 
778aa89d8cdSJohn Baldwin 	if (LOCK_LOG_TEST(&m->lock_object, opts))
7799ed346baSBosko Milekic 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spin done", m);
7802cba8dd3SJohn Baldwin 	KTR_STATE0(KTR_SCHED, "thread", sched_tdname((struct thread *)tid),
7812cba8dd3SJohn Baldwin 	    "running");
7829ed346baSBosko Milekic 
783dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
784dfaa7859SMateusz Guzik 	if (__predict_true(!doing_lockprof))
785dfaa7859SMateusz Guzik 		return;
786dfaa7859SMateusz Guzik #endif
787c6d48c87SMark Johnston #ifdef KDTRACE_HOOKS
788dfaa7859SMateusz Guzik 	spin_time += lockstat_nsecs(&m->lock_object);
78909bdec20SMateusz Guzik 	if (lda.spin_cnt != 0)
79009bdec20SMateusz Guzik 		LOCKSTAT_RECORD1(spin__spin, m, spin_time);
79109bdec20SMateusz Guzik out_lockstat:
792dfaa7859SMateusz Guzik #endif
79332cd0147SMark Johnston 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire, m,
79432cd0147SMark Johnston 	    contested, waittime, file, line);
79536412d79SJohn Baldwin }
79633fb8a38SJohn Baldwin #endif /* SMP */
79736412d79SJohn Baldwin 
798be49509eSMateusz Guzik #ifdef INVARIANTS
799be49509eSMateusz Guzik static void
800be49509eSMateusz Guzik thread_lock_validate(struct mtx *m, int opts, const char *file, int line)
801be49509eSMateusz Guzik {
802be49509eSMateusz Guzik 
803be49509eSMateusz Guzik 	KASSERT(m->mtx_lock != MTX_DESTROYED,
804be49509eSMateusz Guzik 	    ("thread_lock() of destroyed mutex @ %s:%d", file, line));
805be49509eSMateusz Guzik 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
806be49509eSMateusz Guzik 	    ("thread_lock() of sleep mutex %s @ %s:%d",
807be49509eSMateusz Guzik 	    m->lock_object.lo_name, file, line));
8083fd19ce7SMateusz Guzik 	KASSERT((m->lock_object.lo_flags & LO_RECURSABLE) == 0,
8093fd19ce7SMateusz Guzik 	    ("thread_lock: got a recursive mutex %s @ %s:%d\n",
810be49509eSMateusz Guzik 	    m->lock_object.lo_name, file, line));
811be49509eSMateusz Guzik 	WITNESS_CHECKORDER(&m->lock_object,
812be49509eSMateusz Guzik 	    opts | LOP_NEWORDER | LOP_EXCLUSIVE, file, line, NULL);
813be49509eSMateusz Guzik }
814be49509eSMateusz Guzik #else
815be49509eSMateusz Guzik #define thread_lock_validate(m, opts, file, line) do { } while (0)
816be49509eSMateusz Guzik #endif
817be49509eSMateusz Guzik 
818be49509eSMateusz Guzik #ifndef LOCK_PROFILING
819be49509eSMateusz Guzik #if LOCK_DEBUG > 0
820be49509eSMateusz Guzik void
821be49509eSMateusz Guzik _thread_lock(struct thread *td, int opts, const char *file, int line)
822be49509eSMateusz Guzik #else
823be49509eSMateusz Guzik void
824be49509eSMateusz Guzik _thread_lock(struct thread *td)
825be49509eSMateusz Guzik #endif
826be49509eSMateusz Guzik {
827be49509eSMateusz Guzik 	struct mtx *m;
8283fd19ce7SMateusz Guzik 	uintptr_t tid;
829be49509eSMateusz Guzik 
830be49509eSMateusz Guzik 	tid = (uintptr_t)curthread;
831be49509eSMateusz Guzik 
8322c50bafeSMateusz Guzik 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(spin__acquire)))
8332c50bafeSMateusz Guzik 		goto slowpath_noirq;
834be49509eSMateusz Guzik 	spinlock_enter();
835be49509eSMateusz Guzik 	m = td->td_lock;
836be49509eSMateusz Guzik 	thread_lock_validate(m, 0, file, line);
8373fd19ce7SMateusz Guzik 	if (__predict_false(m == &blocked_lock))
838be49509eSMateusz Guzik 		goto slowpath_unlocked;
8393fd19ce7SMateusz Guzik 	if (__predict_false(!_mtx_obtain_lock(m, tid)))
840be49509eSMateusz Guzik 		goto slowpath_unlocked;
841be49509eSMateusz Guzik 	if (__predict_true(m == td->td_lock)) {
842be49509eSMateusz Guzik 		WITNESS_LOCK(&m->lock_object, LOP_EXCLUSIVE, file, line);
843be49509eSMateusz Guzik 		return;
844be49509eSMateusz Guzik 	}
845be49509eSMateusz Guzik 	_mtx_release_lock_quick(m);
846be49509eSMateusz Guzik slowpath_unlocked:
847be49509eSMateusz Guzik 	spinlock_exit();
8482c50bafeSMateusz Guzik slowpath_noirq:
8492c50bafeSMateusz Guzik #if LOCK_DEBUG > 0
8502c50bafeSMateusz Guzik 	thread_lock_flags_(td, opts, file, line);
8512c50bafeSMateusz Guzik #else
852be49509eSMateusz Guzik 	thread_lock_flags_(td, 0, 0, 0);
8532c50bafeSMateusz Guzik #endif
854be49509eSMateusz Guzik }
855be49509eSMateusz Guzik #endif
856be49509eSMateusz Guzik 
8572502c107SJeff Roberson void
858ccdf2333SAttilio Rao thread_lock_flags_(struct thread *td, int opts, const char *file, int line)
8592502c107SJeff Roberson {
8602502c107SJeff Roberson 	struct mtx *m;
8615e5ad162SMateusz Guzik 	uintptr_t tid, v;
862a0d45f0fSMateusz Guzik 	struct lock_delay_arg lda;
8631723a064SJeff Roberson #ifdef LOCK_PROFILING
8641723a064SJeff Roberson 	int contested = 0;
8651723a064SJeff Roberson 	uint64_t waittime = 0;
8661723a064SJeff Roberson #endif
867a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
868076dd8ebSAndriy Gapon 	int64_t spin_time = 0;
869a5aedd68SStacey Son #endif
870dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
871dfaa7859SMateusz Guzik 	int doing_lockprof = 1;
872dfaa7859SMateusz Guzik #endif
8732502c107SJeff Roberson 
8742502c107SJeff Roberson 	tid = (uintptr_t)curthread;
87535370593SAndriy Gapon 
876f61d6c5aSMark Johnston 	if (SCHEDULER_STOPPED()) {
877f61d6c5aSMark Johnston 		/*
878f61d6c5aSMark Johnston 		 * Ensure that spinlock sections are balanced even when the
879f61d6c5aSMark Johnston 		 * scheduler is stopped, since we may otherwise inadvertently
880f61d6c5aSMark Johnston 		 * re-enable interrupts while dumping core.
881f61d6c5aSMark Johnston 		 */
882f61d6c5aSMark Johnston 		spinlock_enter();
88335370593SAndriy Gapon 		return;
884f61d6c5aSMark Johnston 	}
88535370593SAndriy Gapon 
886a0d45f0fSMateusz Guzik 	lock_delay_arg_init(&lda, &mtx_spin_delay);
887a0d45f0fSMateusz Guzik 
8881f4d28c7SMateusz Guzik #ifdef HWPMC_HOOKS
8891f4d28c7SMateusz Guzik 	PMC_SOFT_CALL( , , lock, failed);
8901f4d28c7SMateusz Guzik #endif
8911f4d28c7SMateusz Guzik 
892dfaa7859SMateusz Guzik #ifdef LOCK_PROFILING
893dfaa7859SMateusz Guzik 	doing_lockprof = 1;
894df1c30f6SWarner Losh #elif defined(KDTRACE_HOOKS)
895dfaa7859SMateusz Guzik 	doing_lockprof = lockstat_enabled;
896dfaa7859SMateusz Guzik 	if (__predict_false(doing_lockprof))
897e2b25737SMark Johnston 		spin_time -= lockstat_nsecs(&td->td_lock->lock_object);
898076dd8ebSAndriy Gapon #endif
8999f4e008dSMateusz Guzik 	spinlock_enter();
9009f4e008dSMateusz Guzik 
9012502c107SJeff Roberson 	for (;;) {
9022502c107SJeff Roberson retry:
903710eacdcSJeff Roberson 		m = td->td_lock;
904be49509eSMateusz Guzik 		thread_lock_validate(m, opts, file, line);
9051f4d28c7SMateusz Guzik 		v = MTX_READ_VALUE(m);
906fc4f686dSMateusz Guzik 		for (;;) {
9071f4d28c7SMateusz Guzik 			if (v == MTX_UNOWNED) {
90890836c32SMateusz Guzik 				if (_mtx_obtain_lock_fetch(m, &v, tid))
909fc4f686dSMateusz Guzik 					break;
9105e5ad162SMateusz Guzik 				continue;
9111f4d28c7SMateusz Guzik 			}
9123fd19ce7SMateusz Guzik 			MPASS(v != tid);
913eea4f254SJeff Roberson 			lock_profile_obtain_lock_failed(&m->lock_object,
914eea4f254SJeff Roberson 			    &contested, &waittime);
9152502c107SJeff Roberson 			/* Give interrupts a chance while we spin. */
9162502c107SJeff Roberson 			spinlock_exit();
9175e5ad162SMateusz Guzik 			do {
91815140a8aSMateusz Guzik 				if (__predict_true(lda.spin_cnt < 10000000)) {
919a0d45f0fSMateusz Guzik 					lock_delay(&lda);
920a0d45f0fSMateusz Guzik 				} else {
92115140a8aSMateusz Guzik 					_mtx_lock_indefinite_check(m, &lda);
922a0d45f0fSMateusz Guzik 				}
9239f4e008dSMateusz Guzik 				if (m != td->td_lock) {
9249f4e008dSMateusz Guzik 					spinlock_enter();
9252502c107SJeff Roberson 					goto retry;
9269f4e008dSMateusz Guzik 				}
9275e5ad162SMateusz Guzik 				v = MTX_READ_VALUE(m);
9285e5ad162SMateusz Guzik 			} while (v != MTX_UNOWNED);
9292502c107SJeff Roberson 			spinlock_enter();
9302502c107SJeff Roberson 		}
9312502c107SJeff Roberson 		if (m == td->td_lock)
9322502c107SJeff Roberson 			break;
9339f4e008dSMateusz Guzik 		_mtx_release_lock_quick(m);
9342502c107SJeff Roberson 	}
935dfaa7859SMateusz Guzik 	LOCK_LOG_LOCK("LOCK", &m->lock_object, opts, m->mtx_recurse, file,
936dfaa7859SMateusz Guzik 	    line);
937dfaa7859SMateusz Guzik 	WITNESS_LOCK(&m->lock_object, opts | LOP_EXCLUSIVE, file, line);
938dfaa7859SMateusz Guzik 
939dfaa7859SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
940dfaa7859SMateusz Guzik 	if (__predict_true(!doing_lockprof))
941dfaa7859SMateusz Guzik 		return;
942dfaa7859SMateusz Guzik #endif
943076dd8ebSAndriy Gapon #ifdef KDTRACE_HOOKS
944e2b25737SMark Johnston 	spin_time += lockstat_nsecs(&m->lock_object);
945076dd8ebSAndriy Gapon #endif
9463fd19ce7SMateusz Guzik 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(spin__acquire, m, contested,
9473fd19ce7SMateusz Guzik 	    waittime, file, line);
9485002e195SMark Johnston #ifdef KDTRACE_HOOKS
949d0f68f91SMark Johnston 	if (lda.spin_cnt != 0)
95032cd0147SMark Johnston 		LOCKSTAT_RECORD1(thread__spin, m, spin_time);
9515002e195SMark Johnston #endif
9522502c107SJeff Roberson }
9532502c107SJeff Roberson 
9542502c107SJeff Roberson struct mtx *
9552502c107SJeff Roberson thread_lock_block(struct thread *td)
9562502c107SJeff Roberson {
9572502c107SJeff Roberson 	struct mtx *lock;
9582502c107SJeff Roberson 
959710eacdcSJeff Roberson 	lock = td->td_lock;
96061a74c5cSJeff Roberson 	mtx_assert(lock, MA_OWNED);
9612502c107SJeff Roberson 	td->td_lock = &blocked_lock;
9622502c107SJeff Roberson 
9632502c107SJeff Roberson 	return (lock);
9642502c107SJeff Roberson }
9652502c107SJeff Roberson 
9662502c107SJeff Roberson void
9672502c107SJeff Roberson thread_lock_unblock(struct thread *td, struct mtx *new)
9682502c107SJeff Roberson {
96961a74c5cSJeff Roberson 
9702502c107SJeff Roberson 	mtx_assert(new, MA_OWNED);
97161a74c5cSJeff Roberson 	KASSERT(td->td_lock == &blocked_lock,
97261a74c5cSJeff Roberson 	    ("thread %p lock %p not blocked_lock %p",
97361a74c5cSJeff Roberson 	    td, td->td_lock, &blocked_lock));
97465d32cd8SMatt Jacob 	atomic_store_rel_ptr((volatile void *)&td->td_lock, (uintptr_t)new);
9752502c107SJeff Roberson }
9762502c107SJeff Roberson 
9772502c107SJeff Roberson void
97861a74c5cSJeff Roberson thread_lock_block_wait(struct thread *td)
97961a74c5cSJeff Roberson {
98061a74c5cSJeff Roberson 
98161a74c5cSJeff Roberson 	while (td->td_lock == &blocked_lock)
98261a74c5cSJeff Roberson 		cpu_spinwait();
98361a74c5cSJeff Roberson 
98461a74c5cSJeff Roberson 	/* Acquire fence to be certain that all thread state is visible. */
98561a74c5cSJeff Roberson 	atomic_thread_fence_acq();
98661a74c5cSJeff Roberson }
98761a74c5cSJeff Roberson 
98861a74c5cSJeff Roberson void
9892502c107SJeff Roberson thread_lock_set(struct thread *td, struct mtx *new)
9902502c107SJeff Roberson {
9912502c107SJeff Roberson 	struct mtx *lock;
9922502c107SJeff Roberson 
9932502c107SJeff Roberson 	mtx_assert(new, MA_OWNED);
994710eacdcSJeff Roberson 	lock = td->td_lock;
99561a74c5cSJeff Roberson 	mtx_assert(lock, MA_OWNED);
9962502c107SJeff Roberson 	td->td_lock = new;
9972502c107SJeff Roberson 	mtx_unlock_spin(lock);
9982502c107SJeff Roberson }
9992502c107SJeff Roberson 
10009ed346baSBosko Milekic /*
10017f44c618SAttilio Rao  * __mtx_unlock_sleep: the tougher part of releasing an MTX_DEF lock.
10029ed346baSBosko Milekic  *
10033b3cf014SMateusz Guzik  * We are only called here if the lock is recursed, contested (i.e. we
10043b3cf014SMateusz Guzik  * need to wake up a blocked thread) or lockstat probe is active.
10059ed346baSBosko Milekic  */
100609f1319aSMateusz Guzik #if LOCK_DEBUG > 0
100736412d79SJohn Baldwin void
1008b584eb2eSMateusz Guzik __mtx_unlock_sleep(volatile uintptr_t *c, uintptr_t v, int opts,
1009b584eb2eSMateusz Guzik     const char *file, int line)
101009f1319aSMateusz Guzik #else
101109f1319aSMateusz Guzik void
1012b584eb2eSMateusz Guzik __mtx_unlock_sleep(volatile uintptr_t *c, uintptr_t v)
101309f1319aSMateusz Guzik #endif
101436412d79SJohn Baldwin {
10157f44c618SAttilio Rao 	struct mtx *m;
1016961a7b24SJohn Baldwin 	struct turnstile *ts;
1017b584eb2eSMateusz Guzik 	uintptr_t tid;
10189ed346baSBosko Milekic 
101935370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
102035370593SAndriy Gapon 		return;
102135370593SAndriy Gapon 
10223b3cf014SMateusz Guzik 	tid = (uintptr_t)curthread;
10237f44c618SAttilio Rao 	m = mtxlock2mtx(c);
1024b584eb2eSMateusz Guzik 
1025b584eb2eSMateusz Guzik 	if (__predict_false(v == tid))
10263b3cf014SMateusz Guzik 		v = MTX_READ_VALUE(m);
102790836c32SMateusz Guzik 
1028b584eb2eSMateusz Guzik 	if (__predict_false(v & MTX_RECURSED)) {
102936412d79SJohn Baldwin 		if (--(m->mtx_recurse) == 0)
103008812b39SBosko Milekic 			atomic_clear_ptr(&m->mtx_lock, MTX_RECURSED);
1031aa89d8cdSJohn Baldwin 		if (LOCK_LOG_TEST(&m->lock_object, opts))
10329ed346baSBosko Milekic 			CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p unrecurse", m);
103336412d79SJohn Baldwin 		return;
103436412d79SJohn Baldwin 	}
10359ed346baSBosko Milekic 
10363b3cf014SMateusz Guzik 	LOCKSTAT_PROFILE_RELEASE_LOCK(adaptive__release, m);
10373b3cf014SMateusz Guzik 	if (v == tid && _mtx_release_lock(m, tid))
10383b3cf014SMateusz Guzik 		return;
10393b3cf014SMateusz Guzik 
10402502c107SJeff Roberson 	/*
10412502c107SJeff Roberson 	 * We have to lock the chain before the turnstile so this turnstile
10422502c107SJeff Roberson 	 * can be removed from the hash list if it is empty.
10432502c107SJeff Roberson 	 */
10442502c107SJeff Roberson 	turnstile_chain_lock(&m->lock_object);
10458448e020SMateusz Guzik 	_mtx_release_lock_quick(m);
1046aa89d8cdSJohn Baldwin 	ts = turnstile_lookup(&m->lock_object);
10478448e020SMateusz Guzik 	MPASS(ts != NULL);
1048aa89d8cdSJohn Baldwin 	if (LOCK_LOG_TEST(&m->lock_object, opts))
10499ed346baSBosko Milekic 		CTR1(KTR_LOCK, "_mtx_unlock_sleep: %p contested", m);
10507aa4f685SJohn Baldwin 	turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
1051bf9c6c31SJohn Baldwin 
10522502c107SJeff Roberson 	/*
10532502c107SJeff Roberson 	 * This turnstile is now no longer associated with the mutex.  We can
10542502c107SJeff Roberson 	 * unlock the chain lock so a new turnstile may take it's place.
10552502c107SJeff Roberson 	 */
1056d0a22279SMateusz Guzik 	turnstile_unpend(ts);
10572502c107SJeff Roberson 	turnstile_chain_unlock(&m->lock_object);
10589ed346baSBosko Milekic }
10599ed346baSBosko Milekic 
10609ed346baSBosko Milekic /*
10619ed346baSBosko Milekic  * All the unlocking of MTX_SPIN locks is done inline.
1062961135eaSJohn Baldwin  * See the __mtx_unlock_spin() macro for the details.
10639ed346baSBosko Milekic  */
10649ed346baSBosko Milekic 
10659ed346baSBosko Milekic /*
106615ec816aSJohn Baldwin  * The backing function for the INVARIANTS-enabled mtx_assert()
10679ed346baSBosko Milekic  */
10681103f3b0SJohn Baldwin #ifdef INVARIANT_SUPPORT
10690cde2e34SJason Evans void
10707f44c618SAttilio Rao __mtx_assert(const volatile uintptr_t *c, int what, const char *file, int line)
10710cde2e34SJason Evans {
10727f44c618SAttilio Rao 	const struct mtx *m;
10735cb0fbe4SJohn Baldwin 
1074*879e0604SMateusz Guzik 	if (KERNEL_PANICKED() || dumping || SCHEDULER_STOPPED())
10755cb0fbe4SJohn Baldwin 		return;
10767f44c618SAttilio Rao 
10777f44c618SAttilio Rao 	m = mtxlock2mtx(c);
10787f44c618SAttilio Rao 
1079a10f4966SJake Burkholder 	switch (what) {
10800cde2e34SJason Evans 	case MA_OWNED:
10810cde2e34SJason Evans 	case MA_OWNED | MA_RECURSED:
10820cde2e34SJason Evans 	case MA_OWNED | MA_NOTRECURSED:
1083a10f4966SJake Burkholder 		if (!mtx_owned(m))
10840cde2e34SJason Evans 			panic("mutex %s not owned at %s:%d",
1085aa89d8cdSJohn Baldwin 			    m->lock_object.lo_name, file, line);
1086a10f4966SJake Burkholder 		if (mtx_recursed(m)) {
1087a10f4966SJake Burkholder 			if ((what & MA_NOTRECURSED) != 0)
10880cde2e34SJason Evans 				panic("mutex %s recursed at %s:%d",
1089aa89d8cdSJohn Baldwin 				    m->lock_object.lo_name, file, line);
1090a10f4966SJake Burkholder 		} else if ((what & MA_RECURSED) != 0) {
10910cde2e34SJason Evans 			panic("mutex %s unrecursed at %s:%d",
1092aa89d8cdSJohn Baldwin 			    m->lock_object.lo_name, file, line);
10930cde2e34SJason Evans 		}
10940cde2e34SJason Evans 		break;
10950cde2e34SJason Evans 	case MA_NOTOWNED:
1096a10f4966SJake Burkholder 		if (mtx_owned(m))
10970cde2e34SJason Evans 			panic("mutex %s owned at %s:%d",
1098aa89d8cdSJohn Baldwin 			    m->lock_object.lo_name, file, line);
10990cde2e34SJason Evans 		break;
11000cde2e34SJason Evans 	default:
110156771ca7SJason Evans 		panic("unknown mtx_assert at %s:%d", file, line);
11020cde2e34SJason Evans 	}
11030cde2e34SJason Evans }
11040cde2e34SJason Evans #endif
11050cde2e34SJason Evans 
11069ed346baSBosko Milekic /*
1107c27b5699SAndrew R. Reiter  * General init routine used by the MTX_SYSINIT() macro.
1108c27b5699SAndrew R. Reiter  */
1109c27b5699SAndrew R. Reiter void
1110c27b5699SAndrew R. Reiter mtx_sysinit(void *arg)
1111c27b5699SAndrew R. Reiter {
1112c27b5699SAndrew R. Reiter 	struct mtx_args *margs = arg;
1113c27b5699SAndrew R. Reiter 
11147f44c618SAttilio Rao 	mtx_init((struct mtx *)margs->ma_mtx, margs->ma_desc, NULL,
11157f44c618SAttilio Rao 	    margs->ma_opts);
1116c27b5699SAndrew R. Reiter }
1117c27b5699SAndrew R. Reiter 
1118c27b5699SAndrew R. Reiter /*
11199ed346baSBosko Milekic  * Mutex initialization routine; initialize lock `m' of type contained in
11200c88508aSJohn Baldwin  * `opts' with options contained in `opts' and name `name.'  The optional
11210c88508aSJohn Baldwin  * lock type `type' is used as a general lock category name for use with
11220c88508aSJohn Baldwin  * witness.
11239ed346baSBosko Milekic  */
112436412d79SJohn Baldwin void
11257f44c618SAttilio Rao _mtx_init(volatile uintptr_t *c, const char *name, const char *type, int opts)
112636412d79SJohn Baldwin {
11277f44c618SAttilio Rao 	struct mtx *m;
112883a81bcbSJohn Baldwin 	struct lock_class *class;
112983a81bcbSJohn Baldwin 	int flags;
11309ed346baSBosko Milekic 
11317f44c618SAttilio Rao 	m = mtxlock2mtx(c);
11327f44c618SAttilio Rao 
113319284646SJohn Baldwin 	MPASS((opts & ~(MTX_SPIN | MTX_QUIET | MTX_RECURSE |
1134fd07ddcfSDmitry Chagin 	    MTX_NOWITNESS | MTX_DUPOK | MTX_NOPROFILE | MTX_NEW)) == 0);
1135353998acSAttilio Rao 	ASSERT_ATOMIC_LOAD_PTR(m->mtx_lock,
1136353998acSAttilio Rao 	    ("%s: mtx_lock not aligned for %s: %p", __func__, name,
1137353998acSAttilio Rao 	    &m->mtx_lock));
11389ed346baSBosko Milekic 
113983a81bcbSJohn Baldwin 	/* Determine lock class and lock flags. */
114019284646SJohn Baldwin 	if (opts & MTX_SPIN)
114183a81bcbSJohn Baldwin 		class = &lock_class_mtx_spin;
114219284646SJohn Baldwin 	else
114383a81bcbSJohn Baldwin 		class = &lock_class_mtx_sleep;
114483a81bcbSJohn Baldwin 	flags = 0;
114519284646SJohn Baldwin 	if (opts & MTX_QUIET)
114683a81bcbSJohn Baldwin 		flags |= LO_QUIET;
114719284646SJohn Baldwin 	if (opts & MTX_RECURSE)
114883a81bcbSJohn Baldwin 		flags |= LO_RECURSABLE;
114919284646SJohn Baldwin 	if ((opts & MTX_NOWITNESS) == 0)
115083a81bcbSJohn Baldwin 		flags |= LO_WITNESS;
1151f22a4b62SJeff Roberson 	if (opts & MTX_DUPOK)
115283a81bcbSJohn Baldwin 		flags |= LO_DUPOK;
11537c0435b9SKip Macy 	if (opts & MTX_NOPROFILE)
11547c0435b9SKip Macy 		flags |= LO_NOPROFILE;
1155fd07ddcfSDmitry Chagin 	if (opts & MTX_NEW)
1156fd07ddcfSDmitry Chagin 		flags |= LO_NEW;
115719284646SJohn Baldwin 
115883a81bcbSJohn Baldwin 	/* Initialize mutex. */
1159b5fb43e5SJohn Baldwin 	lock_init(&m->lock_object, class, name, type, flags);
1160b5fb43e5SJohn Baldwin 
116119284646SJohn Baldwin 	m->mtx_lock = MTX_UNOWNED;
116283a81bcbSJohn Baldwin 	m->mtx_recurse = 0;
116336412d79SJohn Baldwin }
116436412d79SJohn Baldwin 
11659ed346baSBosko Milekic /*
116619284646SJohn Baldwin  * Remove lock `m' from all_mtx queue.  We don't allow MTX_QUIET to be
116719284646SJohn Baldwin  * passed in as a flag here because if the corresponding mtx_init() was
116819284646SJohn Baldwin  * called with MTX_QUIET set, then it will already be set in the mutex's
116919284646SJohn Baldwin  * flags.
11709ed346baSBosko Milekic  */
117136412d79SJohn Baldwin void
11727f44c618SAttilio Rao _mtx_destroy(volatile uintptr_t *c)
117336412d79SJohn Baldwin {
11747f44c618SAttilio Rao 	struct mtx *m;
11757f44c618SAttilio Rao 
11767f44c618SAttilio Rao 	m = mtxlock2mtx(c);
117736412d79SJohn Baldwin 
117819284646SJohn Baldwin 	if (!mtx_owned(m))
117919284646SJohn Baldwin 		MPASS(mtx_unowned(m));
118019284646SJohn Baldwin 	else {
118108812b39SBosko Milekic 		MPASS((m->mtx_lock & (MTX_RECURSED|MTX_CONTESTED)) == 0);
11829ed346baSBosko Milekic 
1183861a2308SScott Long 		/* Perform the non-mtx related part of mtx_unlock_spin(). */
1184aa89d8cdSJohn Baldwin 		if (LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin)
1185861a2308SScott Long 			spinlock_exit();
1186764e4d54SJohn Baldwin 		else
1187ce1c953eSMark Johnston 			TD_LOCKS_DEC(curthread);
1188861a2308SScott Long 
1189d3df4af3SJeff Roberson 		lock_profile_release_lock(&m->lock_object);
119019284646SJohn Baldwin 		/* Tell witness this isn't locked to make it happy. */
1191aa89d8cdSJohn Baldwin 		WITNESS_UNLOCK(&m->lock_object, LOP_EXCLUSIVE, __FILE__,
1192c86b6ff5SJohn Baldwin 		    __LINE__);
119336412d79SJohn Baldwin 	}
11940384fff8SJason Evans 
1195186abbd7SJohn Baldwin 	m->mtx_lock = MTX_DESTROYED;
1196aa89d8cdSJohn Baldwin 	lock_destroy(&m->lock_object);
11970384fff8SJason Evans }
1198d23f5958SMatthew Dillon 
1199d23f5958SMatthew Dillon /*
1200c53c013bSJohn Baldwin  * Intialize the mutex code and system mutexes.  This is called from the MD
1201c53c013bSJohn Baldwin  * startup code prior to mi_startup().  The per-CPU data space needs to be
1202c53c013bSJohn Baldwin  * setup before this is called.
1203c53c013bSJohn Baldwin  */
1204c53c013bSJohn Baldwin void
1205c53c013bSJohn Baldwin mutex_init(void)
1206c53c013bSJohn Baldwin {
1207c53c013bSJohn Baldwin 
1208961a7b24SJohn Baldwin 	/* Setup turnstiles so that sleep mutexes work. */
1209961a7b24SJohn Baldwin 	init_turnstiles();
1210961a7b24SJohn Baldwin 
1211c53c013bSJohn Baldwin 	/*
1212c53c013bSJohn Baldwin 	 * Initialize mutexes.
1213c53c013bSJohn Baldwin 	 */
12140c88508aSJohn Baldwin 	mtx_init(&Giant, "Giant", NULL, MTX_DEF | MTX_RECURSE);
12152502c107SJeff Roberson 	mtx_init(&blocked_lock, "blocked lock", NULL, MTX_SPIN);
12162502c107SJeff Roberson 	blocked_lock.mtx_lock = 0xdeadc0de;	/* Always blocked. */
12170c88508aSJohn Baldwin 	mtx_init(&proc0.p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
12186afb32fcSKonstantin Belousov 	mtx_init(&proc0.p_slock, "process slock", NULL, MTX_SPIN);
12195c7bebf9SKonstantin Belousov 	mtx_init(&proc0.p_statmtx, "pstatl", NULL, MTX_SPIN);
12205c7bebf9SKonstantin Belousov 	mtx_init(&proc0.p_itimmtx, "pitiml", NULL, MTX_SPIN);
12215c7bebf9SKonstantin Belousov 	mtx_init(&proc0.p_profmtx, "pprofl", NULL, MTX_SPIN);
12228c4b6380SJohn Baldwin 	mtx_init(&devmtx, "cdev", NULL, MTX_DEF);
1223c53c013bSJohn Baldwin 	mtx_lock(&Giant);
1224c53c013bSJohn Baldwin }
1225d272fe53SJohn Baldwin 
122615140a8aSMateusz Guzik static void __noinline
122715140a8aSMateusz Guzik _mtx_lock_indefinite_check(struct mtx *m, struct lock_delay_arg *ldap)
122815140a8aSMateusz Guzik {
122915140a8aSMateusz Guzik 	struct thread *td;
123015140a8aSMateusz Guzik 
123115140a8aSMateusz Guzik 	ldap->spin_cnt++;
1232*879e0604SMateusz Guzik 	if (ldap->spin_cnt < 60000000 || kdb_active || KERNEL_PANICKED())
12334cbbb748SJohn Baldwin 		cpu_lock_delay();
123415140a8aSMateusz Guzik 	else {
123515140a8aSMateusz Guzik 		td = mtx_owner(m);
123615140a8aSMateusz Guzik 
123715140a8aSMateusz Guzik 		/* If the mutex is unlocked, try again. */
123815140a8aSMateusz Guzik 		if (td == NULL)
123915140a8aSMateusz Guzik 			return;
124015140a8aSMateusz Guzik 
124115140a8aSMateusz Guzik 		printf( "spin lock %p (%s) held by %p (tid %d) too long\n",
124215140a8aSMateusz Guzik 		    m, m->lock_object.lo_name, td, td->td_tid);
124315140a8aSMateusz Guzik #ifdef WITNESS
124415140a8aSMateusz Guzik 		witness_display_spinlock(&m->lock_object, td, printf);
124515140a8aSMateusz Guzik #endif
124615140a8aSMateusz Guzik 		panic("spin lock held too long");
124715140a8aSMateusz Guzik 	}
124815140a8aSMateusz Guzik 	cpu_spinwait();
124915140a8aSMateusz Guzik }
125015140a8aSMateusz Guzik 
1251d2576988SMateusz Guzik void
1252d2576988SMateusz Guzik mtx_spin_wait_unlocked(struct mtx *m)
1253d2576988SMateusz Guzik {
1254d2576988SMateusz Guzik 	struct lock_delay_arg lda;
1255d2576988SMateusz Guzik 
1256500ca73dSMateusz Guzik 	KASSERT(m->mtx_lock != MTX_DESTROYED,
1257500ca73dSMateusz Guzik 	    ("%s() of destroyed mutex %p", __func__, m));
1258500ca73dSMateusz Guzik 	KASSERT(LOCK_CLASS(&m->lock_object) == &lock_class_mtx_spin,
1259500ca73dSMateusz Guzik 	    ("%s() of sleep mutex %p (%s)", __func__, m,
1260500ca73dSMateusz Guzik 	    m->lock_object.lo_name));
1261500ca73dSMateusz Guzik 	KASSERT(!mtx_owned(m), ("%s() waiting on myself on lock %p (%s)", __func__, m,
1262500ca73dSMateusz Guzik 	    m->lock_object.lo_name));
1263500ca73dSMateusz Guzik 
1264d2576988SMateusz Guzik 	lda.spin_cnt = 0;
1265d2576988SMateusz Guzik 
1266d2576988SMateusz Guzik 	while (atomic_load_acq_ptr(&m->mtx_lock) != MTX_UNOWNED) {
1267d2576988SMateusz Guzik 		if (__predict_true(lda.spin_cnt < 10000000)) {
1268d2576988SMateusz Guzik 			cpu_spinwait();
1269d2576988SMateusz Guzik 			lda.spin_cnt++;
1270d2576988SMateusz Guzik 		} else {
1271d2576988SMateusz Guzik 			_mtx_lock_indefinite_check(m, &lda);
1272d2576988SMateusz Guzik 		}
1273d2576988SMateusz Guzik 	}
1274d2576988SMateusz Guzik }
1275d2576988SMateusz Guzik 
1276d272fe53SJohn Baldwin #ifdef DDB
1277d272fe53SJohn Baldwin void
1278d576deedSPawel Jakub Dawidek db_show_mtx(const struct lock_object *lock)
1279d272fe53SJohn Baldwin {
1280d272fe53SJohn Baldwin 	struct thread *td;
1281d576deedSPawel Jakub Dawidek 	const struct mtx *m;
1282d272fe53SJohn Baldwin 
1283d576deedSPawel Jakub Dawidek 	m = (const struct mtx *)lock;
1284d272fe53SJohn Baldwin 
1285d272fe53SJohn Baldwin 	db_printf(" flags: {");
128683a81bcbSJohn Baldwin 	if (LOCK_CLASS(lock) == &lock_class_mtx_spin)
1287d272fe53SJohn Baldwin 		db_printf("SPIN");
1288d272fe53SJohn Baldwin 	else
1289d272fe53SJohn Baldwin 		db_printf("DEF");
1290aa89d8cdSJohn Baldwin 	if (m->lock_object.lo_flags & LO_RECURSABLE)
1291d272fe53SJohn Baldwin 		db_printf(", RECURSE");
1292aa89d8cdSJohn Baldwin 	if (m->lock_object.lo_flags & LO_DUPOK)
1293d272fe53SJohn Baldwin 		db_printf(", DUPOK");
1294d272fe53SJohn Baldwin 	db_printf("}\n");
1295d272fe53SJohn Baldwin 	db_printf(" state: {");
1296d272fe53SJohn Baldwin 	if (mtx_unowned(m))
1297d272fe53SJohn Baldwin 		db_printf("UNOWNED");
1298c0bfd703SJohn Baldwin 	else if (mtx_destroyed(m))
1299c0bfd703SJohn Baldwin 		db_printf("DESTROYED");
1300d272fe53SJohn Baldwin 	else {
1301d272fe53SJohn Baldwin 		db_printf("OWNED");
1302d272fe53SJohn Baldwin 		if (m->mtx_lock & MTX_CONTESTED)
1303d272fe53SJohn Baldwin 			db_printf(", CONTESTED");
1304d272fe53SJohn Baldwin 		if (m->mtx_lock & MTX_RECURSED)
1305d272fe53SJohn Baldwin 			db_printf(", RECURSED");
1306d272fe53SJohn Baldwin 	}
1307d272fe53SJohn Baldwin 	db_printf("}\n");
1308c0bfd703SJohn Baldwin 	if (!mtx_unowned(m) && !mtx_destroyed(m)) {
1309d272fe53SJohn Baldwin 		td = mtx_owner(m);
1310d272fe53SJohn Baldwin 		db_printf(" owner: %p (tid %d, pid %d, \"%s\")\n", td,
1311431f8906SJulian Elischer 		    td->td_tid, td->td_proc->p_pid, td->td_name);
1312d272fe53SJohn Baldwin 		if (mtx_recursed(m))
1313d272fe53SJohn Baldwin 			db_printf(" recursed: %d\n", m->mtx_recurse);
1314d272fe53SJohn Baldwin 	}
1315d272fe53SJohn Baldwin }
1316d272fe53SJohn Baldwin #endif
1317