xref: /freebsd/sys/kern/kern_sx.c (revision f26db6948d5a49459358114afc35e07b4f846594)
19454b2d8SWarner Losh /*-
28a36da99SPedro F. Giffuni  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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>
46677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
47677b542eSDavid E. O'Brien 
486281b30aSJason Evans #include <sys/param.h>
497a7ce668SAndriy Gapon #include <sys/systm.h>
50cd2fe4e6SAttilio Rao #include <sys/kdb.h>
510453ade5SMateusz Guzik #include <sys/kernel.h>
526281b30aSJason Evans #include <sys/ktr.h>
5319284646SJohn Baldwin #include <sys/lock.h>
546281b30aSJason Evans #include <sys/mutex.h>
55d272fe53SJohn Baldwin #include <sys/proc.h>
562cba8dd3SJohn Baldwin #include <sys/sched.h>
574e7f640dSJohn Baldwin #include <sys/sleepqueue.h>
586281b30aSJason Evans #include <sys/sx.h>
591ada9041SMateusz Guzik #include <sys/smp.h>
60e31d0833SAttilio Rao #include <sys/sysctl.h>
614e7f640dSJohn Baldwin 
62e31d0833SAttilio Rao #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
634e7f640dSJohn Baldwin #include <machine/cpu.h>
644e7f640dSJohn Baldwin #endif
656281b30aSJason Evans 
66462a7addSJohn Baldwin #ifdef DDB
67d272fe53SJohn Baldwin #include <ddb/ddb.h>
684e7f640dSJohn Baldwin #endif
69d272fe53SJohn Baldwin 
701ae1c2a3SAttilio Rao #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
711ae1c2a3SAttilio Rao #define	ADAPTIVE_SX
724e7f640dSJohn Baldwin #endif
734e7f640dSJohn Baldwin 
74f5f9340bSFabien Thomas #ifdef HWPMC_HOOKS
75f5f9340bSFabien Thomas #include <sys/pmckern.h>
76f5f9340bSFabien Thomas PMC_SOFT_DECLARE( , , lock, failed);
77f5f9340bSFabien Thomas #endif
78f5f9340bSFabien Thomas 
794e7f640dSJohn Baldwin /* Handy macros for sleep queues. */
804e7f640dSJohn Baldwin #define	SQ_EXCLUSIVE_QUEUE	0
814e7f640dSJohn Baldwin #define	SQ_SHARED_QUEUE		1
824e7f640dSJohn Baldwin 
834e7f640dSJohn Baldwin /*
844e7f640dSJohn Baldwin  * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file.  We
854e7f640dSJohn Baldwin  * drop Giant anytime we have to sleep or if we adaptively spin.
864e7f640dSJohn Baldwin  */
874e7f640dSJohn Baldwin #define	GIANT_DECLARE							\
884e7f640dSJohn Baldwin 	int _giantcnt = 0;						\
894e7f640dSJohn Baldwin 	WITNESS_SAVE_DECL(Giant)					\
904e7f640dSJohn Baldwin 
91e41d6166SMateusz Guzik #define	GIANT_SAVE(work) do {						\
92fb106123SMateusz Guzik 	if (__predict_false(mtx_owned(&Giant))) {			\
93e41d6166SMateusz Guzik 		work++;							\
944e7f640dSJohn Baldwin 		WITNESS_SAVE(&Giant.lock_object, Giant);		\
954e7f640dSJohn Baldwin 		while (mtx_owned(&Giant)) {				\
964e7f640dSJohn Baldwin 			_giantcnt++;					\
974e7f640dSJohn Baldwin 			mtx_unlock(&Giant);				\
984e7f640dSJohn Baldwin 		}							\
994e7f640dSJohn Baldwin 	}								\
1004e7f640dSJohn Baldwin } while (0)
1014e7f640dSJohn Baldwin 
1024e7f640dSJohn Baldwin #define GIANT_RESTORE() do {						\
1034e7f640dSJohn Baldwin 	if (_giantcnt > 0) {						\
1044e7f640dSJohn Baldwin 		mtx_assert(&Giant, MA_NOTOWNED);			\
1054e7f640dSJohn Baldwin 		while (_giantcnt--)					\
1064e7f640dSJohn Baldwin 			mtx_lock(&Giant);				\
1074e7f640dSJohn Baldwin 		WITNESS_RESTORE(&Giant.lock_object, Giant);		\
1084e7f640dSJohn Baldwin 	}								\
1094e7f640dSJohn Baldwin } while (0)
1104e7f640dSJohn Baldwin 
1114e7f640dSJohn Baldwin /*
112da7d0d1eSJohn Baldwin  * Returns true if an exclusive lock is recursed.  It assumes
113da7d0d1eSJohn Baldwin  * curthread currently has an exclusive lock.
1144e7f640dSJohn Baldwin  */
1154e7f640dSJohn Baldwin #define	sx_recursed(sx)		((sx)->sx_recurse != 0)
1164e7f640dSJohn Baldwin 
117d576deedSPawel Jakub Dawidek static void	assert_sx(const struct lock_object *lock, int what);
1184e7f640dSJohn Baldwin #ifdef DDB
119d576deedSPawel Jakub Dawidek static void	db_show_sx(const struct lock_object *lock);
120d272fe53SJohn Baldwin #endif
1217faf4d90SDavide Italiano static void	lock_sx(struct lock_object *lock, uintptr_t how);
122a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
123d576deedSPawel Jakub Dawidek static int	owner_sx(const struct lock_object *lock, struct thread **owner);
124a5aedd68SStacey Son #endif
1257faf4d90SDavide Italiano static uintptr_t unlock_sx(struct lock_object *lock);
126d272fe53SJohn Baldwin 
12719284646SJohn Baldwin struct lock_class lock_class_sx = {
128ae8dde30SJohn Baldwin 	.lc_name = "sx",
129ae8dde30SJohn Baldwin 	.lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
130f9721b43SAttilio Rao 	.lc_assert = assert_sx,
131d272fe53SJohn Baldwin #ifdef DDB
132ae8dde30SJohn Baldwin 	.lc_ddb_show = db_show_sx,
133d272fe53SJohn Baldwin #endif
1346e21afd4SJohn Baldwin 	.lc_lock = lock_sx,
1356e21afd4SJohn Baldwin 	.lc_unlock = unlock_sx,
136a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
137a5aedd68SStacey Son 	.lc_owner = owner_sx,
138a5aedd68SStacey Son #endif
13919284646SJohn Baldwin };
14019284646SJohn Baldwin 
141781a35dfSJohn Baldwin #ifndef INVARIANTS
142781a35dfSJohn Baldwin #define	_sx_assert(sx, what, file, line)
143781a35dfSJohn Baldwin #endif
144781a35dfSJohn Baldwin 
1451ae1c2a3SAttilio Rao #ifdef ADAPTIVE_SX
146e0e259a8SMateusz Guzik static __read_frequently u_int asx_retries;
147e0e259a8SMateusz Guzik static __read_frequently u_int asx_loops;
1486472ac3dSEd Schouten static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD, NULL, "sxlock debugging");
149fbbb13f9SMatthew D Fleming SYSCTL_UINT(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
150fbbb13f9SMatthew D Fleming SYSCTL_UINT(_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 
1548e5a3e9aSMateusz Guzik SYSCTL_INT(_debug_sx, OID_AUTO, delay_base, CTLFLAG_RW, &sx_delay.base,
1551ada9041SMateusz Guzik     0, "");
1561ada9041SMateusz Guzik SYSCTL_INT(_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);
1681ae1c2a3SAttilio Rao #endif
1691ae1c2a3SAttilio Rao 
1706281b30aSJason Evans void
171d576deedSPawel Jakub Dawidek assert_sx(const struct lock_object *lock, int what)
172f9721b43SAttilio Rao {
173f9721b43SAttilio Rao 
174d576deedSPawel Jakub Dawidek 	sx_assert((const struct sx *)lock, what);
175f9721b43SAttilio Rao }
176f9721b43SAttilio Rao 
177f9721b43SAttilio Rao void
1787faf4d90SDavide Italiano lock_sx(struct lock_object *lock, uintptr_t how)
1796e21afd4SJohn Baldwin {
1806e21afd4SJohn Baldwin 	struct sx *sx;
1816e21afd4SJohn Baldwin 
1826e21afd4SJohn Baldwin 	sx = (struct sx *)lock;
1836e21afd4SJohn Baldwin 	if (how)
1846e21afd4SJohn Baldwin 		sx_slock(sx);
185cf6b879fSDavide Italiano 	else
186cf6b879fSDavide Italiano 		sx_xlock(sx);
1876e21afd4SJohn Baldwin }
1886e21afd4SJohn Baldwin 
1897faf4d90SDavide Italiano uintptr_t
1906e21afd4SJohn Baldwin unlock_sx(struct lock_object *lock)
1916e21afd4SJohn Baldwin {
1926e21afd4SJohn Baldwin 	struct sx *sx;
1936e21afd4SJohn Baldwin 
1946e21afd4SJohn Baldwin 	sx = (struct sx *)lock;
1957ec137e5SJohn Baldwin 	sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
1966e21afd4SJohn Baldwin 	if (sx_xlocked(sx)) {
1976e21afd4SJohn Baldwin 		sx_xunlock(sx);
198cf6b879fSDavide Italiano 		return (0);
1996e21afd4SJohn Baldwin 	} else {
2006e21afd4SJohn Baldwin 		sx_sunlock(sx);
201cf6b879fSDavide Italiano 		return (1);
2026e21afd4SJohn Baldwin 	}
2036e21afd4SJohn Baldwin }
2046e21afd4SJohn Baldwin 
205a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
206a5aedd68SStacey Son int
207d576deedSPawel Jakub Dawidek owner_sx(const struct lock_object *lock, struct thread **owner)
208a5aedd68SStacey Son {
209c365a293SMark Johnston 	const struct sx *sx;
210c365a293SMark Johnston 	uintptr_t x;
211a5aedd68SStacey Son 
212c365a293SMark Johnston 	sx = (const struct sx *)lock;
213c365a293SMark Johnston 	x = sx->sx_lock;
214c365a293SMark Johnston 	*owner = NULL;
215a5aedd68SStacey Son 	return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
216c365a293SMark Johnston 	    ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
217a5aedd68SStacey Son }
218a5aedd68SStacey Son #endif
219a5aedd68SStacey Son 
2206e21afd4SJohn Baldwin void
221c27b5699SAndrew R. Reiter sx_sysinit(void *arg)
222c27b5699SAndrew R. Reiter {
223c27b5699SAndrew R. Reiter 	struct sx_args *sargs = arg;
224c27b5699SAndrew R. Reiter 
225e4cd31ddSJeff Roberson 	sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
226c27b5699SAndrew R. Reiter }
227c27b5699SAndrew R. Reiter 
228c27b5699SAndrew R. Reiter void
2294e7f640dSJohn Baldwin sx_init_flags(struct sx *sx, const char *description, int opts)
2306281b30aSJason Evans {
2314e7f640dSJohn Baldwin 	int flags;
2326281b30aSJason Evans 
233b0d67325SJohn Baldwin 	MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
234*f26db694SMateusz Guzik 	    SX_NOPROFILE | SX_NEW)) == 0);
235353998acSAttilio Rao 	ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
236353998acSAttilio Rao 	    ("%s: sx_lock not aligned for %s: %p", __func__, description,
237353998acSAttilio Rao 	    &sx->sx_lock));
238b0d67325SJohn Baldwin 
239f0830182SAttilio Rao 	flags = LO_SLEEPABLE | LO_UPGRADABLE;
2404e7f640dSJohn Baldwin 	if (opts & SX_DUPOK)
2414e7f640dSJohn Baldwin 		flags |= LO_DUPOK;
2424e7f640dSJohn Baldwin 	if (opts & SX_NOPROFILE)
2434e7f640dSJohn Baldwin 		flags |= LO_NOPROFILE;
2444e7f640dSJohn Baldwin 	if (!(opts & SX_NOWITNESS))
2454e7f640dSJohn Baldwin 		flags |= LO_WITNESS;
246f0830182SAttilio Rao 	if (opts & SX_RECURSE)
247f0830182SAttilio Rao 		flags |= LO_RECURSABLE;
2484e7f640dSJohn Baldwin 	if (opts & SX_QUIET)
2494e7f640dSJohn Baldwin 		flags |= LO_QUIET;
250fd07ddcfSDmitry Chagin 	if (opts & SX_NEW)
251fd07ddcfSDmitry Chagin 		flags |= LO_NEW;
2524e7f640dSJohn Baldwin 
253b5fb43e5SJohn Baldwin 	lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
2544e7f640dSJohn Baldwin 	sx->sx_lock = SX_LOCK_UNLOCKED;
2554e7f640dSJohn Baldwin 	sx->sx_recurse = 0;
2566281b30aSJason Evans }
2576281b30aSJason Evans 
2586281b30aSJason Evans void
2596281b30aSJason Evans sx_destroy(struct sx *sx)
2606281b30aSJason Evans {
2616281b30aSJason Evans 
2624e7f640dSJohn Baldwin 	KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
2634e7f640dSJohn Baldwin 	KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
2640026c92cSJohn Baldwin 	sx->sx_lock = SX_LOCK_DESTROYED;
265aa89d8cdSJohn Baldwin 	lock_destroy(&sx->lock_object);
2666281b30aSJason Evans }
2676281b30aSJason Evans 
268f9819486SAttilio Rao int
269013c0b49SMateusz Guzik sx_try_slock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
2705f36700aSJohn Baldwin {
2714e7f640dSJohn Baldwin 	uintptr_t x;
2725f36700aSJohn Baldwin 
27335370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
27435370593SAndriy Gapon 		return (1);
27535370593SAndriy Gapon 
276cd2fe4e6SAttilio Rao 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
277e3ae0dfeSAttilio Rao 	    ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
278e3ae0dfeSAttilio Rao 	    curthread, sx->lock_object.lo_name, file, line));
279e3ae0dfeSAttilio Rao 
2804e7f640dSJohn Baldwin 	x = sx->sx_lock;
2815c5df0d9SMateusz Guzik 	for (;;) {
2820026c92cSJohn Baldwin 		KASSERT(x != SX_LOCK_DESTROYED,
2830026c92cSJohn Baldwin 		    ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
284764a938bSPawel Jakub Dawidek 		if (!(x & SX_LOCK_SHARED))
285764a938bSPawel Jakub Dawidek 			break;
2865c5df0d9SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, x + SX_ONE_SHARER)) {
287aa89d8cdSJohn Baldwin 			LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
288aa89d8cdSJohn Baldwin 			WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
289de2c95ccSMark Johnston 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
290de2c95ccSMark Johnston 			    sx, 0, 0, file, line, LOCKSTAT_READER);
291ce1c953eSMark Johnston 			TD_LOCKS_INC(curthread);
2922466d12bSMateusz Guzik 			curthread->td_sx_slocks++;
2935f36700aSJohn Baldwin 			return (1);
2945f36700aSJohn Baldwin 		}
295764a938bSPawel Jakub Dawidek 	}
2964e7f640dSJohn Baldwin 
2974e7f640dSJohn Baldwin 	LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
2984e7f640dSJohn Baldwin 	return (0);
2995f36700aSJohn Baldwin }
3005f36700aSJohn Baldwin 
301f9819486SAttilio Rao int
302013c0b49SMateusz Guzik sx_try_slock_(struct sx *sx, const char *file, int line)
303013c0b49SMateusz Guzik {
304013c0b49SMateusz Guzik 
305013c0b49SMateusz Guzik 	return (sx_try_slock_int(sx LOCK_FILE_LINE_ARG));
306013c0b49SMateusz Guzik }
307013c0b49SMateusz Guzik 
308013c0b49SMateusz Guzik int
309f9819486SAttilio Rao _sx_xlock(struct sx *sx, int opts, const char *file, int line)
3106281b30aSJason Evans {
3116ebb77b6SMateusz Guzik 	uintptr_t tid, x;
312f9819486SAttilio Rao 	int error = 0;
3136281b30aSJason Evans 
314704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
315704cb42fSMark Johnston 	    !TD_IS_IDLETHREAD(curthread),
316e3ae0dfeSAttilio Rao 	    ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
317e3ae0dfeSAttilio Rao 	    curthread, sx->lock_object.lo_name, file, line));
3180026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
3190026c92cSJohn Baldwin 	    ("sx_xlock() of destroyed sx @ %s:%d", file, line));
320aa89d8cdSJohn Baldwin 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
32141313430SJohn Baldwin 	    line, NULL);
3226ebb77b6SMateusz Guzik 	tid = (uintptr_t)curthread;
3236ebb77b6SMateusz Guzik 	x = SX_LOCK_UNLOCKED;
3246ebb77b6SMateusz Guzik 	if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
325013c0b49SMateusz Guzik 		error = _sx_xlock_hard(sx, x, opts LOCK_FILE_LINE_ARG);
3266ebb77b6SMateusz Guzik 	else
3276ebb77b6SMateusz Guzik 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
3286ebb77b6SMateusz Guzik 		    0, 0, file, line, LOCKSTAT_WRITER);
329f9819486SAttilio Rao 	if (!error) {
330f9819486SAttilio Rao 		LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
331f9819486SAttilio Rao 		    file, line);
332aa89d8cdSJohn Baldwin 		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
333ce1c953eSMark Johnston 		TD_LOCKS_INC(curthread);
3346281b30aSJason Evans 	}
3356281b30aSJason Evans 
336f9819486SAttilio Rao 	return (error);
337f9819486SAttilio Rao }
338f9819486SAttilio Rao 
3395f36700aSJohn Baldwin int
340013c0b49SMateusz Guzik sx_try_xlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
3415f36700aSJohn Baldwin {
3425c5df0d9SMateusz Guzik 	struct thread *td;
3435c5df0d9SMateusz Guzik 	uintptr_t tid, x;
3444e7f640dSJohn Baldwin 	int rval;
3455c5df0d9SMateusz Guzik 	bool recursed;
3465f36700aSJohn Baldwin 
3475c5df0d9SMateusz Guzik 	td = curthread;
3485c5df0d9SMateusz Guzik 	tid = (uintptr_t)td;
3495c5df0d9SMateusz Guzik 	if (SCHEDULER_STOPPED_TD(td))
35035370593SAndriy Gapon 		return (1);
35135370593SAndriy Gapon 
352704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
353e3ae0dfeSAttilio Rao 	    ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
354e3ae0dfeSAttilio Rao 	    curthread, sx->lock_object.lo_name, file, line));
3550026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
3560026c92cSJohn Baldwin 	    ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
3574e7f640dSJohn Baldwin 
3585c5df0d9SMateusz Guzik 	rval = 1;
3595c5df0d9SMateusz Guzik 	recursed = false;
3605c5df0d9SMateusz Guzik 	x = SX_LOCK_UNLOCKED;
361b247fd39SMateusz Guzik 	for (;;) {
362b247fd39SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
363b247fd39SMateusz Guzik 			break;
364b247fd39SMateusz Guzik 		if (x == SX_LOCK_UNLOCKED)
365b247fd39SMateusz Guzik 			continue;
3665c5df0d9SMateusz Guzik 		if (x == tid && (sx->lock_object.lo_flags & LO_RECURSABLE)) {
3674e7f640dSJohn Baldwin 			sx->sx_recurse++;
3684e7f640dSJohn Baldwin 			atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
369b247fd39SMateusz Guzik 			break;
3705c5df0d9SMateusz Guzik 		}
371b247fd39SMateusz Guzik 		rval = 0;
372b247fd39SMateusz Guzik 		break;
3735c5df0d9SMateusz Guzik 	}
3745c5df0d9SMateusz Guzik 
3754e7f640dSJohn Baldwin 	LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
3764e7f640dSJohn Baldwin 	if (rval) {
3774e7f640dSJohn Baldwin 		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
3784e7f640dSJohn Baldwin 		    file, line);
3795c5df0d9SMateusz Guzik 		if (!recursed)
380de2c95ccSMark Johnston 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
381de2c95ccSMark Johnston 			    sx, 0, 0, file, line, LOCKSTAT_WRITER);
382ce1c953eSMark Johnston 		TD_LOCKS_INC(curthread);
3835f36700aSJohn Baldwin 	}
3844e7f640dSJohn Baldwin 
3854e7f640dSJohn Baldwin 	return (rval);
3865f36700aSJohn Baldwin }
3875f36700aSJohn Baldwin 
388013c0b49SMateusz Guzik int
389013c0b49SMateusz Guzik sx_try_xlock_(struct sx *sx, const char *file, int line)
390013c0b49SMateusz Guzik {
391013c0b49SMateusz Guzik 
392013c0b49SMateusz Guzik 	return (sx_try_xlock_int(sx LOCK_FILE_LINE_ARG));
393013c0b49SMateusz Guzik }
394013c0b49SMateusz Guzik 
3956281b30aSJason Evans void
39619284646SJohn Baldwin _sx_xunlock(struct sx *sx, const char *file, int line)
3976281b30aSJason Evans {
3986281b30aSJason Evans 
3990026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
4000026c92cSJohn Baldwin 	    ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
4017ec137e5SJohn Baldwin 	_sx_assert(sx, SA_XLOCKED, file, line);
402aa89d8cdSJohn Baldwin 	WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
4034e7f640dSJohn Baldwin 	LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
4044e7f640dSJohn Baldwin 	    line);
4050108a980SMateusz Guzik #if LOCK_DEBUG > 0
4066ebb77b6SMateusz Guzik 	_sx_xunlock_hard(sx, (uintptr_t)curthread, file, line);
407ffd5c94cSMateusz Guzik #else
408ffd5c94cSMateusz Guzik 	__sx_xunlock(sx, curthread, file, line);
409ffd5c94cSMateusz Guzik #endif
410ce1c953eSMark Johnston 	TD_LOCKS_DEC(curthread);
4116281b30aSJason Evans }
412d55229b7SJason Evans 
4134e7f640dSJohn Baldwin /*
4144e7f640dSJohn Baldwin  * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
4154e7f640dSJohn Baldwin  * This will only succeed if this thread holds a single shared lock.
4164e7f640dSJohn Baldwin  * Return 1 if if the upgrade succeed, 0 otherwise.
4174e7f640dSJohn Baldwin  */
418d55229b7SJason Evans int
419013c0b49SMateusz Guzik sx_try_upgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
420d55229b7SJason Evans {
4214e7f640dSJohn Baldwin 	uintptr_t x;
422a8e747c5SMateusz Guzik 	uintptr_t waiters;
4234e7f640dSJohn Baldwin 	int success;
424d55229b7SJason Evans 
42535370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
42635370593SAndriy Gapon 		return (1);
42735370593SAndriy Gapon 
4280026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
4290026c92cSJohn Baldwin 	    ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
4307ec137e5SJohn Baldwin 	_sx_assert(sx, SA_SLOCKED, file, line);
431d55229b7SJason Evans 
4324e7f640dSJohn Baldwin 	/*
4334e7f640dSJohn Baldwin 	 * Try to switch from one shared lock to an exclusive lock.  We need
4344e7f640dSJohn Baldwin 	 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
4354e7f640dSJohn Baldwin 	 * we will wake up the exclusive waiters when we drop the lock.
4364e7f640dSJohn Baldwin 	 */
437a8e747c5SMateusz Guzik 	success = 0;
438a8e747c5SMateusz Guzik 	x = SX_READ_VALUE(sx);
439a8e747c5SMateusz Guzik 	for (;;) {
440a8e747c5SMateusz Guzik 		if (SX_SHARERS(x) > 1)
441a8e747c5SMateusz Guzik 			break;
4422466d12bSMateusz Guzik 		waiters = (x & SX_LOCK_WAITERS);
443a8e747c5SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
444a8e747c5SMateusz Guzik 		    (uintptr_t)curthread | waiters)) {
445a8e747c5SMateusz Guzik 			success = 1;
446a8e747c5SMateusz Guzik 			break;
447a8e747c5SMateusz Guzik 		}
448a8e747c5SMateusz Guzik 	}
4494e7f640dSJohn Baldwin 	LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
450a5aedd68SStacey Son 	if (success) {
4512466d12bSMateusz Guzik 		curthread->td_sx_slocks--;
452aa89d8cdSJohn Baldwin 		WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
453b0b7cb50SJohn Baldwin 		    file, line);
45432cd0147SMark Johnston 		LOCKSTAT_RECORD0(sx__upgrade, sx);
455a5aedd68SStacey Son 	}
4564e7f640dSJohn Baldwin 	return (success);
457d55229b7SJason Evans }
458d55229b7SJason Evans 
459013c0b49SMateusz Guzik int
460013c0b49SMateusz Guzik sx_try_upgrade_(struct sx *sx, const char *file, int line)
461013c0b49SMateusz Guzik {
462013c0b49SMateusz Guzik 
463013c0b49SMateusz Guzik 	return (sx_try_upgrade_int(sx LOCK_FILE_LINE_ARG));
464013c0b49SMateusz Guzik }
465013c0b49SMateusz Guzik 
4664e7f640dSJohn Baldwin /*
4674e7f640dSJohn Baldwin  * Downgrade an unrecursed exclusive lock into a single shared lock.
4684e7f640dSJohn Baldwin  */
469d55229b7SJason Evans void
470013c0b49SMateusz Guzik sx_downgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
471d55229b7SJason Evans {
4724e7f640dSJohn Baldwin 	uintptr_t x;
473da7bbd2cSJohn Baldwin 	int wakeup_swapper;
474d55229b7SJason Evans 
47535370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
47635370593SAndriy Gapon 		return;
47735370593SAndriy Gapon 
4780026c92cSJohn Baldwin 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
4790026c92cSJohn Baldwin 	    ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
4807ec137e5SJohn Baldwin 	_sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
4814e7f640dSJohn Baldwin #ifndef INVARIANTS
4824e7f640dSJohn Baldwin 	if (sx_recursed(sx))
4834e7f640dSJohn Baldwin 		panic("downgrade of a recursed lock");
4844e7f640dSJohn Baldwin #endif
485d55229b7SJason Evans 
486aa89d8cdSJohn Baldwin 	WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
487d55229b7SJason Evans 
4884e7f640dSJohn Baldwin 	/*
4894e7f640dSJohn Baldwin 	 * Try to switch from an exclusive lock with no shared waiters
4904e7f640dSJohn Baldwin 	 * to one sharer with no shared waiters.  If there are
4914e7f640dSJohn Baldwin 	 * exclusive waiters, we don't need to lock the sleep queue so
4924e7f640dSJohn Baldwin 	 * long as we preserve the flag.  We do one quick try and if
4934e7f640dSJohn Baldwin 	 * that fails we grab the sleepq lock to keep the flags from
4944e7f640dSJohn Baldwin 	 * changing and do it the slow way.
4954e7f640dSJohn Baldwin 	 *
4964e7f640dSJohn Baldwin 	 * We have to lock the sleep queue if there are shared waiters
4974e7f640dSJohn Baldwin 	 * so we can wake them up.
4984e7f640dSJohn Baldwin 	 */
4994e7f640dSJohn Baldwin 	x = sx->sx_lock;
5004e7f640dSJohn Baldwin 	if (!(x & SX_LOCK_SHARED_WAITERS) &&
5014e7f640dSJohn Baldwin 	    atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
50226d94f99SMark Johnston 	    (x & SX_LOCK_EXCLUSIVE_WAITERS)))
50326d94f99SMark Johnston 		goto out;
5044e7f640dSJohn Baldwin 
5054e7f640dSJohn Baldwin 	/*
5064e7f640dSJohn Baldwin 	 * Lock the sleep queue so we can read the waiters bits
5074e7f640dSJohn Baldwin 	 * without any races and wakeup any shared waiters.
5084e7f640dSJohn Baldwin 	 */
5094e7f640dSJohn Baldwin 	sleepq_lock(&sx->lock_object);
5104e7f640dSJohn Baldwin 
5114e7f640dSJohn Baldwin 	/*
5124e7f640dSJohn Baldwin 	 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
5134e7f640dSJohn Baldwin 	 * shared lock.  If there are any shared waiters, wake them up.
5144e7f640dSJohn Baldwin 	 */
515da7bbd2cSJohn Baldwin 	wakeup_swapper = 0;
5164e7f640dSJohn Baldwin 	x = sx->sx_lock;
5174e7f640dSJohn Baldwin 	atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
5184e7f640dSJohn Baldwin 	    (x & SX_LOCK_EXCLUSIVE_WAITERS));
5194e7f640dSJohn Baldwin 	if (x & SX_LOCK_SHARED_WAITERS)
520da7bbd2cSJohn Baldwin 		wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
521da7bbd2cSJohn Baldwin 		    0, SQ_SHARED_QUEUE);
5224e7f640dSJohn Baldwin 	sleepq_release(&sx->lock_object);
523d55229b7SJason Evans 
524da7bbd2cSJohn Baldwin 	if (wakeup_swapper)
525da7bbd2cSJohn Baldwin 		kick_proc0();
52626d94f99SMark Johnston 
52726d94f99SMark Johnston out:
5282466d12bSMateusz Guzik 	curthread->td_sx_slocks++;
52926d94f99SMark Johnston 	LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
53026d94f99SMark Johnston 	LOCKSTAT_RECORD0(sx__downgrade, sx);
5314e7f640dSJohn Baldwin }
532d55229b7SJason Evans 
533013c0b49SMateusz Guzik void
534013c0b49SMateusz Guzik sx_downgrade_(struct sx *sx, const char *file, int line)
535013c0b49SMateusz Guzik {
536013c0b49SMateusz Guzik 
537013c0b49SMateusz Guzik 	sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
538013c0b49SMateusz Guzik }
539013c0b49SMateusz Guzik 
5402466d12bSMateusz Guzik #ifdef	ADAPTIVE_SX
5412466d12bSMateusz Guzik static inline void
5422466d12bSMateusz Guzik sx_drop_critical(uintptr_t x, bool *in_critical, int *extra_work)
5432466d12bSMateusz Guzik {
5442466d12bSMateusz Guzik 
5452466d12bSMateusz Guzik 	if (x & SX_LOCK_WRITE_SPINNER)
5462466d12bSMateusz Guzik 		return;
5472466d12bSMateusz Guzik 	if (*in_critical) {
5482466d12bSMateusz Guzik 		critical_exit();
5492466d12bSMateusz Guzik 		*in_critical = false;
5502466d12bSMateusz Guzik 		(*extra_work)--;
5512466d12bSMateusz Guzik 	}
5522466d12bSMateusz Guzik }
5532466d12bSMateusz Guzik #else
5542466d12bSMateusz Guzik #define sx_drop_critical(x, in_critical, extra_work) do { } while(0)
5552466d12bSMateusz Guzik #endif
5562466d12bSMateusz Guzik 
5574e7f640dSJohn Baldwin /*
5584e7f640dSJohn Baldwin  * This function represents the so-called 'hard case' for sx_xlock
5594e7f640dSJohn Baldwin  * operation.  All 'easy case' failures are redirected to this.  Note
5604e7f640dSJohn Baldwin  * that ideally this would be a static function, but it needs to be
5614e7f640dSJohn Baldwin  * accessible from at least sx.h.
5624e7f640dSJohn Baldwin  */
563f9819486SAttilio Rao int
564013c0b49SMateusz Guzik _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
5654e7f640dSJohn Baldwin {
5664e7f640dSJohn Baldwin 	GIANT_DECLARE;
5672466d12bSMateusz Guzik 	uintptr_t tid, setx;
5684e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
5694e7f640dSJohn Baldwin 	volatile struct thread *owner;
570d07e22cdSMateusz Guzik 	u_int i, n, spintries = 0;
5711dce110fSMatt Macy 	enum { READERS, WRITER } sleep_reason = READERS;
5722466d12bSMateusz Guzik 	bool in_critical = false;
5734e7f640dSJohn Baldwin #endif
5741723a064SJeff Roberson #ifdef LOCK_PROFILING
5751723a064SJeff Roberson 	uint64_t waittime = 0;
5761723a064SJeff Roberson 	int contested = 0;
5771723a064SJeff Roberson #endif
5781723a064SJeff Roberson 	int error = 0;
57904126895SMateusz Guzik #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
5801ada9041SMateusz Guzik 	struct lock_delay_arg lda;
5811ada9041SMateusz Guzik #endif
582a5aedd68SStacey Son #ifdef	KDTRACE_HOOKS
58361852185SMateusz Guzik 	u_int sleep_cnt = 0;
584a5aedd68SStacey Son 	int64_t sleep_time = 0;
585076dd8ebSAndriy Gapon 	int64_t all_time = 0;
586a5aedd68SStacey Son #endif
587e41d6166SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
5881dce110fSMatt Macy 	uintptr_t state = 0;
5892466d12bSMateusz Guzik 	int doing_lockprof = 0;
590e41d6166SMateusz Guzik #endif
591284194f1SMateusz Guzik 	int extra_work = 0;
5924e7f640dSJohn Baldwin 
593013c0b49SMateusz Guzik 	tid = (uintptr_t)curthread;
59409bdec20SMateusz Guzik 
59509bdec20SMateusz Guzik #ifdef KDTRACE_HOOKS
59609bdec20SMateusz Guzik 	if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
59709bdec20SMateusz Guzik 		while (x == SX_LOCK_UNLOCKED) {
59809bdec20SMateusz Guzik 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
59909bdec20SMateusz Guzik 				goto out_lockstat;
60009bdec20SMateusz Guzik 		}
60109bdec20SMateusz Guzik 		extra_work = 1;
6022466d12bSMateusz Guzik 		doing_lockprof = 1;
60309bdec20SMateusz Guzik 		all_time -= lockstat_nsecs(&sx->lock_object);
60409bdec20SMateusz Guzik 		state = x;
60509bdec20SMateusz Guzik 	}
60609bdec20SMateusz Guzik #endif
60709bdec20SMateusz Guzik #ifdef LOCK_PROFILING
60809bdec20SMateusz Guzik 	extra_work = 1;
6092466d12bSMateusz Guzik 	doing_lockprof = 1;
61009bdec20SMateusz Guzik 	state = x;
61109bdec20SMateusz Guzik #endif
61209bdec20SMateusz Guzik 
61335370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
61435370593SAndriy Gapon 		return (0);
61535370593SAndriy Gapon 
616fa5000a4SMateusz Guzik #if defined(ADAPTIVE_SX)
6171ada9041SMateusz Guzik 	lock_delay_arg_init(&lda, &sx_delay);
618fa5000a4SMateusz Guzik #elif defined(KDTRACE_HOOKS)
619fa5000a4SMateusz Guzik 	lock_delay_arg_init(&lda, NULL);
6201ada9041SMateusz Guzik #endif
6211ada9041SMateusz Guzik 
622c1aaf63cSMateusz Guzik 	if (__predict_false(x == SX_LOCK_UNLOCKED))
623c1aaf63cSMateusz Guzik 		x = SX_READ_VALUE(sx);
624c1aaf63cSMateusz Guzik 
6254e7f640dSJohn Baldwin 	/* If we already hold an exclusive lock, then recurse. */
626c5f61e6fSMateusz Guzik 	if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
627f0830182SAttilio Rao 		KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
628b0d67325SJohn Baldwin 	    ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
629b0d67325SJohn Baldwin 		    sx->lock_object.lo_name, file, line));
6304e7f640dSJohn Baldwin 		sx->sx_recurse++;
6314e7f640dSJohn Baldwin 		atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
6324e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
6334e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
634f9819486SAttilio Rao 		return (0);
6354e7f640dSJohn Baldwin 	}
6364e7f640dSJohn Baldwin 
6374e7f640dSJohn Baldwin 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
6384e7f640dSJohn Baldwin 		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
6394e7f640dSJohn Baldwin 		    sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
6404e7f640dSJohn Baldwin 
641ae7d25a4SMateusz Guzik #ifdef HWPMC_HOOKS
642ae7d25a4SMateusz Guzik 	PMC_SOFT_CALL( , , lock, failed);
643ae7d25a4SMateusz Guzik #endif
644ae7d25a4SMateusz Guzik 	lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
645ae7d25a4SMateusz Guzik 	    &waittime);
646ae7d25a4SMateusz Guzik 
647fb106123SMateusz Guzik #ifndef INVARIANTS
648fb106123SMateusz Guzik 	GIANT_SAVE(extra_work);
649fb106123SMateusz Guzik #endif
650e41d6166SMateusz 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
6644e7f640dSJohn Baldwin 		/*
6654e7f640dSJohn Baldwin 		 * If the lock is write locked and the owner is
6664e7f640dSJohn Baldwin 		 * running on another CPU, spin until the owner stops
6674e7f640dSJohn Baldwin 		 * running or the state of the lock changes.
6684e7f640dSJohn Baldwin 		 */
6691ae1c2a3SAttilio Rao 		if ((x & SX_LOCK_SHARED) == 0) {
6702466d12bSMateusz Guzik 			sx_drop_critical(x, &in_critical, &extra_work);
671d94df98cSMateusz Guzik 			sleep_reason = WRITER;
672c5f61e6fSMateusz Guzik 			owner = lv_sx_owner(x);
673d94df98cSMateusz Guzik 			if (!TD_IS_RUNNING(owner))
674d94df98cSMateusz Guzik 				goto sleepq;
6754e7f640dSJohn Baldwin 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
676d94df98cSMateusz Guzik 				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
6774e7f640dSJohn Baldwin 				    __func__, sx, owner);
678d94df98cSMateusz Guzik 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
679d94df98cSMateusz Guzik 			    "spinning", "lockname:\"%s\"",
6802cba8dd3SJohn Baldwin 			    sx->lock_object.lo_name);
681c5f61e6fSMateusz Guzik 			do {
6821ada9041SMateusz Guzik 				lock_delay(&lda);
683c5f61e6fSMateusz Guzik 				x = SX_READ_VALUE(sx);
684c5f61e6fSMateusz Guzik 				owner = lv_sx_owner(x);
685d94df98cSMateusz Guzik 			} while (owner != NULL && TD_IS_RUNNING(owner));
686d94df98cSMateusz Guzik 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
687d94df98cSMateusz Guzik 			    "running");
6884e7f640dSJohn Baldwin 			continue;
689d94df98cSMateusz Guzik 		} else if (SX_SHARERS(x) > 0) {
690d94df98cSMateusz Guzik 			sleep_reason = READERS;
691d94df98cSMateusz Guzik 			if (spintries == asx_retries)
692d94df98cSMateusz Guzik 				goto sleepq;
6932466d12bSMateusz Guzik 			if (!(x & SX_LOCK_WRITE_SPINNER)) {
6942466d12bSMateusz Guzik 				if (!in_critical) {
6952466d12bSMateusz Guzik 					critical_enter();
6962466d12bSMateusz Guzik 					in_critical = true;
6972466d12bSMateusz Guzik 					extra_work++;
6982466d12bSMateusz Guzik 				}
6992466d12bSMateusz Guzik 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
7002466d12bSMateusz Guzik 				    x | SX_LOCK_WRITE_SPINNER)) {
7012466d12bSMateusz Guzik 					critical_exit();
7022466d12bSMateusz Guzik 					in_critical = false;
7032466d12bSMateusz Guzik 					extra_work--;
7042466d12bSMateusz Guzik 					continue;
7052466d12bSMateusz Guzik 				}
7062466d12bSMateusz Guzik 			}
7071ae1c2a3SAttilio Rao 			spintries++;
708d94df98cSMateusz Guzik 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
709d94df98cSMateusz Guzik 			    "spinning", "lockname:\"%s\"",
710d94df98cSMateusz Guzik 			    sx->lock_object.lo_name);
711d07e22cdSMateusz Guzik 			n = SX_SHARERS(x);
7122466d12bSMateusz Guzik 			for (i = 0; i < asx_loops; i += n) {
713d07e22cdSMateusz Guzik 				lock_delay_spin(n);
71420a15d17SMateusz Guzik 				x = SX_READ_VALUE(sx);
7152466d12bSMateusz Guzik 				if (!(x & SX_LOCK_WRITE_SPINNER))
7162466d12bSMateusz Guzik 					break;
7172466d12bSMateusz Guzik 				if (!(x & SX_LOCK_SHARED))
7182466d12bSMateusz Guzik 					break;
7192466d12bSMateusz Guzik 				n = SX_SHARERS(x);
7202466d12bSMateusz Guzik 				if (n == 0)
7211ae1c2a3SAttilio Rao 					break;
7221ae1c2a3SAttilio Rao 			}
72320a15d17SMateusz Guzik #ifdef KDTRACE_HOOKS
72420a15d17SMateusz Guzik 			lda.spin_cnt += i;
72520a15d17SMateusz Guzik #endif
726d94df98cSMateusz Guzik 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
727d94df98cSMateusz Guzik 			    "running");
728efa9f177SMateusz Guzik 			if (i < asx_loops)
7291ae1c2a3SAttilio Rao 				continue;
7301ae1c2a3SAttilio Rao 		}
731fb106123SMateusz Guzik sleepq:
732cde25ed4SMateusz Guzik #endif
7334e7f640dSJohn Baldwin 		sleepq_lock(&sx->lock_object);
734c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
73593118b62SMateusz Guzik retry_sleepq:
7364e7f640dSJohn Baldwin 
7374e7f640dSJohn Baldwin 		/*
7384e7f640dSJohn Baldwin 		 * If the lock was released while spinning on the
7394e7f640dSJohn Baldwin 		 * sleep queue chain lock, try again.
7404e7f640dSJohn Baldwin 		 */
7414e7f640dSJohn Baldwin 		if (x == SX_LOCK_UNLOCKED) {
7424e7f640dSJohn Baldwin 			sleepq_release(&sx->lock_object);
7432466d12bSMateusz Guzik 			sx_drop_critical(x, &in_critical, &extra_work);
7444e7f640dSJohn Baldwin 			continue;
7454e7f640dSJohn Baldwin 		}
7464e7f640dSJohn Baldwin 
7474e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
7484e7f640dSJohn Baldwin 		/*
7494e7f640dSJohn Baldwin 		 * The current lock owner might have started executing
7504e7f640dSJohn Baldwin 		 * on another CPU (or the lock could have changed
7514e7f640dSJohn Baldwin 		 * owners) while we were waiting on the sleep queue
7524e7f640dSJohn Baldwin 		 * chain lock.  If so, drop the sleep queue lock and try
7534e7f640dSJohn Baldwin 		 * again.
7544e7f640dSJohn Baldwin 		 */
75528f1a9e3SMateusz Guzik 		if (!(x & SX_LOCK_SHARED)) {
7564e7f640dSJohn Baldwin 			owner = (struct thread *)SX_OWNER(x);
7574e7f640dSJohn Baldwin 			if (TD_IS_RUNNING(owner)) {
7584e7f640dSJohn Baldwin 				sleepq_release(&sx->lock_object);
7592466d12bSMateusz Guzik 				sx_drop_critical(x, &in_critical,
7602466d12bSMateusz Guzik 				    &extra_work);
7614e7f640dSJohn Baldwin 				continue;
7624e7f640dSJohn Baldwin 			}
763d94df98cSMateusz Guzik 		} else if (SX_SHARERS(x) > 0 && sleep_reason == WRITER) {
76428f1a9e3SMateusz Guzik 			sleepq_release(&sx->lock_object);
7652466d12bSMateusz Guzik 			sx_drop_critical(x, &in_critical, &extra_work);
76628f1a9e3SMateusz Guzik 			continue;
76728f1a9e3SMateusz Guzik 		}
7684e7f640dSJohn Baldwin #endif
7694e7f640dSJohn Baldwin 
7704e7f640dSJohn Baldwin 		/*
7714e7f640dSJohn Baldwin 		 * If an exclusive lock was released with both shared
7724e7f640dSJohn Baldwin 		 * and exclusive waiters and a shared waiter hasn't
7734e7f640dSJohn Baldwin 		 * woken up and acquired the lock yet, sx_lock will be
7744e7f640dSJohn Baldwin 		 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
7754e7f640dSJohn Baldwin 		 * If we see that value, try to acquire it once.  Note
7764e7f640dSJohn Baldwin 		 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
7774e7f640dSJohn Baldwin 		 * as there are other exclusive waiters still.  If we
7784e7f640dSJohn Baldwin 		 * fail, restart the loop.
7794e7f640dSJohn Baldwin 		 */
7802466d12bSMateusz Guzik 		setx = x & (SX_LOCK_WAITERS | SX_LOCK_WRITE_SPINNER);
7812466d12bSMateusz Guzik 		if ((x & ~setx) == SX_LOCK_SHARED) {
7822466d12bSMateusz Guzik 			setx &= ~SX_LOCK_WRITE_SPINNER;
7832466d12bSMateusz Guzik 			if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid | setx))
78493118b62SMateusz Guzik 				goto retry_sleepq;
7854e7f640dSJohn Baldwin 			sleepq_release(&sx->lock_object);
7864e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p claimed by new writer",
7874e7f640dSJohn Baldwin 			    __func__, sx);
7884e7f640dSJohn Baldwin 			break;
7894e7f640dSJohn Baldwin 		}
7904e7f640dSJohn Baldwin 
7912466d12bSMateusz Guzik #ifdef ADAPTIVE_SX
7922466d12bSMateusz Guzik 		/*
7932466d12bSMateusz Guzik 		 * It is possible we set the SX_LOCK_WRITE_SPINNER bit.
7942466d12bSMateusz Guzik 		 * It is an invariant that when the bit is set, there is
7952466d12bSMateusz Guzik 		 * a writer ready to grab the lock. Thus clear the bit since
7962466d12bSMateusz Guzik 		 * we are going to sleep.
7972466d12bSMateusz Guzik 		 */
7982466d12bSMateusz Guzik 		if (in_critical) {
7992466d12bSMateusz Guzik 			if ((x & SX_LOCK_WRITE_SPINNER) ||
8002466d12bSMateusz Guzik 			    !((x & SX_LOCK_EXCLUSIVE_WAITERS))) {
8012466d12bSMateusz Guzik 				setx = x & ~SX_LOCK_WRITE_SPINNER;
8022466d12bSMateusz Guzik 				setx |= SX_LOCK_EXCLUSIVE_WAITERS;
8032466d12bSMateusz Guzik 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
8042466d12bSMateusz Guzik 				    setx)) {
8052466d12bSMateusz Guzik 					goto retry_sleepq;
8062466d12bSMateusz Guzik 				}
8072466d12bSMateusz Guzik 			}
8082466d12bSMateusz Guzik 			critical_exit();
8092466d12bSMateusz Guzik 			in_critical = false;
8102466d12bSMateusz Guzik 		} else {
8112466d12bSMateusz Guzik #endif
8124e7f640dSJohn Baldwin 			/*
8134e7f640dSJohn Baldwin 			 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
8144e7f640dSJohn Baldwin 			 * than loop back and retry.
8154e7f640dSJohn Baldwin 			 */
8164e7f640dSJohn Baldwin 			if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
81793118b62SMateusz Guzik 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
8184e7f640dSJohn Baldwin 				    x | SX_LOCK_EXCLUSIVE_WAITERS)) {
81993118b62SMateusz Guzik 					goto retry_sleepq;
8204e7f640dSJohn Baldwin 				}
8214e7f640dSJohn Baldwin 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
8224e7f640dSJohn Baldwin 					CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
8234e7f640dSJohn Baldwin 					    __func__, sx);
8244e7f640dSJohn Baldwin 			}
8252466d12bSMateusz Guzik #ifdef ADAPTIVE_SX
8262466d12bSMateusz Guzik 		}
8272466d12bSMateusz Guzik #endif
8284e7f640dSJohn Baldwin 
8294e7f640dSJohn Baldwin 		/*
8304e7f640dSJohn Baldwin 		 * Since we have been unable to acquire the exclusive
8314e7f640dSJohn Baldwin 		 * lock and the exclusive waiters flag is set, we have
8324e7f640dSJohn Baldwin 		 * to sleep.
8334e7f640dSJohn Baldwin 		 */
8344e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
8354e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
8364e7f640dSJohn Baldwin 			    __func__, sx);
8374e7f640dSJohn Baldwin 
838a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
839e2b25737SMark Johnston 		sleep_time -= lockstat_nsecs(&sx->lock_object);
840a5aedd68SStacey Son #endif
8414e7f640dSJohn Baldwin 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
842f9819486SAttilio Rao 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
843f9819486SAttilio Rao 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
844f9819486SAttilio Rao 		if (!(opts & SX_INTERRUPTIBLE))
845c5aa6b58SJeff Roberson 			sleepq_wait(&sx->lock_object, 0);
846f9819486SAttilio Rao 		else
847c5aa6b58SJeff Roberson 			error = sleepq_wait_sig(&sx->lock_object, 0);
848a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
849e2b25737SMark Johnston 		sleep_time += lockstat_nsecs(&sx->lock_object);
850a5aedd68SStacey Son 		sleep_cnt++;
851a5aedd68SStacey Son #endif
852f9819486SAttilio Rao 		if (error) {
853f9819486SAttilio Rao 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
854f9819486SAttilio Rao 				CTR2(KTR_LOCK,
855f9819486SAttilio Rao 			"%s: interruptible sleep by %p suspended by signal",
856f9819486SAttilio Rao 				    __func__, sx);
857f9819486SAttilio Rao 			break;
858f9819486SAttilio Rao 		}
8594e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
8604e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
8614e7f640dSJohn Baldwin 			    __func__, sx);
862c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
8634e7f640dSJohn Baldwin 	}
864e41d6166SMateusz Guzik 	if (__predict_true(!extra_work))
865e41d6166SMateusz Guzik 		return (error);
8662466d12bSMateusz Guzik #ifdef ADAPTIVE_SX
8672466d12bSMateusz Guzik 	if (in_critical)
8682466d12bSMateusz Guzik 		critical_exit();
8692466d12bSMateusz Guzik #endif
870ee252fc9SMateusz Guzik 	GIANT_RESTORE();
8712466d12bSMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
8722466d12bSMateusz Guzik 	if (__predict_true(!doing_lockprof))
8732466d12bSMateusz Guzik 		return (error);
874e41d6166SMateusz Guzik #endif
875076dd8ebSAndriy Gapon #ifdef KDTRACE_HOOKS
876e2b25737SMark Johnston 	all_time += lockstat_nsecs(&sx->lock_object);
877076dd8ebSAndriy Gapon 	if (sleep_time)
87832cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
879076dd8ebSAndriy Gapon 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
880076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
8811ada9041SMateusz Guzik 	if (lda.spin_cnt > sleep_cnt)
88232cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
883076dd8ebSAndriy Gapon 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
884076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
88509bdec20SMateusz Guzik out_lockstat:
886076dd8ebSAndriy Gapon #endif
887f9819486SAttilio Rao 	if (!error)
888de2c95ccSMark Johnston 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
889de2c95ccSMark Johnston 		    contested, waittime, file, line, LOCKSTAT_WRITER);
890f9819486SAttilio Rao 	return (error);
8914e7f640dSJohn Baldwin }
8924e7f640dSJohn Baldwin 
8934e7f640dSJohn Baldwin /*
8944e7f640dSJohn Baldwin  * This function represents the so-called 'hard case' for sx_xunlock
8954e7f640dSJohn Baldwin  * operation.  All 'easy case' failures are redirected to this.  Note
8964e7f640dSJohn Baldwin  * that ideally this would be a static function, but it needs to be
8974e7f640dSJohn Baldwin  * accessible from at least sx.h.
8984e7f640dSJohn Baldwin  */
8994e7f640dSJohn Baldwin void
900b584eb2eSMateusz Guzik _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
9014e7f640dSJohn Baldwin {
902b584eb2eSMateusz Guzik 	uintptr_t tid, setx;
903da7bbd2cSJohn Baldwin 	int queue, wakeup_swapper;
9044e7f640dSJohn Baldwin 
90535370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
90635370593SAndriy Gapon 		return;
90735370593SAndriy Gapon 
908b584eb2eSMateusz Guzik 	tid = (uintptr_t)curthread;
9094e7f640dSJohn Baldwin 
910b584eb2eSMateusz Guzik 	if (__predict_false(x == tid))
9113b3cf014SMateusz Guzik 		x = SX_READ_VALUE(sx);
912b584eb2eSMateusz Guzik 
913b584eb2eSMateusz Guzik 	MPASS(!(x & SX_LOCK_SHARED));
914b584eb2eSMateusz Guzik 
915b584eb2eSMateusz Guzik 	if (__predict_false(x & SX_LOCK_RECURSED)) {
9166ebb77b6SMateusz Guzik 		/* The lock is recursed, unrecurse one level. */
9174e7f640dSJohn Baldwin 		if ((--sx->sx_recurse) == 0)
9184e7f640dSJohn Baldwin 			atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
9194e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
9204e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
9214e7f640dSJohn Baldwin 		return;
9224e7f640dSJohn Baldwin 	}
9233b3cf014SMateusz Guzik 
9243b3cf014SMateusz Guzik 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
9253b3cf014SMateusz Guzik 	if (x == tid &&
9263b3cf014SMateusz Guzik 	    atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
9273b3cf014SMateusz Guzik 		return;
9283b3cf014SMateusz Guzik 
9294e7f640dSJohn Baldwin 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
9304e7f640dSJohn Baldwin 		CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
9314e7f640dSJohn Baldwin 
9324e7f640dSJohn Baldwin 	sleepq_lock(&sx->lock_object);
933bc24577cSMateusz Guzik 	x = SX_READ_VALUE(sx);
9342d96bd88SMateusz Guzik 	MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
9354e7f640dSJohn Baldwin 
9364e7f640dSJohn Baldwin 	/*
9374e7f640dSJohn Baldwin 	 * The wake up algorithm here is quite simple and probably not
9384e7f640dSJohn Baldwin 	 * ideal.  It gives precedence to shared waiters if they are
9394e7f640dSJohn Baldwin 	 * present.  For this condition, we have to preserve the
9404e7f640dSJohn Baldwin 	 * state of the exclusive waiters flag.
9412028867dSAttilio Rao 	 * If interruptible sleeps left the shared queue empty avoid a
9422028867dSAttilio Rao 	 * starvation for the threads sleeping on the exclusive queue by giving
9432028867dSAttilio Rao 	 * them precedence and cleaning up the shared waiters bit anyway.
9444e7f640dSJohn Baldwin 	 */
945bc24577cSMateusz Guzik 	setx = SX_LOCK_UNLOCKED;
9464e7f640dSJohn Baldwin 	queue = SQ_SHARED_QUEUE;
9472466d12bSMateusz Guzik 	if ((x & SX_LOCK_EXCLUSIVE_WAITERS) != 0 &&
9482466d12bSMateusz Guzik 	    sleepq_sleepcnt(&sx->lock_object, SQ_EXCLUSIVE_QUEUE) != 0) {
9492466d12bSMateusz Guzik 		queue = SQ_EXCLUSIVE_QUEUE;
9502466d12bSMateusz Guzik 		setx |= (x & SX_LOCK_SHARED_WAITERS);
951bc24577cSMateusz Guzik 	}
952bc24577cSMateusz Guzik 	atomic_store_rel_ptr(&sx->sx_lock, setx);
9534e7f640dSJohn Baldwin 
9544e7f640dSJohn Baldwin 	/* Wake up all the waiters for the specific queue. */
9554e7f640dSJohn Baldwin 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
9564e7f640dSJohn Baldwin 		CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
9574e7f640dSJohn Baldwin 		    __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
9584e7f640dSJohn Baldwin 		    "exclusive");
959bc24577cSMateusz Guzik 
960da7bbd2cSJohn Baldwin 	wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
961da7bbd2cSJohn Baldwin 	    queue);
962c5aa6b58SJeff Roberson 	sleepq_release(&sx->lock_object);
963da7bbd2cSJohn Baldwin 	if (wakeup_swapper)
964da7bbd2cSJohn Baldwin 		kick_proc0();
9654e7f640dSJohn Baldwin }
9664e7f640dSJohn Baldwin 
967834f70f3SMateusz Guzik static bool __always_inline
9682466d12bSMateusz Guzik __sx_can_read(struct thread *td, uintptr_t x, bool fp)
9692466d12bSMateusz Guzik {
9702466d12bSMateusz Guzik 
9712466d12bSMateusz Guzik 	if ((x & (SX_LOCK_SHARED | SX_LOCK_EXCLUSIVE_WAITERS | SX_LOCK_WRITE_SPINNER))
9722466d12bSMateusz Guzik 			== SX_LOCK_SHARED)
9732466d12bSMateusz Guzik 		return (true);
9742466d12bSMateusz Guzik 	if (!fp && td->td_sx_slocks && (x & SX_LOCK_SHARED))
9752466d12bSMateusz Guzik 		return (true);
9762466d12bSMateusz Guzik 	return (false);
9772466d12bSMateusz Guzik }
9782466d12bSMateusz Guzik 
9792466d12bSMateusz Guzik static bool __always_inline
9802466d12bSMateusz Guzik __sx_slock_try(struct sx *sx, struct thread *td, uintptr_t *xp, bool fp
9812466d12bSMateusz Guzik     LOCK_FILE_LINE_ARG_DEF)
982834f70f3SMateusz Guzik {
983834f70f3SMateusz Guzik 
984834f70f3SMateusz Guzik 	/*
985834f70f3SMateusz Guzik 	 * If no other thread has an exclusive lock then try to bump up
986834f70f3SMateusz Guzik 	 * the count of sharers.  Since we have to preserve the state
987834f70f3SMateusz Guzik 	 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
988834f70f3SMateusz Guzik 	 * shared lock loop back and retry.
989834f70f3SMateusz Guzik 	 */
9902466d12bSMateusz Guzik 	while (__sx_can_read(td, *xp, fp)) {
991834f70f3SMateusz Guzik 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
992834f70f3SMateusz Guzik 		    *xp + SX_ONE_SHARER)) {
993834f70f3SMateusz Guzik 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
994834f70f3SMateusz Guzik 				CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
995834f70f3SMateusz Guzik 				    __func__, sx, (void *)*xp,
996834f70f3SMateusz Guzik 				    (void *)(*xp + SX_ONE_SHARER));
9972466d12bSMateusz Guzik 			td->td_sx_slocks++;
998834f70f3SMateusz Guzik 			return (true);
999834f70f3SMateusz Guzik 		}
1000834f70f3SMateusz Guzik 	}
1001834f70f3SMateusz Guzik 	return (false);
1002834f70f3SMateusz Guzik }
1003834f70f3SMateusz Guzik 
1004834f70f3SMateusz Guzik static int __noinline
1005013c0b49SMateusz Guzik _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
10064e7f640dSJohn Baldwin {
10074e7f640dSJohn Baldwin 	GIANT_DECLARE;
10082466d12bSMateusz Guzik 	struct thread *td;
10094e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
10104e7f640dSJohn Baldwin 	volatile struct thread *owner;
10112466d12bSMateusz Guzik 	u_int i, n, spintries = 0;
10124e7f640dSJohn Baldwin #endif
10131723a064SJeff Roberson #ifdef LOCK_PROFILING
1014c1a6d9faSAttilio Rao 	uint64_t waittime = 0;
1015c1a6d9faSAttilio Rao 	int contested = 0;
10161723a064SJeff Roberson #endif
1017c1a6d9faSAttilio Rao 	int error = 0;
101804126895SMateusz Guzik #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
10191ada9041SMateusz Guzik 	struct lock_delay_arg lda;
10201ada9041SMateusz Guzik #endif
1021a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
102261852185SMateusz Guzik 	u_int sleep_cnt = 0;
1023a5aedd68SStacey Son 	int64_t sleep_time = 0;
1024076dd8ebSAndriy Gapon 	int64_t all_time = 0;
1025a5aedd68SStacey Son #endif
1026e41d6166SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
10271dce110fSMatt Macy 	uintptr_t state = 0;
1028e41d6166SMateusz Guzik #endif
1029284194f1SMateusz Guzik 	int extra_work = 0;
1030c1a6d9faSAttilio Rao 
10312466d12bSMateusz Guzik 	td = curthread;
10322466d12bSMateusz Guzik 
103309bdec20SMateusz Guzik #ifdef KDTRACE_HOOKS
103409bdec20SMateusz Guzik 	if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
10352466d12bSMateusz Guzik 		if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
103609bdec20SMateusz Guzik 			goto out_lockstat;
103709bdec20SMateusz Guzik 		extra_work = 1;
103809bdec20SMateusz Guzik 		all_time -= lockstat_nsecs(&sx->lock_object);
103909bdec20SMateusz Guzik 		state = x;
104009bdec20SMateusz Guzik 	}
104109bdec20SMateusz Guzik #endif
104209bdec20SMateusz Guzik #ifdef LOCK_PROFILING
104309bdec20SMateusz Guzik 	extra_work = 1;
104409bdec20SMateusz Guzik 	state = x;
104509bdec20SMateusz Guzik #endif
104609bdec20SMateusz Guzik 
104735370593SAndriy Gapon 	if (SCHEDULER_STOPPED())
104835370593SAndriy Gapon 		return (0);
104935370593SAndriy Gapon 
1050fa5000a4SMateusz Guzik #if defined(ADAPTIVE_SX)
10511ada9041SMateusz Guzik 	lock_delay_arg_init(&lda, &sx_delay);
1052fa5000a4SMateusz Guzik #elif defined(KDTRACE_HOOKS)
1053fa5000a4SMateusz Guzik 	lock_delay_arg_init(&lda, NULL);
10541ada9041SMateusz Guzik #endif
1055e41d6166SMateusz Guzik 
1056ae7d25a4SMateusz Guzik #ifdef HWPMC_HOOKS
1057ae7d25a4SMateusz Guzik 	PMC_SOFT_CALL( , , lock, failed);
1058ae7d25a4SMateusz Guzik #endif
1059ae7d25a4SMateusz Guzik 	lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
1060ae7d25a4SMateusz Guzik 	    &waittime);
1061ae7d25a4SMateusz Guzik 
1062fb106123SMateusz Guzik #ifndef INVARIANTS
1063fb106123SMateusz Guzik 	GIANT_SAVE(extra_work);
1064fb106123SMateusz Guzik #endif
1065076dd8ebSAndriy Gapon 
10664e7f640dSJohn Baldwin 	/*
10674e7f640dSJohn Baldwin 	 * As with rwlocks, we don't make any attempt to try to block
10684e7f640dSJohn Baldwin 	 * shared locks once there is an exclusive waiter.
10694e7f640dSJohn Baldwin 	 */
10704e7f640dSJohn Baldwin 	for (;;) {
10712466d12bSMateusz Guzik 		if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
10724e7f640dSJohn Baldwin 			break;
1073fb106123SMateusz Guzik #ifdef INVARIANTS
1074fb106123SMateusz Guzik 		GIANT_SAVE(extra_work);
1075fb106123SMateusz Guzik #endif
1076c5f61e6fSMateusz Guzik #ifdef KDTRACE_HOOKS
1077c5f61e6fSMateusz Guzik 		lda.spin_cnt++;
1078c5f61e6fSMateusz Guzik #endif
1079c5f61e6fSMateusz Guzik 
10804e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
10814e7f640dSJohn Baldwin 		/*
10824e7f640dSJohn Baldwin 		 * If the owner is running on another CPU, spin until
10834e7f640dSJohn Baldwin 		 * the owner stops running or the state of the lock
10844e7f640dSJohn Baldwin 		 * changes.
10854e7f640dSJohn Baldwin 		 */
10862466d12bSMateusz Guzik 		if ((x & SX_LOCK_SHARED) == 0) {
1087c5f61e6fSMateusz Guzik 			owner = lv_sx_owner(x);
10884e7f640dSJohn Baldwin 			if (TD_IS_RUNNING(owner)) {
10894e7f640dSJohn Baldwin 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
10904e7f640dSJohn Baldwin 					CTR3(KTR_LOCK,
10914e7f640dSJohn Baldwin 					    "%s: spinning on %p held by %p",
10924e7f640dSJohn Baldwin 					    __func__, sx, owner);
10932cba8dd3SJohn Baldwin 				KTR_STATE1(KTR_SCHED, "thread",
10942cba8dd3SJohn Baldwin 				    sched_tdname(curthread), "spinning",
10952cba8dd3SJohn Baldwin 				    "lockname:\"%s\"", sx->lock_object.lo_name);
1096c5f61e6fSMateusz Guzik 				do {
10971ada9041SMateusz Guzik 					lock_delay(&lda);
1098c5f61e6fSMateusz Guzik 					x = SX_READ_VALUE(sx);
1099c5f61e6fSMateusz Guzik 					owner = lv_sx_owner(x);
1100c5f61e6fSMateusz Guzik 				} while (owner != NULL && TD_IS_RUNNING(owner));
11012cba8dd3SJohn Baldwin 				KTR_STATE0(KTR_SCHED, "thread",
11022cba8dd3SJohn Baldwin 				    sched_tdname(curthread), "running");
11034e7f640dSJohn Baldwin 				continue;
11044e7f640dSJohn Baldwin 			}
11052466d12bSMateusz Guzik 		} else {
11062466d12bSMateusz Guzik 			if ((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) {
11072466d12bSMateusz Guzik 				MPASS(!__sx_can_read(td, x, false));
11082466d12bSMateusz Guzik 				lock_delay_spin(2);
11092466d12bSMateusz Guzik 				x = SX_READ_VALUE(sx);
11102466d12bSMateusz Guzik 				continue;
11112466d12bSMateusz Guzik 			}
11122466d12bSMateusz Guzik 			if (spintries < asx_retries) {
11132466d12bSMateusz Guzik 				KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
11142466d12bSMateusz Guzik 				    "spinning", "lockname:\"%s\"",
11152466d12bSMateusz Guzik 				    sx->lock_object.lo_name);
11162466d12bSMateusz Guzik 				n = SX_SHARERS(x);
11172466d12bSMateusz Guzik 				for (i = 0; i < asx_loops; i += n) {
11182466d12bSMateusz Guzik 					lock_delay_spin(n);
11192466d12bSMateusz Guzik 					x = SX_READ_VALUE(sx);
11202466d12bSMateusz Guzik 					if (!(x & SX_LOCK_SHARED))
11212466d12bSMateusz Guzik 						break;
11222466d12bSMateusz Guzik 					n = SX_SHARERS(x);
11232466d12bSMateusz Guzik 					if (n == 0)
11242466d12bSMateusz Guzik 						break;
11252466d12bSMateusz Guzik 					if (__sx_can_read(td, x, false))
11262466d12bSMateusz Guzik 						break;
11272466d12bSMateusz Guzik 				}
11282466d12bSMateusz Guzik #ifdef KDTRACE_HOOKS
11292466d12bSMateusz Guzik 				lda.spin_cnt += i;
11302466d12bSMateusz Guzik #endif
11312466d12bSMateusz Guzik 				KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
11322466d12bSMateusz Guzik 				    "running");
11332466d12bSMateusz Guzik 				if (i < asx_loops)
11342466d12bSMateusz Guzik 					continue;
11352466d12bSMateusz Guzik 			}
11362466d12bSMateusz Guzik 		}
11374e7f640dSJohn Baldwin #endif
11384e7f640dSJohn Baldwin 
11394e7f640dSJohn Baldwin 		/*
11404e7f640dSJohn Baldwin 		 * Some other thread already has an exclusive lock, so
11414e7f640dSJohn Baldwin 		 * start the process of blocking.
11424e7f640dSJohn Baldwin 		 */
11434e7f640dSJohn Baldwin 		sleepq_lock(&sx->lock_object);
1144c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
114593118b62SMateusz Guzik retry_sleepq:
11462466d12bSMateusz Guzik 		if (((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) ||
11472466d12bSMateusz Guzik 		    __sx_can_read(td, x, false)) {
11484e7f640dSJohn Baldwin 			sleepq_release(&sx->lock_object);
11494e7f640dSJohn Baldwin 			continue;
11504e7f640dSJohn Baldwin 		}
11514e7f640dSJohn Baldwin 
11524e7f640dSJohn Baldwin #ifdef ADAPTIVE_SX
11534e7f640dSJohn Baldwin 		/*
11544e7f640dSJohn Baldwin 		 * If the owner is running on another CPU, spin until
11554e7f640dSJohn Baldwin 		 * the owner stops running or the state of the lock
11564e7f640dSJohn Baldwin 		 * changes.
11574e7f640dSJohn Baldwin 		 */
1158*f26db694SMateusz Guzik 		if (!(x & SX_LOCK_SHARED)) {
11594e7f640dSJohn Baldwin 			owner = (struct thread *)SX_OWNER(x);
11604e7f640dSJohn Baldwin 			if (TD_IS_RUNNING(owner)) {
11614e7f640dSJohn Baldwin 				sleepq_release(&sx->lock_object);
1162c5f61e6fSMateusz Guzik 				x = SX_READ_VALUE(sx);
11634e7f640dSJohn Baldwin 				continue;
11644e7f640dSJohn Baldwin 			}
11654e7f640dSJohn Baldwin 		}
11664e7f640dSJohn Baldwin #endif
11674e7f640dSJohn Baldwin 
11684e7f640dSJohn Baldwin 		/*
11694e7f640dSJohn Baldwin 		 * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
11704e7f640dSJohn Baldwin 		 * fail to set it drop the sleep queue lock and loop
11714e7f640dSJohn Baldwin 		 * back.
11724e7f640dSJohn Baldwin 		 */
11734e7f640dSJohn Baldwin 		if (!(x & SX_LOCK_SHARED_WAITERS)) {
117493118b62SMateusz Guzik 			if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
117593118b62SMateusz Guzik 			    x | SX_LOCK_SHARED_WAITERS))
117693118b62SMateusz Guzik 				goto retry_sleepq;
11774e7f640dSJohn Baldwin 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
11784e7f640dSJohn Baldwin 				CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
11794e7f640dSJohn Baldwin 				    __func__, sx);
11804e7f640dSJohn Baldwin 		}
11814e7f640dSJohn Baldwin 
11824e7f640dSJohn Baldwin 		/*
11834e7f640dSJohn Baldwin 		 * Since we have been unable to acquire the shared lock,
11844e7f640dSJohn Baldwin 		 * we have to sleep.
11854e7f640dSJohn Baldwin 		 */
11864e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
11874e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
11884e7f640dSJohn Baldwin 			    __func__, sx);
11894e7f640dSJohn Baldwin 
1190a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
1191e2b25737SMark Johnston 		sleep_time -= lockstat_nsecs(&sx->lock_object);
1192a5aedd68SStacey Son #endif
11934e7f640dSJohn Baldwin 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1194f9819486SAttilio Rao 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1195f9819486SAttilio Rao 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1196f9819486SAttilio Rao 		if (!(opts & SX_INTERRUPTIBLE))
1197c5aa6b58SJeff Roberson 			sleepq_wait(&sx->lock_object, 0);
1198f9819486SAttilio Rao 		else
1199c5aa6b58SJeff Roberson 			error = sleepq_wait_sig(&sx->lock_object, 0);
1200a5aedd68SStacey Son #ifdef KDTRACE_HOOKS
1201e2b25737SMark Johnston 		sleep_time += lockstat_nsecs(&sx->lock_object);
1202a5aedd68SStacey Son 		sleep_cnt++;
1203a5aedd68SStacey Son #endif
1204f9819486SAttilio Rao 		if (error) {
1205f9819486SAttilio Rao 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1206f9819486SAttilio Rao 				CTR2(KTR_LOCK,
1207f9819486SAttilio Rao 			"%s: interruptible sleep by %p suspended by signal",
1208f9819486SAttilio Rao 				    __func__, sx);
1209f9819486SAttilio Rao 			break;
1210f9819486SAttilio Rao 		}
12114e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
12124e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
12134e7f640dSJohn Baldwin 			    __func__, sx);
1214c5f61e6fSMateusz Guzik 		x = SX_READ_VALUE(sx);
12154e7f640dSJohn Baldwin 	}
1216e41d6166SMateusz Guzik #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1217e41d6166SMateusz Guzik 	if (__predict_true(!extra_work))
1218e41d6166SMateusz Guzik 		return (error);
1219e41d6166SMateusz Guzik #endif
1220076dd8ebSAndriy Gapon #ifdef KDTRACE_HOOKS
1221e2b25737SMark Johnston 	all_time += lockstat_nsecs(&sx->lock_object);
1222076dd8ebSAndriy Gapon 	if (sleep_time)
122332cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1224076dd8ebSAndriy Gapon 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1225076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
12261ada9041SMateusz Guzik 	if (lda.spin_cnt > sleep_cnt)
122732cd0147SMark Johnston 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1228076dd8ebSAndriy Gapon 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1229076dd8ebSAndriy Gapon 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
123009bdec20SMateusz Guzik out_lockstat:
1231076dd8ebSAndriy Gapon #endif
12323ae56ce9SMateusz Guzik 	if (error == 0) {
1233de2c95ccSMark Johnston 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1234de2c95ccSMark Johnston 		    contested, waittime, file, line, LOCKSTAT_READER);
12353ae56ce9SMateusz Guzik 	}
12364e7f640dSJohn Baldwin 	GIANT_RESTORE();
1237f9819486SAttilio Rao 	return (error);
12384e7f640dSJohn Baldwin }
12394e7f640dSJohn Baldwin 
1240834f70f3SMateusz Guzik int
1241013c0b49SMateusz Guzik _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
12424e7f640dSJohn Baldwin {
12432466d12bSMateusz Guzik 	struct thread *td;
12444e7f640dSJohn Baldwin 	uintptr_t x;
1245834f70f3SMateusz Guzik 	int error;
12464e7f640dSJohn Baldwin 
1247704cb42fSMark Johnston 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1248704cb42fSMark Johnston 	    !TD_IS_IDLETHREAD(curthread),
1249834f70f3SMateusz Guzik 	    ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1250834f70f3SMateusz Guzik 	    curthread, sx->lock_object.lo_name, file, line));
12513ae56ce9SMateusz Guzik 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1252834f70f3SMateusz Guzik 	    ("sx_slock() of destroyed sx @ %s:%d", file, line));
1253834f70f3SMateusz Guzik 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1254834f70f3SMateusz Guzik 
1255834f70f3SMateusz Guzik 	error = 0;
12562466d12bSMateusz Guzik 	td = curthread;
1257c5f61e6fSMateusz Guzik 	x = SX_READ_VALUE(sx);
1258e4ccf57fSMateusz Guzik 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__acquire) ||
12592466d12bSMateusz Guzik 	    !__sx_slock_try(sx, td, &x, true LOCK_FILE_LINE_ARG)))
1260013c0b49SMateusz Guzik 		error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1261e4ccf57fSMateusz Guzik 	else
1262e4ccf57fSMateusz Guzik 		lock_profile_obtain_lock_success(&sx->lock_object, 0, 0,
1263e4ccf57fSMateusz Guzik 		    file, line);
1264834f70f3SMateusz Guzik 	if (error == 0) {
1265834f70f3SMateusz Guzik 		LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1266834f70f3SMateusz Guzik 		WITNESS_LOCK(&sx->lock_object, 0, file, line);
1267834f70f3SMateusz Guzik 		TD_LOCKS_INC(curthread);
1268834f70f3SMateusz Guzik 	}
1269834f70f3SMateusz Guzik 	return (error);
1270834f70f3SMateusz Guzik }
1271834f70f3SMateusz Guzik 
1272013c0b49SMateusz Guzik int
1273013c0b49SMateusz Guzik _sx_slock(struct sx *sx, int opts, const char *file, int line)
1274013c0b49SMateusz Guzik {
1275013c0b49SMateusz Guzik 
1276013c0b49SMateusz Guzik 	return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1277013c0b49SMateusz Guzik }
1278013c0b49SMateusz Guzik 
1279834f70f3SMateusz Guzik static bool __always_inline
12802466d12bSMateusz Guzik _sx_sunlock_try(struct sx *sx, struct thread *td, uintptr_t *xp)
1281834f70f3SMateusz Guzik {
1282834f70f3SMateusz Guzik 
12834e7f640dSJohn Baldwin 	for (;;) {
12842466d12bSMateusz Guzik 		if (SX_SHARERS(*xp) > 1 || !(*xp & SX_LOCK_WAITERS)) {
1285834f70f3SMateusz Guzik 			if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1286834f70f3SMateusz Guzik 			    *xp - SX_ONE_SHARER)) {
12874e7f640dSJohn Baldwin 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
12884e7f640dSJohn Baldwin 					CTR4(KTR_LOCK,
12894e7f640dSJohn Baldwin 					    "%s: %p succeeded %p -> %p",
1290834f70f3SMateusz Guzik 					    __func__, sx, (void *)*xp,
1291834f70f3SMateusz Guzik 					    (void *)(*xp - SX_ONE_SHARER));
12922466d12bSMateusz Guzik 				td->td_sx_slocks--;
1293834f70f3SMateusz Guzik 				return (true);
12944e7f640dSJohn Baldwin 			}
12954e7f640dSJohn Baldwin 			continue;
12964e7f640dSJohn Baldwin 		}
1297834f70f3SMateusz Guzik 		break;
1298834f70f3SMateusz Guzik 	}
1299834f70f3SMateusz Guzik 	return (false);
1300834f70f3SMateusz Guzik }
1301834f70f3SMateusz Guzik 
1302834f70f3SMateusz Guzik static void __noinline
13032466d12bSMateusz Guzik _sx_sunlock_hard(struct sx *sx, struct thread *td, uintptr_t x
13042466d12bSMateusz Guzik     LOCK_FILE_LINE_ARG_DEF)
1305834f70f3SMateusz Guzik {
13061b54ffc8SMateusz Guzik 	int wakeup_swapper = 0;
13072466d12bSMateusz Guzik 	uintptr_t setx, queue;
1308834f70f3SMateusz Guzik 
1309834f70f3SMateusz Guzik 	if (SCHEDULER_STOPPED())
1310834f70f3SMateusz Guzik 		return;
1311834f70f3SMateusz Guzik 
13122466d12bSMateusz Guzik 	if (_sx_sunlock_try(sx, td, &x))
1313cec17473SMateusz Guzik 		goto out_lockstat;
13144e7f640dSJohn Baldwin 
13154e7f640dSJohn Baldwin 	sleepq_lock(&sx->lock_object);
1316cec17473SMateusz Guzik 	x = SX_READ_VALUE(sx);
1317cec17473SMateusz Guzik 	for (;;) {
13182466d12bSMateusz Guzik 		if (_sx_sunlock_try(sx, td, &x))
13191b54ffc8SMateusz Guzik 			break;
13201b54ffc8SMateusz Guzik 
13214e7f640dSJohn Baldwin 		/*
13224e7f640dSJohn Baldwin 		 * Wake up semantic here is quite simple:
13234e7f640dSJohn Baldwin 		 * Just wake up all the exclusive waiters.
13244e7f640dSJohn Baldwin 		 * Note that the state of the lock could have changed,
13254e7f640dSJohn Baldwin 		 * so if it fails loop back and retry.
13264e7f640dSJohn Baldwin 		 */
13272466d12bSMateusz Guzik 		setx = SX_LOCK_UNLOCKED;
13282466d12bSMateusz Guzik 		queue = SQ_SHARED_QUEUE;
13292466d12bSMateusz Guzik 		if (x & SX_LOCK_EXCLUSIVE_WAITERS) {
13302466d12bSMateusz Guzik 			setx |= (x & SX_LOCK_SHARED_WAITERS);
13312466d12bSMateusz Guzik 			queue = SQ_EXCLUSIVE_QUEUE;
13322466d12bSMateusz Guzik 		}
13332466d12bSMateusz Guzik 		setx |= (x & SX_LOCK_WRITE_SPINNER);
1334cec17473SMateusz Guzik 		if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
13354e7f640dSJohn Baldwin 			continue;
13364e7f640dSJohn Baldwin 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
13374e7f640dSJohn Baldwin 			CTR2(KTR_LOCK, "%s: %p waking up all thread on"
13384e7f640dSJohn Baldwin 			    "exclusive queue", __func__, sx);
1339da7bbd2cSJohn Baldwin 		wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
13402466d12bSMateusz Guzik 		    0, queue);
13412466d12bSMateusz Guzik 		td->td_sx_slocks--;
1342cec17473SMateusz Guzik 		break;
1343cec17473SMateusz Guzik 	}
1344c5aa6b58SJeff Roberson 	sleepq_release(&sx->lock_object);
1345da7bbd2cSJohn Baldwin 	if (wakeup_swapper)
1346da7bbd2cSJohn Baldwin 		kick_proc0();
1347cec17473SMateusz Guzik out_lockstat:
1348dbe4541dSMark Johnston 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1349834f70f3SMateusz Guzik }
1350834f70f3SMateusz Guzik 
1351834f70f3SMateusz Guzik void
1352013c0b49SMateusz Guzik _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1353834f70f3SMateusz Guzik {
13542466d12bSMateusz Guzik 	struct thread *td;
1355834f70f3SMateusz Guzik 	uintptr_t x;
1356834f70f3SMateusz Guzik 
1357834f70f3SMateusz Guzik 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1358834f70f3SMateusz Guzik 	    ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1359834f70f3SMateusz Guzik 	_sx_assert(sx, SA_SLOCKED, file, line);
1360834f70f3SMateusz Guzik 	WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1361834f70f3SMateusz Guzik 	LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1362834f70f3SMateusz Guzik 
13632466d12bSMateusz Guzik 	td = curthread;
1364834f70f3SMateusz Guzik 	x = SX_READ_VALUE(sx);
1365e4ccf57fSMateusz Guzik 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__release) ||
13662466d12bSMateusz Guzik 	    !_sx_sunlock_try(sx, td, &x)))
13672466d12bSMateusz Guzik 		_sx_sunlock_hard(sx, td, x LOCK_FILE_LINE_ARG);
1368e4ccf57fSMateusz Guzik 	else
1369e4ccf57fSMateusz Guzik 		lock_profile_release_lock(&sx->lock_object);
1370834f70f3SMateusz Guzik 
13713ae56ce9SMateusz Guzik 	TD_LOCKS_DEC(curthread);
1372d55229b7SJason Evans }
13734e5e677bSJohn Baldwin 
1374013c0b49SMateusz Guzik void
1375013c0b49SMateusz Guzik _sx_sunlock(struct sx *sx, const char *file, int line)
1376013c0b49SMateusz Guzik {
1377013c0b49SMateusz Guzik 
1378013c0b49SMateusz Guzik 	_sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1379013c0b49SMateusz Guzik }
1380013c0b49SMateusz Guzik 
13814e5e677bSJohn Baldwin #ifdef INVARIANT_SUPPORT
1382781a35dfSJohn Baldwin #ifndef INVARIANTS
1383781a35dfSJohn Baldwin #undef	_sx_assert
1384781a35dfSJohn Baldwin #endif
1385781a35dfSJohn Baldwin 
13864e5e677bSJohn Baldwin /*
13874e5e677bSJohn Baldwin  * In the non-WITNESS case, sx_assert() can only detect that at least
13884e5e677bSJohn Baldwin  * *some* thread owns an slock, but it cannot guarantee that *this*
13894e5e677bSJohn Baldwin  * thread owns an slock.
13904e5e677bSJohn Baldwin  */
13914e5e677bSJohn Baldwin void
1392d576deedSPawel Jakub Dawidek _sx_assert(const struct sx *sx, int what, const char *file, int line)
13934e5e677bSJohn Baldwin {
13944e7f640dSJohn Baldwin #ifndef WITNESS
13954e7f640dSJohn Baldwin 	int slocked = 0;
13964e7f640dSJohn Baldwin #endif
13974e5e677bSJohn Baldwin 
1398d54474e6SEric van Gyzen 	if (SCHEDULER_STOPPED())
139903129ba9SJohn Baldwin 		return;
14004e5e677bSJohn Baldwin 	switch (what) {
14017ec137e5SJohn Baldwin 	case SA_SLOCKED:
14027ec137e5SJohn Baldwin 	case SA_SLOCKED | SA_NOTRECURSED:
14037ec137e5SJohn Baldwin 	case SA_SLOCKED | SA_RECURSED:
14044e7f640dSJohn Baldwin #ifndef WITNESS
14054e7f640dSJohn Baldwin 		slocked = 1;
14064e7f640dSJohn Baldwin 		/* FALLTHROUGH */
14074e7f640dSJohn Baldwin #endif
14087ec137e5SJohn Baldwin 	case SA_LOCKED:
14097ec137e5SJohn Baldwin 	case SA_LOCKED | SA_NOTRECURSED:
14107ec137e5SJohn Baldwin 	case SA_LOCKED | SA_RECURSED:
14114e5e677bSJohn Baldwin #ifdef WITNESS
1412aa89d8cdSJohn Baldwin 		witness_assert(&sx->lock_object, what, file, line);
14134e5e677bSJohn Baldwin #else
14144e7f640dSJohn Baldwin 		/*
14154e7f640dSJohn Baldwin 		 * If some other thread has an exclusive lock or we
14164e7f640dSJohn Baldwin 		 * have one and are asserting a shared lock, fail.
14174e7f640dSJohn Baldwin 		 * Also, if no one has a lock at all, fail.
14184e7f640dSJohn Baldwin 		 */
14194e7f640dSJohn Baldwin 		if (sx->sx_lock == SX_LOCK_UNLOCKED ||
14204e7f640dSJohn Baldwin 		    (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
14214e7f640dSJohn Baldwin 		    sx_xholder(sx) != curthread)))
142203129ba9SJohn Baldwin 			panic("Lock %s not %slocked @ %s:%d\n",
14234e7f640dSJohn Baldwin 			    sx->lock_object.lo_name, slocked ? "share " : "",
14244e7f640dSJohn Baldwin 			    file, line);
14254e7f640dSJohn Baldwin 
14264e7f640dSJohn Baldwin 		if (!(sx->sx_lock & SX_LOCK_SHARED)) {
14274e7f640dSJohn Baldwin 			if (sx_recursed(sx)) {
14287ec137e5SJohn Baldwin 				if (what & SA_NOTRECURSED)
14294e7f640dSJohn Baldwin 					panic("Lock %s recursed @ %s:%d\n",
14304e7f640dSJohn Baldwin 					    sx->lock_object.lo_name, file,
14314e7f640dSJohn Baldwin 					    line);
14327ec137e5SJohn Baldwin 			} else if (what & SA_RECURSED)
14334e7f640dSJohn Baldwin 				panic("Lock %s not recursed @ %s:%d\n",
14344e7f640dSJohn Baldwin 				    sx->lock_object.lo_name, file, line);
14354e7f640dSJohn Baldwin 		}
14364e5e677bSJohn Baldwin #endif
14374e5e677bSJohn Baldwin 		break;
14387ec137e5SJohn Baldwin 	case SA_XLOCKED:
14397ec137e5SJohn Baldwin 	case SA_XLOCKED | SA_NOTRECURSED:
14407ec137e5SJohn Baldwin 	case SA_XLOCKED | SA_RECURSED:
14414e7f640dSJohn Baldwin 		if (sx_xholder(sx) != curthread)
144203129ba9SJohn Baldwin 			panic("Lock %s not exclusively locked @ %s:%d\n",
1443aa89d8cdSJohn Baldwin 			    sx->lock_object.lo_name, file, line);
14444e7f640dSJohn Baldwin 		if (sx_recursed(sx)) {
14457ec137e5SJohn Baldwin 			if (what & SA_NOTRECURSED)
14464e7f640dSJohn Baldwin 				panic("Lock %s recursed @ %s:%d\n",
14474e7f640dSJohn Baldwin 				    sx->lock_object.lo_name, file, line);
14487ec137e5SJohn Baldwin 		} else if (what & SA_RECURSED)
14494e7f640dSJohn Baldwin 			panic("Lock %s not recursed @ %s:%d\n",
14504e7f640dSJohn Baldwin 			    sx->lock_object.lo_name, file, line);
14514e5e677bSJohn Baldwin 		break;
14527ec137e5SJohn Baldwin 	case SA_UNLOCKED:
145319b0efd3SPawel Jakub Dawidek #ifdef WITNESS
1454aa89d8cdSJohn Baldwin 		witness_assert(&sx->lock_object, what, file, line);
145519b0efd3SPawel Jakub Dawidek #else
1456f6739b1dSPawel Jakub Dawidek 		/*
14574e7f640dSJohn Baldwin 		 * If we hold an exclusve lock fail.  We can't
14584e7f640dSJohn Baldwin 		 * reliably check to see if we hold a shared lock or
14594e7f640dSJohn Baldwin 		 * not.
1460f6739b1dSPawel Jakub Dawidek 		 */
14614e7f640dSJohn Baldwin 		if (sx_xholder(sx) == curthread)
146203129ba9SJohn Baldwin 			panic("Lock %s exclusively locked @ %s:%d\n",
1463aa89d8cdSJohn Baldwin 			    sx->lock_object.lo_name, file, line);
146419b0efd3SPawel Jakub Dawidek #endif
146519b0efd3SPawel Jakub Dawidek 		break;
14664e5e677bSJohn Baldwin 	default:
14674e5e677bSJohn Baldwin 		panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
14684e5e677bSJohn Baldwin 		    line);
14694e5e677bSJohn Baldwin 	}
14704e5e677bSJohn Baldwin }
14714e5e677bSJohn Baldwin #endif	/* INVARIANT_SUPPORT */
1472d272fe53SJohn Baldwin 
1473d272fe53SJohn Baldwin #ifdef DDB
14744e7f640dSJohn Baldwin static void
1475d576deedSPawel Jakub Dawidek db_show_sx(const struct lock_object *lock)
1476d272fe53SJohn Baldwin {
1477d272fe53SJohn Baldwin 	struct thread *td;
1478d576deedSPawel Jakub Dawidek 	const struct sx *sx;
1479d272fe53SJohn Baldwin 
1480d576deedSPawel Jakub Dawidek 	sx = (const struct sx *)lock;
1481d272fe53SJohn Baldwin 
1482d272fe53SJohn Baldwin 	db_printf(" state: ");
14834e7f640dSJohn Baldwin 	if (sx->sx_lock == SX_LOCK_UNLOCKED)
14844e7f640dSJohn Baldwin 		db_printf("UNLOCKED\n");
14850026c92cSJohn Baldwin 	else if (sx->sx_lock == SX_LOCK_DESTROYED) {
14860026c92cSJohn Baldwin 		db_printf("DESTROYED\n");
14870026c92cSJohn Baldwin 		return;
14880026c92cSJohn Baldwin 	} else if (sx->sx_lock & SX_LOCK_SHARED)
14894e7f640dSJohn Baldwin 		db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
14904e7f640dSJohn Baldwin 	else {
14914e7f640dSJohn Baldwin 		td = sx_xholder(sx);
1492d272fe53SJohn Baldwin 		db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1493431f8906SJulian Elischer 		    td->td_tid, td->td_proc->p_pid, td->td_name);
14944e7f640dSJohn Baldwin 		if (sx_recursed(sx))
14954e7f640dSJohn Baldwin 			db_printf(" recursed: %d\n", sx->sx_recurse);
14964e7f640dSJohn Baldwin 	}
14974e7f640dSJohn Baldwin 
14984e7f640dSJohn Baldwin 	db_printf(" waiters: ");
14994e7f640dSJohn Baldwin 	switch(sx->sx_lock &
15004e7f640dSJohn Baldwin 	    (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
15014e7f640dSJohn Baldwin 	case SX_LOCK_SHARED_WAITERS:
15024e7f640dSJohn Baldwin 		db_printf("shared\n");
15034e7f640dSJohn Baldwin 		break;
15044e7f640dSJohn Baldwin 	case SX_LOCK_EXCLUSIVE_WAITERS:
15054e7f640dSJohn Baldwin 		db_printf("exclusive\n");
15064e7f640dSJohn Baldwin 		break;
15074e7f640dSJohn Baldwin 	case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
15084e7f640dSJohn Baldwin 		db_printf("exclusive and shared\n");
15094e7f640dSJohn Baldwin 		break;
15104e7f640dSJohn Baldwin 	default:
15114e7f640dSJohn Baldwin 		db_printf("none\n");
15124e7f640dSJohn Baldwin 	}
1513d272fe53SJohn Baldwin }
1514462a7addSJohn Baldwin 
1515462a7addSJohn Baldwin /*
1516462a7addSJohn Baldwin  * Check to see if a thread that is blocked on a sleep queue is actually
1517462a7addSJohn Baldwin  * blocked on an sx lock.  If so, output some details and return true.
1518462a7addSJohn Baldwin  * If the lock has an exclusive owner, return that in *ownerp.
1519462a7addSJohn Baldwin  */
1520462a7addSJohn Baldwin int
1521462a7addSJohn Baldwin sx_chain(struct thread *td, struct thread **ownerp)
1522462a7addSJohn Baldwin {
1523462a7addSJohn Baldwin 	struct sx *sx;
1524462a7addSJohn Baldwin 
1525462a7addSJohn Baldwin 	/*
15264e7f640dSJohn Baldwin 	 * Check to see if this thread is blocked on an sx lock.
15274e7f640dSJohn Baldwin 	 * First, we check the lock class.  If that is ok, then we
15284e7f640dSJohn Baldwin 	 * compare the lock name against the wait message.
1529462a7addSJohn Baldwin 	 */
15304e7f640dSJohn Baldwin 	sx = td->td_wchan;
15314e7f640dSJohn Baldwin 	if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
15324e7f640dSJohn Baldwin 	    sx->lock_object.lo_name != td->td_wmesg)
1533462a7addSJohn Baldwin 		return (0);
1534462a7addSJohn Baldwin 
1535462a7addSJohn Baldwin 	/* We think we have an sx lock, so output some details. */
1536462a7addSJohn Baldwin 	db_printf("blocked on sx \"%s\" ", td->td_wmesg);
15374e7f640dSJohn Baldwin 	*ownerp = sx_xholder(sx);
15384e7f640dSJohn Baldwin 	if (sx->sx_lock & SX_LOCK_SHARED)
15394e7f640dSJohn Baldwin 		db_printf("SLOCK (count %ju)\n",
15404e7f640dSJohn Baldwin 		    (uintmax_t)SX_SHARERS(sx->sx_lock));
15414e7f640dSJohn Baldwin 	else
1542462a7addSJohn Baldwin 		db_printf("XLOCK\n");
1543462a7addSJohn Baldwin 	return (1);
1544462a7addSJohn Baldwin }
1545d272fe53SJohn Baldwin #endif
1546