xref: /freebsd/sys/kern/kern_sx.c (revision a52a51a2d5900e475c3dc6203e09a376316ce90f)
19454b2d8SWarner Losh /*-
24d846d26SWarner Losh  * SPDX-License-Identifier: BSD-2-Clause
38a36da99SPedro F. Giffuni  *
44e7f640dSJohn Baldwin  * Copyright (c) 2007 Attilio Rao <attilio@freebsd.org>
54e7f640dSJohn Baldwin  * Copyright (c) 2001 Jason Evans <jasone@freebsd.org>
64e7f640dSJohn Baldwin  * All rights reserved.
76281b30aSJason Evans  *
86281b30aSJason Evans  * Redistribution and use in source and binary forms, with or without
96281b30aSJason Evans  * modification, are permitted provided that the following conditions
106281b30aSJason Evans  * are met:
116281b30aSJason Evans  * 1. Redistributions of source code must retain the above copyright
126281b30aSJason Evans  *    notice(s), this list of conditions and the following disclaimer as
136281b30aSJason Evans  *    the first lines of this file unmodified other than the possible
146281b30aSJason Evans  *    addition of one or more copyright notices.
156281b30aSJason Evans  * 2. Redistributions in binary form must reproduce the above copyright
166281b30aSJason Evans  *    notice(s), this list of conditions and the following disclaimer in the
176281b30aSJason Evans  *    documentation and/or other materials provided with the distribution.
186281b30aSJason Evans  *
196281b30aSJason Evans  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
206281b30aSJason Evans  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
216281b30aSJason Evans  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
226281b30aSJason Evans  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
236281b30aSJason Evans  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
246281b30aSJason Evans  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
256281b30aSJason Evans  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
266281b30aSJason Evans  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
276281b30aSJason Evans  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
286281b30aSJason Evans  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
296281b30aSJason Evans  * DAMAGE.
306281b30aSJason Evans  */
316281b30aSJason Evans 
326281b30aSJason Evans /*
334e7f640dSJohn Baldwin  * Shared/exclusive locks.  This implementation attempts to ensure
344e7f640dSJohn Baldwin  * deterministic lock granting behavior, so that slocks and xlocks are
354e7f640dSJohn Baldwin  * interleaved.
366281b30aSJason Evans  *
376281b30aSJason Evans  * Priority propagation will not generally raise the priority of lock holders,
386281b30aSJason Evans  * so should not be relied upon in combination with sx locks.
396281b30aSJason Evans  */
406281b30aSJason Evans 
414e7f640dSJohn Baldwin #include "opt_ddb.h"
42f5f9340bSFabien Thomas #include "opt_hwpmc_hooks.h"
43e31d0833SAttilio Rao #include "opt_no_adaptive_sx.h"
444e7f640dSJohn Baldwin 
456281b30aSJason Evans #include <sys/param.h>
467a7ce668SAndriy Gapon #include <sys/systm.h>
47cd2fe4e6SAttilio Rao #include <sys/kdb.h>
480453ade5SMateusz Guzik #include <sys/kernel.h>
496281b30aSJason Evans #include <sys/ktr.h>
5019284646SJohn Baldwin #include <sys/lock.h>
516281b30aSJason Evans #include <sys/mutex.h>
52d272fe53SJohn Baldwin #include <sys/proc.h>
532cba8dd3SJohn Baldwin #include <sys/sched.h>
544e7f640dSJohn Baldwin #include <sys/sleepqueue.h>
556281b30aSJason Evans #include <sys/sx.h>
561ada9041SMateusz Guzik #include <sys/smp.h>
57e31d0833SAttilio Rao #include <sys/sysctl.h>
584e7f640dSJohn Baldwin 
59e31d0833SAttilio Rao #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
604e7f640dSJohn Baldwin #include <machine/cpu.h>
614e7f640dSJohn Baldwin #endif
626281b30aSJason Evans 
63462a7addSJohn Baldwin #ifdef DDB
64d272fe53SJohn Baldwin #include <ddb/ddb.h>
654e7f640dSJohn Baldwin #endif
66d272fe53SJohn Baldwin 
671ae1c2a3SAttilio Rao #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
681ae1c2a3SAttilio Rao #define	ADAPTIVE_SX
694e7f640dSJohn Baldwin #endif
704e7f640dSJohn Baldwin 
71f5f9340bSFabien Thomas #ifdef HWPMC_HOOKS
72f5f9340bSFabien Thomas #include <sys/pmckern.h>
73f5f9340bSFabien Thomas PMC_SOFT_DECLARE( , , lock, failed);
74f5f9340bSFabien Thomas #endif
75f5f9340bSFabien Thomas 
764e7f640dSJohn Baldwin /* Handy macros for sleep queues. */
774e7f640dSJohn Baldwin #define	SQ_EXCLUSIVE_QUEUE	0
784e7f640dSJohn Baldwin #define	SQ_SHARED_QUEUE		1
794e7f640dSJohn Baldwin 
804e7f640dSJohn Baldwin /*
814e7f640dSJohn Baldwin  * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file.  We
824e7f640dSJohn Baldwin  * drop Giant anytime we have to sleep or if we adaptively spin.
834e7f640dSJohn Baldwin  */
844e7f640dSJohn Baldwin #define	GIANT_DECLARE							\
854e7f640dSJohn Baldwin 	int _giantcnt = 0;						\
864e7f640dSJohn Baldwin 	WITNESS_SAVE_DECL(Giant)					\
874e7f640dSJohn Baldwin 
88e41d6166SMateusz Guzik #define	GIANT_SAVE(work) do {						\
89fb106123SMateusz Guzik 	if (__predict_false(mtx_owned(&Giant))) {			\
90e41d6166SMateusz Guzik 		work++;							\
914e7f640dSJohn Baldwin 		WITNESS_SAVE(&Giant.lock_object, Giant);		\
924e7f640dSJohn Baldwin 		while (mtx_owned(&Giant)) {				\
934e7f640dSJohn Baldwin 			_giantcnt++;					\
944e7f640dSJohn Baldwin 			mtx_unlock(&Giant);				\
954e7f640dSJohn Baldwin 		}							\
964e7f640dSJohn Baldwin 	}								\
974e7f640dSJohn Baldwin } while (0)
984e7f640dSJohn Baldwin 
994e7f640dSJohn Baldwin #define GIANT_RESTORE() do {						\
1004e7f640dSJohn Baldwin 	if (_giantcnt > 0) {						\
1014e7f640dSJohn Baldwin 		mtx_assert(&Giant, MA_NOTOWNED);			\
1024e7f640dSJohn Baldwin 		while (_giantcnt--)					\
1034e7f640dSJohn Baldwin 			mtx_lock(&Giant);				\
1044e7f640dSJohn Baldwin 		WITNESS_RESTORE(&Giant.lock_object, Giant);		\
1054e7f640dSJohn Baldwin 	}								\
1064e7f640dSJohn Baldwin } while (0)
1074e7f640dSJohn Baldwin 
1084e7f640dSJohn Baldwin /*
109da7d0d1eSJohn Baldwin  * Returns true if an exclusive lock is recursed.  It assumes
110da7d0d1eSJohn Baldwin  * curthread currently has an exclusive lock.
1114e7f640dSJohn Baldwin  */
1124e7f640dSJohn Baldwin #define	sx_recursed(sx)		((sx)->sx_recurse != 0)
1134e7f640dSJohn Baldwin 
114d576deedSPawel Jakub Dawidek static void	assert_sx(const struct lock_object *lock, int what);
1154e7f640dSJohn Baldwin #ifdef DDB
116d576deedSPawel Jakub Dawidek static void	db_show_sx(const struct lock_object *lock);
117d272fe53SJohn Baldwin #endif
1187faf4d90SDavide Italiano static void	lock_sx(struct lock_object *lock, uintptr_t how);
119a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
120d576deedSPawel Jakub Dawidek static int	owner_sx(const struct lock_object *lock, struct thread **owner);
121a5aedd68SStacey Son #endif
1227faf4d90SDavide Italiano static uintptr_t unlock_sx(struct lock_object *lock);
123d272fe53SJohn Baldwin 
12419284646SJohn Baldwin struct lock_class lock_class_sx = {
125ae8dde30SJohn Baldwin 	.lc_name = "sx",
126ae8dde30SJohn Baldwin 	.lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
127f9721b43SAttilio Rao 	.lc_assert = assert_sx,
128d272fe53SJohn Baldwin #ifdef DDB
129ae8dde30SJohn Baldwin 	.lc_ddb_show = db_show_sx,
130d272fe53SJohn Baldwin #endif
1316e21afd4SJohn Baldwin 	.lc_lock = lock_sx,
1326e21afd4SJohn Baldwin 	.lc_unlock = unlock_sx,
133a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
134a5aedd68SStacey Son 	.lc_owner = owner_sx,
135a5aedd68SStacey Son #endif
13619284646SJohn Baldwin };
13719284646SJohn Baldwin 
138781a35dfSJohn Baldwin #ifndef INVARIANTS
139781a35dfSJohn Baldwin #define	_sx_assert(sx, what, file, line)
140781a35dfSJohn Baldwin #endif
141781a35dfSJohn Baldwin 
1421ae1c2a3SAttilio Rao #ifdef ADAPTIVE_SX
1432e77cad1SMateusz Guzik #ifdef SX_CUSTOM_BACKOFF
1446b8dd26eSMateusz Guzik static u_short __read_frequently asx_retries;
1456b8dd26eSMateusz Guzik static u_short __read_frequently asx_loops;
1467029da5cSPawel Biernacki static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
1477029da5cSPawel Biernacki     "sxlock debugging");
1486b8dd26eSMateusz Guzik SYSCTL_U16(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
1496b8dd26eSMateusz Guzik SYSCTL_U16(_debug_sx, OID_AUTO, loops, CTLFLAG_RW, &asx_loops, 0, "");
1501ada9041SMateusz Guzik 
151574adb65SMateusz Guzik static struct lock_delay_config __read_frequently sx_delay;
1521ada9041SMateusz Guzik 
1536b8dd26eSMateusz Guzik SYSCTL_U16(_debug_sx, OID_AUTO, delay_base, CTLFLAG_RW, &sx_delay.base,
1541ada9041SMateusz Guzik     0, "");
1556b8dd26eSMateusz Guzik SYSCTL_U16(_debug_sx, OID_AUTO, delay_max, CTLFLAG_RW, &sx_delay.max,
1561ada9041SMateusz Guzik     0, "");
1571ada9041SMateusz Guzik 
158e0e259a8SMateusz Guzik static void
159e0e259a8SMateusz Guzik sx_lock_delay_init(void *arg __unused)
160e0e259a8SMateusz Guzik {
161e0e259a8SMateusz Guzik 
162e0e259a8SMateusz Guzik 	lock_delay_default_init(&sx_delay);
163e0e259a8SMateusz Guzik 	asx_retries = 10;
164e0e259a8SMateusz Guzik 	asx_loops = max(10000, sx_delay.max);
165e0e259a8SMateusz Guzik }
166e0e259a8SMateusz Guzik LOCK_DELAY_SYSINIT(sx_lock_delay_init);
1672e77cad1SMateusz Guzik #else
1682e77cad1SMateusz Guzik #define sx_delay	locks_delay
1692e77cad1SMateusz Guzik #define asx_retries	locks_delay_retries
1702e77cad1SMateusz Guzik #define asx_loops	locks_delay_loops
1712e77cad1SMateusz Guzik #endif
1721ae1c2a3SAttilio Rao #endif
1731ae1c2a3SAttilio Rao 
1746281b30aSJason Evans void
175d576deedSPawel Jakub Dawidek assert_sx(const struct lock_object *lock, int what)
176f9721b43SAttilio Rao {
177f9721b43SAttilio Rao 
178d576deedSPawel Jakub Dawidek 	sx_assert((const struct sx *)lock, what);
179f9721b43SAttilio Rao }
180f9721b43SAttilio Rao 
181f9721b43SAttilio Rao void
1827faf4d90SDavide Italiano lock_sx(struct lock_object *lock, uintptr_t how)
1836e21afd4SJohn Baldwin {
1846e21afd4SJohn Baldwin 	struct sx *sx;
1856e21afd4SJohn Baldwin 
1866e21afd4SJohn Baldwin 	sx = (struct sx *)lock;
1876e21afd4SJohn Baldwin 	if (how)
1886e21afd4SJohn Baldwin 		sx_slock(sx);
189cf6b879fSDavide Italiano 	else
190cf6b879fSDavide Italiano 		sx_xlock(sx);
1916e21afd4SJohn Baldwin }
1926e21afd4SJohn Baldwin 
1937faf4d90SDavide Italiano uintptr_t
1946e21afd4SJohn Baldwin unlock_sx(struct lock_object *lock)
1956e21afd4SJohn Baldwin {
1966e21afd4SJohn Baldwin 	struct sx *sx;
1976e21afd4SJohn Baldwin 
1986e21afd4SJohn Baldwin 	sx = (struct sx *)lock;
1997ec137e5SJohn Baldwin 	sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
2006e21afd4SJohn Baldwin 	if (sx_xlocked(sx)) {
2016e21afd4SJohn Baldwin 		sx_xunlock(sx);
202cf6b879fSDavide Italiano 		return (0);
2036e21afd4SJohn Baldwin 	} else {
2046e21afd4SJohn Baldwin 		sx_sunlock(sx);
205cf6b879fSDavide Italiano 		return (1);
2066e21afd4SJohn Baldwin 	}
2076e21afd4SJohn Baldwin }
2086e21afd4SJohn Baldwin 
209a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
210a5aedd68SStacey Son int
211d576deedSPawel Jakub Dawidek owner_sx(const struct lock_object *lock, struct thread **owner)
212a5aedd68SStacey Son {
213c365a293SMark Johnston 	const struct sx *sx;
214c365a293SMark Johnston 	uintptr_t x;
215a5aedd68SStacey Son 
216c365a293SMark Johnston 	sx = (const struct sx *)lock;
217c365a293SMark Johnston 	x = sx->sx_lock;
218c365a293SMark Johnston 	*owner = NULL;
219a5aedd68SStacey Son 	return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
220c365a293SMark Johnston 	    ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
221a5aedd68SStacey Son }
222a5aedd68SStacey Son #endif
223a5aedd68SStacey Son 
2246e21afd4SJohn Baldwin void
225c27b5699SAndrew R. Reiter sx_sysinit(void *arg)
226c27b5699SAndrew R. Reiter {
227c27b5699SAndrew R. Reiter 	struct sx_args *sargs = arg;
228c27b5699SAndrew R. Reiter 
229e4cd31ddSJeff Roberson 	sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
230c27b5699SAndrew R. Reiter }
231c27b5699SAndrew R. Reiter 
232c27b5699SAndrew R. Reiter void
2334e7f640dSJohn Baldwin sx_init_flags(struct sx *sx, const char *description, int opts)
2346281b30aSJason Evans {
2354e7f640dSJohn Baldwin 	int flags;
2366281b30aSJason Evans 
237b0d67325SJohn Baldwin 	MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
238f26db694SMateusz Guzik 	    SX_NOPROFILE | SX_NEW)) == 0);
239353998acSAttilio Rao 	ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
240353998acSAttilio Rao 	    ("%s: sx_lock not aligned for %s: %p", __func__, description,
241353998acSAttilio Rao 	    &sx->sx_lock));
242b0d67325SJohn Baldwin 
243f0830182SAttilio Rao 	flags = LO_SLEEPABLE | LO_UPGRADABLE;
2444e7f640dSJohn Baldwin 	if (opts & SX_DUPOK)
2454e7f640dSJohn Baldwin 		flags |= LO_DUPOK;
2464e7f640dSJohn Baldwin 	if (opts & SX_NOPROFILE)
2474e7f640dSJohn Baldwin 		flags |= LO_NOPROFILE;
2484e7f640dSJohn Baldwin 	if (!(opts & SX_NOWITNESS))
2494e7f640dSJohn Baldwin 		flags |= LO_WITNESS;
250f0830182SAttilio Rao 	if (opts & SX_RECURSE)
251f0830182SAttilio Rao 		flags |= LO_RECURSABLE;
2524e7f640dSJohn Baldwin 	if (opts & SX_QUIET)
2534e7f640dSJohn Baldwin 		flags |= LO_QUIET;
254fd07ddcfSDmitry Chagin 	if (opts & SX_NEW)
255fd07ddcfSDmitry Chagin 		flags |= LO_NEW;
2564e7f640dSJohn Baldwin 
257b5fb43e5SJohn Baldwin 	lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
2584e7f640dSJohn Baldwin 	sx->sx_lock = SX_LOCK_UNLOCKED;
2594e7f640dSJohn Baldwin 	sx->sx_recurse = 0;
2606281b30aSJason Evans }
2616281b30aSJason Evans 
2626281b30aSJason Evans void
2636281b30aSJason Evans sx_destroy(struct sx *sx)
2646281b30aSJason Evans {
2656281b30aSJason Evans 
2664e7f640dSJohn Baldwin 	KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
2674e7f640dSJohn Baldwin 	KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
2680026c92cSJohn Baldwin 	sx->sx_lock = SX_LOCK_DESTROYED;
269aa89d8cdSJohn Baldwin 	lock_destroy(&sx->lock_object);
2706281b30aSJason Evans }
2716281b30aSJason Evans 
272f9819486SAttilio Rao int
273013c0b49SMateusz Guzik sx_try_slock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
2745f36700aSJohn Baldwin {
2754e7f640dSJohn Baldwin 	uintptr_t x;
2765f36700aSJohn Baldwin 
27735370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
27835370593SAndriy Gapon 		return (1);
27935370593SAndriy Gapon 
280cd2fe4e6SAttilio Rao 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
281*a52a51a2SJohn Baldwin 	    ("sx_try_slock() by idle thread %p on sx %p @ %s:%d",
282*a52a51a2SJohn Baldwin 	    curthread, sx, file, line));
283e3ae0dfeSAttilio Rao 
2844e7f640dSJohn Baldwin 	x = sx->sx_lock;
2855c5df0d9SMateusz Guzik 	for (;;) {
2860026c92cSJohn Baldwin 		KASSERT(x != SX_LOCK_DESTROYED,
2870026c92cSJohn Baldwin 		    ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
288764a938bSPawel Jakub Dawidek 		if (!(x & SX_LOCK_SHARED))
289764a938bSPawel Jakub Dawidek 			break;
2905c5df0d9SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, x + SX_ONE_SHARER)) {
291aa89d8cdSJohn Baldwin 			LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
292aa89d8cdSJohn Baldwin 			WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
293de2c95ccSMark Johnston 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
294de2c95ccSMark Johnston 			    sx, 0, 0, file, line, LOCKSTAT_READER);
295ce1c953eSMark Johnston 			TD_LOCKS_INC(curthread);
2962466d12bSMateusz Guzik 			curthread->td_sx_slocks++;
2975f36700aSJohn Baldwin 			return (1);
2985f36700aSJohn Baldwin 		}
299764a938bSPawel Jakub Dawidek 	}
3004e7f640dSJohn Baldwin 
3014e7f640dSJohn Baldwin 	LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
3024e7f640dSJohn Baldwin 	return (0);
3035f36700aSJohn Baldwin }
3045f36700aSJohn Baldwin 
305f9819486SAttilio Rao int
306013c0b49SMateusz Guzik sx_try_slock_(struct sx *sx, const char *file, int line)
307013c0b49SMateusz Guzik {
308013c0b49SMateusz Guzik 
309013c0b49SMateusz Guzik 	return (sx_try_slock_int(sx LOCK_FILE_LINE_ARG));
310013c0b49SMateusz Guzik }
311013c0b49SMateusz Guzik 
312013c0b49SMateusz Guzik int
313f9819486SAttilio Rao _sx_xlock(struct sx *sx, int opts, const char *file, int line)
3146281b30aSJason Evans {
3156ebb77b6SMateusz Guzik 	uintptr_t tid, x;
316f9819486SAttilio Rao 	int error = 0;
3176281b30aSJason Evans 
318704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
319704cb42fSMark Johnston 	    !TD_IS_IDLETHREAD(curthread),
320*a52a51a2SJohn Baldwin 	    ("sx_xlock() by idle thread %p on sx %p @ %s:%d",
321*a52a51a2SJohn Baldwin 	    curthread, sx, file, line));
3220026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
3230026c92cSJohn Baldwin 	    ("sx_xlock() of destroyed sx @ %s:%d", file, line));
324aa89d8cdSJohn Baldwin 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
32541313430SJohn Baldwin 	    line, NULL);
3266ebb77b6SMateusz Guzik 	tid = (uintptr_t)curthread;
3276ebb77b6SMateusz Guzik 	x = SX_LOCK_UNLOCKED;
3286ebb77b6SMateusz Guzik 	if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
329013c0b49SMateusz Guzik 		error = _sx_xlock_hard(sx, x, opts LOCK_FILE_LINE_ARG);
3306ebb77b6SMateusz Guzik 	else
3316ebb77b6SMateusz Guzik 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
3326ebb77b6SMateusz Guzik 		    0, 0, file, line, LOCKSTAT_WRITER);
333f9819486SAttilio Rao 	if (!error) {
334f9819486SAttilio Rao 		LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
335f9819486SAttilio Rao 		    file, line);
336aa89d8cdSJohn Baldwin 		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
337ce1c953eSMark Johnston 		TD_LOCKS_INC(curthread);
3386281b30aSJason Evans 	}
3396281b30aSJason Evans 
340f9819486SAttilio Rao 	return (error);
341f9819486SAttilio Rao }
342f9819486SAttilio Rao 
3435f36700aSJohn Baldwin int
344013c0b49SMateusz Guzik sx_try_xlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
3455f36700aSJohn Baldwin {
3465c5df0d9SMateusz Guzik 	struct thread *td;
3475c5df0d9SMateusz Guzik 	uintptr_t tid, x;
3484e7f640dSJohn Baldwin 	int rval;
3495c5df0d9SMateusz Guzik 	bool recursed;
3505f36700aSJohn Baldwin 
3515c5df0d9SMateusz Guzik 	td = curthread;
3525c5df0d9SMateusz Guzik 	tid = (uintptr_t)td;
3536b353101SOlivier Certner 	if (SCHEDULER_STOPPED())
35435370593SAndriy Gapon 		return (1);
35535370593SAndriy Gapon 
356704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
357*a52a51a2SJohn Baldwin 	    ("sx_try_xlock() by idle thread %p on sx %p @ %s:%d",
358*a52a51a2SJohn Baldwin 	    curthread, sx, file, line));
3590026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
3600026c92cSJohn Baldwin 	    ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
3614e7f640dSJohn Baldwin 
3625c5df0d9SMateusz Guzik 	rval = 1;
3635c5df0d9SMateusz Guzik 	recursed = false;
3645c5df0d9SMateusz Guzik 	x = SX_LOCK_UNLOCKED;
365b247fd39SMateusz Guzik 	for (;;) {
366b247fd39SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
367b247fd39SMateusz Guzik 			break;
368b247fd39SMateusz Guzik 		if (x == SX_LOCK_UNLOCKED)
369b247fd39SMateusz Guzik 			continue;
3705c5df0d9SMateusz Guzik 		if (x == tid && (sx->lock_object.lo_flags & LO_RECURSABLE)) {
3714e7f640dSJohn Baldwin 			sx->sx_recurse++;
3724e7f640dSJohn Baldwin 			atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
373b247fd39SMateusz Guzik 			break;
3745c5df0d9SMateusz Guzik 		}
375b247fd39SMateusz Guzik 		rval = 0;
376b247fd39SMateusz Guzik 		break;
3775c5df0d9SMateusz Guzik 	}
3785c5df0d9SMateusz Guzik 
3794e7f640dSJohn Baldwin 	LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
3804e7f640dSJohn Baldwin 	if (rval) {
3814e7f640dSJohn Baldwin 		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
3824e7f640dSJohn Baldwin 		    file, line);
3835c5df0d9SMateusz Guzik 		if (!recursed)
384de2c95ccSMark Johnston 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
385de2c95ccSMark Johnston 			    sx, 0, 0, file, line, LOCKSTAT_WRITER);
386ce1c953eSMark Johnston 		TD_LOCKS_INC(curthread);
3875f36700aSJohn Baldwin 	}
3884e7f640dSJohn Baldwin 
3894e7f640dSJohn Baldwin 	return (rval);
3905f36700aSJohn Baldwin }
3915f36700aSJohn Baldwin 
392013c0b49SMateusz Guzik int
393013c0b49SMateusz Guzik sx_try_xlock_(struct sx *sx, const char *file, int line)
394013c0b49SMateusz Guzik {
395013c0b49SMateusz Guzik 
396013c0b49SMateusz Guzik 	return (sx_try_xlock_int(sx LOCK_FILE_LINE_ARG));
397013c0b49SMateusz Guzik }
398013c0b49SMateusz Guzik 
3996281b30aSJason Evans void
40019284646SJohn Baldwin _sx_xunlock(struct sx *sx, const char *file, int line)
4016281b30aSJason Evans {
4026281b30aSJason Evans 
4030026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
4040026c92cSJohn Baldwin 	    ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
4057ec137e5SJohn Baldwin 	_sx_assert(sx, SA_XLOCKED, file, line);
406aa89d8cdSJohn Baldwin 	WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
4074e7f640dSJohn Baldwin 	LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
4084e7f640dSJohn Baldwin 	    line);
4090108a980SMateusz Guzik #if LOCK_DEBUG > 0
4106ebb77b6SMateusz Guzik 	_sx_xunlock_hard(sx, (uintptr_t)curthread, file, line);
411ffd5c94cSMateusz Guzik #else
412ffd5c94cSMateusz Guzik 	__sx_xunlock(sx, curthread, file, line);
413ffd5c94cSMateusz Guzik #endif
414ce1c953eSMark Johnston 	TD_LOCKS_DEC(curthread);
4156281b30aSJason Evans }
416d55229b7SJason Evans 
4174e7f640dSJohn Baldwin /*
4184e7f640dSJohn Baldwin  * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
4194e7f640dSJohn Baldwin  * This will only succeed if this thread holds a single shared lock.
4204e7f640dSJohn Baldwin  * Return 1 if if the upgrade succeed, 0 otherwise.
4214e7f640dSJohn Baldwin  */
422d55229b7SJason Evans int
423013c0b49SMateusz Guzik sx_try_upgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
424d55229b7SJason Evans {
4254e7f640dSJohn Baldwin 	uintptr_t x;
426a8e747c5SMateusz Guzik 	uintptr_t waiters;
4274e7f640dSJohn Baldwin 	int success;
428d55229b7SJason Evans 
42935370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
43035370593SAndriy Gapon 		return (1);
43135370593SAndriy Gapon 
4320026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
4330026c92cSJohn Baldwin 	    ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
4347ec137e5SJohn Baldwin 	_sx_assert(sx, SA_SLOCKED, file, line);
435d55229b7SJason Evans 
4364e7f640dSJohn Baldwin 	/*
4374e7f640dSJohn Baldwin 	 * Try to switch from one shared lock to an exclusive lock.  We need
4384e7f640dSJohn Baldwin 	 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
4394e7f640dSJohn Baldwin 	 * we will wake up the exclusive waiters when we drop the lock.
4404e7f640dSJohn Baldwin 	 */
441a8e747c5SMateusz Guzik 	success = 0;
442a8e747c5SMateusz Guzik 	x = SX_READ_VALUE(sx);
443a8e747c5SMateusz Guzik 	for (;;) {
444a8e747c5SMateusz Guzik 		if (SX_SHARERS(x) > 1)
445a8e747c5SMateusz Guzik 			break;
4462466d12bSMateusz Guzik 		waiters = (x & SX_LOCK_WAITERS);
447a8e747c5SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
448a8e747c5SMateusz Guzik 		    (uintptr_t)curthread | waiters)) {
449a8e747c5SMateusz Guzik 			success = 1;
450a8e747c5SMateusz Guzik 			break;
451a8e747c5SMateusz Guzik 		}
452a8e747c5SMateusz Guzik 	}
4534e7f640dSJohn Baldwin 	LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
454a5aedd68SStacey Son 	if (success) {
4552466d12bSMateusz Guzik 		curthread->td_sx_slocks--;
456aa89d8cdSJohn Baldwin 		WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
457b0b7cb50SJohn Baldwin 		    file, line);
45832cd0147SMark Johnston 		LOCKSTAT_RECORD0(sx__upgrade, sx);
459a5aedd68SStacey Son 	}
4604e7f640dSJohn Baldwin 	return (success);
461d55229b7SJason Evans }
462d55229b7SJason Evans 
463013c0b49SMateusz Guzik int
464013c0b49SMateusz Guzik sx_try_upgrade_(struct sx *sx, const char *file, int line)
465013c0b49SMateusz Guzik {
466013c0b49SMateusz Guzik 
467013c0b49SMateusz Guzik 	return (sx_try_upgrade_int(sx LOCK_FILE_LINE_ARG));
468013c0b49SMateusz Guzik }
469013c0b49SMateusz Guzik 
4704e7f640dSJohn Baldwin /*
4714e7f640dSJohn Baldwin  * Downgrade an unrecursed exclusive lock into a single shared lock.
4724e7f640dSJohn Baldwin  */
473d55229b7SJason Evans void
474013c0b49SMateusz Guzik sx_downgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
475d55229b7SJason Evans {
4764e7f640dSJohn Baldwin 	uintptr_t x;
477d55229b7SJason Evans 
47835370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
47935370593SAndriy Gapon 		return;
48035370593SAndriy Gapon 
4810026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
4820026c92cSJohn Baldwin 	    ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
4837ec137e5SJohn Baldwin 	_sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
4844e7f640dSJohn Baldwin #ifndef INVARIANTS
4854e7f640dSJohn Baldwin 	if (sx_recursed(sx))
4864e7f640dSJohn Baldwin 		panic("downgrade of a recursed lock");
4874e7f640dSJohn Baldwin #endif
488d55229b7SJason Evans 
489aa89d8cdSJohn Baldwin 	WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
490d55229b7SJason Evans 
4914e7f640dSJohn Baldwin 	/*
4924e7f640dSJohn Baldwin 	 * Try to switch from an exclusive lock with no shared waiters
4934e7f640dSJohn Baldwin 	 * to one sharer with no shared waiters.  If there are
4944e7f640dSJohn Baldwin 	 * exclusive waiters, we don't need to lock the sleep queue so
4954e7f640dSJohn Baldwin 	 * long as we preserve the flag.  We do one quick try and if
4964e7f640dSJohn Baldwin 	 * that fails we grab the sleepq lock to keep the flags from
4974e7f640dSJohn Baldwin 	 * changing and do it the slow way.
4984e7f640dSJohn Baldwin 	 *
4994e7f640dSJohn Baldwin 	 * We have to lock the sleep queue if there are shared waiters
5004e7f640dSJohn Baldwin 	 * so we can wake them up.
5014e7f640dSJohn Baldwin 	 */
5024e7f640dSJohn Baldwin 	x = sx->sx_lock;
5034e7f640dSJohn Baldwin 	if (!(x & SX_LOCK_SHARED_WAITERS) &&
5044e7f640dSJohn Baldwin 	    atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
50526d94f99SMark Johnston 	    (x & SX_LOCK_EXCLUSIVE_WAITERS)))
50626d94f99SMark Johnston 		goto out;
5074e7f640dSJohn Baldwin 
5084e7f640dSJohn Baldwin 	/*
5094e7f640dSJohn Baldwin 	 * Lock the sleep queue so we can read the waiters bits
5104e7f640dSJohn Baldwin 	 * without any races and wakeup any shared waiters.
5114e7f640dSJohn Baldwin 	 */
5124e7f640dSJohn Baldwin 	sleepq_lock(&sx->lock_object);
5134e7f640dSJohn Baldwin 
5144e7f640dSJohn Baldwin 	/*
5154e7f640dSJohn Baldwin 	 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
5164e7f640dSJohn Baldwin 	 * shared lock.  If there are any shared waiters, wake them up.
5174e7f640dSJohn Baldwin 	 */
5184e7f640dSJohn Baldwin 	x = sx->sx_lock;
5194e7f640dSJohn Baldwin 	atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
5204e7f640dSJohn Baldwin 	    (x & SX_LOCK_EXCLUSIVE_WAITERS));
5214e7f640dSJohn Baldwin 	if (x & SX_LOCK_SHARED_WAITERS)
52201518f5eSMark Johnston 		sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
52301518f5eSMark Johnston 		    SQ_SHARED_QUEUE);
5244e7f640dSJohn Baldwin 	sleepq_release(&sx->lock_object);
525d55229b7SJason Evans 
52626d94f99SMark Johnston out:
5272466d12bSMateusz Guzik 	curthread->td_sx_slocks++;
52826d94f99SMark Johnston 	LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
52926d94f99SMark Johnston 	LOCKSTAT_RECORD0(sx__downgrade, sx);
5304e7f640dSJohn Baldwin }
531d55229b7SJason Evans 
532013c0b49SMateusz Guzik void
533013c0b49SMateusz Guzik sx_downgrade_(struct sx *sx, const char *file, int line)
534013c0b49SMateusz Guzik {
535013c0b49SMateusz Guzik 
536013c0b49SMateusz Guzik 	sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
537013c0b49SMateusz Guzik }
538013c0b49SMateusz Guzik 
5392466d12bSMateusz Guzik #ifdef	ADAPTIVE_SX
5402466d12bSMateusz Guzik static inline void
5412466d12bSMateusz Guzik sx_drop_critical(uintptr_t x, bool *in_critical, int *extra_work)
5422466d12bSMateusz Guzik {
5432466d12bSMateusz Guzik 
5442466d12bSMateusz Guzik 	if (x & SX_LOCK_WRITE_SPINNER)
5452466d12bSMateusz Guzik 		return;
5462466d12bSMateusz Guzik 	if (*in_critical) {
5472466d12bSMateusz Guzik 		critical_exit();
5482466d12bSMateusz Guzik 		*in_critical = false;
5492466d12bSMateusz Guzik 		(*extra_work)--;
5502466d12bSMateusz Guzik 	}
5512466d12bSMateusz Guzik }
5522466d12bSMateusz Guzik #else
5532466d12bSMateusz Guzik #define sx_drop_critical(x, in_critical, extra_work) do { } while (0)
5542466d12bSMateusz Guzik #endif
5552466d12bSMateusz Guzik 
5564e7f640dSJohn Baldwin /*
5574e7f640dSJohn Baldwin  * This function represents the so-called 'hard case' for sx_xlock
5584e7f640dSJohn Baldwin  * operation.  All 'easy case' failures are redirected to this.  Note
5594e7f640dSJohn Baldwin  * that ideally this would be a static function, but it needs to be
5604e7f640dSJohn Baldwin  * accessible from at least sx.h.
5614e7f640dSJohn Baldwin  */
562f9819486SAttilio Rao int
563013c0b49SMateusz Guzik _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
5644e7f640dSJohn Baldwin {
5654e7f640dSJohn Baldwin 	GIANT_DECLARE;
5662466d12bSMateusz Guzik 	uintptr_t tid, setx;
5674e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
568094c148bSMateusz Guzik 	struct thread *owner;
569d07e22cdSMateusz Guzik 	u_int i, n, spintries = 0;
5701dce110fSMatt Macy 	enum { READERS, WRITER } sleep_reason = READERS;
5712466d12bSMateusz Guzik 	bool in_critical = false;
5724e7f640dSJohn Baldwin #endif
5731723a064SJeff Roberson #ifdef LOCK_PROFILING
5741723a064SJeff Roberson 	uint64_t waittime = 0;
5751723a064SJeff Roberson 	int contested = 0;
5761723a064SJeff Roberson #endif
5771723a064SJeff Roberson 	int error = 0;
57804126895SMateusz Guzik #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
5791ada9041SMateusz Guzik 	struct lock_delay_arg lda;
5801ada9041SMateusz Guzik #endif
581a5aedd68SStacey Son #ifdef	KDTRACE_HOOKS
58261852185SMateusz Guzik 	u_int sleep_cnt = 0;
583a5aedd68SStacey Son 	int64_t sleep_time = 0;
584076dd8ebSAndriy Gapon 	int64_t all_time = 0;
585928864a9SKristof Provost 	uintptr_t state = 0;
586a5aedd68SStacey Son #endif
587e41d6166SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
5882466d12bSMateusz Guzik 	int doing_lockprof = 0;
589e41d6166SMateusz Guzik #endif
590284194f1SMateusz Guzik 	int extra_work = 0;
5914e7f640dSJohn Baldwin 
592013c0b49SMateusz Guzik 	tid = (uintptr_t)curthread;
59309bdec20SMateusz Guzik 
59409bdec20SMateusz Guzik #ifdef KDTRACE_HOOKS
59509bdec20SMateusz Guzik 	if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
59609bdec20SMateusz Guzik 		while (x == SX_LOCK_UNLOCKED) {
59709bdec20SMateusz Guzik 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
59809bdec20SMateusz Guzik 				goto out_lockstat;
59909bdec20SMateusz Guzik 		}
60009bdec20SMateusz Guzik 		extra_work = 1;
6012466d12bSMateusz Guzik 		doing_lockprof = 1;
60209bdec20SMateusz Guzik 		all_time -= lockstat_nsecs(&sx->lock_object);
60309bdec20SMateusz Guzik 	}
604928864a9SKristof Provost 	state = x;
60509bdec20SMateusz Guzik #endif
60609bdec20SMateusz Guzik #ifdef LOCK_PROFILING
60709bdec20SMateusz Guzik 	extra_work = 1;
6082466d12bSMateusz Guzik 	doing_lockprof = 1;
60909bdec20SMateusz Guzik #endif
61009bdec20SMateusz Guzik 
61135370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
61235370593SAndriy Gapon 		return (0);
61335370593SAndriy Gapon 
614c1aaf63cSMateusz Guzik 	if (__predict_false(x == SX_LOCK_UNLOCKED))
615c1aaf63cSMateusz Guzik 		x = SX_READ_VALUE(sx);
616c1aaf63cSMateusz Guzik 
6174e7f640dSJohn Baldwin 	/* If we already hold an exclusive lock, then recurse. */
618c5f61e6fSMateusz Guzik 	if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
619f0830182SAttilio Rao 		KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
620*a52a51a2SJohn Baldwin 	    ("_sx_xlock_hard: recursed on non-recursive sx %p @ %s:%d\n",
621*a52a51a2SJohn Baldwin 		    sx, file, line));
6224e7f640dSJohn Baldwin 		sx->sx_recurse++;
6234e7f640dSJohn Baldwin 		atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
6244e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
6254e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
626f9819486SAttilio Rao 		return (0);
6274e7f640dSJohn Baldwin 	}
6284e7f640dSJohn Baldwin 
6294e7f640dSJohn Baldwin 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
6304e7f640dSJohn Baldwin 		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
6314e7f640dSJohn Baldwin 		    sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
6324e7f640dSJohn Baldwin 
633f90d57b8SMateusz Guzik #if defined(ADAPTIVE_SX)
634f90d57b8SMateusz Guzik 	lock_delay_arg_init(&lda, &sx_delay);
635f90d57b8SMateusz Guzik #elif defined(KDTRACE_HOOKS)
636f90d57b8SMateusz Guzik 	lock_delay_arg_init_noadapt(&lda);
637f90d57b8SMateusz Guzik #endif
638f90d57b8SMateusz Guzik 
639ae7d25a4SMateusz Guzik #ifdef HWPMC_HOOKS
640ae7d25a4SMateusz Guzik 	PMC_SOFT_CALL( , , lock, failed);
641ae7d25a4SMateusz Guzik #endif
6426a467cc5SMateusz Guzik 	lock_profile_obtain_lock_failed(&sx->lock_object, false, &contested,
643ae7d25a4SMateusz Guzik 	    &waittime);
644ae7d25a4SMateusz Guzik 
645fb106123SMateusz Guzik #ifndef INVARIANTS
646fb106123SMateusz Guzik 	GIANT_SAVE(extra_work);
647fb106123SMateusz Guzik #endif
648e41d6166SMateusz Guzik 
6497530de77SMateusz Guzik 	THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
6507530de77SMateusz Guzik 
651fc4f686dSMateusz Guzik 	for (;;) {
652c5f61e6fSMateusz Guzik 		if (x == SX_LOCK_UNLOCKED) {
653fa474043SMateusz Guzik 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
654fc4f686dSMateusz Guzik 				break;
655c5f61e6fSMateusz Guzik 			continue;
656c5f61e6fSMateusz Guzik 		}
657fb106123SMateusz Guzik #ifdef INVARIANTS
658fb106123SMateusz Guzik 		GIANT_SAVE(extra_work);
659fb106123SMateusz Guzik #endif
660a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
6611ada9041SMateusz Guzik 		lda.spin_cnt++;
662a5aedd68SStacey Son #endif
6634e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
664befd3e35SMateusz Guzik 		if (x == (SX_LOCK_SHARED | SX_LOCK_WRITE_SPINNER)) {
665befd3e35SMateusz Guzik 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
666befd3e35SMateusz Guzik 				break;
667befd3e35SMateusz Guzik 			continue;
668befd3e35SMateusz Guzik 		}
669befd3e35SMateusz Guzik 
6704e7f640dSJohn Baldwin 		/*
6714e7f640dSJohn Baldwin 		 * If the lock is write locked and the owner is
6724e7f640dSJohn Baldwin 		 * running on another CPU, spin until the owner stops
6734e7f640dSJohn Baldwin 		 * running or the state of the lock changes.
6744e7f640dSJohn Baldwin 		 */
6751ae1c2a3SAttilio Rao 		if ((x & SX_LOCK_SHARED) == 0) {
6762466d12bSMateusz Guzik 			sx_drop_critical(x, &in_critical, &extra_work);
677d94df98cSMateusz Guzik 			sleep_reason = WRITER;
678c5f61e6fSMateusz Guzik 			owner = lv_sx_owner(x);
679d94df98cSMateusz Guzik 			if (!TD_IS_RUNNING(owner))
680d94df98cSMateusz Guzik 				goto sleepq;
6814e7f640dSJohn Baldwin 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
682d94df98cSMateusz Guzik 				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
6834e7f640dSJohn Baldwin 				    __func__, sx, owner);
684d94df98cSMateusz Guzik 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
685d94df98cSMateusz Guzik 			    "spinning", "lockname:\"%s\"",
6862cba8dd3SJohn Baldwin 			    sx->lock_object.lo_name);
687c5f61e6fSMateusz Guzik 			do {
6881ada9041SMateusz Guzik 				lock_delay(&lda);
689c5f61e6fSMateusz Guzik 				x = SX_READ_VALUE(sx);
690c5f61e6fSMateusz Guzik 				owner = lv_sx_owner(x);
691d94df98cSMateusz Guzik 			} while (owner != NULL && TD_IS_RUNNING(owner));
692d94df98cSMateusz Guzik 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
693d94df98cSMateusz Guzik 			    "running");
6944e7f640dSJohn Baldwin 			continue;
695d94df98cSMateusz Guzik 		} else if (SX_SHARERS(x) > 0) {
696d94df98cSMateusz Guzik 			sleep_reason = READERS;
697d94df98cSMateusz Guzik 			if (spintries == asx_retries)
698d94df98cSMateusz Guzik 				goto sleepq;
6992466d12bSMateusz Guzik 			if (!(x & SX_LOCK_WRITE_SPINNER)) {
7002466d12bSMateusz Guzik 				if (!in_critical) {
7012466d12bSMateusz Guzik 					critical_enter();
7022466d12bSMateusz Guzik 					in_critical = true;
7032466d12bSMateusz Guzik 					extra_work++;
7042466d12bSMateusz Guzik 				}
7052466d12bSMateusz Guzik 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
7062466d12bSMateusz Guzik 				    x | SX_LOCK_WRITE_SPINNER)) {
7072466d12bSMateusz Guzik 					critical_exit();
7082466d12bSMateusz Guzik 					in_critical = false;
7092466d12bSMateusz Guzik 					extra_work--;
7102466d12bSMateusz Guzik 					continue;
7112466d12bSMateusz Guzik 				}
7122466d12bSMateusz Guzik 			}
7131ae1c2a3SAttilio Rao 			spintries++;
714d94df98cSMateusz Guzik 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
715d94df98cSMateusz Guzik 			    "spinning", "lockname:\"%s\"",
716d94df98cSMateusz Guzik 			    sx->lock_object.lo_name);
717d07e22cdSMateusz Guzik 			n = SX_SHARERS(x);
7182466d12bSMateusz Guzik 			for (i = 0; i < asx_loops; i += n) {
719d07e22cdSMateusz Guzik 				lock_delay_spin(n);
72020a15d17SMateusz Guzik 				x = SX_READ_VALUE(sx);
7212466d12bSMateusz Guzik 				if (!(x & SX_LOCK_WRITE_SPINNER))
7222466d12bSMateusz Guzik 					break;
7232466d12bSMateusz Guzik 				if (!(x & SX_LOCK_SHARED))
7242466d12bSMateusz Guzik 					break;
7252466d12bSMateusz Guzik 				n = SX_SHARERS(x);
7262466d12bSMateusz Guzik 				if (n == 0)
7271ae1c2a3SAttilio Rao 					break;
7281ae1c2a3SAttilio Rao 			}
72920a15d17SMateusz Guzik #ifdef KDTRACE_HOOKS
73020a15d17SMateusz Guzik 			lda.spin_cnt += i;
73120a15d17SMateusz Guzik #endif
732d94df98cSMateusz Guzik 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
733d94df98cSMateusz Guzik 			    "running");
734efa9f177SMateusz Guzik 			if (i < asx_loops)
7351ae1c2a3SAttilio Rao 				continue;
7361ae1c2a3SAttilio Rao 		}
737fb106123SMateusz Guzik sleepq:
738cde25ed4SMateusz Guzik #endif
7394e7f640dSJohn Baldwin 		sleepq_lock(&sx->lock_object);
740c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
74193118b62SMateusz Guzik retry_sleepq:
7424e7f640dSJohn Baldwin 
7434e7f640dSJohn Baldwin 		/*
7444e7f640dSJohn Baldwin 		 * If the lock was released while spinning on the
7454e7f640dSJohn Baldwin 		 * sleep queue chain lock, try again.
7464e7f640dSJohn Baldwin 		 */
7474e7f640dSJohn Baldwin 		if (x == SX_LOCK_UNLOCKED) {
7484e7f640dSJohn Baldwin 			sleepq_release(&sx->lock_object);
7492466d12bSMateusz Guzik 			sx_drop_critical(x, &in_critical, &extra_work);
7504e7f640dSJohn Baldwin 			continue;
7514e7f640dSJohn Baldwin 		}
7524e7f640dSJohn Baldwin 
7534e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
7544e7f640dSJohn Baldwin 		/*
7554e7f640dSJohn Baldwin 		 * The current lock owner might have started executing
7564e7f640dSJohn Baldwin 		 * on another CPU (or the lock could have changed
7574e7f640dSJohn Baldwin 		 * owners) while we were waiting on the sleep queue
7584e7f640dSJohn Baldwin 		 * chain lock.  If so, drop the sleep queue lock and try
7594e7f640dSJohn Baldwin 		 * again.
7604e7f640dSJohn Baldwin 		 */
76128f1a9e3SMateusz Guzik 		if (!(x & SX_LOCK_SHARED)) {
7624e7f640dSJohn Baldwin 			owner = (struct thread *)SX_OWNER(x);
7634e7f640dSJohn Baldwin 			if (TD_IS_RUNNING(owner)) {
7644e7f640dSJohn Baldwin 				sleepq_release(&sx->lock_object);
7652466d12bSMateusz Guzik 				sx_drop_critical(x, &in_critical,
7662466d12bSMateusz Guzik 				    &extra_work);
7674e7f640dSJohn Baldwin 				continue;
7684e7f640dSJohn Baldwin 			}
769d94df98cSMateusz Guzik 		} else if (SX_SHARERS(x) > 0 && sleep_reason == WRITER) {
77028f1a9e3SMateusz Guzik 			sleepq_release(&sx->lock_object);
7712466d12bSMateusz Guzik 			sx_drop_critical(x, &in_critical, &extra_work);
77228f1a9e3SMateusz Guzik 			continue;
77328f1a9e3SMateusz Guzik 		}
7744e7f640dSJohn Baldwin #endif
7754e7f640dSJohn Baldwin 
7764e7f640dSJohn Baldwin 		/*
7774e7f640dSJohn Baldwin 		 * If an exclusive lock was released with both shared
7784e7f640dSJohn Baldwin 		 * and exclusive waiters and a shared waiter hasn't
7794e7f640dSJohn Baldwin 		 * woken up and acquired the lock yet, sx_lock will be
7804e7f640dSJohn Baldwin 		 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
7814e7f640dSJohn Baldwin 		 * If we see that value, try to acquire it once.  Note
7824e7f640dSJohn Baldwin 		 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
7834e7f640dSJohn Baldwin 		 * as there are other exclusive waiters still.  If we
7844e7f640dSJohn Baldwin 		 * fail, restart the loop.
7854e7f640dSJohn Baldwin 		 */
7862466d12bSMateusz Guzik 		setx = x & (SX_LOCK_WAITERS | SX_LOCK_WRITE_SPINNER);
7872466d12bSMateusz Guzik 		if ((x & ~setx) == SX_LOCK_SHARED) {
7882466d12bSMateusz Guzik 			setx &= ~SX_LOCK_WRITE_SPINNER;
7892466d12bSMateusz Guzik 			if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid | setx))
79093118b62SMateusz Guzik 				goto retry_sleepq;
7914e7f640dSJohn Baldwin 			sleepq_release(&sx->lock_object);
7924e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p claimed by new writer",
7934e7f640dSJohn Baldwin 			    __func__, sx);
7944e7f640dSJohn Baldwin 			break;
7954e7f640dSJohn Baldwin 		}
7964e7f640dSJohn Baldwin 
7972466d12bSMateusz Guzik #ifdef ADAPTIVE_SX
7982466d12bSMateusz Guzik 		/*
7992466d12bSMateusz Guzik 		 * It is possible we set the SX_LOCK_WRITE_SPINNER bit.
8002466d12bSMateusz Guzik 		 * It is an invariant that when the bit is set, there is
8012466d12bSMateusz Guzik 		 * a writer ready to grab the lock. Thus clear the bit since
8022466d12bSMateusz Guzik 		 * we are going to sleep.
8032466d12bSMateusz Guzik 		 */
8042466d12bSMateusz Guzik 		if (in_critical) {
8052466d12bSMateusz Guzik 			if ((x & SX_LOCK_WRITE_SPINNER) ||
8062466d12bSMateusz Guzik 			    !((x & SX_LOCK_EXCLUSIVE_WAITERS))) {
8072466d12bSMateusz Guzik 				setx = x & ~SX_LOCK_WRITE_SPINNER;
8082466d12bSMateusz Guzik 				setx |= SX_LOCK_EXCLUSIVE_WAITERS;
8092466d12bSMateusz Guzik 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
8102466d12bSMateusz Guzik 				    setx)) {
8112466d12bSMateusz Guzik 					goto retry_sleepq;
8122466d12bSMateusz Guzik 				}
8132466d12bSMateusz Guzik 			}
8142466d12bSMateusz Guzik 			critical_exit();
8152466d12bSMateusz Guzik 			in_critical = false;
8162466d12bSMateusz Guzik 		} else {
8172466d12bSMateusz Guzik #endif
8184e7f640dSJohn Baldwin 			/*
8194e7f640dSJohn Baldwin 			 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
8204e7f640dSJohn Baldwin 			 * than loop back and retry.
8214e7f640dSJohn Baldwin 			 */
8224e7f640dSJohn Baldwin 			if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
82393118b62SMateusz Guzik 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
8244e7f640dSJohn Baldwin 				    x | SX_LOCK_EXCLUSIVE_WAITERS)) {
82593118b62SMateusz Guzik 					goto retry_sleepq;
8264e7f640dSJohn Baldwin 				}
8274e7f640dSJohn Baldwin 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
8284e7f640dSJohn Baldwin 					CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
8294e7f640dSJohn Baldwin 					    __func__, sx);
8304e7f640dSJohn Baldwin 			}
8312466d12bSMateusz Guzik #ifdef ADAPTIVE_SX
8322466d12bSMateusz Guzik 		}
8332466d12bSMateusz Guzik #endif
8344e7f640dSJohn Baldwin 
8354e7f640dSJohn Baldwin 		/*
8364e7f640dSJohn Baldwin 		 * Since we have been unable to acquire the exclusive
8374e7f640dSJohn Baldwin 		 * lock and the exclusive waiters flag is set, we have
8384e7f640dSJohn Baldwin 		 * to sleep.
8394e7f640dSJohn Baldwin 		 */
8404e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
8414e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
8424e7f640dSJohn Baldwin 			    __func__, sx);
8434e7f640dSJohn Baldwin 
844a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
845e2b25737SMark Johnston 		sleep_time -= lockstat_nsecs(&sx->lock_object);
846a5aedd68SStacey Son #endif
8474e7f640dSJohn Baldwin 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
848f9819486SAttilio Rao 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
849f9819486SAttilio Rao 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
850c35f527eSMateusz Guzik 		/*
851c35f527eSMateusz Guzik 		 * Hack: this can land in thread_suspend_check which will
852c35f527eSMateusz Guzik 		 * conditionally take a mutex, tripping over an assert if a
853c35f527eSMateusz Guzik 		 * lock we are waiting for is set.
854c35f527eSMateusz Guzik 		 */
855c35f527eSMateusz Guzik 		THREAD_CONTENTION_DONE(&sx->lock_object);
856f9819486SAttilio Rao 		if (!(opts & SX_INTERRUPTIBLE))
857c5aa6b58SJeff Roberson 			sleepq_wait(&sx->lock_object, 0);
858f9819486SAttilio Rao 		else
859c5aa6b58SJeff Roberson 			error = sleepq_wait_sig(&sx->lock_object, 0);
8608bd79453SMateusz Guzik 		THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
861a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
862e2b25737SMark Johnston 		sleep_time += lockstat_nsecs(&sx->lock_object);
863a5aedd68SStacey Son 		sleep_cnt++;
864a5aedd68SStacey Son #endif
865f9819486SAttilio Rao 		if (error) {
866f9819486SAttilio Rao 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
867f9819486SAttilio Rao 				CTR2(KTR_LOCK,
868f9819486SAttilio Rao 			"%s: interruptible sleep by %p suspended by signal",
869f9819486SAttilio Rao 				    __func__, sx);
870f9819486SAttilio Rao 			break;
871f9819486SAttilio Rao 		}
8724e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
8734e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
8744e7f640dSJohn Baldwin 			    __func__, sx);
875c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
8764e7f640dSJohn Baldwin 	}
8777530de77SMateusz Guzik 	THREAD_CONTENTION_DONE(&sx->lock_object);
878e41d6166SMateusz Guzik 	if (__predict_true(!extra_work))
879e41d6166SMateusz Guzik 		return (error);
8802466d12bSMateusz Guzik #ifdef ADAPTIVE_SX
8812466d12bSMateusz Guzik 	if (in_critical)
8822466d12bSMateusz Guzik 		critical_exit();
8832466d12bSMateusz Guzik #endif
884ee252fc9SMateusz Guzik 	GIANT_RESTORE();
8852466d12bSMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
8862466d12bSMateusz Guzik 	if (__predict_true(!doing_lockprof))
8872466d12bSMateusz Guzik 		return (error);
888e41d6166SMateusz Guzik #endif
889076dd8ebSAndriy Gapon #ifdef KDTRACE_HOOKS
890e2b25737SMark Johnston 	all_time += lockstat_nsecs(&sx->lock_object);
891076dd8ebSAndriy Gapon 	if (sleep_time)
89232cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
893076dd8ebSAndriy Gapon 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
894076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
8951ada9041SMateusz Guzik 	if (lda.spin_cnt > sleep_cnt)
89632cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
897076dd8ebSAndriy Gapon 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
898076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
89909bdec20SMateusz Guzik out_lockstat:
900076dd8ebSAndriy Gapon #endif
901f9819486SAttilio Rao 	if (!error)
902de2c95ccSMark Johnston 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
903de2c95ccSMark Johnston 		    contested, waittime, file, line, LOCKSTAT_WRITER);
904f9819486SAttilio Rao 	return (error);
9054e7f640dSJohn Baldwin }
9064e7f640dSJohn Baldwin 
9074e7f640dSJohn Baldwin /*
9084e7f640dSJohn Baldwin  * This function represents the so-called 'hard case' for sx_xunlock
9094e7f640dSJohn Baldwin  * operation.  All 'easy case' failures are redirected to this.  Note
9104e7f640dSJohn Baldwin  * that ideally this would be a static function, but it needs to be
9114e7f640dSJohn Baldwin  * accessible from at least sx.h.
9124e7f640dSJohn Baldwin  */
9134e7f640dSJohn Baldwin void
914b584eb2eSMateusz Guzik _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
9154e7f640dSJohn Baldwin {
916b584eb2eSMateusz Guzik 	uintptr_t tid, setx;
91701518f5eSMark Johnston 	int queue;
9184e7f640dSJohn Baldwin 
91935370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
92035370593SAndriy Gapon 		return;
92135370593SAndriy Gapon 
922b584eb2eSMateusz Guzik 	tid = (uintptr_t)curthread;
9234e7f640dSJohn Baldwin 
924b584eb2eSMateusz Guzik 	if (__predict_false(x == tid))
9253b3cf014SMateusz Guzik 		x = SX_READ_VALUE(sx);
926b584eb2eSMateusz Guzik 
927b584eb2eSMateusz Guzik 	MPASS(!(x & SX_LOCK_SHARED));
928b584eb2eSMateusz Guzik 
929b584eb2eSMateusz Guzik 	if (__predict_false(x & SX_LOCK_RECURSED)) {
9306ebb77b6SMateusz Guzik 		/* The lock is recursed, unrecurse one level. */
9314e7f640dSJohn Baldwin 		if ((--sx->sx_recurse) == 0)
9324e7f640dSJohn Baldwin 			atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
9334e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
9344e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
9354e7f640dSJohn Baldwin 		return;
9364e7f640dSJohn Baldwin 	}
9373b3cf014SMateusz Guzik 
9383b3cf014SMateusz Guzik 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
9393b3cf014SMateusz Guzik 	if (x == tid &&
9403b3cf014SMateusz Guzik 	    atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
9413b3cf014SMateusz Guzik 		return;
9423b3cf014SMateusz Guzik 
9434e7f640dSJohn Baldwin 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
9444e7f640dSJohn Baldwin 		CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
9454e7f640dSJohn Baldwin 
9464e7f640dSJohn Baldwin 	sleepq_lock(&sx->lock_object);
947bc24577cSMateusz Guzik 	x = SX_READ_VALUE(sx);
9482d96bd88SMateusz Guzik 	MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
9494e7f640dSJohn Baldwin 
9504e7f640dSJohn Baldwin 	/*
9514e7f640dSJohn Baldwin 	 * The wake up algorithm here is quite simple and probably not
9524e7f640dSJohn Baldwin 	 * ideal.  It gives precedence to shared waiters if they are
9534e7f640dSJohn Baldwin 	 * present.  For this condition, we have to preserve the
9544e7f640dSJohn Baldwin 	 * state of the exclusive waiters flag.
9552028867dSAttilio Rao 	 * If interruptible sleeps left the shared queue empty avoid a
9562028867dSAttilio Rao 	 * starvation for the threads sleeping on the exclusive queue by giving
9572028867dSAttilio Rao 	 * them precedence and cleaning up the shared waiters bit anyway.
9584e7f640dSJohn Baldwin 	 */
959bc24577cSMateusz Guzik 	setx = SX_LOCK_UNLOCKED;
9604e7f640dSJohn Baldwin 	queue = SQ_SHARED_QUEUE;
9612466d12bSMateusz Guzik 	if ((x & SX_LOCK_EXCLUSIVE_WAITERS) != 0 &&
9622466d12bSMateusz Guzik 	    sleepq_sleepcnt(&sx->lock_object, SQ_EXCLUSIVE_QUEUE) != 0) {
9632466d12bSMateusz Guzik 		queue = SQ_EXCLUSIVE_QUEUE;
9642466d12bSMateusz Guzik 		setx |= (x & SX_LOCK_SHARED_WAITERS);
965bc24577cSMateusz Guzik 	}
966bc24577cSMateusz Guzik 	atomic_store_rel_ptr(&sx->sx_lock, setx);
9674e7f640dSJohn Baldwin 
9684e7f640dSJohn Baldwin 	/* Wake up all the waiters for the specific queue. */
9694e7f640dSJohn Baldwin 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
9704e7f640dSJohn Baldwin 		CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
9714e7f640dSJohn Baldwin 		    __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
9724e7f640dSJohn Baldwin 		    "exclusive");
973bc24577cSMateusz Guzik 
97401518f5eSMark Johnston 	sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0, queue);
975c5aa6b58SJeff Roberson 	sleepq_release(&sx->lock_object);
9764e7f640dSJohn Baldwin }
9774e7f640dSJohn Baldwin 
9783c84b4b3SRyan Libby static __always_inline bool
9792466d12bSMateusz Guzik __sx_can_read(struct thread *td, uintptr_t x, bool fp)
9802466d12bSMateusz Guzik {
9812466d12bSMateusz Guzik 
9822466d12bSMateusz Guzik 	if ((x & (SX_LOCK_SHARED | SX_LOCK_EXCLUSIVE_WAITERS | SX_LOCK_WRITE_SPINNER))
9832466d12bSMateusz Guzik 			== SX_LOCK_SHARED)
9842466d12bSMateusz Guzik 		return (true);
9852466d12bSMateusz Guzik 	if (!fp && td->td_sx_slocks && (x & SX_LOCK_SHARED))
9862466d12bSMateusz Guzik 		return (true);
9872466d12bSMateusz Guzik 	return (false);
9882466d12bSMateusz Guzik }
9892466d12bSMateusz Guzik 
9903c84b4b3SRyan Libby static __always_inline bool
9912466d12bSMateusz Guzik __sx_slock_try(struct sx *sx, struct thread *td, uintptr_t *xp, bool fp
9922466d12bSMateusz Guzik     LOCK_FILE_LINE_ARG_DEF)
993834f70f3SMateusz Guzik {
994834f70f3SMateusz Guzik 
995834f70f3SMateusz Guzik 	/*
996834f70f3SMateusz Guzik 	 * If no other thread has an exclusive lock then try to bump up
997834f70f3SMateusz Guzik 	 * the count of sharers.  Since we have to preserve the state
998834f70f3SMateusz Guzik 	 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
999834f70f3SMateusz Guzik 	 * shared lock loop back and retry.
1000834f70f3SMateusz Guzik 	 */
10012466d12bSMateusz Guzik 	while (__sx_can_read(td, *xp, fp)) {
1002834f70f3SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
1003834f70f3SMateusz Guzik 		    *xp + SX_ONE_SHARER)) {
1004834f70f3SMateusz Guzik 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1005834f70f3SMateusz Guzik 				CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
1006834f70f3SMateusz Guzik 				    __func__, sx, (void *)*xp,
1007834f70f3SMateusz Guzik 				    (void *)(*xp + SX_ONE_SHARER));
10082466d12bSMateusz Guzik 			td->td_sx_slocks++;
1009834f70f3SMateusz Guzik 			return (true);
1010834f70f3SMateusz Guzik 		}
1011834f70f3SMateusz Guzik 	}
1012834f70f3SMateusz Guzik 	return (false);
1013834f70f3SMateusz Guzik }
1014834f70f3SMateusz Guzik 
1015834f70f3SMateusz Guzik static int __noinline
1016013c0b49SMateusz Guzik _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
10174e7f640dSJohn Baldwin {
10184e7f640dSJohn Baldwin 	GIANT_DECLARE;
10192466d12bSMateusz Guzik 	struct thread *td;
10204e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
1021094c148bSMateusz Guzik 	struct thread *owner;
10222466d12bSMateusz Guzik 	u_int i, n, spintries = 0;
10234e7f640dSJohn Baldwin #endif
10241723a064SJeff Roberson #ifdef LOCK_PROFILING
1025c1a6d9faSAttilio Rao 	uint64_t waittime = 0;
1026c1a6d9faSAttilio Rao 	int contested = 0;
10271723a064SJeff Roberson #endif
1028c1a6d9faSAttilio Rao 	int error = 0;
102904126895SMateusz Guzik #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
10301ada9041SMateusz Guzik 	struct lock_delay_arg lda;
10311ada9041SMateusz Guzik #endif
1032a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
103361852185SMateusz Guzik 	u_int sleep_cnt = 0;
1034a5aedd68SStacey Son 	int64_t sleep_time = 0;
1035076dd8ebSAndriy Gapon 	int64_t all_time = 0;
10361dce110fSMatt Macy 	uintptr_t state = 0;
1037e41d6166SMateusz Guzik #endif
1038de709b14SMateusz Guzik 	int extra_work __sdt_used = 0;
1039c1a6d9faSAttilio Rao 
10402466d12bSMateusz Guzik 	td = curthread;
10412466d12bSMateusz Guzik 
104209bdec20SMateusz Guzik #ifdef KDTRACE_HOOKS
104309bdec20SMateusz Guzik 	if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
10442466d12bSMateusz Guzik 		if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
104509bdec20SMateusz Guzik 			goto out_lockstat;
104609bdec20SMateusz Guzik 		extra_work = 1;
104709bdec20SMateusz Guzik 		all_time -= lockstat_nsecs(&sx->lock_object);
104809bdec20SMateusz Guzik 	}
1049928864a9SKristof Provost 	state = x;
105009bdec20SMateusz Guzik #endif
105109bdec20SMateusz Guzik #ifdef LOCK_PROFILING
105209bdec20SMateusz Guzik 	extra_work = 1;
105309bdec20SMateusz Guzik #endif
105409bdec20SMateusz Guzik 
105535370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
105635370593SAndriy Gapon 		return (0);
105735370593SAndriy Gapon 
1058fa5000a4SMateusz Guzik #if defined(ADAPTIVE_SX)
10591ada9041SMateusz Guzik 	lock_delay_arg_init(&lda, &sx_delay);
1060fa5000a4SMateusz Guzik #elif defined(KDTRACE_HOOKS)
1061c795344fSMateusz Guzik 	lock_delay_arg_init_noadapt(&lda);
10621ada9041SMateusz Guzik #endif
1063e41d6166SMateusz Guzik 
1064ae7d25a4SMateusz Guzik #ifdef HWPMC_HOOKS
1065ae7d25a4SMateusz Guzik 	PMC_SOFT_CALL( , , lock, failed);
1066ae7d25a4SMateusz Guzik #endif
10676a467cc5SMateusz Guzik 	lock_profile_obtain_lock_failed(&sx->lock_object, false, &contested,
1068ae7d25a4SMateusz Guzik 	    &waittime);
1069ae7d25a4SMateusz Guzik 
1070fb106123SMateusz Guzik #ifndef INVARIANTS
1071fb106123SMateusz Guzik 	GIANT_SAVE(extra_work);
1072fb106123SMateusz Guzik #endif
1073076dd8ebSAndriy Gapon 
10747530de77SMateusz Guzik 	THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
10757530de77SMateusz Guzik 
10764e7f640dSJohn Baldwin 	/*
10774e7f640dSJohn Baldwin 	 * As with rwlocks, we don't make any attempt to try to block
10784e7f640dSJohn Baldwin 	 * shared locks once there is an exclusive waiter.
10794e7f640dSJohn Baldwin 	 */
10804e7f640dSJohn Baldwin 	for (;;) {
10812466d12bSMateusz Guzik 		if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
10824e7f640dSJohn Baldwin 			break;
1083fb106123SMateusz Guzik #ifdef INVARIANTS
1084fb106123SMateusz Guzik 		GIANT_SAVE(extra_work);
1085fb106123SMateusz Guzik #endif
1086c5f61e6fSMateusz Guzik #ifdef KDTRACE_HOOKS
1087c5f61e6fSMateusz Guzik 		lda.spin_cnt++;
1088c5f61e6fSMateusz Guzik #endif
1089c5f61e6fSMateusz Guzik 
10904e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
10914e7f640dSJohn Baldwin 		/*
10924e7f640dSJohn Baldwin 		 * If the owner is running on another CPU, spin until
10934e7f640dSJohn Baldwin 		 * the owner stops running or the state of the lock
10944e7f640dSJohn Baldwin 		 * changes.
10954e7f640dSJohn Baldwin 		 */
10962466d12bSMateusz Guzik 		if ((x & SX_LOCK_SHARED) == 0) {
1097c5f61e6fSMateusz Guzik 			owner = lv_sx_owner(x);
10984e7f640dSJohn Baldwin 			if (TD_IS_RUNNING(owner)) {
10994e7f640dSJohn Baldwin 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
11004e7f640dSJohn Baldwin 					CTR3(KTR_LOCK,
11014e7f640dSJohn Baldwin 					    "%s: spinning on %p held by %p",
11024e7f640dSJohn Baldwin 					    __func__, sx, owner);
11032cba8dd3SJohn Baldwin 				KTR_STATE1(KTR_SCHED, "thread",
11042cba8dd3SJohn Baldwin 				    sched_tdname(curthread), "spinning",
11052cba8dd3SJohn Baldwin 				    "lockname:\"%s\"", sx->lock_object.lo_name);
1106c5f61e6fSMateusz Guzik 				do {
11071ada9041SMateusz Guzik 					lock_delay(&lda);
1108c5f61e6fSMateusz Guzik 					x = SX_READ_VALUE(sx);
1109c5f61e6fSMateusz Guzik 					owner = lv_sx_owner(x);
1110c5f61e6fSMateusz Guzik 				} while (owner != NULL && TD_IS_RUNNING(owner));
11112cba8dd3SJohn Baldwin 				KTR_STATE0(KTR_SCHED, "thread",
11122cba8dd3SJohn Baldwin 				    sched_tdname(curthread), "running");
11134e7f640dSJohn Baldwin 				continue;
11144e7f640dSJohn Baldwin 			}
11152466d12bSMateusz Guzik 		} else {
11162466d12bSMateusz Guzik 			if ((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) {
11172466d12bSMateusz Guzik 				MPASS(!__sx_can_read(td, x, false));
11182466d12bSMateusz Guzik 				lock_delay_spin(2);
11192466d12bSMateusz Guzik 				x = SX_READ_VALUE(sx);
11202466d12bSMateusz Guzik 				continue;
11212466d12bSMateusz Guzik 			}
11222466d12bSMateusz Guzik 			if (spintries < asx_retries) {
11232466d12bSMateusz Guzik 				KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
11242466d12bSMateusz Guzik 				    "spinning", "lockname:\"%s\"",
11252466d12bSMateusz Guzik 				    sx->lock_object.lo_name);
11262466d12bSMateusz Guzik 				n = SX_SHARERS(x);
11272466d12bSMateusz Guzik 				for (i = 0; i < asx_loops; i += n) {
11282466d12bSMateusz Guzik 					lock_delay_spin(n);
11292466d12bSMateusz Guzik 					x = SX_READ_VALUE(sx);
11302466d12bSMateusz Guzik 					if (!(x & SX_LOCK_SHARED))
11312466d12bSMateusz Guzik 						break;
11322466d12bSMateusz Guzik 					n = SX_SHARERS(x);
11332466d12bSMateusz Guzik 					if (n == 0)
11342466d12bSMateusz Guzik 						break;
11352466d12bSMateusz Guzik 					if (__sx_can_read(td, x, false))
11362466d12bSMateusz Guzik 						break;
11372466d12bSMateusz Guzik 				}
11382466d12bSMateusz Guzik #ifdef KDTRACE_HOOKS
11392466d12bSMateusz Guzik 				lda.spin_cnt += i;
11402466d12bSMateusz Guzik #endif
11412466d12bSMateusz Guzik 				KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
11422466d12bSMateusz Guzik 				    "running");
11432466d12bSMateusz Guzik 				if (i < asx_loops)
11442466d12bSMateusz Guzik 					continue;
11452466d12bSMateusz Guzik 			}
11462466d12bSMateusz Guzik 		}
11474e7f640dSJohn Baldwin #endif
11484e7f640dSJohn Baldwin 
11494e7f640dSJohn Baldwin 		/*
11504e7f640dSJohn Baldwin 		 * Some other thread already has an exclusive lock, so
11514e7f640dSJohn Baldwin 		 * start the process of blocking.
11524e7f640dSJohn Baldwin 		 */
11534e7f640dSJohn Baldwin 		sleepq_lock(&sx->lock_object);
1154c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
115593118b62SMateusz Guzik retry_sleepq:
11562466d12bSMateusz Guzik 		if (((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) ||
11572466d12bSMateusz Guzik 		    __sx_can_read(td, x, false)) {
11584e7f640dSJohn Baldwin 			sleepq_release(&sx->lock_object);
11594e7f640dSJohn Baldwin 			continue;
11604e7f640dSJohn Baldwin 		}
11614e7f640dSJohn Baldwin 
11624e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
11634e7f640dSJohn Baldwin 		/*
11644e7f640dSJohn Baldwin 		 * If the owner is running on another CPU, spin until
11654e7f640dSJohn Baldwin 		 * the owner stops running or the state of the lock
11664e7f640dSJohn Baldwin 		 * changes.
11674e7f640dSJohn Baldwin 		 */
1168f26db694SMateusz Guzik 		if (!(x & SX_LOCK_SHARED)) {
11694e7f640dSJohn Baldwin 			owner = (struct thread *)SX_OWNER(x);
11704e7f640dSJohn Baldwin 			if (TD_IS_RUNNING(owner)) {
11714e7f640dSJohn Baldwin 				sleepq_release(&sx->lock_object);
1172c5f61e6fSMateusz Guzik 				x = SX_READ_VALUE(sx);
11734e7f640dSJohn Baldwin 				continue;
11744e7f640dSJohn Baldwin 			}
11754e7f640dSJohn Baldwin 		}
11764e7f640dSJohn Baldwin #endif
11774e7f640dSJohn Baldwin 
11784e7f640dSJohn Baldwin 		/*
11794e7f640dSJohn Baldwin 		 * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
11804e7f640dSJohn Baldwin 		 * fail to set it drop the sleep queue lock and loop
11814e7f640dSJohn Baldwin 		 * back.
11824e7f640dSJohn Baldwin 		 */
11834e7f640dSJohn Baldwin 		if (!(x & SX_LOCK_SHARED_WAITERS)) {
118493118b62SMateusz Guzik 			if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
118593118b62SMateusz Guzik 			    x | SX_LOCK_SHARED_WAITERS))
118693118b62SMateusz Guzik 				goto retry_sleepq;
11874e7f640dSJohn Baldwin 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
11884e7f640dSJohn Baldwin 				CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
11894e7f640dSJohn Baldwin 				    __func__, sx);
11904e7f640dSJohn Baldwin 		}
11914e7f640dSJohn Baldwin 
11924e7f640dSJohn Baldwin 		/*
11934e7f640dSJohn Baldwin 		 * Since we have been unable to acquire the shared lock,
11944e7f640dSJohn Baldwin 		 * we have to sleep.
11954e7f640dSJohn Baldwin 		 */
11964e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
11974e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
11984e7f640dSJohn Baldwin 			    __func__, sx);
11994e7f640dSJohn Baldwin 
1200a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
1201e2b25737SMark Johnston 		sleep_time -= lockstat_nsecs(&sx->lock_object);
1202a5aedd68SStacey Son #endif
12034e7f640dSJohn Baldwin 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1204f9819486SAttilio Rao 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1205f9819486SAttilio Rao 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1206c35f527eSMateusz Guzik 		/*
1207c35f527eSMateusz Guzik 		 * Hack: this can land in thread_suspend_check which will
1208c35f527eSMateusz Guzik 		 * conditionally take a mutex, tripping over an assert if a
1209c35f527eSMateusz Guzik 		 * lock we are waiting for is set.
1210c35f527eSMateusz Guzik 		 */
1211c35f527eSMateusz Guzik 		THREAD_CONTENTION_DONE(&sx->lock_object);
1212f9819486SAttilio Rao 		if (!(opts & SX_INTERRUPTIBLE))
1213c5aa6b58SJeff Roberson 			sleepq_wait(&sx->lock_object, 0);
1214f9819486SAttilio Rao 		else
1215c5aa6b58SJeff Roberson 			error = sleepq_wait_sig(&sx->lock_object, 0);
1216c35f527eSMateusz Guzik 		THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
1217a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
1218e2b25737SMark Johnston 		sleep_time += lockstat_nsecs(&sx->lock_object);
1219a5aedd68SStacey Son 		sleep_cnt++;
1220a5aedd68SStacey Son #endif
1221f9819486SAttilio Rao 		if (error) {
1222f9819486SAttilio Rao 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1223f9819486SAttilio Rao 				CTR2(KTR_LOCK,
1224f9819486SAttilio Rao 			"%s: interruptible sleep by %p suspended by signal",
1225f9819486SAttilio Rao 				    __func__, sx);
1226f9819486SAttilio Rao 			break;
1227f9819486SAttilio Rao 		}
12284e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
12294e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
12304e7f640dSJohn Baldwin 			    __func__, sx);
1231c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
12324e7f640dSJohn Baldwin 	}
12337530de77SMateusz Guzik 	THREAD_CONTENTION_DONE(&sx->lock_object);
1234e41d6166SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1235e41d6166SMateusz Guzik 	if (__predict_true(!extra_work))
1236e41d6166SMateusz Guzik 		return (error);
1237e41d6166SMateusz Guzik #endif
1238076dd8ebSAndriy Gapon #ifdef KDTRACE_HOOKS
1239e2b25737SMark Johnston 	all_time += lockstat_nsecs(&sx->lock_object);
1240076dd8ebSAndriy Gapon 	if (sleep_time)
124132cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1242076dd8ebSAndriy Gapon 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1243076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
12441ada9041SMateusz Guzik 	if (lda.spin_cnt > sleep_cnt)
124532cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1246076dd8ebSAndriy Gapon 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1247076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
124809bdec20SMateusz Guzik out_lockstat:
1249076dd8ebSAndriy Gapon #endif
12503ae56ce9SMateusz Guzik 	if (error == 0) {
1251de2c95ccSMark Johnston 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1252de2c95ccSMark Johnston 		    contested, waittime, file, line, LOCKSTAT_READER);
12533ae56ce9SMateusz Guzik 	}
12544e7f640dSJohn Baldwin 	GIANT_RESTORE();
1255f9819486SAttilio Rao 	return (error);
12564e7f640dSJohn Baldwin }
12574e7f640dSJohn Baldwin 
1258834f70f3SMateusz Guzik int
1259013c0b49SMateusz Guzik _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
12604e7f640dSJohn Baldwin {
12612466d12bSMateusz Guzik 	struct thread *td;
12624e7f640dSJohn Baldwin 	uintptr_t x;
1263834f70f3SMateusz Guzik 	int error;
12644e7f640dSJohn Baldwin 
1265704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1266704cb42fSMark Johnston 	    !TD_IS_IDLETHREAD(curthread),
1267*a52a51a2SJohn Baldwin 	    ("sx_slock() by idle thread %p on sx %p @ %s:%d",
1268*a52a51a2SJohn Baldwin 	    curthread, sx, file, line));
12693ae56ce9SMateusz Guzik 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1270834f70f3SMateusz Guzik 	    ("sx_slock() of destroyed sx @ %s:%d", file, line));
1271834f70f3SMateusz Guzik 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1272834f70f3SMateusz Guzik 
1273834f70f3SMateusz Guzik 	error = 0;
12742466d12bSMateusz Guzik 	td = curthread;
1275c5f61e6fSMateusz Guzik 	x = SX_READ_VALUE(sx);
1276e4ccf57fSMateusz Guzik 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__acquire) ||
12772466d12bSMateusz Guzik 	    !__sx_slock_try(sx, td, &x, true LOCK_FILE_LINE_ARG)))
1278013c0b49SMateusz Guzik 		error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1279e4ccf57fSMateusz Guzik 	else
12806a467cc5SMateusz Guzik 		lock_profile_obtain_lock_success(&sx->lock_object, false, 0, 0,
1281e4ccf57fSMateusz Guzik 		    file, line);
1282834f70f3SMateusz Guzik 	if (error == 0) {
1283834f70f3SMateusz Guzik 		LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1284834f70f3SMateusz Guzik 		WITNESS_LOCK(&sx->lock_object, 0, file, line);
1285834f70f3SMateusz Guzik 		TD_LOCKS_INC(curthread);
1286834f70f3SMateusz Guzik 	}
1287834f70f3SMateusz Guzik 	return (error);
1288834f70f3SMateusz Guzik }
1289834f70f3SMateusz Guzik 
1290013c0b49SMateusz Guzik int
1291013c0b49SMateusz Guzik _sx_slock(struct sx *sx, int opts, const char *file, int line)
1292013c0b49SMateusz Guzik {
1293013c0b49SMateusz Guzik 
1294013c0b49SMateusz Guzik 	return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1295013c0b49SMateusz Guzik }
1296013c0b49SMateusz Guzik 
12973c84b4b3SRyan Libby static __always_inline bool
12982466d12bSMateusz Guzik _sx_sunlock_try(struct sx *sx, struct thread *td, uintptr_t *xp)
1299834f70f3SMateusz Guzik {
1300834f70f3SMateusz Guzik 
13014e7f640dSJohn Baldwin 	for (;;) {
13022466d12bSMateusz Guzik 		if (SX_SHARERS(*xp) > 1 || !(*xp & SX_LOCK_WAITERS)) {
1303834f70f3SMateusz Guzik 			if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1304834f70f3SMateusz Guzik 			    *xp - SX_ONE_SHARER)) {
13054e7f640dSJohn Baldwin 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
13064e7f640dSJohn Baldwin 					CTR4(KTR_LOCK,
13074e7f640dSJohn Baldwin 					    "%s: %p succeeded %p -> %p",
1308834f70f3SMateusz Guzik 					    __func__, sx, (void *)*xp,
1309834f70f3SMateusz Guzik 					    (void *)(*xp - SX_ONE_SHARER));
13102466d12bSMateusz Guzik 				td->td_sx_slocks--;
1311834f70f3SMateusz Guzik 				return (true);
13124e7f640dSJohn Baldwin 			}
13134e7f640dSJohn Baldwin 			continue;
13144e7f640dSJohn Baldwin 		}
1315834f70f3SMateusz Guzik 		break;
1316834f70f3SMateusz Guzik 	}
1317834f70f3SMateusz Guzik 	return (false);
1318834f70f3SMateusz Guzik }
1319834f70f3SMateusz Guzik 
1320834f70f3SMateusz Guzik static void __noinline
13212466d12bSMateusz Guzik _sx_sunlock_hard(struct sx *sx, struct thread *td, uintptr_t x
13222466d12bSMateusz Guzik     LOCK_FILE_LINE_ARG_DEF)
1323834f70f3SMateusz Guzik {
13242466d12bSMateusz Guzik 	uintptr_t setx, queue;
1325834f70f3SMateusz Guzik 
1326834f70f3SMateusz Guzik 	if (SCHEDULER_STOPPED())
1327834f70f3SMateusz Guzik 		return;
1328834f70f3SMateusz Guzik 
13292466d12bSMateusz Guzik 	if (_sx_sunlock_try(sx, td, &x))
1330cec17473SMateusz Guzik 		goto out_lockstat;
13314e7f640dSJohn Baldwin 
13324e7f640dSJohn Baldwin 	sleepq_lock(&sx->lock_object);
1333cec17473SMateusz Guzik 	x = SX_READ_VALUE(sx);
1334cec17473SMateusz Guzik 	for (;;) {
13352466d12bSMateusz Guzik 		if (_sx_sunlock_try(sx, td, &x))
13361b54ffc8SMateusz Guzik 			break;
13371b54ffc8SMateusz Guzik 
13384e7f640dSJohn Baldwin 		/*
13394e7f640dSJohn Baldwin 		 * Wake up semantic here is quite simple:
13404e7f640dSJohn Baldwin 		 * Just wake up all the exclusive waiters.
13414e7f640dSJohn Baldwin 		 * Note that the state of the lock could have changed,
13424e7f640dSJohn Baldwin 		 * so if it fails loop back and retry.
13434e7f640dSJohn Baldwin 		 */
13442466d12bSMateusz Guzik 		setx = SX_LOCK_UNLOCKED;
13452466d12bSMateusz Guzik 		queue = SQ_SHARED_QUEUE;
13462466d12bSMateusz Guzik 		if (x & SX_LOCK_EXCLUSIVE_WAITERS) {
13472466d12bSMateusz Guzik 			setx |= (x & SX_LOCK_SHARED_WAITERS);
13482466d12bSMateusz Guzik 			queue = SQ_EXCLUSIVE_QUEUE;
13492466d12bSMateusz Guzik 		}
13502466d12bSMateusz Guzik 		setx |= (x & SX_LOCK_WRITE_SPINNER);
1351cec17473SMateusz Guzik 		if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
13524e7f640dSJohn Baldwin 			continue;
13534e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
13544e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p waking up all thread on"
13554e7f640dSJohn Baldwin 			    "exclusive queue", __func__, sx);
135601518f5eSMark Johnston 		sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0, queue);
13572466d12bSMateusz Guzik 		td->td_sx_slocks--;
1358cec17473SMateusz Guzik 		break;
1359cec17473SMateusz Guzik 	}
1360c5aa6b58SJeff Roberson 	sleepq_release(&sx->lock_object);
1361cec17473SMateusz Guzik out_lockstat:
1362dbe4541dSMark Johnston 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1363834f70f3SMateusz Guzik }
1364834f70f3SMateusz Guzik 
1365834f70f3SMateusz Guzik void
1366013c0b49SMateusz Guzik _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1367834f70f3SMateusz Guzik {
13682466d12bSMateusz Guzik 	struct thread *td;
1369834f70f3SMateusz Guzik 	uintptr_t x;
1370834f70f3SMateusz Guzik 
1371834f70f3SMateusz Guzik 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1372834f70f3SMateusz Guzik 	    ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1373834f70f3SMateusz Guzik 	_sx_assert(sx, SA_SLOCKED, file, line);
1374834f70f3SMateusz Guzik 	WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1375834f70f3SMateusz Guzik 	LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1376834f70f3SMateusz Guzik 
13772466d12bSMateusz Guzik 	td = curthread;
1378834f70f3SMateusz Guzik 	x = SX_READ_VALUE(sx);
1379e4ccf57fSMateusz Guzik 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__release) ||
13802466d12bSMateusz Guzik 	    !_sx_sunlock_try(sx, td, &x)))
13812466d12bSMateusz Guzik 		_sx_sunlock_hard(sx, td, x LOCK_FILE_LINE_ARG);
1382e4ccf57fSMateusz Guzik 	else
13836a467cc5SMateusz Guzik 		lock_profile_release_lock(&sx->lock_object, false);
1384834f70f3SMateusz Guzik 
13853ae56ce9SMateusz Guzik 	TD_LOCKS_DEC(curthread);
1386d55229b7SJason Evans }
13874e5e677bSJohn Baldwin 
1388013c0b49SMateusz Guzik void
1389013c0b49SMateusz Guzik _sx_sunlock(struct sx *sx, const char *file, int line)
1390013c0b49SMateusz Guzik {
1391013c0b49SMateusz Guzik 
1392013c0b49SMateusz Guzik 	_sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1393013c0b49SMateusz Guzik }
1394013c0b49SMateusz Guzik 
13954e5e677bSJohn Baldwin #ifdef INVARIANT_SUPPORT
1396781a35dfSJohn Baldwin #ifndef INVARIANTS
1397781a35dfSJohn Baldwin #undef	_sx_assert
1398781a35dfSJohn Baldwin #endif
1399781a35dfSJohn Baldwin 
14004e5e677bSJohn Baldwin /*
14014e5e677bSJohn Baldwin  * In the non-WITNESS case, sx_assert() can only detect that at least
14024e5e677bSJohn Baldwin  * *some* thread owns an slock, but it cannot guarantee that *this*
14034e5e677bSJohn Baldwin  * thread owns an slock.
14044e5e677bSJohn Baldwin  */
14054e5e677bSJohn Baldwin void
1406d576deedSPawel Jakub Dawidek _sx_assert(const struct sx *sx, int what, const char *file, int line)
14074e5e677bSJohn Baldwin {
14084e7f640dSJohn Baldwin #ifndef WITNESS
14094e7f640dSJohn Baldwin 	int slocked = 0;
14104e7f640dSJohn Baldwin #endif
14114e5e677bSJohn Baldwin 
1412d54474e6SEric van Gyzen 	if (SCHEDULER_STOPPED())
141303129ba9SJohn Baldwin 		return;
14144e5e677bSJohn Baldwin 	switch (what) {
14157ec137e5SJohn Baldwin 	case SA_SLOCKED:
14167ec137e5SJohn Baldwin 	case SA_SLOCKED | SA_NOTRECURSED:
14177ec137e5SJohn Baldwin 	case SA_SLOCKED | SA_RECURSED:
14184e7f640dSJohn Baldwin #ifndef WITNESS
14194e7f640dSJohn Baldwin 		slocked = 1;
14204e7f640dSJohn Baldwin 		/* FALLTHROUGH */
14214e7f640dSJohn Baldwin #endif
14227ec137e5SJohn Baldwin 	case SA_LOCKED:
14237ec137e5SJohn Baldwin 	case SA_LOCKED | SA_NOTRECURSED:
14247ec137e5SJohn Baldwin 	case SA_LOCKED | SA_RECURSED:
14254e5e677bSJohn Baldwin #ifdef WITNESS
1426aa89d8cdSJohn Baldwin 		witness_assert(&sx->lock_object, what, file, line);
14274e5e677bSJohn Baldwin #else
14284e7f640dSJohn Baldwin 		/*
14294e7f640dSJohn Baldwin 		 * If some other thread has an exclusive lock or we
14304e7f640dSJohn Baldwin 		 * have one and are asserting a shared lock, fail.
14314e7f640dSJohn Baldwin 		 * Also, if no one has a lock at all, fail.
14324e7f640dSJohn Baldwin 		 */
14334e7f640dSJohn Baldwin 		if (sx->sx_lock == SX_LOCK_UNLOCKED ||
14344e7f640dSJohn Baldwin 		    (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
14354e7f640dSJohn Baldwin 		    sx_xholder(sx) != curthread)))
143603129ba9SJohn Baldwin 			panic("Lock %s not %slocked @ %s:%d\n",
14374e7f640dSJohn Baldwin 			    sx->lock_object.lo_name, slocked ? "share " : "",
14384e7f640dSJohn Baldwin 			    file, line);
14394e7f640dSJohn Baldwin 
14404e7f640dSJohn Baldwin 		if (!(sx->sx_lock & SX_LOCK_SHARED)) {
14414e7f640dSJohn Baldwin 			if (sx_recursed(sx)) {
14427ec137e5SJohn Baldwin 				if (what & SA_NOTRECURSED)
14434e7f640dSJohn Baldwin 					panic("Lock %s recursed @ %s:%d\n",
14444e7f640dSJohn Baldwin 					    sx->lock_object.lo_name, file,
14454e7f640dSJohn Baldwin 					    line);
14467ec137e5SJohn Baldwin 			} else if (what & SA_RECURSED)
14474e7f640dSJohn Baldwin 				panic("Lock %s not recursed @ %s:%d\n",
14484e7f640dSJohn Baldwin 				    sx->lock_object.lo_name, file, line);
14494e7f640dSJohn Baldwin 		}
14504e5e677bSJohn Baldwin #endif
14514e5e677bSJohn Baldwin 		break;
14527ec137e5SJohn Baldwin 	case SA_XLOCKED:
14537ec137e5SJohn Baldwin 	case SA_XLOCKED | SA_NOTRECURSED:
14547ec137e5SJohn Baldwin 	case SA_XLOCKED | SA_RECURSED:
14554e7f640dSJohn Baldwin 		if (sx_xholder(sx) != curthread)
145603129ba9SJohn Baldwin 			panic("Lock %s not exclusively locked @ %s:%d\n",
1457aa89d8cdSJohn Baldwin 			    sx->lock_object.lo_name, file, line);
14584e7f640dSJohn Baldwin 		if (sx_recursed(sx)) {
14597ec137e5SJohn Baldwin 			if (what & SA_NOTRECURSED)
14604e7f640dSJohn Baldwin 				panic("Lock %s recursed @ %s:%d\n",
14614e7f640dSJohn Baldwin 				    sx->lock_object.lo_name, file, line);
14627ec137e5SJohn Baldwin 		} else if (what & SA_RECURSED)
14634e7f640dSJohn Baldwin 			panic("Lock %s not recursed @ %s:%d\n",
14644e7f640dSJohn Baldwin 			    sx->lock_object.lo_name, file, line);
14654e5e677bSJohn Baldwin 		break;
14667ec137e5SJohn Baldwin 	case SA_UNLOCKED:
146719b0efd3SPawel Jakub Dawidek #ifdef WITNESS
1468aa89d8cdSJohn Baldwin 		witness_assert(&sx->lock_object, what, file, line);
146919b0efd3SPawel Jakub Dawidek #else
1470f6739b1dSPawel Jakub Dawidek 		/*
14714e7f640dSJohn Baldwin 		 * If we hold an exclusve lock fail.  We can't
14724e7f640dSJohn Baldwin 		 * reliably check to see if we hold a shared lock or
14734e7f640dSJohn Baldwin 		 * not.
1474f6739b1dSPawel Jakub Dawidek 		 */
14754e7f640dSJohn Baldwin 		if (sx_xholder(sx) == curthread)
147603129ba9SJohn Baldwin 			panic("Lock %s exclusively locked @ %s:%d\n",
1477aa89d8cdSJohn Baldwin 			    sx->lock_object.lo_name, file, line);
147819b0efd3SPawel Jakub Dawidek #endif
147919b0efd3SPawel Jakub Dawidek 		break;
14804e5e677bSJohn Baldwin 	default:
14814e5e677bSJohn Baldwin 		panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
14824e5e677bSJohn Baldwin 		    line);
14834e5e677bSJohn Baldwin 	}
14844e5e677bSJohn Baldwin }
14854e5e677bSJohn Baldwin #endif	/* INVARIANT_SUPPORT */
1486d272fe53SJohn Baldwin 
1487d272fe53SJohn Baldwin #ifdef DDB
14884e7f640dSJohn Baldwin static void
1489d576deedSPawel Jakub Dawidek db_show_sx(const struct lock_object *lock)
1490d272fe53SJohn Baldwin {
1491d272fe53SJohn Baldwin 	struct thread *td;
1492d576deedSPawel Jakub Dawidek 	const struct sx *sx;
1493d272fe53SJohn Baldwin 
1494d576deedSPawel Jakub Dawidek 	sx = (const struct sx *)lock;
1495d272fe53SJohn Baldwin 
1496d272fe53SJohn Baldwin 	db_printf(" state: ");
14974e7f640dSJohn Baldwin 	if (sx->sx_lock == SX_LOCK_UNLOCKED)
14984e7f640dSJohn Baldwin 		db_printf("UNLOCKED\n");
14990026c92cSJohn Baldwin 	else if (sx->sx_lock == SX_LOCK_DESTROYED) {
15000026c92cSJohn Baldwin 		db_printf("DESTROYED\n");
15010026c92cSJohn Baldwin 		return;
15020026c92cSJohn Baldwin 	} else if (sx->sx_lock & SX_LOCK_SHARED)
15034e7f640dSJohn Baldwin 		db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
15044e7f640dSJohn Baldwin 	else {
15054e7f640dSJohn Baldwin 		td = sx_xholder(sx);
1506d272fe53SJohn Baldwin 		db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1507431f8906SJulian Elischer 		    td->td_tid, td->td_proc->p_pid, td->td_name);
15084e7f640dSJohn Baldwin 		if (sx_recursed(sx))
15094e7f640dSJohn Baldwin 			db_printf(" recursed: %d\n", sx->sx_recurse);
15104e7f640dSJohn Baldwin 	}
15114e7f640dSJohn Baldwin 
15124e7f640dSJohn Baldwin 	db_printf(" waiters: ");
15134e7f640dSJohn Baldwin 	switch(sx->sx_lock &
15144e7f640dSJohn Baldwin 	    (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
15154e7f640dSJohn Baldwin 	case SX_LOCK_SHARED_WAITERS:
15164e7f640dSJohn Baldwin 		db_printf("shared\n");
15174e7f640dSJohn Baldwin 		break;
15184e7f640dSJohn Baldwin 	case SX_LOCK_EXCLUSIVE_WAITERS:
15194e7f640dSJohn Baldwin 		db_printf("exclusive\n");
15204e7f640dSJohn Baldwin 		break;
15214e7f640dSJohn Baldwin 	case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
15224e7f640dSJohn Baldwin 		db_printf("exclusive and shared\n");
15234e7f640dSJohn Baldwin 		break;
15244e7f640dSJohn Baldwin 	default:
15254e7f640dSJohn Baldwin 		db_printf("none\n");
15264e7f640dSJohn Baldwin 	}
1527d272fe53SJohn Baldwin }
1528462a7addSJohn Baldwin 
1529462a7addSJohn Baldwin /*
1530462a7addSJohn Baldwin  * Check to see if a thread that is blocked on a sleep queue is actually
1531462a7addSJohn Baldwin  * blocked on an sx lock.  If so, output some details and return true.
1532462a7addSJohn Baldwin  * If the lock has an exclusive owner, return that in *ownerp.
1533462a7addSJohn Baldwin  */
1534462a7addSJohn Baldwin int
1535462a7addSJohn Baldwin sx_chain(struct thread *td, struct thread **ownerp)
1536462a7addSJohn Baldwin {
1537fea73412SConrad Meyer 	const struct sx *sx;
1538462a7addSJohn Baldwin 
1539462a7addSJohn Baldwin 	/*
15404e7f640dSJohn Baldwin 	 * Check to see if this thread is blocked on an sx lock.
15414e7f640dSJohn Baldwin 	 * First, we check the lock class.  If that is ok, then we
15424e7f640dSJohn Baldwin 	 * compare the lock name against the wait message.
1543462a7addSJohn Baldwin 	 */
15444e7f640dSJohn Baldwin 	sx = td->td_wchan;
15454e7f640dSJohn Baldwin 	if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
15464e7f640dSJohn Baldwin 	    sx->lock_object.lo_name != td->td_wmesg)
1547462a7addSJohn Baldwin 		return (0);
1548462a7addSJohn Baldwin 
1549462a7addSJohn Baldwin 	/* We think we have an sx lock, so output some details. */
1550462a7addSJohn Baldwin 	db_printf("blocked on sx \"%s\" ", td->td_wmesg);
15514e7f640dSJohn Baldwin 	*ownerp = sx_xholder(sx);
15524e7f640dSJohn Baldwin 	if (sx->sx_lock & SX_LOCK_SHARED)
15534e7f640dSJohn Baldwin 		db_printf("SLOCK (count %ju)\n",
15544e7f640dSJohn Baldwin 		    (uintmax_t)SX_SHARERS(sx->sx_lock));
15554e7f640dSJohn Baldwin 	else
1556462a7addSJohn Baldwin 		db_printf("XLOCK\n");
1557462a7addSJohn Baldwin 	return (1);
1558462a7addSJohn Baldwin }
1559d272fe53SJohn Baldwin #endif
1560