xref: /freebsd/sys/kern/kern_sx.c (revision c35f527ed115b792463d30c7d3c8904e435caead)
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 
45677b542eSDavid E. O'Brien #include <sys/cdefs.h>
466281b30aSJason Evans #include <sys/param.h>
477a7ce668SAndriy Gapon #include <sys/systm.h>
48cd2fe4e6SAttilio Rao #include <sys/kdb.h>
490453ade5SMateusz Guzik #include <sys/kernel.h>
506281b30aSJason Evans #include <sys/ktr.h>
5119284646SJohn Baldwin #include <sys/lock.h>
526281b30aSJason Evans #include <sys/mutex.h>
53d272fe53SJohn Baldwin #include <sys/proc.h>
542cba8dd3SJohn Baldwin #include <sys/sched.h>
554e7f640dSJohn Baldwin #include <sys/sleepqueue.h>
566281b30aSJason Evans #include <sys/sx.h>
571ada9041SMateusz Guzik #include <sys/smp.h>
58e31d0833SAttilio Rao #include <sys/sysctl.h>
594e7f640dSJohn Baldwin 
60e31d0833SAttilio Rao #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
614e7f640dSJohn Baldwin #include <machine/cpu.h>
624e7f640dSJohn Baldwin #endif
636281b30aSJason Evans 
64462a7addSJohn Baldwin #ifdef DDB
65d272fe53SJohn Baldwin #include <ddb/ddb.h>
664e7f640dSJohn Baldwin #endif
67d272fe53SJohn Baldwin 
681ae1c2a3SAttilio Rao #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
691ae1c2a3SAttilio Rao #define	ADAPTIVE_SX
704e7f640dSJohn Baldwin #endif
714e7f640dSJohn Baldwin 
72f5f9340bSFabien Thomas #ifdef HWPMC_HOOKS
73f5f9340bSFabien Thomas #include <sys/pmckern.h>
74f5f9340bSFabien Thomas PMC_SOFT_DECLARE( , , lock, failed);
75f5f9340bSFabien Thomas #endif
76f5f9340bSFabien Thomas 
774e7f640dSJohn Baldwin /* Handy macros for sleep queues. */
784e7f640dSJohn Baldwin #define	SQ_EXCLUSIVE_QUEUE	0
794e7f640dSJohn Baldwin #define	SQ_SHARED_QUEUE		1
804e7f640dSJohn Baldwin 
814e7f640dSJohn Baldwin /*
824e7f640dSJohn Baldwin  * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file.  We
834e7f640dSJohn Baldwin  * drop Giant anytime we have to sleep or if we adaptively spin.
844e7f640dSJohn Baldwin  */
854e7f640dSJohn Baldwin #define	GIANT_DECLARE							\
864e7f640dSJohn Baldwin 	int _giantcnt = 0;						\
874e7f640dSJohn Baldwin 	WITNESS_SAVE_DECL(Giant)					\
884e7f640dSJohn Baldwin 
89e41d6166SMateusz Guzik #define	GIANT_SAVE(work) do {						\
90fb106123SMateusz Guzik 	if (__predict_false(mtx_owned(&Giant))) {			\
91e41d6166SMateusz Guzik 		work++;							\
924e7f640dSJohn Baldwin 		WITNESS_SAVE(&Giant.lock_object, Giant);		\
934e7f640dSJohn Baldwin 		while (mtx_owned(&Giant)) {				\
944e7f640dSJohn Baldwin 			_giantcnt++;					\
954e7f640dSJohn Baldwin 			mtx_unlock(&Giant);				\
964e7f640dSJohn Baldwin 		}							\
974e7f640dSJohn Baldwin 	}								\
984e7f640dSJohn Baldwin } while (0)
994e7f640dSJohn Baldwin 
1004e7f640dSJohn Baldwin #define GIANT_RESTORE() do {						\
1014e7f640dSJohn Baldwin 	if (_giantcnt > 0) {						\
1024e7f640dSJohn Baldwin 		mtx_assert(&Giant, MA_NOTOWNED);			\
1034e7f640dSJohn Baldwin 		while (_giantcnt--)					\
1044e7f640dSJohn Baldwin 			mtx_lock(&Giant);				\
1054e7f640dSJohn Baldwin 		WITNESS_RESTORE(&Giant.lock_object, Giant);		\
1064e7f640dSJohn Baldwin 	}								\
1074e7f640dSJohn Baldwin } while (0)
1084e7f640dSJohn Baldwin 
1094e7f640dSJohn Baldwin /*
110da7d0d1eSJohn Baldwin  * Returns true if an exclusive lock is recursed.  It assumes
111da7d0d1eSJohn Baldwin  * curthread currently has an exclusive lock.
1124e7f640dSJohn Baldwin  */
1134e7f640dSJohn Baldwin #define	sx_recursed(sx)		((sx)->sx_recurse != 0)
1144e7f640dSJohn Baldwin 
115d576deedSPawel Jakub Dawidek static void	assert_sx(const struct lock_object *lock, int what);
1164e7f640dSJohn Baldwin #ifdef DDB
117d576deedSPawel Jakub Dawidek static void	db_show_sx(const struct lock_object *lock);
118d272fe53SJohn Baldwin #endif
1197faf4d90SDavide Italiano static void	lock_sx(struct lock_object *lock, uintptr_t how);
120a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
121d576deedSPawel Jakub Dawidek static int	owner_sx(const struct lock_object *lock, struct thread **owner);
122a5aedd68SStacey Son #endif
1237faf4d90SDavide Italiano static uintptr_t unlock_sx(struct lock_object *lock);
124d272fe53SJohn Baldwin 
12519284646SJohn Baldwin struct lock_class lock_class_sx = {
126ae8dde30SJohn Baldwin 	.lc_name = "sx",
127ae8dde30SJohn Baldwin 	.lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
128f9721b43SAttilio Rao 	.lc_assert = assert_sx,
129d272fe53SJohn Baldwin #ifdef DDB
130ae8dde30SJohn Baldwin 	.lc_ddb_show = db_show_sx,
131d272fe53SJohn Baldwin #endif
1326e21afd4SJohn Baldwin 	.lc_lock = lock_sx,
1336e21afd4SJohn Baldwin 	.lc_unlock = unlock_sx,
134a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
135a5aedd68SStacey Son 	.lc_owner = owner_sx,
136a5aedd68SStacey Son #endif
13719284646SJohn Baldwin };
13819284646SJohn Baldwin 
139781a35dfSJohn Baldwin #ifndef INVARIANTS
140781a35dfSJohn Baldwin #define	_sx_assert(sx, what, file, line)
141781a35dfSJohn Baldwin #endif
142781a35dfSJohn Baldwin 
1431ae1c2a3SAttilio Rao #ifdef ADAPTIVE_SX
1442e77cad1SMateusz Guzik #ifdef SX_CUSTOM_BACKOFF
1456b8dd26eSMateusz Guzik static u_short __read_frequently asx_retries;
1466b8dd26eSMateusz Guzik static u_short __read_frequently asx_loops;
1477029da5cSPawel Biernacki static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
1487029da5cSPawel Biernacki     "sxlock debugging");
1496b8dd26eSMateusz Guzik SYSCTL_U16(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
1506b8dd26eSMateusz Guzik SYSCTL_U16(_debug_sx, OID_AUTO, loops, CTLFLAG_RW, &asx_loops, 0, "");
1511ada9041SMateusz Guzik 
152574adb65SMateusz Guzik static struct lock_delay_config __read_frequently sx_delay;
1531ada9041SMateusz Guzik 
1546b8dd26eSMateusz Guzik SYSCTL_U16(_debug_sx, OID_AUTO, delay_base, CTLFLAG_RW, &sx_delay.base,
1551ada9041SMateusz Guzik     0, "");
1566b8dd26eSMateusz Guzik SYSCTL_U16(_debug_sx, OID_AUTO, delay_max, CTLFLAG_RW, &sx_delay.max,
1571ada9041SMateusz Guzik     0, "");
1581ada9041SMateusz Guzik 
159e0e259a8SMateusz Guzik static void
160e0e259a8SMateusz Guzik sx_lock_delay_init(void *arg __unused)
161e0e259a8SMateusz Guzik {
162e0e259a8SMateusz Guzik 
163e0e259a8SMateusz Guzik 	lock_delay_default_init(&sx_delay);
164e0e259a8SMateusz Guzik 	asx_retries = 10;
165e0e259a8SMateusz Guzik 	asx_loops = max(10000, sx_delay.max);
166e0e259a8SMateusz Guzik }
167e0e259a8SMateusz Guzik LOCK_DELAY_SYSINIT(sx_lock_delay_init);
1682e77cad1SMateusz Guzik #else
1692e77cad1SMateusz Guzik #define sx_delay	locks_delay
1702e77cad1SMateusz Guzik #define asx_retries	locks_delay_retries
1712e77cad1SMateusz Guzik #define asx_loops	locks_delay_loops
1722e77cad1SMateusz Guzik #endif
1731ae1c2a3SAttilio Rao #endif
1741ae1c2a3SAttilio Rao 
1756281b30aSJason Evans void
176d576deedSPawel Jakub Dawidek assert_sx(const struct lock_object *lock, int what)
177f9721b43SAttilio Rao {
178f9721b43SAttilio Rao 
179d576deedSPawel Jakub Dawidek 	sx_assert((const struct sx *)lock, what);
180f9721b43SAttilio Rao }
181f9721b43SAttilio Rao 
182f9721b43SAttilio Rao void
1837faf4d90SDavide Italiano lock_sx(struct lock_object *lock, uintptr_t how)
1846e21afd4SJohn Baldwin {
1856e21afd4SJohn Baldwin 	struct sx *sx;
1866e21afd4SJohn Baldwin 
1876e21afd4SJohn Baldwin 	sx = (struct sx *)lock;
1886e21afd4SJohn Baldwin 	if (how)
1896e21afd4SJohn Baldwin 		sx_slock(sx);
190cf6b879fSDavide Italiano 	else
191cf6b879fSDavide Italiano 		sx_xlock(sx);
1926e21afd4SJohn Baldwin }
1936e21afd4SJohn Baldwin 
1947faf4d90SDavide Italiano uintptr_t
1956e21afd4SJohn Baldwin unlock_sx(struct lock_object *lock)
1966e21afd4SJohn Baldwin {
1976e21afd4SJohn Baldwin 	struct sx *sx;
1986e21afd4SJohn Baldwin 
1996e21afd4SJohn Baldwin 	sx = (struct sx *)lock;
2007ec137e5SJohn Baldwin 	sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
2016e21afd4SJohn Baldwin 	if (sx_xlocked(sx)) {
2026e21afd4SJohn Baldwin 		sx_xunlock(sx);
203cf6b879fSDavide Italiano 		return (0);
2046e21afd4SJohn Baldwin 	} else {
2056e21afd4SJohn Baldwin 		sx_sunlock(sx);
206cf6b879fSDavide Italiano 		return (1);
2076e21afd4SJohn Baldwin 	}
2086e21afd4SJohn Baldwin }
2096e21afd4SJohn Baldwin 
210a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
211a5aedd68SStacey Son int
212d576deedSPawel Jakub Dawidek owner_sx(const struct lock_object *lock, struct thread **owner)
213a5aedd68SStacey Son {
214c365a293SMark Johnston 	const struct sx *sx;
215c365a293SMark Johnston 	uintptr_t x;
216a5aedd68SStacey Son 
217c365a293SMark Johnston 	sx = (const struct sx *)lock;
218c365a293SMark Johnston 	x = sx->sx_lock;
219c365a293SMark Johnston 	*owner = NULL;
220a5aedd68SStacey Son 	return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
221c365a293SMark Johnston 	    ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
222a5aedd68SStacey Son }
223a5aedd68SStacey Son #endif
224a5aedd68SStacey Son 
2256e21afd4SJohn Baldwin void
226c27b5699SAndrew R. Reiter sx_sysinit(void *arg)
227c27b5699SAndrew R. Reiter {
228c27b5699SAndrew R. Reiter 	struct sx_args *sargs = arg;
229c27b5699SAndrew R. Reiter 
230e4cd31ddSJeff Roberson 	sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
231c27b5699SAndrew R. Reiter }
232c27b5699SAndrew R. Reiter 
233c27b5699SAndrew R. Reiter void
2344e7f640dSJohn Baldwin sx_init_flags(struct sx *sx, const char *description, int opts)
2356281b30aSJason Evans {
2364e7f640dSJohn Baldwin 	int flags;
2376281b30aSJason Evans 
238b0d67325SJohn Baldwin 	MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
239f26db694SMateusz Guzik 	    SX_NOPROFILE | SX_NEW)) == 0);
240353998acSAttilio Rao 	ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
241353998acSAttilio Rao 	    ("%s: sx_lock not aligned for %s: %p", __func__, description,
242353998acSAttilio Rao 	    &sx->sx_lock));
243b0d67325SJohn Baldwin 
244f0830182SAttilio Rao 	flags = LO_SLEEPABLE | LO_UPGRADABLE;
2454e7f640dSJohn Baldwin 	if (opts & SX_DUPOK)
2464e7f640dSJohn Baldwin 		flags |= LO_DUPOK;
2474e7f640dSJohn Baldwin 	if (opts & SX_NOPROFILE)
2484e7f640dSJohn Baldwin 		flags |= LO_NOPROFILE;
2494e7f640dSJohn Baldwin 	if (!(opts & SX_NOWITNESS))
2504e7f640dSJohn Baldwin 		flags |= LO_WITNESS;
251f0830182SAttilio Rao 	if (opts & SX_RECURSE)
252f0830182SAttilio Rao 		flags |= LO_RECURSABLE;
2534e7f640dSJohn Baldwin 	if (opts & SX_QUIET)
2544e7f640dSJohn Baldwin 		flags |= LO_QUIET;
255fd07ddcfSDmitry Chagin 	if (opts & SX_NEW)
256fd07ddcfSDmitry Chagin 		flags |= LO_NEW;
2574e7f640dSJohn Baldwin 
258b5fb43e5SJohn Baldwin 	lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
2594e7f640dSJohn Baldwin 	sx->sx_lock = SX_LOCK_UNLOCKED;
2604e7f640dSJohn Baldwin 	sx->sx_recurse = 0;
2616281b30aSJason Evans }
2626281b30aSJason Evans 
2636281b30aSJason Evans void
2646281b30aSJason Evans sx_destroy(struct sx *sx)
2656281b30aSJason Evans {
2666281b30aSJason Evans 
2674e7f640dSJohn Baldwin 	KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
2684e7f640dSJohn Baldwin 	KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
2690026c92cSJohn Baldwin 	sx->sx_lock = SX_LOCK_DESTROYED;
270aa89d8cdSJohn Baldwin 	lock_destroy(&sx->lock_object);
2716281b30aSJason Evans }
2726281b30aSJason Evans 
273f9819486SAttilio Rao int
274013c0b49SMateusz Guzik sx_try_slock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
2755f36700aSJohn Baldwin {
2764e7f640dSJohn Baldwin 	uintptr_t x;
2775f36700aSJohn Baldwin 
27835370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
27935370593SAndriy Gapon 		return (1);
28035370593SAndriy Gapon 
281cd2fe4e6SAttilio Rao 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
282e3ae0dfeSAttilio Rao 	    ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
283e3ae0dfeSAttilio Rao 	    curthread, sx->lock_object.lo_name, file, line));
284e3ae0dfeSAttilio Rao 
2854e7f640dSJohn Baldwin 	x = sx->sx_lock;
2865c5df0d9SMateusz Guzik 	for (;;) {
2870026c92cSJohn Baldwin 		KASSERT(x != SX_LOCK_DESTROYED,
2880026c92cSJohn Baldwin 		    ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
289764a938bSPawel Jakub Dawidek 		if (!(x & SX_LOCK_SHARED))
290764a938bSPawel Jakub Dawidek 			break;
2915c5df0d9SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, x + SX_ONE_SHARER)) {
292aa89d8cdSJohn Baldwin 			LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
293aa89d8cdSJohn Baldwin 			WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
294de2c95ccSMark Johnston 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
295de2c95ccSMark Johnston 			    sx, 0, 0, file, line, LOCKSTAT_READER);
296ce1c953eSMark Johnston 			TD_LOCKS_INC(curthread);
2972466d12bSMateusz Guzik 			curthread->td_sx_slocks++;
2985f36700aSJohn Baldwin 			return (1);
2995f36700aSJohn Baldwin 		}
300764a938bSPawel Jakub Dawidek 	}
3014e7f640dSJohn Baldwin 
3024e7f640dSJohn Baldwin 	LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
3034e7f640dSJohn Baldwin 	return (0);
3045f36700aSJohn Baldwin }
3055f36700aSJohn Baldwin 
306f9819486SAttilio Rao int
307013c0b49SMateusz Guzik sx_try_slock_(struct sx *sx, const char *file, int line)
308013c0b49SMateusz Guzik {
309013c0b49SMateusz Guzik 
310013c0b49SMateusz Guzik 	return (sx_try_slock_int(sx LOCK_FILE_LINE_ARG));
311013c0b49SMateusz Guzik }
312013c0b49SMateusz Guzik 
313013c0b49SMateusz Guzik int
314f9819486SAttilio Rao _sx_xlock(struct sx *sx, int opts, const char *file, int line)
3156281b30aSJason Evans {
3166ebb77b6SMateusz Guzik 	uintptr_t tid, x;
317f9819486SAttilio Rao 	int error = 0;
3186281b30aSJason Evans 
319704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
320704cb42fSMark Johnston 	    !TD_IS_IDLETHREAD(curthread),
321e3ae0dfeSAttilio Rao 	    ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
322e3ae0dfeSAttilio Rao 	    curthread, sx->lock_object.lo_name, file, line));
3230026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
3240026c92cSJohn Baldwin 	    ("sx_xlock() of destroyed sx @ %s:%d", file, line));
325aa89d8cdSJohn Baldwin 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
32641313430SJohn Baldwin 	    line, NULL);
3276ebb77b6SMateusz Guzik 	tid = (uintptr_t)curthread;
3286ebb77b6SMateusz Guzik 	x = SX_LOCK_UNLOCKED;
3296ebb77b6SMateusz Guzik 	if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
330013c0b49SMateusz Guzik 		error = _sx_xlock_hard(sx, x, opts LOCK_FILE_LINE_ARG);
3316ebb77b6SMateusz Guzik 	else
3326ebb77b6SMateusz Guzik 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
3336ebb77b6SMateusz Guzik 		    0, 0, file, line, LOCKSTAT_WRITER);
334f9819486SAttilio Rao 	if (!error) {
335f9819486SAttilio Rao 		LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
336f9819486SAttilio Rao 		    file, line);
337aa89d8cdSJohn Baldwin 		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
338ce1c953eSMark Johnston 		TD_LOCKS_INC(curthread);
3396281b30aSJason Evans 	}
3406281b30aSJason Evans 
341f9819486SAttilio Rao 	return (error);
342f9819486SAttilio Rao }
343f9819486SAttilio Rao 
3445f36700aSJohn Baldwin int
345013c0b49SMateusz Guzik sx_try_xlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
3465f36700aSJohn Baldwin {
3475c5df0d9SMateusz Guzik 	struct thread *td;
3485c5df0d9SMateusz Guzik 	uintptr_t tid, x;
3494e7f640dSJohn Baldwin 	int rval;
3505c5df0d9SMateusz Guzik 	bool recursed;
3515f36700aSJohn Baldwin 
3525c5df0d9SMateusz Guzik 	td = curthread;
3535c5df0d9SMateusz Guzik 	tid = (uintptr_t)td;
3545c5df0d9SMateusz Guzik 	if (SCHEDULER_STOPPED_TD(td))
35535370593SAndriy Gapon 		return (1);
35635370593SAndriy Gapon 
357704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
358e3ae0dfeSAttilio Rao 	    ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
359e3ae0dfeSAttilio Rao 	    curthread, sx->lock_object.lo_name, file, line));
3600026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
3610026c92cSJohn Baldwin 	    ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
3624e7f640dSJohn Baldwin 
3635c5df0d9SMateusz Guzik 	rval = 1;
3645c5df0d9SMateusz Guzik 	recursed = false;
3655c5df0d9SMateusz Guzik 	x = SX_LOCK_UNLOCKED;
366b247fd39SMateusz Guzik 	for (;;) {
367b247fd39SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
368b247fd39SMateusz Guzik 			break;
369b247fd39SMateusz Guzik 		if (x == SX_LOCK_UNLOCKED)
370b247fd39SMateusz Guzik 			continue;
3715c5df0d9SMateusz Guzik 		if (x == tid && (sx->lock_object.lo_flags & LO_RECURSABLE)) {
3724e7f640dSJohn Baldwin 			sx->sx_recurse++;
3734e7f640dSJohn Baldwin 			atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
374b247fd39SMateusz Guzik 			break;
3755c5df0d9SMateusz Guzik 		}
376b247fd39SMateusz Guzik 		rval = 0;
377b247fd39SMateusz Guzik 		break;
3785c5df0d9SMateusz Guzik 	}
3795c5df0d9SMateusz Guzik 
3804e7f640dSJohn Baldwin 	LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
3814e7f640dSJohn Baldwin 	if (rval) {
3824e7f640dSJohn Baldwin 		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
3834e7f640dSJohn Baldwin 		    file, line);
3845c5df0d9SMateusz Guzik 		if (!recursed)
385de2c95ccSMark Johnston 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
386de2c95ccSMark Johnston 			    sx, 0, 0, file, line, LOCKSTAT_WRITER);
387ce1c953eSMark Johnston 		TD_LOCKS_INC(curthread);
3885f36700aSJohn Baldwin 	}
3894e7f640dSJohn Baldwin 
3904e7f640dSJohn Baldwin 	return (rval);
3915f36700aSJohn Baldwin }
3925f36700aSJohn Baldwin 
393013c0b49SMateusz Guzik int
394013c0b49SMateusz Guzik sx_try_xlock_(struct sx *sx, const char *file, int line)
395013c0b49SMateusz Guzik {
396013c0b49SMateusz Guzik 
397013c0b49SMateusz Guzik 	return (sx_try_xlock_int(sx LOCK_FILE_LINE_ARG));
398013c0b49SMateusz Guzik }
399013c0b49SMateusz Guzik 
4006281b30aSJason Evans void
40119284646SJohn Baldwin _sx_xunlock(struct sx *sx, const char *file, int line)
4026281b30aSJason Evans {
4036281b30aSJason Evans 
4040026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
4050026c92cSJohn Baldwin 	    ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
4067ec137e5SJohn Baldwin 	_sx_assert(sx, SA_XLOCKED, file, line);
407aa89d8cdSJohn Baldwin 	WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
4084e7f640dSJohn Baldwin 	LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
4094e7f640dSJohn Baldwin 	    line);
4100108a980SMateusz Guzik #if LOCK_DEBUG > 0
4116ebb77b6SMateusz Guzik 	_sx_xunlock_hard(sx, (uintptr_t)curthread, file, line);
412ffd5c94cSMateusz Guzik #else
413ffd5c94cSMateusz Guzik 	__sx_xunlock(sx, curthread, file, line);
414ffd5c94cSMateusz Guzik #endif
415ce1c953eSMark Johnston 	TD_LOCKS_DEC(curthread);
4166281b30aSJason Evans }
417d55229b7SJason Evans 
4184e7f640dSJohn Baldwin /*
4194e7f640dSJohn Baldwin  * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
4204e7f640dSJohn Baldwin  * This will only succeed if this thread holds a single shared lock.
4214e7f640dSJohn Baldwin  * Return 1 if if the upgrade succeed, 0 otherwise.
4224e7f640dSJohn Baldwin  */
423d55229b7SJason Evans int
424013c0b49SMateusz Guzik sx_try_upgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
425d55229b7SJason Evans {
4264e7f640dSJohn Baldwin 	uintptr_t x;
427a8e747c5SMateusz Guzik 	uintptr_t waiters;
4284e7f640dSJohn Baldwin 	int success;
429d55229b7SJason Evans 
43035370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
43135370593SAndriy Gapon 		return (1);
43235370593SAndriy Gapon 
4330026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
4340026c92cSJohn Baldwin 	    ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
4357ec137e5SJohn Baldwin 	_sx_assert(sx, SA_SLOCKED, file, line);
436d55229b7SJason Evans 
4374e7f640dSJohn Baldwin 	/*
4384e7f640dSJohn Baldwin 	 * Try to switch from one shared lock to an exclusive lock.  We need
4394e7f640dSJohn Baldwin 	 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
4404e7f640dSJohn Baldwin 	 * we will wake up the exclusive waiters when we drop the lock.
4414e7f640dSJohn Baldwin 	 */
442a8e747c5SMateusz Guzik 	success = 0;
443a8e747c5SMateusz Guzik 	x = SX_READ_VALUE(sx);
444a8e747c5SMateusz Guzik 	for (;;) {
445a8e747c5SMateusz Guzik 		if (SX_SHARERS(x) > 1)
446a8e747c5SMateusz Guzik 			break;
4472466d12bSMateusz Guzik 		waiters = (x & SX_LOCK_WAITERS);
448a8e747c5SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
449a8e747c5SMateusz Guzik 		    (uintptr_t)curthread | waiters)) {
450a8e747c5SMateusz Guzik 			success = 1;
451a8e747c5SMateusz Guzik 			break;
452a8e747c5SMateusz Guzik 		}
453a8e747c5SMateusz Guzik 	}
4544e7f640dSJohn Baldwin 	LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
455a5aedd68SStacey Son 	if (success) {
4562466d12bSMateusz Guzik 		curthread->td_sx_slocks--;
457aa89d8cdSJohn Baldwin 		WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
458b0b7cb50SJohn Baldwin 		    file, line);
45932cd0147SMark Johnston 		LOCKSTAT_RECORD0(sx__upgrade, sx);
460a5aedd68SStacey Son 	}
4614e7f640dSJohn Baldwin 	return (success);
462d55229b7SJason Evans }
463d55229b7SJason Evans 
464013c0b49SMateusz Guzik int
465013c0b49SMateusz Guzik sx_try_upgrade_(struct sx *sx, const char *file, int line)
466013c0b49SMateusz Guzik {
467013c0b49SMateusz Guzik 
468013c0b49SMateusz Guzik 	return (sx_try_upgrade_int(sx LOCK_FILE_LINE_ARG));
469013c0b49SMateusz Guzik }
470013c0b49SMateusz Guzik 
4714e7f640dSJohn Baldwin /*
4724e7f640dSJohn Baldwin  * Downgrade an unrecursed exclusive lock into a single shared lock.
4734e7f640dSJohn Baldwin  */
474d55229b7SJason Evans void
475013c0b49SMateusz Guzik sx_downgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
476d55229b7SJason Evans {
4774e7f640dSJohn Baldwin 	uintptr_t x;
478da7bbd2cSJohn Baldwin 	int wakeup_swapper;
479d55229b7SJason Evans 
48035370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
48135370593SAndriy Gapon 		return;
48235370593SAndriy Gapon 
4830026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
4840026c92cSJohn Baldwin 	    ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
4857ec137e5SJohn Baldwin 	_sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
4864e7f640dSJohn Baldwin #ifndef INVARIANTS
4874e7f640dSJohn Baldwin 	if (sx_recursed(sx))
4884e7f640dSJohn Baldwin 		panic("downgrade of a recursed lock");
4894e7f640dSJohn Baldwin #endif
490d55229b7SJason Evans 
491aa89d8cdSJohn Baldwin 	WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
492d55229b7SJason Evans 
4934e7f640dSJohn Baldwin 	/*
4944e7f640dSJohn Baldwin 	 * Try to switch from an exclusive lock with no shared waiters
4954e7f640dSJohn Baldwin 	 * to one sharer with no shared waiters.  If there are
4964e7f640dSJohn Baldwin 	 * exclusive waiters, we don't need to lock the sleep queue so
4974e7f640dSJohn Baldwin 	 * long as we preserve the flag.  We do one quick try and if
4984e7f640dSJohn Baldwin 	 * that fails we grab the sleepq lock to keep the flags from
4994e7f640dSJohn Baldwin 	 * changing and do it the slow way.
5004e7f640dSJohn Baldwin 	 *
5014e7f640dSJohn Baldwin 	 * We have to lock the sleep queue if there are shared waiters
5024e7f640dSJohn Baldwin 	 * so we can wake them up.
5034e7f640dSJohn Baldwin 	 */
5044e7f640dSJohn Baldwin 	x = sx->sx_lock;
5054e7f640dSJohn Baldwin 	if (!(x & SX_LOCK_SHARED_WAITERS) &&
5064e7f640dSJohn Baldwin 	    atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
50726d94f99SMark Johnston 	    (x & SX_LOCK_EXCLUSIVE_WAITERS)))
50826d94f99SMark Johnston 		goto out;
5094e7f640dSJohn Baldwin 
5104e7f640dSJohn Baldwin 	/*
5114e7f640dSJohn Baldwin 	 * Lock the sleep queue so we can read the waiters bits
5124e7f640dSJohn Baldwin 	 * without any races and wakeup any shared waiters.
5134e7f640dSJohn Baldwin 	 */
5144e7f640dSJohn Baldwin 	sleepq_lock(&sx->lock_object);
5154e7f640dSJohn Baldwin 
5164e7f640dSJohn Baldwin 	/*
5174e7f640dSJohn Baldwin 	 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
5184e7f640dSJohn Baldwin 	 * shared lock.  If there are any shared waiters, wake them up.
5194e7f640dSJohn Baldwin 	 */
520da7bbd2cSJohn Baldwin 	wakeup_swapper = 0;
5214e7f640dSJohn Baldwin 	x = sx->sx_lock;
5224e7f640dSJohn Baldwin 	atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
5234e7f640dSJohn Baldwin 	    (x & SX_LOCK_EXCLUSIVE_WAITERS));
5244e7f640dSJohn Baldwin 	if (x & SX_LOCK_SHARED_WAITERS)
525da7bbd2cSJohn Baldwin 		wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
526da7bbd2cSJohn Baldwin 		    0, SQ_SHARED_QUEUE);
5274e7f640dSJohn Baldwin 	sleepq_release(&sx->lock_object);
528d55229b7SJason Evans 
529da7bbd2cSJohn Baldwin 	if (wakeup_swapper)
530da7bbd2cSJohn Baldwin 		kick_proc0();
53126d94f99SMark Johnston 
53226d94f99SMark Johnston out:
5332466d12bSMateusz Guzik 	curthread->td_sx_slocks++;
53426d94f99SMark Johnston 	LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
53526d94f99SMark Johnston 	LOCKSTAT_RECORD0(sx__downgrade, sx);
5364e7f640dSJohn Baldwin }
537d55229b7SJason Evans 
538013c0b49SMateusz Guzik void
539013c0b49SMateusz Guzik sx_downgrade_(struct sx *sx, const char *file, int line)
540013c0b49SMateusz Guzik {
541013c0b49SMateusz Guzik 
542013c0b49SMateusz Guzik 	sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
543013c0b49SMateusz Guzik }
544013c0b49SMateusz Guzik 
5452466d12bSMateusz Guzik #ifdef	ADAPTIVE_SX
5462466d12bSMateusz Guzik static inline void
5472466d12bSMateusz Guzik sx_drop_critical(uintptr_t x, bool *in_critical, int *extra_work)
5482466d12bSMateusz Guzik {
5492466d12bSMateusz Guzik 
5502466d12bSMateusz Guzik 	if (x & SX_LOCK_WRITE_SPINNER)
5512466d12bSMateusz Guzik 		return;
5522466d12bSMateusz Guzik 	if (*in_critical) {
5532466d12bSMateusz Guzik 		critical_exit();
5542466d12bSMateusz Guzik 		*in_critical = false;
5552466d12bSMateusz Guzik 		(*extra_work)--;
5562466d12bSMateusz Guzik 	}
5572466d12bSMateusz Guzik }
5582466d12bSMateusz Guzik #else
5592466d12bSMateusz Guzik #define sx_drop_critical(x, in_critical, extra_work) do { } while (0)
5602466d12bSMateusz Guzik #endif
5612466d12bSMateusz Guzik 
5624e7f640dSJohn Baldwin /*
5634e7f640dSJohn Baldwin  * This function represents the so-called 'hard case' for sx_xlock
5644e7f640dSJohn Baldwin  * operation.  All 'easy case' failures are redirected to this.  Note
5654e7f640dSJohn Baldwin  * that ideally this would be a static function, but it needs to be
5664e7f640dSJohn Baldwin  * accessible from at least sx.h.
5674e7f640dSJohn Baldwin  */
568f9819486SAttilio Rao int
569013c0b49SMateusz Guzik _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
5704e7f640dSJohn Baldwin {
5714e7f640dSJohn Baldwin 	GIANT_DECLARE;
5722466d12bSMateusz Guzik 	uintptr_t tid, setx;
5734e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
574094c148bSMateusz Guzik 	struct thread *owner;
575d07e22cdSMateusz Guzik 	u_int i, n, spintries = 0;
5761dce110fSMatt Macy 	enum { READERS, WRITER } sleep_reason = READERS;
5772466d12bSMateusz Guzik 	bool in_critical = false;
5784e7f640dSJohn Baldwin #endif
5791723a064SJeff Roberson #ifdef LOCK_PROFILING
5801723a064SJeff Roberson 	uint64_t waittime = 0;
5811723a064SJeff Roberson 	int contested = 0;
5821723a064SJeff Roberson #endif
5831723a064SJeff Roberson 	int error = 0;
58404126895SMateusz Guzik #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
5851ada9041SMateusz Guzik 	struct lock_delay_arg lda;
5861ada9041SMateusz Guzik #endif
587a5aedd68SStacey Son #ifdef	KDTRACE_HOOKS
58861852185SMateusz Guzik 	u_int sleep_cnt = 0;
589a5aedd68SStacey Son 	int64_t sleep_time = 0;
590076dd8ebSAndriy Gapon 	int64_t all_time = 0;
591a5aedd68SStacey Son #endif
592e41d6166SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
5931dce110fSMatt Macy 	uintptr_t state = 0;
5942466d12bSMateusz Guzik 	int doing_lockprof = 0;
595e41d6166SMateusz Guzik #endif
596284194f1SMateusz Guzik 	int extra_work = 0;
5974e7f640dSJohn Baldwin 
598013c0b49SMateusz Guzik 	tid = (uintptr_t)curthread;
59909bdec20SMateusz Guzik 
60009bdec20SMateusz Guzik #ifdef KDTRACE_HOOKS
60109bdec20SMateusz Guzik 	if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
60209bdec20SMateusz Guzik 		while (x == SX_LOCK_UNLOCKED) {
60309bdec20SMateusz Guzik 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
60409bdec20SMateusz Guzik 				goto out_lockstat;
60509bdec20SMateusz Guzik 		}
60609bdec20SMateusz Guzik 		extra_work = 1;
6072466d12bSMateusz Guzik 		doing_lockprof = 1;
60809bdec20SMateusz Guzik 		all_time -= lockstat_nsecs(&sx->lock_object);
60909bdec20SMateusz Guzik 		state = x;
61009bdec20SMateusz Guzik 	}
61109bdec20SMateusz Guzik #endif
61209bdec20SMateusz Guzik #ifdef LOCK_PROFILING
61309bdec20SMateusz Guzik 	extra_work = 1;
6142466d12bSMateusz Guzik 	doing_lockprof = 1;
61509bdec20SMateusz Guzik 	state = x;
61609bdec20SMateusz Guzik #endif
61709bdec20SMateusz Guzik 
61835370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
61935370593SAndriy Gapon 		return (0);
62035370593SAndriy Gapon 
621c1aaf63cSMateusz Guzik 	if (__predict_false(x == SX_LOCK_UNLOCKED))
622c1aaf63cSMateusz Guzik 		x = SX_READ_VALUE(sx);
623c1aaf63cSMateusz Guzik 
6244e7f640dSJohn Baldwin 	/* If we already hold an exclusive lock, then recurse. */
625c5f61e6fSMateusz Guzik 	if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
626f0830182SAttilio Rao 		KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
627b0d67325SJohn Baldwin 	    ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
628b0d67325SJohn Baldwin 		    sx->lock_object.lo_name, file, line));
6294e7f640dSJohn Baldwin 		sx->sx_recurse++;
6304e7f640dSJohn Baldwin 		atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
6314e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
6324e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
633f9819486SAttilio Rao 		return (0);
6344e7f640dSJohn Baldwin 	}
6354e7f640dSJohn Baldwin 
6364e7f640dSJohn Baldwin 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
6374e7f640dSJohn Baldwin 		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
6384e7f640dSJohn Baldwin 		    sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
6394e7f640dSJohn Baldwin 
640f90d57b8SMateusz Guzik #if defined(ADAPTIVE_SX)
641f90d57b8SMateusz Guzik 	lock_delay_arg_init(&lda, &sx_delay);
642f90d57b8SMateusz Guzik #elif defined(KDTRACE_HOOKS)
643f90d57b8SMateusz Guzik 	lock_delay_arg_init_noadapt(&lda);
644f90d57b8SMateusz Guzik #endif
645f90d57b8SMateusz Guzik 
646ae7d25a4SMateusz Guzik #ifdef HWPMC_HOOKS
647ae7d25a4SMateusz Guzik 	PMC_SOFT_CALL( , , lock, failed);
648ae7d25a4SMateusz Guzik #endif
6496a467cc5SMateusz Guzik 	lock_profile_obtain_lock_failed(&sx->lock_object, false, &contested,
650ae7d25a4SMateusz Guzik 	    &waittime);
651ae7d25a4SMateusz Guzik 
652fb106123SMateusz Guzik #ifndef INVARIANTS
653fb106123SMateusz Guzik 	GIANT_SAVE(extra_work);
654fb106123SMateusz Guzik #endif
655e41d6166SMateusz Guzik 
6567530de77SMateusz Guzik 	THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
6577530de77SMateusz Guzik 
658fc4f686dSMateusz Guzik 	for (;;) {
659c5f61e6fSMateusz Guzik 		if (x == SX_LOCK_UNLOCKED) {
660fa474043SMateusz Guzik 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
661fc4f686dSMateusz Guzik 				break;
662c5f61e6fSMateusz Guzik 			continue;
663c5f61e6fSMateusz Guzik 		}
664fb106123SMateusz Guzik #ifdef INVARIANTS
665fb106123SMateusz Guzik 		GIANT_SAVE(extra_work);
666fb106123SMateusz Guzik #endif
667a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
6681ada9041SMateusz Guzik 		lda.spin_cnt++;
669a5aedd68SStacey Son #endif
6704e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
671befd3e35SMateusz Guzik 		if (x == (SX_LOCK_SHARED | SX_LOCK_WRITE_SPINNER)) {
672befd3e35SMateusz Guzik 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
673befd3e35SMateusz Guzik 				break;
674befd3e35SMateusz Guzik 			continue;
675befd3e35SMateusz Guzik 		}
676befd3e35SMateusz Guzik 
6774e7f640dSJohn Baldwin 		/*
6784e7f640dSJohn Baldwin 		 * If the lock is write locked and the owner is
6794e7f640dSJohn Baldwin 		 * running on another CPU, spin until the owner stops
6804e7f640dSJohn Baldwin 		 * running or the state of the lock changes.
6814e7f640dSJohn Baldwin 		 */
6821ae1c2a3SAttilio Rao 		if ((x & SX_LOCK_SHARED) == 0) {
6832466d12bSMateusz Guzik 			sx_drop_critical(x, &in_critical, &extra_work);
684d94df98cSMateusz Guzik 			sleep_reason = WRITER;
685c5f61e6fSMateusz Guzik 			owner = lv_sx_owner(x);
686d94df98cSMateusz Guzik 			if (!TD_IS_RUNNING(owner))
687d94df98cSMateusz Guzik 				goto sleepq;
6884e7f640dSJohn Baldwin 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
689d94df98cSMateusz Guzik 				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
6904e7f640dSJohn Baldwin 				    __func__, sx, owner);
691d94df98cSMateusz Guzik 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
692d94df98cSMateusz Guzik 			    "spinning", "lockname:\"%s\"",
6932cba8dd3SJohn Baldwin 			    sx->lock_object.lo_name);
694c5f61e6fSMateusz Guzik 			do {
6951ada9041SMateusz Guzik 				lock_delay(&lda);
696c5f61e6fSMateusz Guzik 				x = SX_READ_VALUE(sx);
697c5f61e6fSMateusz Guzik 				owner = lv_sx_owner(x);
698d94df98cSMateusz Guzik 			} while (owner != NULL && TD_IS_RUNNING(owner));
699d94df98cSMateusz Guzik 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
700d94df98cSMateusz Guzik 			    "running");
7014e7f640dSJohn Baldwin 			continue;
702d94df98cSMateusz Guzik 		} else if (SX_SHARERS(x) > 0) {
703d94df98cSMateusz Guzik 			sleep_reason = READERS;
704d94df98cSMateusz Guzik 			if (spintries == asx_retries)
705d94df98cSMateusz Guzik 				goto sleepq;
7062466d12bSMateusz Guzik 			if (!(x & SX_LOCK_WRITE_SPINNER)) {
7072466d12bSMateusz Guzik 				if (!in_critical) {
7082466d12bSMateusz Guzik 					critical_enter();
7092466d12bSMateusz Guzik 					in_critical = true;
7102466d12bSMateusz Guzik 					extra_work++;
7112466d12bSMateusz Guzik 				}
7122466d12bSMateusz Guzik 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
7132466d12bSMateusz Guzik 				    x | SX_LOCK_WRITE_SPINNER)) {
7142466d12bSMateusz Guzik 					critical_exit();
7152466d12bSMateusz Guzik 					in_critical = false;
7162466d12bSMateusz Guzik 					extra_work--;
7172466d12bSMateusz Guzik 					continue;
7182466d12bSMateusz Guzik 				}
7192466d12bSMateusz Guzik 			}
7201ae1c2a3SAttilio Rao 			spintries++;
721d94df98cSMateusz Guzik 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
722d94df98cSMateusz Guzik 			    "spinning", "lockname:\"%s\"",
723d94df98cSMateusz Guzik 			    sx->lock_object.lo_name);
724d07e22cdSMateusz Guzik 			n = SX_SHARERS(x);
7252466d12bSMateusz Guzik 			for (i = 0; i < asx_loops; i += n) {
726d07e22cdSMateusz Guzik 				lock_delay_spin(n);
72720a15d17SMateusz Guzik 				x = SX_READ_VALUE(sx);
7282466d12bSMateusz Guzik 				if (!(x & SX_LOCK_WRITE_SPINNER))
7292466d12bSMateusz Guzik 					break;
7302466d12bSMateusz Guzik 				if (!(x & SX_LOCK_SHARED))
7312466d12bSMateusz Guzik 					break;
7322466d12bSMateusz Guzik 				n = SX_SHARERS(x);
7332466d12bSMateusz Guzik 				if (n == 0)
7341ae1c2a3SAttilio Rao 					break;
7351ae1c2a3SAttilio Rao 			}
73620a15d17SMateusz Guzik #ifdef KDTRACE_HOOKS
73720a15d17SMateusz Guzik 			lda.spin_cnt += i;
73820a15d17SMateusz Guzik #endif
739d94df98cSMateusz Guzik 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
740d94df98cSMateusz Guzik 			    "running");
741efa9f177SMateusz Guzik 			if (i < asx_loops)
7421ae1c2a3SAttilio Rao 				continue;
7431ae1c2a3SAttilio Rao 		}
744fb106123SMateusz Guzik sleepq:
745cde25ed4SMateusz Guzik #endif
7464e7f640dSJohn Baldwin 		sleepq_lock(&sx->lock_object);
747c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
74893118b62SMateusz Guzik retry_sleepq:
7494e7f640dSJohn Baldwin 
7504e7f640dSJohn Baldwin 		/*
7514e7f640dSJohn Baldwin 		 * If the lock was released while spinning on the
7524e7f640dSJohn Baldwin 		 * sleep queue chain lock, try again.
7534e7f640dSJohn Baldwin 		 */
7544e7f640dSJohn Baldwin 		if (x == SX_LOCK_UNLOCKED) {
7554e7f640dSJohn Baldwin 			sleepq_release(&sx->lock_object);
7562466d12bSMateusz Guzik 			sx_drop_critical(x, &in_critical, &extra_work);
7574e7f640dSJohn Baldwin 			continue;
7584e7f640dSJohn Baldwin 		}
7594e7f640dSJohn Baldwin 
7604e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
7614e7f640dSJohn Baldwin 		/*
7624e7f640dSJohn Baldwin 		 * The current lock owner might have started executing
7634e7f640dSJohn Baldwin 		 * on another CPU (or the lock could have changed
7644e7f640dSJohn Baldwin 		 * owners) while we were waiting on the sleep queue
7654e7f640dSJohn Baldwin 		 * chain lock.  If so, drop the sleep queue lock and try
7664e7f640dSJohn Baldwin 		 * again.
7674e7f640dSJohn Baldwin 		 */
76828f1a9e3SMateusz Guzik 		if (!(x & SX_LOCK_SHARED)) {
7694e7f640dSJohn Baldwin 			owner = (struct thread *)SX_OWNER(x);
7704e7f640dSJohn Baldwin 			if (TD_IS_RUNNING(owner)) {
7714e7f640dSJohn Baldwin 				sleepq_release(&sx->lock_object);
7722466d12bSMateusz Guzik 				sx_drop_critical(x, &in_critical,
7732466d12bSMateusz Guzik 				    &extra_work);
7744e7f640dSJohn Baldwin 				continue;
7754e7f640dSJohn Baldwin 			}
776d94df98cSMateusz Guzik 		} else if (SX_SHARERS(x) > 0 && sleep_reason == WRITER) {
77728f1a9e3SMateusz Guzik 			sleepq_release(&sx->lock_object);
7782466d12bSMateusz Guzik 			sx_drop_critical(x, &in_critical, &extra_work);
77928f1a9e3SMateusz Guzik 			continue;
78028f1a9e3SMateusz Guzik 		}
7814e7f640dSJohn Baldwin #endif
7824e7f640dSJohn Baldwin 
7834e7f640dSJohn Baldwin 		/*
7844e7f640dSJohn Baldwin 		 * If an exclusive lock was released with both shared
7854e7f640dSJohn Baldwin 		 * and exclusive waiters and a shared waiter hasn't
7864e7f640dSJohn Baldwin 		 * woken up and acquired the lock yet, sx_lock will be
7874e7f640dSJohn Baldwin 		 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
7884e7f640dSJohn Baldwin 		 * If we see that value, try to acquire it once.  Note
7894e7f640dSJohn Baldwin 		 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
7904e7f640dSJohn Baldwin 		 * as there are other exclusive waiters still.  If we
7914e7f640dSJohn Baldwin 		 * fail, restart the loop.
7924e7f640dSJohn Baldwin 		 */
7932466d12bSMateusz Guzik 		setx = x & (SX_LOCK_WAITERS | SX_LOCK_WRITE_SPINNER);
7942466d12bSMateusz Guzik 		if ((x & ~setx) == SX_LOCK_SHARED) {
7952466d12bSMateusz Guzik 			setx &= ~SX_LOCK_WRITE_SPINNER;
7962466d12bSMateusz Guzik 			if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid | setx))
79793118b62SMateusz Guzik 				goto retry_sleepq;
7984e7f640dSJohn Baldwin 			sleepq_release(&sx->lock_object);
7994e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p claimed by new writer",
8004e7f640dSJohn Baldwin 			    __func__, sx);
8014e7f640dSJohn Baldwin 			break;
8024e7f640dSJohn Baldwin 		}
8034e7f640dSJohn Baldwin 
8042466d12bSMateusz Guzik #ifdef ADAPTIVE_SX
8052466d12bSMateusz Guzik 		/*
8062466d12bSMateusz Guzik 		 * It is possible we set the SX_LOCK_WRITE_SPINNER bit.
8072466d12bSMateusz Guzik 		 * It is an invariant that when the bit is set, there is
8082466d12bSMateusz Guzik 		 * a writer ready to grab the lock. Thus clear the bit since
8092466d12bSMateusz Guzik 		 * we are going to sleep.
8102466d12bSMateusz Guzik 		 */
8112466d12bSMateusz Guzik 		if (in_critical) {
8122466d12bSMateusz Guzik 			if ((x & SX_LOCK_WRITE_SPINNER) ||
8132466d12bSMateusz Guzik 			    !((x & SX_LOCK_EXCLUSIVE_WAITERS))) {
8142466d12bSMateusz Guzik 				setx = x & ~SX_LOCK_WRITE_SPINNER;
8152466d12bSMateusz Guzik 				setx |= SX_LOCK_EXCLUSIVE_WAITERS;
8162466d12bSMateusz Guzik 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
8172466d12bSMateusz Guzik 				    setx)) {
8182466d12bSMateusz Guzik 					goto retry_sleepq;
8192466d12bSMateusz Guzik 				}
8202466d12bSMateusz Guzik 			}
8212466d12bSMateusz Guzik 			critical_exit();
8222466d12bSMateusz Guzik 			in_critical = false;
8232466d12bSMateusz Guzik 		} else {
8242466d12bSMateusz Guzik #endif
8254e7f640dSJohn Baldwin 			/*
8264e7f640dSJohn Baldwin 			 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
8274e7f640dSJohn Baldwin 			 * than loop back and retry.
8284e7f640dSJohn Baldwin 			 */
8294e7f640dSJohn Baldwin 			if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
83093118b62SMateusz Guzik 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
8314e7f640dSJohn Baldwin 				    x | SX_LOCK_EXCLUSIVE_WAITERS)) {
83293118b62SMateusz Guzik 					goto retry_sleepq;
8334e7f640dSJohn Baldwin 				}
8344e7f640dSJohn Baldwin 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
8354e7f640dSJohn Baldwin 					CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
8364e7f640dSJohn Baldwin 					    __func__, sx);
8374e7f640dSJohn Baldwin 			}
8382466d12bSMateusz Guzik #ifdef ADAPTIVE_SX
8392466d12bSMateusz Guzik 		}
8402466d12bSMateusz Guzik #endif
8414e7f640dSJohn Baldwin 
8424e7f640dSJohn Baldwin 		/*
8434e7f640dSJohn Baldwin 		 * Since we have been unable to acquire the exclusive
8444e7f640dSJohn Baldwin 		 * lock and the exclusive waiters flag is set, we have
8454e7f640dSJohn Baldwin 		 * to sleep.
8464e7f640dSJohn Baldwin 		 */
8474e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
8484e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
8494e7f640dSJohn Baldwin 			    __func__, sx);
8504e7f640dSJohn Baldwin 
851a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
852e2b25737SMark Johnston 		sleep_time -= lockstat_nsecs(&sx->lock_object);
853a5aedd68SStacey Son #endif
8544e7f640dSJohn Baldwin 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
855f9819486SAttilio Rao 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
856f9819486SAttilio Rao 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
857*c35f527eSMateusz Guzik 		/*
858*c35f527eSMateusz Guzik 		 * Hack: this can land in thread_suspend_check which will
859*c35f527eSMateusz Guzik 		 * conditionally take a mutex, tripping over an assert if a
860*c35f527eSMateusz Guzik 		 * lock we are waiting for is set.
861*c35f527eSMateusz Guzik 		 */
862*c35f527eSMateusz Guzik 		THREAD_CONTENTION_DONE(&sx->lock_object);
863f9819486SAttilio Rao 		if (!(opts & SX_INTERRUPTIBLE))
864c5aa6b58SJeff Roberson 			sleepq_wait(&sx->lock_object, 0);
865f9819486SAttilio Rao 		else
866c5aa6b58SJeff Roberson 			error = sleepq_wait_sig(&sx->lock_object, 0);
867*c35f527eSMateusz Guzik 		THREAD_CONTENTION_DONE(&sx->lock_object);
868a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
869e2b25737SMark Johnston 		sleep_time += lockstat_nsecs(&sx->lock_object);
870a5aedd68SStacey Son 		sleep_cnt++;
871a5aedd68SStacey Son #endif
872f9819486SAttilio Rao 		if (error) {
873f9819486SAttilio Rao 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
874f9819486SAttilio Rao 				CTR2(KTR_LOCK,
875f9819486SAttilio Rao 			"%s: interruptible sleep by %p suspended by signal",
876f9819486SAttilio Rao 				    __func__, sx);
877f9819486SAttilio Rao 			break;
878f9819486SAttilio Rao 		}
8794e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
8804e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
8814e7f640dSJohn Baldwin 			    __func__, sx);
882c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
8834e7f640dSJohn Baldwin 	}
8847530de77SMateusz Guzik 	THREAD_CONTENTION_DONE(&sx->lock_object);
885e41d6166SMateusz Guzik 	if (__predict_true(!extra_work))
886e41d6166SMateusz Guzik 		return (error);
8872466d12bSMateusz Guzik #ifdef ADAPTIVE_SX
8882466d12bSMateusz Guzik 	if (in_critical)
8892466d12bSMateusz Guzik 		critical_exit();
8902466d12bSMateusz Guzik #endif
891ee252fc9SMateusz Guzik 	GIANT_RESTORE();
8922466d12bSMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
8932466d12bSMateusz Guzik 	if (__predict_true(!doing_lockprof))
8942466d12bSMateusz Guzik 		return (error);
895e41d6166SMateusz Guzik #endif
896076dd8ebSAndriy Gapon #ifdef KDTRACE_HOOKS
897e2b25737SMark Johnston 	all_time += lockstat_nsecs(&sx->lock_object);
898076dd8ebSAndriy Gapon 	if (sleep_time)
89932cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
900076dd8ebSAndriy Gapon 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
901076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
9021ada9041SMateusz Guzik 	if (lda.spin_cnt > sleep_cnt)
90332cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
904076dd8ebSAndriy Gapon 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
905076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
90609bdec20SMateusz Guzik out_lockstat:
907076dd8ebSAndriy Gapon #endif
908f9819486SAttilio Rao 	if (!error)
909de2c95ccSMark Johnston 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
910de2c95ccSMark Johnston 		    contested, waittime, file, line, LOCKSTAT_WRITER);
911f9819486SAttilio Rao 	return (error);
9124e7f640dSJohn Baldwin }
9134e7f640dSJohn Baldwin 
9144e7f640dSJohn Baldwin /*
9154e7f640dSJohn Baldwin  * This function represents the so-called 'hard case' for sx_xunlock
9164e7f640dSJohn Baldwin  * operation.  All 'easy case' failures are redirected to this.  Note
9174e7f640dSJohn Baldwin  * that ideally this would be a static function, but it needs to be
9184e7f640dSJohn Baldwin  * accessible from at least sx.h.
9194e7f640dSJohn Baldwin  */
9204e7f640dSJohn Baldwin void
921b584eb2eSMateusz Guzik _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
9224e7f640dSJohn Baldwin {
923b584eb2eSMateusz Guzik 	uintptr_t tid, setx;
924da7bbd2cSJohn Baldwin 	int queue, wakeup_swapper;
9254e7f640dSJohn Baldwin 
92635370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
92735370593SAndriy Gapon 		return;
92835370593SAndriy Gapon 
929b584eb2eSMateusz Guzik 	tid = (uintptr_t)curthread;
9304e7f640dSJohn Baldwin 
931b584eb2eSMateusz Guzik 	if (__predict_false(x == tid))
9323b3cf014SMateusz Guzik 		x = SX_READ_VALUE(sx);
933b584eb2eSMateusz Guzik 
934b584eb2eSMateusz Guzik 	MPASS(!(x & SX_LOCK_SHARED));
935b584eb2eSMateusz Guzik 
936b584eb2eSMateusz Guzik 	if (__predict_false(x & SX_LOCK_RECURSED)) {
9376ebb77b6SMateusz Guzik 		/* The lock is recursed, unrecurse one level. */
9384e7f640dSJohn Baldwin 		if ((--sx->sx_recurse) == 0)
9394e7f640dSJohn Baldwin 			atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
9404e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
9414e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
9424e7f640dSJohn Baldwin 		return;
9434e7f640dSJohn Baldwin 	}
9443b3cf014SMateusz Guzik 
9453b3cf014SMateusz Guzik 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
9463b3cf014SMateusz Guzik 	if (x == tid &&
9473b3cf014SMateusz Guzik 	    atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
9483b3cf014SMateusz Guzik 		return;
9493b3cf014SMateusz Guzik 
9504e7f640dSJohn Baldwin 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
9514e7f640dSJohn Baldwin 		CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
9524e7f640dSJohn Baldwin 
9534e7f640dSJohn Baldwin 	sleepq_lock(&sx->lock_object);
954bc24577cSMateusz Guzik 	x = SX_READ_VALUE(sx);
9552d96bd88SMateusz Guzik 	MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
9564e7f640dSJohn Baldwin 
9574e7f640dSJohn Baldwin 	/*
9584e7f640dSJohn Baldwin 	 * The wake up algorithm here is quite simple and probably not
9594e7f640dSJohn Baldwin 	 * ideal.  It gives precedence to shared waiters if they are
9604e7f640dSJohn Baldwin 	 * present.  For this condition, we have to preserve the
9614e7f640dSJohn Baldwin 	 * state of the exclusive waiters flag.
9622028867dSAttilio Rao 	 * If interruptible sleeps left the shared queue empty avoid a
9632028867dSAttilio Rao 	 * starvation for the threads sleeping on the exclusive queue by giving
9642028867dSAttilio Rao 	 * them precedence and cleaning up the shared waiters bit anyway.
9654e7f640dSJohn Baldwin 	 */
966bc24577cSMateusz Guzik 	setx = SX_LOCK_UNLOCKED;
9674e7f640dSJohn Baldwin 	queue = SQ_SHARED_QUEUE;
9682466d12bSMateusz Guzik 	if ((x & SX_LOCK_EXCLUSIVE_WAITERS) != 0 &&
9692466d12bSMateusz Guzik 	    sleepq_sleepcnt(&sx->lock_object, SQ_EXCLUSIVE_QUEUE) != 0) {
9702466d12bSMateusz Guzik 		queue = SQ_EXCLUSIVE_QUEUE;
9712466d12bSMateusz Guzik 		setx |= (x & SX_LOCK_SHARED_WAITERS);
972bc24577cSMateusz Guzik 	}
973bc24577cSMateusz Guzik 	atomic_store_rel_ptr(&sx->sx_lock, setx);
9744e7f640dSJohn Baldwin 
9754e7f640dSJohn Baldwin 	/* Wake up all the waiters for the specific queue. */
9764e7f640dSJohn Baldwin 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
9774e7f640dSJohn Baldwin 		CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
9784e7f640dSJohn Baldwin 		    __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
9794e7f640dSJohn Baldwin 		    "exclusive");
980bc24577cSMateusz Guzik 
981da7bbd2cSJohn Baldwin 	wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
982da7bbd2cSJohn Baldwin 	    queue);
983c5aa6b58SJeff Roberson 	sleepq_release(&sx->lock_object);
984da7bbd2cSJohn Baldwin 	if (wakeup_swapper)
985da7bbd2cSJohn Baldwin 		kick_proc0();
9864e7f640dSJohn Baldwin }
9874e7f640dSJohn Baldwin 
988834f70f3SMateusz Guzik static bool __always_inline
9892466d12bSMateusz Guzik __sx_can_read(struct thread *td, uintptr_t x, bool fp)
9902466d12bSMateusz Guzik {
9912466d12bSMateusz Guzik 
9922466d12bSMateusz Guzik 	if ((x & (SX_LOCK_SHARED | SX_LOCK_EXCLUSIVE_WAITERS | SX_LOCK_WRITE_SPINNER))
9932466d12bSMateusz Guzik 			== SX_LOCK_SHARED)
9942466d12bSMateusz Guzik 		return (true);
9952466d12bSMateusz Guzik 	if (!fp && td->td_sx_slocks && (x & SX_LOCK_SHARED))
9962466d12bSMateusz Guzik 		return (true);
9972466d12bSMateusz Guzik 	return (false);
9982466d12bSMateusz Guzik }
9992466d12bSMateusz Guzik 
10002466d12bSMateusz Guzik static bool __always_inline
10012466d12bSMateusz Guzik __sx_slock_try(struct sx *sx, struct thread *td, uintptr_t *xp, bool fp
10022466d12bSMateusz Guzik     LOCK_FILE_LINE_ARG_DEF)
1003834f70f3SMateusz Guzik {
1004834f70f3SMateusz Guzik 
1005834f70f3SMateusz Guzik 	/*
1006834f70f3SMateusz Guzik 	 * If no other thread has an exclusive lock then try to bump up
1007834f70f3SMateusz Guzik 	 * the count of sharers.  Since we have to preserve the state
1008834f70f3SMateusz Guzik 	 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
1009834f70f3SMateusz Guzik 	 * shared lock loop back and retry.
1010834f70f3SMateusz Guzik 	 */
10112466d12bSMateusz Guzik 	while (__sx_can_read(td, *xp, fp)) {
1012834f70f3SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
1013834f70f3SMateusz Guzik 		    *xp + SX_ONE_SHARER)) {
1014834f70f3SMateusz Guzik 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1015834f70f3SMateusz Guzik 				CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
1016834f70f3SMateusz Guzik 				    __func__, sx, (void *)*xp,
1017834f70f3SMateusz Guzik 				    (void *)(*xp + SX_ONE_SHARER));
10182466d12bSMateusz Guzik 			td->td_sx_slocks++;
1019834f70f3SMateusz Guzik 			return (true);
1020834f70f3SMateusz Guzik 		}
1021834f70f3SMateusz Guzik 	}
1022834f70f3SMateusz Guzik 	return (false);
1023834f70f3SMateusz Guzik }
1024834f70f3SMateusz Guzik 
1025834f70f3SMateusz Guzik static int __noinline
1026013c0b49SMateusz Guzik _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
10274e7f640dSJohn Baldwin {
10284e7f640dSJohn Baldwin 	GIANT_DECLARE;
10292466d12bSMateusz Guzik 	struct thread *td;
10304e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
1031094c148bSMateusz Guzik 	struct thread *owner;
10322466d12bSMateusz Guzik 	u_int i, n, spintries = 0;
10334e7f640dSJohn Baldwin #endif
10341723a064SJeff Roberson #ifdef LOCK_PROFILING
1035c1a6d9faSAttilio Rao 	uint64_t waittime = 0;
1036c1a6d9faSAttilio Rao 	int contested = 0;
10371723a064SJeff Roberson #endif
1038c1a6d9faSAttilio Rao 	int error = 0;
103904126895SMateusz Guzik #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
10401ada9041SMateusz Guzik 	struct lock_delay_arg lda;
10411ada9041SMateusz Guzik #endif
1042a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
104361852185SMateusz Guzik 	u_int sleep_cnt = 0;
1044a5aedd68SStacey Son 	int64_t sleep_time = 0;
1045076dd8ebSAndriy Gapon 	int64_t all_time = 0;
1046a5aedd68SStacey Son #endif
1047e41d6166SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
10481dce110fSMatt Macy 	uintptr_t state = 0;
1049e41d6166SMateusz Guzik #endif
1050de709b14SMateusz Guzik 	int extra_work __sdt_used = 0;
1051c1a6d9faSAttilio Rao 
10522466d12bSMateusz Guzik 	td = curthread;
10532466d12bSMateusz Guzik 
105409bdec20SMateusz Guzik #ifdef KDTRACE_HOOKS
105509bdec20SMateusz Guzik 	if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
10562466d12bSMateusz Guzik 		if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
105709bdec20SMateusz Guzik 			goto out_lockstat;
105809bdec20SMateusz Guzik 		extra_work = 1;
105909bdec20SMateusz Guzik 		all_time -= lockstat_nsecs(&sx->lock_object);
106009bdec20SMateusz Guzik 		state = x;
106109bdec20SMateusz Guzik 	}
106209bdec20SMateusz Guzik #endif
106309bdec20SMateusz Guzik #ifdef LOCK_PROFILING
106409bdec20SMateusz Guzik 	extra_work = 1;
106509bdec20SMateusz Guzik 	state = x;
106609bdec20SMateusz Guzik #endif
106709bdec20SMateusz Guzik 
106835370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
106935370593SAndriy Gapon 		return (0);
107035370593SAndriy Gapon 
1071fa5000a4SMateusz Guzik #if defined(ADAPTIVE_SX)
10721ada9041SMateusz Guzik 	lock_delay_arg_init(&lda, &sx_delay);
1073fa5000a4SMateusz Guzik #elif defined(KDTRACE_HOOKS)
1074c795344fSMateusz Guzik 	lock_delay_arg_init_noadapt(&lda);
10751ada9041SMateusz Guzik #endif
1076e41d6166SMateusz Guzik 
1077ae7d25a4SMateusz Guzik #ifdef HWPMC_HOOKS
1078ae7d25a4SMateusz Guzik 	PMC_SOFT_CALL( , , lock, failed);
1079ae7d25a4SMateusz Guzik #endif
10806a467cc5SMateusz Guzik 	lock_profile_obtain_lock_failed(&sx->lock_object, false, &contested,
1081ae7d25a4SMateusz Guzik 	    &waittime);
1082ae7d25a4SMateusz Guzik 
1083fb106123SMateusz Guzik #ifndef INVARIANTS
1084fb106123SMateusz Guzik 	GIANT_SAVE(extra_work);
1085fb106123SMateusz Guzik #endif
1086076dd8ebSAndriy Gapon 
10877530de77SMateusz Guzik 	THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
10887530de77SMateusz Guzik 
10894e7f640dSJohn Baldwin 	/*
10904e7f640dSJohn Baldwin 	 * As with rwlocks, we don't make any attempt to try to block
10914e7f640dSJohn Baldwin 	 * shared locks once there is an exclusive waiter.
10924e7f640dSJohn Baldwin 	 */
10934e7f640dSJohn Baldwin 	for (;;) {
10942466d12bSMateusz Guzik 		if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
10954e7f640dSJohn Baldwin 			break;
1096fb106123SMateusz Guzik #ifdef INVARIANTS
1097fb106123SMateusz Guzik 		GIANT_SAVE(extra_work);
1098fb106123SMateusz Guzik #endif
1099c5f61e6fSMateusz Guzik #ifdef KDTRACE_HOOKS
1100c5f61e6fSMateusz Guzik 		lda.spin_cnt++;
1101c5f61e6fSMateusz Guzik #endif
1102c5f61e6fSMateusz Guzik 
11034e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
11044e7f640dSJohn Baldwin 		/*
11054e7f640dSJohn Baldwin 		 * If the owner is running on another CPU, spin until
11064e7f640dSJohn Baldwin 		 * the owner stops running or the state of the lock
11074e7f640dSJohn Baldwin 		 * changes.
11084e7f640dSJohn Baldwin 		 */
11092466d12bSMateusz Guzik 		if ((x & SX_LOCK_SHARED) == 0) {
1110c5f61e6fSMateusz Guzik 			owner = lv_sx_owner(x);
11114e7f640dSJohn Baldwin 			if (TD_IS_RUNNING(owner)) {
11124e7f640dSJohn Baldwin 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
11134e7f640dSJohn Baldwin 					CTR3(KTR_LOCK,
11144e7f640dSJohn Baldwin 					    "%s: spinning on %p held by %p",
11154e7f640dSJohn Baldwin 					    __func__, sx, owner);
11162cba8dd3SJohn Baldwin 				KTR_STATE1(KTR_SCHED, "thread",
11172cba8dd3SJohn Baldwin 				    sched_tdname(curthread), "spinning",
11182cba8dd3SJohn Baldwin 				    "lockname:\"%s\"", sx->lock_object.lo_name);
1119c5f61e6fSMateusz Guzik 				do {
11201ada9041SMateusz Guzik 					lock_delay(&lda);
1121c5f61e6fSMateusz Guzik 					x = SX_READ_VALUE(sx);
1122c5f61e6fSMateusz Guzik 					owner = lv_sx_owner(x);
1123c5f61e6fSMateusz Guzik 				} while (owner != NULL && TD_IS_RUNNING(owner));
11242cba8dd3SJohn Baldwin 				KTR_STATE0(KTR_SCHED, "thread",
11252cba8dd3SJohn Baldwin 				    sched_tdname(curthread), "running");
11264e7f640dSJohn Baldwin 				continue;
11274e7f640dSJohn Baldwin 			}
11282466d12bSMateusz Guzik 		} else {
11292466d12bSMateusz Guzik 			if ((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) {
11302466d12bSMateusz Guzik 				MPASS(!__sx_can_read(td, x, false));
11312466d12bSMateusz Guzik 				lock_delay_spin(2);
11322466d12bSMateusz Guzik 				x = SX_READ_VALUE(sx);
11332466d12bSMateusz Guzik 				continue;
11342466d12bSMateusz Guzik 			}
11352466d12bSMateusz Guzik 			if (spintries < asx_retries) {
11362466d12bSMateusz Guzik 				KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
11372466d12bSMateusz Guzik 				    "spinning", "lockname:\"%s\"",
11382466d12bSMateusz Guzik 				    sx->lock_object.lo_name);
11392466d12bSMateusz Guzik 				n = SX_SHARERS(x);
11402466d12bSMateusz Guzik 				for (i = 0; i < asx_loops; i += n) {
11412466d12bSMateusz Guzik 					lock_delay_spin(n);
11422466d12bSMateusz Guzik 					x = SX_READ_VALUE(sx);
11432466d12bSMateusz Guzik 					if (!(x & SX_LOCK_SHARED))
11442466d12bSMateusz Guzik 						break;
11452466d12bSMateusz Guzik 					n = SX_SHARERS(x);
11462466d12bSMateusz Guzik 					if (n == 0)
11472466d12bSMateusz Guzik 						break;
11482466d12bSMateusz Guzik 					if (__sx_can_read(td, x, false))
11492466d12bSMateusz Guzik 						break;
11502466d12bSMateusz Guzik 				}
11512466d12bSMateusz Guzik #ifdef KDTRACE_HOOKS
11522466d12bSMateusz Guzik 				lda.spin_cnt += i;
11532466d12bSMateusz Guzik #endif
11542466d12bSMateusz Guzik 				KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
11552466d12bSMateusz Guzik 				    "running");
11562466d12bSMateusz Guzik 				if (i < asx_loops)
11572466d12bSMateusz Guzik 					continue;
11582466d12bSMateusz Guzik 			}
11592466d12bSMateusz Guzik 		}
11604e7f640dSJohn Baldwin #endif
11614e7f640dSJohn Baldwin 
11624e7f640dSJohn Baldwin 		/*
11634e7f640dSJohn Baldwin 		 * Some other thread already has an exclusive lock, so
11644e7f640dSJohn Baldwin 		 * start the process of blocking.
11654e7f640dSJohn Baldwin 		 */
11664e7f640dSJohn Baldwin 		sleepq_lock(&sx->lock_object);
1167c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
116893118b62SMateusz Guzik retry_sleepq:
11692466d12bSMateusz Guzik 		if (((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) ||
11702466d12bSMateusz Guzik 		    __sx_can_read(td, x, false)) {
11714e7f640dSJohn Baldwin 			sleepq_release(&sx->lock_object);
11724e7f640dSJohn Baldwin 			continue;
11734e7f640dSJohn Baldwin 		}
11744e7f640dSJohn Baldwin 
11754e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
11764e7f640dSJohn Baldwin 		/*
11774e7f640dSJohn Baldwin 		 * If the owner is running on another CPU, spin until
11784e7f640dSJohn Baldwin 		 * the owner stops running or the state of the lock
11794e7f640dSJohn Baldwin 		 * changes.
11804e7f640dSJohn Baldwin 		 */
1181f26db694SMateusz Guzik 		if (!(x & SX_LOCK_SHARED)) {
11824e7f640dSJohn Baldwin 			owner = (struct thread *)SX_OWNER(x);
11834e7f640dSJohn Baldwin 			if (TD_IS_RUNNING(owner)) {
11844e7f640dSJohn Baldwin 				sleepq_release(&sx->lock_object);
1185c5f61e6fSMateusz Guzik 				x = SX_READ_VALUE(sx);
11864e7f640dSJohn Baldwin 				continue;
11874e7f640dSJohn Baldwin 			}
11884e7f640dSJohn Baldwin 		}
11894e7f640dSJohn Baldwin #endif
11904e7f640dSJohn Baldwin 
11914e7f640dSJohn Baldwin 		/*
11924e7f640dSJohn Baldwin 		 * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
11934e7f640dSJohn Baldwin 		 * fail to set it drop the sleep queue lock and loop
11944e7f640dSJohn Baldwin 		 * back.
11954e7f640dSJohn Baldwin 		 */
11964e7f640dSJohn Baldwin 		if (!(x & SX_LOCK_SHARED_WAITERS)) {
119793118b62SMateusz Guzik 			if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
119893118b62SMateusz Guzik 			    x | SX_LOCK_SHARED_WAITERS))
119993118b62SMateusz Guzik 				goto retry_sleepq;
12004e7f640dSJohn Baldwin 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
12014e7f640dSJohn Baldwin 				CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
12024e7f640dSJohn Baldwin 				    __func__, sx);
12034e7f640dSJohn Baldwin 		}
12044e7f640dSJohn Baldwin 
12054e7f640dSJohn Baldwin 		/*
12064e7f640dSJohn Baldwin 		 * Since we have been unable to acquire the shared lock,
12074e7f640dSJohn Baldwin 		 * we have to sleep.
12084e7f640dSJohn Baldwin 		 */
12094e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
12104e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
12114e7f640dSJohn Baldwin 			    __func__, sx);
12124e7f640dSJohn Baldwin 
1213a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
1214e2b25737SMark Johnston 		sleep_time -= lockstat_nsecs(&sx->lock_object);
1215a5aedd68SStacey Son #endif
12164e7f640dSJohn Baldwin 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1217f9819486SAttilio Rao 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1218f9819486SAttilio Rao 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1219*c35f527eSMateusz Guzik 		/*
1220*c35f527eSMateusz Guzik 		 * Hack: this can land in thread_suspend_check which will
1221*c35f527eSMateusz Guzik 		 * conditionally take a mutex, tripping over an assert if a
1222*c35f527eSMateusz Guzik 		 * lock we are waiting for is set.
1223*c35f527eSMateusz Guzik 		 */
1224*c35f527eSMateusz Guzik 		THREAD_CONTENTION_DONE(&sx->lock_object);
1225f9819486SAttilio Rao 		if (!(opts & SX_INTERRUPTIBLE))
1226c5aa6b58SJeff Roberson 			sleepq_wait(&sx->lock_object, 0);
1227f9819486SAttilio Rao 		else
1228c5aa6b58SJeff Roberson 			error = sleepq_wait_sig(&sx->lock_object, 0);
1229*c35f527eSMateusz Guzik 		THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
1230a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
1231e2b25737SMark Johnston 		sleep_time += lockstat_nsecs(&sx->lock_object);
1232a5aedd68SStacey Son 		sleep_cnt++;
1233a5aedd68SStacey Son #endif
1234f9819486SAttilio Rao 		if (error) {
1235f9819486SAttilio Rao 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1236f9819486SAttilio Rao 				CTR2(KTR_LOCK,
1237f9819486SAttilio Rao 			"%s: interruptible sleep by %p suspended by signal",
1238f9819486SAttilio Rao 				    __func__, sx);
1239f9819486SAttilio Rao 			break;
1240f9819486SAttilio Rao 		}
12414e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
12424e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
12434e7f640dSJohn Baldwin 			    __func__, sx);
1244c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
12454e7f640dSJohn Baldwin 	}
12467530de77SMateusz Guzik 	THREAD_CONTENTION_DONE(&sx->lock_object);
1247e41d6166SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1248e41d6166SMateusz Guzik 	if (__predict_true(!extra_work))
1249e41d6166SMateusz Guzik 		return (error);
1250e41d6166SMateusz Guzik #endif
1251076dd8ebSAndriy Gapon #ifdef KDTRACE_HOOKS
1252e2b25737SMark Johnston 	all_time += lockstat_nsecs(&sx->lock_object);
1253076dd8ebSAndriy Gapon 	if (sleep_time)
125432cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1255076dd8ebSAndriy Gapon 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1256076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
12571ada9041SMateusz Guzik 	if (lda.spin_cnt > sleep_cnt)
125832cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1259076dd8ebSAndriy Gapon 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1260076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
126109bdec20SMateusz Guzik out_lockstat:
1262076dd8ebSAndriy Gapon #endif
12633ae56ce9SMateusz Guzik 	if (error == 0) {
1264de2c95ccSMark Johnston 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1265de2c95ccSMark Johnston 		    contested, waittime, file, line, LOCKSTAT_READER);
12663ae56ce9SMateusz Guzik 	}
12674e7f640dSJohn Baldwin 	GIANT_RESTORE();
1268f9819486SAttilio Rao 	return (error);
12694e7f640dSJohn Baldwin }
12704e7f640dSJohn Baldwin 
1271834f70f3SMateusz Guzik int
1272013c0b49SMateusz Guzik _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
12734e7f640dSJohn Baldwin {
12742466d12bSMateusz Guzik 	struct thread *td;
12754e7f640dSJohn Baldwin 	uintptr_t x;
1276834f70f3SMateusz Guzik 	int error;
12774e7f640dSJohn Baldwin 
1278704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1279704cb42fSMark Johnston 	    !TD_IS_IDLETHREAD(curthread),
1280834f70f3SMateusz Guzik 	    ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1281834f70f3SMateusz Guzik 	    curthread, sx->lock_object.lo_name, file, line));
12823ae56ce9SMateusz Guzik 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1283834f70f3SMateusz Guzik 	    ("sx_slock() of destroyed sx @ %s:%d", file, line));
1284834f70f3SMateusz Guzik 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1285834f70f3SMateusz Guzik 
1286834f70f3SMateusz Guzik 	error = 0;
12872466d12bSMateusz Guzik 	td = curthread;
1288c5f61e6fSMateusz Guzik 	x = SX_READ_VALUE(sx);
1289e4ccf57fSMateusz Guzik 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__acquire) ||
12902466d12bSMateusz Guzik 	    !__sx_slock_try(sx, td, &x, true LOCK_FILE_LINE_ARG)))
1291013c0b49SMateusz Guzik 		error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1292e4ccf57fSMateusz Guzik 	else
12936a467cc5SMateusz Guzik 		lock_profile_obtain_lock_success(&sx->lock_object, false, 0, 0,
1294e4ccf57fSMateusz Guzik 		    file, line);
1295834f70f3SMateusz Guzik 	if (error == 0) {
1296834f70f3SMateusz Guzik 		LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1297834f70f3SMateusz Guzik 		WITNESS_LOCK(&sx->lock_object, 0, file, line);
1298834f70f3SMateusz Guzik 		TD_LOCKS_INC(curthread);
1299834f70f3SMateusz Guzik 	}
1300834f70f3SMateusz Guzik 	return (error);
1301834f70f3SMateusz Guzik }
1302834f70f3SMateusz Guzik 
1303013c0b49SMateusz Guzik int
1304013c0b49SMateusz Guzik _sx_slock(struct sx *sx, int opts, const char *file, int line)
1305013c0b49SMateusz Guzik {
1306013c0b49SMateusz Guzik 
1307013c0b49SMateusz Guzik 	return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1308013c0b49SMateusz Guzik }
1309013c0b49SMateusz Guzik 
1310834f70f3SMateusz Guzik static bool __always_inline
13112466d12bSMateusz Guzik _sx_sunlock_try(struct sx *sx, struct thread *td, uintptr_t *xp)
1312834f70f3SMateusz Guzik {
1313834f70f3SMateusz Guzik 
13144e7f640dSJohn Baldwin 	for (;;) {
13152466d12bSMateusz Guzik 		if (SX_SHARERS(*xp) > 1 || !(*xp & SX_LOCK_WAITERS)) {
1316834f70f3SMateusz Guzik 			if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1317834f70f3SMateusz Guzik 			    *xp - SX_ONE_SHARER)) {
13184e7f640dSJohn Baldwin 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
13194e7f640dSJohn Baldwin 					CTR4(KTR_LOCK,
13204e7f640dSJohn Baldwin 					    "%s: %p succeeded %p -> %p",
1321834f70f3SMateusz Guzik 					    __func__, sx, (void *)*xp,
1322834f70f3SMateusz Guzik 					    (void *)(*xp - SX_ONE_SHARER));
13232466d12bSMateusz Guzik 				td->td_sx_slocks--;
1324834f70f3SMateusz Guzik 				return (true);
13254e7f640dSJohn Baldwin 			}
13264e7f640dSJohn Baldwin 			continue;
13274e7f640dSJohn Baldwin 		}
1328834f70f3SMateusz Guzik 		break;
1329834f70f3SMateusz Guzik 	}
1330834f70f3SMateusz Guzik 	return (false);
1331834f70f3SMateusz Guzik }
1332834f70f3SMateusz Guzik 
1333834f70f3SMateusz Guzik static void __noinline
13342466d12bSMateusz Guzik _sx_sunlock_hard(struct sx *sx, struct thread *td, uintptr_t x
13352466d12bSMateusz Guzik     LOCK_FILE_LINE_ARG_DEF)
1336834f70f3SMateusz Guzik {
13371b54ffc8SMateusz Guzik 	int wakeup_swapper = 0;
13382466d12bSMateusz Guzik 	uintptr_t setx, queue;
1339834f70f3SMateusz Guzik 
1340834f70f3SMateusz Guzik 	if (SCHEDULER_STOPPED())
1341834f70f3SMateusz Guzik 		return;
1342834f70f3SMateusz Guzik 
13432466d12bSMateusz Guzik 	if (_sx_sunlock_try(sx, td, &x))
1344cec17473SMateusz Guzik 		goto out_lockstat;
13454e7f640dSJohn Baldwin 
13464e7f640dSJohn Baldwin 	sleepq_lock(&sx->lock_object);
1347cec17473SMateusz Guzik 	x = SX_READ_VALUE(sx);
1348cec17473SMateusz Guzik 	for (;;) {
13492466d12bSMateusz Guzik 		if (_sx_sunlock_try(sx, td, &x))
13501b54ffc8SMateusz Guzik 			break;
13511b54ffc8SMateusz Guzik 
13524e7f640dSJohn Baldwin 		/*
13534e7f640dSJohn Baldwin 		 * Wake up semantic here is quite simple:
13544e7f640dSJohn Baldwin 		 * Just wake up all the exclusive waiters.
13554e7f640dSJohn Baldwin 		 * Note that the state of the lock could have changed,
13564e7f640dSJohn Baldwin 		 * so if it fails loop back and retry.
13574e7f640dSJohn Baldwin 		 */
13582466d12bSMateusz Guzik 		setx = SX_LOCK_UNLOCKED;
13592466d12bSMateusz Guzik 		queue = SQ_SHARED_QUEUE;
13602466d12bSMateusz Guzik 		if (x & SX_LOCK_EXCLUSIVE_WAITERS) {
13612466d12bSMateusz Guzik 			setx |= (x & SX_LOCK_SHARED_WAITERS);
13622466d12bSMateusz Guzik 			queue = SQ_EXCLUSIVE_QUEUE;
13632466d12bSMateusz Guzik 		}
13642466d12bSMateusz Guzik 		setx |= (x & SX_LOCK_WRITE_SPINNER);
1365cec17473SMateusz Guzik 		if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
13664e7f640dSJohn Baldwin 			continue;
13674e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
13684e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p waking up all thread on"
13694e7f640dSJohn Baldwin 			    "exclusive queue", __func__, sx);
1370da7bbd2cSJohn Baldwin 		wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
13712466d12bSMateusz Guzik 		    0, queue);
13722466d12bSMateusz Guzik 		td->td_sx_slocks--;
1373cec17473SMateusz Guzik 		break;
1374cec17473SMateusz Guzik 	}
1375c5aa6b58SJeff Roberson 	sleepq_release(&sx->lock_object);
1376da7bbd2cSJohn Baldwin 	if (wakeup_swapper)
1377da7bbd2cSJohn Baldwin 		kick_proc0();
1378cec17473SMateusz Guzik out_lockstat:
1379dbe4541dSMark Johnston 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1380834f70f3SMateusz Guzik }
1381834f70f3SMateusz Guzik 
1382834f70f3SMateusz Guzik void
1383013c0b49SMateusz Guzik _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1384834f70f3SMateusz Guzik {
13852466d12bSMateusz Guzik 	struct thread *td;
1386834f70f3SMateusz Guzik 	uintptr_t x;
1387834f70f3SMateusz Guzik 
1388834f70f3SMateusz Guzik 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1389834f70f3SMateusz Guzik 	    ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1390834f70f3SMateusz Guzik 	_sx_assert(sx, SA_SLOCKED, file, line);
1391834f70f3SMateusz Guzik 	WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1392834f70f3SMateusz Guzik 	LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1393834f70f3SMateusz Guzik 
13942466d12bSMateusz Guzik 	td = curthread;
1395834f70f3SMateusz Guzik 	x = SX_READ_VALUE(sx);
1396e4ccf57fSMateusz Guzik 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__release) ||
13972466d12bSMateusz Guzik 	    !_sx_sunlock_try(sx, td, &x)))
13982466d12bSMateusz Guzik 		_sx_sunlock_hard(sx, td, x LOCK_FILE_LINE_ARG);
1399e4ccf57fSMateusz Guzik 	else
14006a467cc5SMateusz Guzik 		lock_profile_release_lock(&sx->lock_object, false);
1401834f70f3SMateusz Guzik 
14023ae56ce9SMateusz Guzik 	TD_LOCKS_DEC(curthread);
1403d55229b7SJason Evans }
14044e5e677bSJohn Baldwin 
1405013c0b49SMateusz Guzik void
1406013c0b49SMateusz Guzik _sx_sunlock(struct sx *sx, const char *file, int line)
1407013c0b49SMateusz Guzik {
1408013c0b49SMateusz Guzik 
1409013c0b49SMateusz Guzik 	_sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1410013c0b49SMateusz Guzik }
1411013c0b49SMateusz Guzik 
14124e5e677bSJohn Baldwin #ifdef INVARIANT_SUPPORT
1413781a35dfSJohn Baldwin #ifndef INVARIANTS
1414781a35dfSJohn Baldwin #undef	_sx_assert
1415781a35dfSJohn Baldwin #endif
1416781a35dfSJohn Baldwin 
14174e5e677bSJohn Baldwin /*
14184e5e677bSJohn Baldwin  * In the non-WITNESS case, sx_assert() can only detect that at least
14194e5e677bSJohn Baldwin  * *some* thread owns an slock, but it cannot guarantee that *this*
14204e5e677bSJohn Baldwin  * thread owns an slock.
14214e5e677bSJohn Baldwin  */
14224e5e677bSJohn Baldwin void
1423d576deedSPawel Jakub Dawidek _sx_assert(const struct sx *sx, int what, const char *file, int line)
14244e5e677bSJohn Baldwin {
14254e7f640dSJohn Baldwin #ifndef WITNESS
14264e7f640dSJohn Baldwin 	int slocked = 0;
14274e7f640dSJohn Baldwin #endif
14284e5e677bSJohn Baldwin 
1429d54474e6SEric van Gyzen 	if (SCHEDULER_STOPPED())
143003129ba9SJohn Baldwin 		return;
14314e5e677bSJohn Baldwin 	switch (what) {
14327ec137e5SJohn Baldwin 	case SA_SLOCKED:
14337ec137e5SJohn Baldwin 	case SA_SLOCKED | SA_NOTRECURSED:
14347ec137e5SJohn Baldwin 	case SA_SLOCKED | SA_RECURSED:
14354e7f640dSJohn Baldwin #ifndef WITNESS
14364e7f640dSJohn Baldwin 		slocked = 1;
14374e7f640dSJohn Baldwin 		/* FALLTHROUGH */
14384e7f640dSJohn Baldwin #endif
14397ec137e5SJohn Baldwin 	case SA_LOCKED:
14407ec137e5SJohn Baldwin 	case SA_LOCKED | SA_NOTRECURSED:
14417ec137e5SJohn Baldwin 	case SA_LOCKED | SA_RECURSED:
14424e5e677bSJohn Baldwin #ifdef WITNESS
1443aa89d8cdSJohn Baldwin 		witness_assert(&sx->lock_object, what, file, line);
14444e5e677bSJohn Baldwin #else
14454e7f640dSJohn Baldwin 		/*
14464e7f640dSJohn Baldwin 		 * If some other thread has an exclusive lock or we
14474e7f640dSJohn Baldwin 		 * have one and are asserting a shared lock, fail.
14484e7f640dSJohn Baldwin 		 * Also, if no one has a lock at all, fail.
14494e7f640dSJohn Baldwin 		 */
14504e7f640dSJohn Baldwin 		if (sx->sx_lock == SX_LOCK_UNLOCKED ||
14514e7f640dSJohn Baldwin 		    (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
14524e7f640dSJohn Baldwin 		    sx_xholder(sx) != curthread)))
145303129ba9SJohn Baldwin 			panic("Lock %s not %slocked @ %s:%d\n",
14544e7f640dSJohn Baldwin 			    sx->lock_object.lo_name, slocked ? "share " : "",
14554e7f640dSJohn Baldwin 			    file, line);
14564e7f640dSJohn Baldwin 
14574e7f640dSJohn Baldwin 		if (!(sx->sx_lock & SX_LOCK_SHARED)) {
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,
14624e7f640dSJohn Baldwin 					    line);
14637ec137e5SJohn Baldwin 			} else if (what & SA_RECURSED)
14644e7f640dSJohn Baldwin 				panic("Lock %s not recursed @ %s:%d\n",
14654e7f640dSJohn Baldwin 				    sx->lock_object.lo_name, file, line);
14664e7f640dSJohn Baldwin 		}
14674e5e677bSJohn Baldwin #endif
14684e5e677bSJohn Baldwin 		break;
14697ec137e5SJohn Baldwin 	case SA_XLOCKED:
14707ec137e5SJohn Baldwin 	case SA_XLOCKED | SA_NOTRECURSED:
14717ec137e5SJohn Baldwin 	case SA_XLOCKED | SA_RECURSED:
14724e7f640dSJohn Baldwin 		if (sx_xholder(sx) != curthread)
147303129ba9SJohn Baldwin 			panic("Lock %s not exclusively locked @ %s:%d\n",
1474aa89d8cdSJohn Baldwin 			    sx->lock_object.lo_name, file, line);
14754e7f640dSJohn Baldwin 		if (sx_recursed(sx)) {
14767ec137e5SJohn Baldwin 			if (what & SA_NOTRECURSED)
14774e7f640dSJohn Baldwin 				panic("Lock %s recursed @ %s:%d\n",
14784e7f640dSJohn Baldwin 				    sx->lock_object.lo_name, file, line);
14797ec137e5SJohn Baldwin 		} else if (what & SA_RECURSED)
14804e7f640dSJohn Baldwin 			panic("Lock %s not recursed @ %s:%d\n",
14814e7f640dSJohn Baldwin 			    sx->lock_object.lo_name, file, line);
14824e5e677bSJohn Baldwin 		break;
14837ec137e5SJohn Baldwin 	case SA_UNLOCKED:
148419b0efd3SPawel Jakub Dawidek #ifdef WITNESS
1485aa89d8cdSJohn Baldwin 		witness_assert(&sx->lock_object, what, file, line);
148619b0efd3SPawel Jakub Dawidek #else
1487f6739b1dSPawel Jakub Dawidek 		/*
14884e7f640dSJohn Baldwin 		 * If we hold an exclusve lock fail.  We can't
14894e7f640dSJohn Baldwin 		 * reliably check to see if we hold a shared lock or
14904e7f640dSJohn Baldwin 		 * not.
1491f6739b1dSPawel Jakub Dawidek 		 */
14924e7f640dSJohn Baldwin 		if (sx_xholder(sx) == curthread)
149303129ba9SJohn Baldwin 			panic("Lock %s exclusively locked @ %s:%d\n",
1494aa89d8cdSJohn Baldwin 			    sx->lock_object.lo_name, file, line);
149519b0efd3SPawel Jakub Dawidek #endif
149619b0efd3SPawel Jakub Dawidek 		break;
14974e5e677bSJohn Baldwin 	default:
14984e5e677bSJohn Baldwin 		panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
14994e5e677bSJohn Baldwin 		    line);
15004e5e677bSJohn Baldwin 	}
15014e5e677bSJohn Baldwin }
15024e5e677bSJohn Baldwin #endif	/* INVARIANT_SUPPORT */
1503d272fe53SJohn Baldwin 
1504d272fe53SJohn Baldwin #ifdef DDB
15054e7f640dSJohn Baldwin static void
1506d576deedSPawel Jakub Dawidek db_show_sx(const struct lock_object *lock)
1507d272fe53SJohn Baldwin {
1508d272fe53SJohn Baldwin 	struct thread *td;
1509d576deedSPawel Jakub Dawidek 	const struct sx *sx;
1510d272fe53SJohn Baldwin 
1511d576deedSPawel Jakub Dawidek 	sx = (const struct sx *)lock;
1512d272fe53SJohn Baldwin 
1513d272fe53SJohn Baldwin 	db_printf(" state: ");
15144e7f640dSJohn Baldwin 	if (sx->sx_lock == SX_LOCK_UNLOCKED)
15154e7f640dSJohn Baldwin 		db_printf("UNLOCKED\n");
15160026c92cSJohn Baldwin 	else if (sx->sx_lock == SX_LOCK_DESTROYED) {
15170026c92cSJohn Baldwin 		db_printf("DESTROYED\n");
15180026c92cSJohn Baldwin 		return;
15190026c92cSJohn Baldwin 	} else if (sx->sx_lock & SX_LOCK_SHARED)
15204e7f640dSJohn Baldwin 		db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
15214e7f640dSJohn Baldwin 	else {
15224e7f640dSJohn Baldwin 		td = sx_xholder(sx);
1523d272fe53SJohn Baldwin 		db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1524431f8906SJulian Elischer 		    td->td_tid, td->td_proc->p_pid, td->td_name);
15254e7f640dSJohn Baldwin 		if (sx_recursed(sx))
15264e7f640dSJohn Baldwin 			db_printf(" recursed: %d\n", sx->sx_recurse);
15274e7f640dSJohn Baldwin 	}
15284e7f640dSJohn Baldwin 
15294e7f640dSJohn Baldwin 	db_printf(" waiters: ");
15304e7f640dSJohn Baldwin 	switch(sx->sx_lock &
15314e7f640dSJohn Baldwin 	    (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
15324e7f640dSJohn Baldwin 	case SX_LOCK_SHARED_WAITERS:
15334e7f640dSJohn Baldwin 		db_printf("shared\n");
15344e7f640dSJohn Baldwin 		break;
15354e7f640dSJohn Baldwin 	case SX_LOCK_EXCLUSIVE_WAITERS:
15364e7f640dSJohn Baldwin 		db_printf("exclusive\n");
15374e7f640dSJohn Baldwin 		break;
15384e7f640dSJohn Baldwin 	case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
15394e7f640dSJohn Baldwin 		db_printf("exclusive and shared\n");
15404e7f640dSJohn Baldwin 		break;
15414e7f640dSJohn Baldwin 	default:
15424e7f640dSJohn Baldwin 		db_printf("none\n");
15434e7f640dSJohn Baldwin 	}
1544d272fe53SJohn Baldwin }
1545462a7addSJohn Baldwin 
1546462a7addSJohn Baldwin /*
1547462a7addSJohn Baldwin  * Check to see if a thread that is blocked on a sleep queue is actually
1548462a7addSJohn Baldwin  * blocked on an sx lock.  If so, output some details and return true.
1549462a7addSJohn Baldwin  * If the lock has an exclusive owner, return that in *ownerp.
1550462a7addSJohn Baldwin  */
1551462a7addSJohn Baldwin int
1552462a7addSJohn Baldwin sx_chain(struct thread *td, struct thread **ownerp)
1553462a7addSJohn Baldwin {
1554fea73412SConrad Meyer 	const struct sx *sx;
1555462a7addSJohn Baldwin 
1556462a7addSJohn Baldwin 	/*
15574e7f640dSJohn Baldwin 	 * Check to see if this thread is blocked on an sx lock.
15584e7f640dSJohn Baldwin 	 * First, we check the lock class.  If that is ok, then we
15594e7f640dSJohn Baldwin 	 * compare the lock name against the wait message.
1560462a7addSJohn Baldwin 	 */
15614e7f640dSJohn Baldwin 	sx = td->td_wchan;
15624e7f640dSJohn Baldwin 	if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
15634e7f640dSJohn Baldwin 	    sx->lock_object.lo_name != td->td_wmesg)
1564462a7addSJohn Baldwin 		return (0);
1565462a7addSJohn Baldwin 
1566462a7addSJohn Baldwin 	/* We think we have an sx lock, so output some details. */
1567462a7addSJohn Baldwin 	db_printf("blocked on sx \"%s\" ", td->td_wmesg);
15684e7f640dSJohn Baldwin 	*ownerp = sx_xholder(sx);
15694e7f640dSJohn Baldwin 	if (sx->sx_lock & SX_LOCK_SHARED)
15704e7f640dSJohn Baldwin 		db_printf("SLOCK (count %ju)\n",
15714e7f640dSJohn Baldwin 		    (uintmax_t)SX_SHARERS(sx->sx_lock));
15724e7f640dSJohn Baldwin 	else
1573462a7addSJohn Baldwin 		db_printf("XLOCK\n");
1574462a7addSJohn Baldwin 	return (1);
1575462a7addSJohn Baldwin }
1576d272fe53SJohn Baldwin #endif
1577