xref: /freebsd/sys/kern/kern_sx.c (revision ce15215befa1022d9a20ec15bdb0739dbe55f10f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2007 Attilio Rao <attilio@freebsd.org>
5  * Copyright (c) 2001 Jason Evans <jasone@freebsd.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice(s), this list of conditions and the following disclaimer as
13  *    the first lines of this file unmodified other than the possible
14  *    addition of one or more copyright notices.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice(s), this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
29  * DAMAGE.
30  */
31 
32 /*
33  * Shared/exclusive locks.  This implementation attempts to ensure
34  * deterministic lock granting behavior, so that slocks and xlocks are
35  * interleaved.
36  *
37  * Priority propagation will not generally raise the priority of lock holders,
38  * so should not be relied upon in combination with sx locks.
39  */
40 
41 #include "opt_ddb.h"
42 #include "opt_hwpmc_hooks.h"
43 #include "opt_no_adaptive_sx.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kdb.h>
48 #include <sys/kernel.h>
49 #include <sys/ktr.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/sched.h>
54 #include <sys/sleepqueue.h>
55 #include <sys/sx.h>
56 #include <sys/smp.h>
57 #include <sys/sysctl.h>
58 
59 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
60 #include <machine/cpu.h>
61 #endif
62 
63 #ifdef DDB
64 #include <ddb/ddb.h>
65 #endif
66 
67 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
68 #define	ADAPTIVE_SX
69 #endif
70 
71 #ifdef HWPMC_HOOKS
72 #include <sys/pmckern.h>
73 PMC_SOFT_DECLARE( , , lock, failed);
74 #endif
75 
76 /* Handy macros for sleep queues. */
77 #define	SQ_EXCLUSIVE_QUEUE	0
78 #define	SQ_SHARED_QUEUE		1
79 
80 /*
81  * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file.  We
82  * drop Giant anytime we have to sleep or if we adaptively spin.
83  */
84 #define	GIANT_DECLARE							\
85 	int _giantcnt = 0;						\
86 	WITNESS_SAVE_DECL(Giant)					\
87 
88 #define	GIANT_SAVE(work) do {						\
89 	if (__predict_false(mtx_owned(&Giant))) {			\
90 		work++;							\
91 		WITNESS_SAVE(&Giant.lock_object, Giant);		\
92 		while (mtx_owned(&Giant)) {				\
93 			_giantcnt++;					\
94 			mtx_unlock(&Giant);				\
95 		}							\
96 	}								\
97 } while (0)
98 
99 #define GIANT_RESTORE() do {						\
100 	if (_giantcnt > 0) {						\
101 		mtx_assert(&Giant, MA_NOTOWNED);			\
102 		while (_giantcnt--)					\
103 			mtx_lock(&Giant);				\
104 		WITNESS_RESTORE(&Giant.lock_object, Giant);		\
105 	}								\
106 } while (0)
107 
108 /*
109  * Returns true if an exclusive lock is recursed.  It assumes
110  * curthread currently has an exclusive lock.
111  */
112 #define	sx_recursed(sx)		((sx)->sx_recurse != 0)
113 
114 static void	assert_sx(const struct lock_object *lock, int what);
115 #ifdef DDB
116 static void	db_show_sx(const struct lock_object *lock);
117 #endif
118 static void	lock_sx(struct lock_object *lock, uintptr_t how);
119 #ifdef KDTRACE_HOOKS
120 static int	owner_sx(const struct lock_object *lock, struct thread **owner);
121 #endif
122 static uintptr_t unlock_sx(struct lock_object *lock);
123 
124 struct lock_class lock_class_sx = {
125 	.lc_name = "sx",
126 	.lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
127 	.lc_assert = assert_sx,
128 #ifdef DDB
129 	.lc_ddb_show = db_show_sx,
130 #endif
131 	.lc_lock = lock_sx,
132 	.lc_unlock = unlock_sx,
133 #ifdef KDTRACE_HOOKS
134 	.lc_owner = owner_sx,
135 #endif
136 };
137 
138 #ifndef INVARIANTS
139 #define	_sx_assert(sx, what, file, line)
140 #endif
141 
142 #ifdef ADAPTIVE_SX
143 #ifdef SX_CUSTOM_BACKOFF
144 static u_short __read_frequently asx_retries;
145 static u_short __read_frequently asx_loops;
146 static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
147     "sxlock debugging");
148 SYSCTL_U16(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
149 SYSCTL_U16(_debug_sx, OID_AUTO, loops, CTLFLAG_RW, &asx_loops, 0, "");
150 
151 static struct lock_delay_config __read_frequently sx_delay;
152 
153 SYSCTL_U16(_debug_sx, OID_AUTO, delay_base, CTLFLAG_RW, &sx_delay.base,
154     0, "");
155 SYSCTL_U16(_debug_sx, OID_AUTO, delay_max, CTLFLAG_RW, &sx_delay.max,
156     0, "");
157 
158 static void
159 sx_lock_delay_init(void *arg __unused)
160 {
161 
162 	lock_delay_default_init(&sx_delay);
163 	asx_retries = 10;
164 	asx_loops = max(10000, sx_delay.max);
165 }
166 LOCK_DELAY_SYSINIT(sx_lock_delay_init);
167 #else
168 #define sx_delay	locks_delay
169 #define asx_retries	locks_delay_retries
170 #define asx_loops	locks_delay_loops
171 #endif
172 #endif
173 
174 void
175 assert_sx(const struct lock_object *lock, int what)
176 {
177 
178 	sx_assert((const struct sx *)lock, what);
179 }
180 
181 void
182 lock_sx(struct lock_object *lock, uintptr_t how)
183 {
184 	struct sx *sx;
185 
186 	sx = (struct sx *)lock;
187 	if (how)
188 		sx_slock(sx);
189 	else
190 		sx_xlock(sx);
191 }
192 
193 uintptr_t
194 unlock_sx(struct lock_object *lock)
195 {
196 	struct sx *sx;
197 
198 	sx = (struct sx *)lock;
199 	sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
200 	if (sx_xlocked(sx)) {
201 		sx_xunlock(sx);
202 		return (0);
203 	} else {
204 		sx_sunlock(sx);
205 		return (1);
206 	}
207 }
208 
209 #ifdef KDTRACE_HOOKS
210 int
211 owner_sx(const struct lock_object *lock, struct thread **owner)
212 {
213 	const struct sx *sx;
214 	uintptr_t x;
215 
216 	sx = (const struct sx *)lock;
217 	x = sx->sx_lock;
218 	*owner = NULL;
219 	return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
220 	    ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
221 }
222 #endif
223 
224 void
225 sx_sysinit(void *arg)
226 {
227 	struct sx_args *sargs = arg;
228 
229 	sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
230 }
231 
232 void
233 sx_init_flags(struct sx *sx, const char *description, int opts)
234 {
235 	int flags;
236 
237 	MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
238 	    SX_NOPROFILE | SX_NEW)) == 0);
239 	ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
240 	    ("%s: sx_lock not aligned for %s: %p", __func__, description,
241 	    &sx->sx_lock));
242 
243 	flags = LO_SLEEPABLE | LO_UPGRADABLE;
244 	if (opts & SX_DUPOK)
245 		flags |= LO_DUPOK;
246 	if (opts & SX_NOPROFILE)
247 		flags |= LO_NOPROFILE;
248 	if (!(opts & SX_NOWITNESS))
249 		flags |= LO_WITNESS;
250 	if (opts & SX_RECURSE)
251 		flags |= LO_RECURSABLE;
252 	if (opts & SX_QUIET)
253 		flags |= LO_QUIET;
254 	if (opts & SX_NEW)
255 		flags |= LO_NEW;
256 
257 	lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
258 	sx->sx_lock = SX_LOCK_UNLOCKED;
259 	sx->sx_recurse = 0;
260 }
261 
262 void
263 sx_destroy(struct sx *sx)
264 {
265 
266 	KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
267 	KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
268 	sx->sx_lock = SX_LOCK_DESTROYED;
269 	lock_destroy(&sx->lock_object);
270 }
271 
272 int
273 sx_try_slock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
274 {
275 	uintptr_t x;
276 
277 	if (SCHEDULER_STOPPED())
278 		return (1);
279 
280 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
281 	    ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
282 	    curthread, sx->lock_object.lo_name, file, line));
283 
284 	x = sx->sx_lock;
285 	for (;;) {
286 		KASSERT(x != SX_LOCK_DESTROYED,
287 		    ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
288 		if (!(x & SX_LOCK_SHARED))
289 			break;
290 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, x + SX_ONE_SHARER)) {
291 			LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
292 			WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
293 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
294 			    sx, 0, 0, file, line, LOCKSTAT_READER);
295 			TD_LOCKS_INC(curthread);
296 			curthread->td_sx_slocks++;
297 			return (1);
298 		}
299 	}
300 
301 	LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
302 	return (0);
303 }
304 
305 int
306 sx_try_slock_(struct sx *sx, const char *file, int line)
307 {
308 
309 	return (sx_try_slock_int(sx LOCK_FILE_LINE_ARG));
310 }
311 
312 int
313 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
314 {
315 	uintptr_t tid, x;
316 	int error = 0;
317 
318 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
319 	    !TD_IS_IDLETHREAD(curthread),
320 	    ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
321 	    curthread, sx->lock_object.lo_name, file, line));
322 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
323 	    ("sx_xlock() of destroyed sx @ %s:%d", file, line));
324 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
325 	    line, NULL);
326 	tid = (uintptr_t)curthread;
327 	x = SX_LOCK_UNLOCKED;
328 	if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
329 		error = _sx_xlock_hard(sx, x, opts LOCK_FILE_LINE_ARG);
330 	else
331 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
332 		    0, 0, file, line, LOCKSTAT_WRITER);
333 	if (!error) {
334 		LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
335 		    file, line);
336 		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
337 		TD_LOCKS_INC(curthread);
338 	}
339 
340 	return (error);
341 }
342 
343 int
344 sx_try_xlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
345 {
346 	struct thread *td;
347 	uintptr_t tid, x;
348 	int rval;
349 	bool recursed;
350 
351 	td = curthread;
352 	tid = (uintptr_t)td;
353 	if (SCHEDULER_STOPPED())
354 		return (1);
355 
356 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
357 	    ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
358 	    curthread, sx->lock_object.lo_name, file, line));
359 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
360 	    ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
361 
362 	rval = 1;
363 	recursed = false;
364 	x = SX_LOCK_UNLOCKED;
365 	for (;;) {
366 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
367 			break;
368 		if (x == SX_LOCK_UNLOCKED)
369 			continue;
370 		if (x == tid && (sx->lock_object.lo_flags & LO_RECURSABLE)) {
371 			sx->sx_recurse++;
372 			atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
373 			break;
374 		}
375 		rval = 0;
376 		break;
377 	}
378 
379 	LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
380 	if (rval) {
381 		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
382 		    file, line);
383 		if (!recursed)
384 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
385 			    sx, 0, 0, file, line, LOCKSTAT_WRITER);
386 		TD_LOCKS_INC(curthread);
387 	}
388 
389 	return (rval);
390 }
391 
392 int
393 sx_try_xlock_(struct sx *sx, const char *file, int line)
394 {
395 
396 	return (sx_try_xlock_int(sx LOCK_FILE_LINE_ARG));
397 }
398 
399 void
400 _sx_xunlock(struct sx *sx, const char *file, int line)
401 {
402 
403 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
404 	    ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
405 	_sx_assert(sx, SA_XLOCKED, file, line);
406 	WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
407 	LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
408 	    line);
409 #if LOCK_DEBUG > 0
410 	_sx_xunlock_hard(sx, (uintptr_t)curthread, file, line);
411 #else
412 	__sx_xunlock(sx, curthread, file, line);
413 #endif
414 	TD_LOCKS_DEC(curthread);
415 }
416 
417 /*
418  * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
419  * This will only succeed if this thread holds a single shared lock.
420  * Return 1 if if the upgrade succeed, 0 otherwise.
421  */
422 int
423 sx_try_upgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
424 {
425 	uintptr_t x;
426 	uintptr_t waiters;
427 	int success;
428 
429 	if (SCHEDULER_STOPPED())
430 		return (1);
431 
432 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
433 	    ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
434 	_sx_assert(sx, SA_SLOCKED, file, line);
435 
436 	/*
437 	 * Try to switch from one shared lock to an exclusive lock.  We need
438 	 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
439 	 * we will wake up the exclusive waiters when we drop the lock.
440 	 */
441 	success = 0;
442 	x = SX_READ_VALUE(sx);
443 	for (;;) {
444 		if (SX_SHARERS(x) > 1)
445 			break;
446 		waiters = (x & SX_LOCK_WAITERS);
447 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
448 		    (uintptr_t)curthread | waiters)) {
449 			success = 1;
450 			break;
451 		}
452 	}
453 	LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
454 	if (success) {
455 		curthread->td_sx_slocks--;
456 		WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
457 		    file, line);
458 		LOCKSTAT_RECORD0(sx__upgrade, sx);
459 	}
460 	return (success);
461 }
462 
463 int
464 sx_try_upgrade_(struct sx *sx, const char *file, int line)
465 {
466 
467 	return (sx_try_upgrade_int(sx LOCK_FILE_LINE_ARG));
468 }
469 
470 /*
471  * Downgrade an unrecursed exclusive lock into a single shared lock.
472  */
473 void
474 sx_downgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
475 {
476 	uintptr_t x;
477 
478 	if (SCHEDULER_STOPPED())
479 		return;
480 
481 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
482 	    ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
483 	_sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
484 #ifndef INVARIANTS
485 	if (sx_recursed(sx))
486 		panic("downgrade of a recursed lock");
487 #endif
488 
489 	WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
490 
491 	/*
492 	 * Try to switch from an exclusive lock with no shared waiters
493 	 * to one sharer with no shared waiters.  If there are
494 	 * exclusive waiters, we don't need to lock the sleep queue so
495 	 * long as we preserve the flag.  We do one quick try and if
496 	 * that fails we grab the sleepq lock to keep the flags from
497 	 * changing and do it the slow way.
498 	 *
499 	 * We have to lock the sleep queue if there are shared waiters
500 	 * so we can wake them up.
501 	 */
502 	x = sx->sx_lock;
503 	if (!(x & SX_LOCK_SHARED_WAITERS) &&
504 	    atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
505 	    (x & SX_LOCK_EXCLUSIVE_WAITERS)))
506 		goto out;
507 
508 	/*
509 	 * Lock the sleep queue so we can read the waiters bits
510 	 * without any races and wakeup any shared waiters.
511 	 */
512 	sleepq_lock(&sx->lock_object);
513 
514 	/*
515 	 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
516 	 * shared lock.  If there are any shared waiters, wake them up.
517 	 */
518 	x = sx->sx_lock;
519 	atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
520 	    (x & SX_LOCK_EXCLUSIVE_WAITERS));
521 	if (x & SX_LOCK_SHARED_WAITERS)
522 		sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
523 		    SQ_SHARED_QUEUE);
524 	sleepq_release(&sx->lock_object);
525 
526 out:
527 	curthread->td_sx_slocks++;
528 	LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
529 	LOCKSTAT_RECORD0(sx__downgrade, sx);
530 }
531 
532 void
533 sx_downgrade_(struct sx *sx, const char *file, int line)
534 {
535 
536 	sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
537 }
538 
539 #ifdef	ADAPTIVE_SX
540 static inline void
541 sx_drop_critical(uintptr_t x, bool *in_critical, int *extra_work)
542 {
543 
544 	if (x & SX_LOCK_WRITE_SPINNER)
545 		return;
546 	if (*in_critical) {
547 		critical_exit();
548 		*in_critical = false;
549 		(*extra_work)--;
550 	}
551 }
552 #else
553 #define sx_drop_critical(x, in_critical, extra_work) do { } while (0)
554 #endif
555 
556 /*
557  * This function represents the so-called 'hard case' for sx_xlock
558  * operation.  All 'easy case' failures are redirected to this.  Note
559  * that ideally this would be a static function, but it needs to be
560  * accessible from at least sx.h.
561  */
562 int
563 _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
564 {
565 	GIANT_DECLARE;
566 	uintptr_t tid, setx;
567 #ifdef ADAPTIVE_SX
568 	struct thread *owner;
569 	u_int i, n, spintries = 0;
570 	enum { READERS, WRITER } sleep_reason = READERS;
571 	bool in_critical = false;
572 #endif
573 #ifdef LOCK_PROFILING
574 	uint64_t waittime = 0;
575 	int contested = 0;
576 #endif
577 	int error = 0;
578 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
579 	struct lock_delay_arg lda;
580 #endif
581 #ifdef	KDTRACE_HOOKS
582 	u_int sleep_cnt = 0;
583 	int64_t sleep_time = 0;
584 	int64_t all_time = 0;
585 #endif
586 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
587 	uintptr_t state = 0;
588 	int doing_lockprof = 0;
589 #endif
590 	int extra_work = 0;
591 
592 	tid = (uintptr_t)curthread;
593 
594 #ifdef KDTRACE_HOOKS
595 	if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
596 		while (x == SX_LOCK_UNLOCKED) {
597 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
598 				goto out_lockstat;
599 		}
600 		extra_work = 1;
601 		doing_lockprof = 1;
602 		all_time -= lockstat_nsecs(&sx->lock_object);
603 		state = x;
604 	}
605 #endif
606 #ifdef LOCK_PROFILING
607 	extra_work = 1;
608 	doing_lockprof = 1;
609 	state = x;
610 #endif
611 
612 	if (SCHEDULER_STOPPED())
613 		return (0);
614 
615 	if (__predict_false(x == SX_LOCK_UNLOCKED))
616 		x = SX_READ_VALUE(sx);
617 
618 	/* If we already hold an exclusive lock, then recurse. */
619 	if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
620 		KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
621 	    ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
622 		    sx->lock_object.lo_name, file, line));
623 		sx->sx_recurse++;
624 		atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
625 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
626 			CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
627 		return (0);
628 	}
629 
630 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
631 		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
632 		    sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
633 
634 #if defined(ADAPTIVE_SX)
635 	lock_delay_arg_init(&lda, &sx_delay);
636 #elif defined(KDTRACE_HOOKS)
637 	lock_delay_arg_init_noadapt(&lda);
638 #endif
639 
640 #ifdef HWPMC_HOOKS
641 	PMC_SOFT_CALL( , , lock, failed);
642 #endif
643 	lock_profile_obtain_lock_failed(&sx->lock_object, false, &contested,
644 	    &waittime);
645 
646 #ifndef INVARIANTS
647 	GIANT_SAVE(extra_work);
648 #endif
649 
650 	THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
651 
652 	for (;;) {
653 		if (x == SX_LOCK_UNLOCKED) {
654 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
655 				break;
656 			continue;
657 		}
658 #ifdef INVARIANTS
659 		GIANT_SAVE(extra_work);
660 #endif
661 #ifdef KDTRACE_HOOKS
662 		lda.spin_cnt++;
663 #endif
664 #ifdef ADAPTIVE_SX
665 		if (x == (SX_LOCK_SHARED | SX_LOCK_WRITE_SPINNER)) {
666 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
667 				break;
668 			continue;
669 		}
670 
671 		/*
672 		 * If the lock is write locked and the owner is
673 		 * running on another CPU, spin until the owner stops
674 		 * running or the state of the lock changes.
675 		 */
676 		if ((x & SX_LOCK_SHARED) == 0) {
677 			sx_drop_critical(x, &in_critical, &extra_work);
678 			sleep_reason = WRITER;
679 			owner = lv_sx_owner(x);
680 			if (!TD_IS_RUNNING(owner))
681 				goto sleepq;
682 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
683 				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
684 				    __func__, sx, owner);
685 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
686 			    "spinning", "lockname:\"%s\"",
687 			    sx->lock_object.lo_name);
688 			do {
689 				lock_delay(&lda);
690 				x = SX_READ_VALUE(sx);
691 				owner = lv_sx_owner(x);
692 			} while (owner != NULL && TD_IS_RUNNING(owner));
693 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
694 			    "running");
695 			continue;
696 		} else if (SX_SHARERS(x) > 0) {
697 			sleep_reason = READERS;
698 			if (spintries == asx_retries)
699 				goto sleepq;
700 			if (!(x & SX_LOCK_WRITE_SPINNER)) {
701 				if (!in_critical) {
702 					critical_enter();
703 					in_critical = true;
704 					extra_work++;
705 				}
706 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
707 				    x | SX_LOCK_WRITE_SPINNER)) {
708 					critical_exit();
709 					in_critical = false;
710 					extra_work--;
711 					continue;
712 				}
713 			}
714 			spintries++;
715 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
716 			    "spinning", "lockname:\"%s\"",
717 			    sx->lock_object.lo_name);
718 			n = SX_SHARERS(x);
719 			for (i = 0; i < asx_loops; i += n) {
720 				lock_delay_spin(n);
721 				x = SX_READ_VALUE(sx);
722 				if (!(x & SX_LOCK_WRITE_SPINNER))
723 					break;
724 				if (!(x & SX_LOCK_SHARED))
725 					break;
726 				n = SX_SHARERS(x);
727 				if (n == 0)
728 					break;
729 			}
730 #ifdef KDTRACE_HOOKS
731 			lda.spin_cnt += i;
732 #endif
733 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
734 			    "running");
735 			if (i < asx_loops)
736 				continue;
737 		}
738 sleepq:
739 #endif
740 		sleepq_lock(&sx->lock_object);
741 		x = SX_READ_VALUE(sx);
742 retry_sleepq:
743 
744 		/*
745 		 * If the lock was released while spinning on the
746 		 * sleep queue chain lock, try again.
747 		 */
748 		if (x == SX_LOCK_UNLOCKED) {
749 			sleepq_release(&sx->lock_object);
750 			sx_drop_critical(x, &in_critical, &extra_work);
751 			continue;
752 		}
753 
754 #ifdef ADAPTIVE_SX
755 		/*
756 		 * The current lock owner might have started executing
757 		 * on another CPU (or the lock could have changed
758 		 * owners) while we were waiting on the sleep queue
759 		 * chain lock.  If so, drop the sleep queue lock and try
760 		 * again.
761 		 */
762 		if (!(x & SX_LOCK_SHARED)) {
763 			owner = (struct thread *)SX_OWNER(x);
764 			if (TD_IS_RUNNING(owner)) {
765 				sleepq_release(&sx->lock_object);
766 				sx_drop_critical(x, &in_critical,
767 				    &extra_work);
768 				continue;
769 			}
770 		} else if (SX_SHARERS(x) > 0 && sleep_reason == WRITER) {
771 			sleepq_release(&sx->lock_object);
772 			sx_drop_critical(x, &in_critical, &extra_work);
773 			continue;
774 		}
775 #endif
776 
777 		/*
778 		 * If an exclusive lock was released with both shared
779 		 * and exclusive waiters and a shared waiter hasn't
780 		 * woken up and acquired the lock yet, sx_lock will be
781 		 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
782 		 * If we see that value, try to acquire it once.  Note
783 		 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
784 		 * as there are other exclusive waiters still.  If we
785 		 * fail, restart the loop.
786 		 */
787 		setx = x & (SX_LOCK_WAITERS | SX_LOCK_WRITE_SPINNER);
788 		if ((x & ~setx) == SX_LOCK_SHARED) {
789 			setx &= ~SX_LOCK_WRITE_SPINNER;
790 			if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid | setx))
791 				goto retry_sleepq;
792 			sleepq_release(&sx->lock_object);
793 			CTR2(KTR_LOCK, "%s: %p claimed by new writer",
794 			    __func__, sx);
795 			break;
796 		}
797 
798 #ifdef ADAPTIVE_SX
799 		/*
800 		 * It is possible we set the SX_LOCK_WRITE_SPINNER bit.
801 		 * It is an invariant that when the bit is set, there is
802 		 * a writer ready to grab the lock. Thus clear the bit since
803 		 * we are going to sleep.
804 		 */
805 		if (in_critical) {
806 			if ((x & SX_LOCK_WRITE_SPINNER) ||
807 			    !((x & SX_LOCK_EXCLUSIVE_WAITERS))) {
808 				setx = x & ~SX_LOCK_WRITE_SPINNER;
809 				setx |= SX_LOCK_EXCLUSIVE_WAITERS;
810 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
811 				    setx)) {
812 					goto retry_sleepq;
813 				}
814 			}
815 			critical_exit();
816 			in_critical = false;
817 		} else {
818 #endif
819 			/*
820 			 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
821 			 * than loop back and retry.
822 			 */
823 			if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
824 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
825 				    x | SX_LOCK_EXCLUSIVE_WAITERS)) {
826 					goto retry_sleepq;
827 				}
828 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
829 					CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
830 					    __func__, sx);
831 			}
832 #ifdef ADAPTIVE_SX
833 		}
834 #endif
835 
836 		/*
837 		 * Since we have been unable to acquire the exclusive
838 		 * lock and the exclusive waiters flag is set, we have
839 		 * to sleep.
840 		 */
841 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
842 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
843 			    __func__, sx);
844 
845 #ifdef KDTRACE_HOOKS
846 		sleep_time -= lockstat_nsecs(&sx->lock_object);
847 #endif
848 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
849 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
850 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
851 		/*
852 		 * Hack: this can land in thread_suspend_check which will
853 		 * conditionally take a mutex, tripping over an assert if a
854 		 * lock we are waiting for is set.
855 		 */
856 		THREAD_CONTENTION_DONE(&sx->lock_object);
857 		if (!(opts & SX_INTERRUPTIBLE))
858 			sleepq_wait(&sx->lock_object, 0);
859 		else
860 			error = sleepq_wait_sig(&sx->lock_object, 0);
861 		THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
862 #ifdef KDTRACE_HOOKS
863 		sleep_time += lockstat_nsecs(&sx->lock_object);
864 		sleep_cnt++;
865 #endif
866 		if (error) {
867 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
868 				CTR2(KTR_LOCK,
869 			"%s: interruptible sleep by %p suspended by signal",
870 				    __func__, sx);
871 			break;
872 		}
873 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
874 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
875 			    __func__, sx);
876 		x = SX_READ_VALUE(sx);
877 	}
878 	THREAD_CONTENTION_DONE(&sx->lock_object);
879 	if (__predict_true(!extra_work))
880 		return (error);
881 #ifdef ADAPTIVE_SX
882 	if (in_critical)
883 		critical_exit();
884 #endif
885 	GIANT_RESTORE();
886 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
887 	if (__predict_true(!doing_lockprof))
888 		return (error);
889 #endif
890 #ifdef KDTRACE_HOOKS
891 	all_time += lockstat_nsecs(&sx->lock_object);
892 	if (sleep_time)
893 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
894 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
895 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
896 	if (lda.spin_cnt > sleep_cnt)
897 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
898 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
899 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
900 out_lockstat:
901 #endif
902 	if (!error)
903 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
904 		    contested, waittime, file, line, LOCKSTAT_WRITER);
905 	return (error);
906 }
907 
908 /*
909  * This function represents the so-called 'hard case' for sx_xunlock
910  * operation.  All 'easy case' failures are redirected to this.  Note
911  * that ideally this would be a static function, but it needs to be
912  * accessible from at least sx.h.
913  */
914 void
915 _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
916 {
917 	uintptr_t tid, setx;
918 	int queue;
919 
920 	if (SCHEDULER_STOPPED())
921 		return;
922 
923 	tid = (uintptr_t)curthread;
924 
925 	if (__predict_false(x == tid))
926 		x = SX_READ_VALUE(sx);
927 
928 	MPASS(!(x & SX_LOCK_SHARED));
929 
930 	if (__predict_false(x & SX_LOCK_RECURSED)) {
931 		/* The lock is recursed, unrecurse one level. */
932 		if ((--sx->sx_recurse) == 0)
933 			atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
934 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
935 			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
936 		return;
937 	}
938 
939 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
940 	if (x == tid &&
941 	    atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
942 		return;
943 
944 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
945 		CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
946 
947 	sleepq_lock(&sx->lock_object);
948 	x = SX_READ_VALUE(sx);
949 	MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
950 
951 	/*
952 	 * The wake up algorithm here is quite simple and probably not
953 	 * ideal.  It gives precedence to shared waiters if they are
954 	 * present.  For this condition, we have to preserve the
955 	 * state of the exclusive waiters flag.
956 	 * If interruptible sleeps left the shared queue empty avoid a
957 	 * starvation for the threads sleeping on the exclusive queue by giving
958 	 * them precedence and cleaning up the shared waiters bit anyway.
959 	 */
960 	setx = SX_LOCK_UNLOCKED;
961 	queue = SQ_SHARED_QUEUE;
962 	if ((x & SX_LOCK_EXCLUSIVE_WAITERS) != 0 &&
963 	    sleepq_sleepcnt(&sx->lock_object, SQ_EXCLUSIVE_QUEUE) != 0) {
964 		queue = SQ_EXCLUSIVE_QUEUE;
965 		setx |= (x & SX_LOCK_SHARED_WAITERS);
966 	}
967 	atomic_store_rel_ptr(&sx->sx_lock, setx);
968 
969 	/* Wake up all the waiters for the specific queue. */
970 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
971 		CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
972 		    __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
973 		    "exclusive");
974 
975 	sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0, queue);
976 	sleepq_release(&sx->lock_object);
977 }
978 
979 static __always_inline bool
980 __sx_can_read(struct thread *td, uintptr_t x, bool fp)
981 {
982 
983 	if ((x & (SX_LOCK_SHARED | SX_LOCK_EXCLUSIVE_WAITERS | SX_LOCK_WRITE_SPINNER))
984 			== SX_LOCK_SHARED)
985 		return (true);
986 	if (!fp && td->td_sx_slocks && (x & SX_LOCK_SHARED))
987 		return (true);
988 	return (false);
989 }
990 
991 static __always_inline bool
992 __sx_slock_try(struct sx *sx, struct thread *td, uintptr_t *xp, bool fp
993     LOCK_FILE_LINE_ARG_DEF)
994 {
995 
996 	/*
997 	 * If no other thread has an exclusive lock then try to bump up
998 	 * the count of sharers.  Since we have to preserve the state
999 	 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
1000 	 * shared lock loop back and retry.
1001 	 */
1002 	while (__sx_can_read(td, *xp, fp)) {
1003 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
1004 		    *xp + SX_ONE_SHARER)) {
1005 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1006 				CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
1007 				    __func__, sx, (void *)*xp,
1008 				    (void *)(*xp + SX_ONE_SHARER));
1009 			td->td_sx_slocks++;
1010 			return (true);
1011 		}
1012 	}
1013 	return (false);
1014 }
1015 
1016 static int __noinline
1017 _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
1018 {
1019 	GIANT_DECLARE;
1020 	struct thread *td;
1021 #ifdef ADAPTIVE_SX
1022 	struct thread *owner;
1023 	u_int i, n, spintries = 0;
1024 #endif
1025 #ifdef LOCK_PROFILING
1026 	uint64_t waittime = 0;
1027 	int contested = 0;
1028 #endif
1029 	int error = 0;
1030 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
1031 	struct lock_delay_arg lda;
1032 #endif
1033 #ifdef KDTRACE_HOOKS
1034 	u_int sleep_cnt = 0;
1035 	int64_t sleep_time = 0;
1036 	int64_t all_time = 0;
1037 #endif
1038 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1039 	uintptr_t state = 0;
1040 #endif
1041 	int extra_work __sdt_used = 0;
1042 
1043 	td = curthread;
1044 
1045 #ifdef KDTRACE_HOOKS
1046 	if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
1047 		if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
1048 			goto out_lockstat;
1049 		extra_work = 1;
1050 		all_time -= lockstat_nsecs(&sx->lock_object);
1051 		state = x;
1052 	}
1053 #endif
1054 #ifdef LOCK_PROFILING
1055 	extra_work = 1;
1056 	state = x;
1057 #endif
1058 
1059 	if (SCHEDULER_STOPPED())
1060 		return (0);
1061 
1062 #if defined(ADAPTIVE_SX)
1063 	lock_delay_arg_init(&lda, &sx_delay);
1064 #elif defined(KDTRACE_HOOKS)
1065 	lock_delay_arg_init_noadapt(&lda);
1066 #endif
1067 
1068 #ifdef HWPMC_HOOKS
1069 	PMC_SOFT_CALL( , , lock, failed);
1070 #endif
1071 	lock_profile_obtain_lock_failed(&sx->lock_object, false, &contested,
1072 	    &waittime);
1073 
1074 #ifndef INVARIANTS
1075 	GIANT_SAVE(extra_work);
1076 #endif
1077 
1078 	THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
1079 
1080 	/*
1081 	 * As with rwlocks, we don't make any attempt to try to block
1082 	 * shared locks once there is an exclusive waiter.
1083 	 */
1084 	for (;;) {
1085 		if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
1086 			break;
1087 #ifdef INVARIANTS
1088 		GIANT_SAVE(extra_work);
1089 #endif
1090 #ifdef KDTRACE_HOOKS
1091 		lda.spin_cnt++;
1092 #endif
1093 
1094 #ifdef ADAPTIVE_SX
1095 		/*
1096 		 * If the owner is running on another CPU, spin until
1097 		 * the owner stops running or the state of the lock
1098 		 * changes.
1099 		 */
1100 		if ((x & SX_LOCK_SHARED) == 0) {
1101 			owner = lv_sx_owner(x);
1102 			if (TD_IS_RUNNING(owner)) {
1103 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
1104 					CTR3(KTR_LOCK,
1105 					    "%s: spinning on %p held by %p",
1106 					    __func__, sx, owner);
1107 				KTR_STATE1(KTR_SCHED, "thread",
1108 				    sched_tdname(curthread), "spinning",
1109 				    "lockname:\"%s\"", sx->lock_object.lo_name);
1110 				do {
1111 					lock_delay(&lda);
1112 					x = SX_READ_VALUE(sx);
1113 					owner = lv_sx_owner(x);
1114 				} while (owner != NULL && TD_IS_RUNNING(owner));
1115 				KTR_STATE0(KTR_SCHED, "thread",
1116 				    sched_tdname(curthread), "running");
1117 				continue;
1118 			}
1119 		} else {
1120 			if ((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) {
1121 				MPASS(!__sx_can_read(td, x, false));
1122 				lock_delay_spin(2);
1123 				x = SX_READ_VALUE(sx);
1124 				continue;
1125 			}
1126 			if (spintries < asx_retries) {
1127 				KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1128 				    "spinning", "lockname:\"%s\"",
1129 				    sx->lock_object.lo_name);
1130 				n = SX_SHARERS(x);
1131 				for (i = 0; i < asx_loops; i += n) {
1132 					lock_delay_spin(n);
1133 					x = SX_READ_VALUE(sx);
1134 					if (!(x & SX_LOCK_SHARED))
1135 						break;
1136 					n = SX_SHARERS(x);
1137 					if (n == 0)
1138 						break;
1139 					if (__sx_can_read(td, x, false))
1140 						break;
1141 				}
1142 #ifdef KDTRACE_HOOKS
1143 				lda.spin_cnt += i;
1144 #endif
1145 				KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1146 				    "running");
1147 				if (i < asx_loops)
1148 					continue;
1149 			}
1150 		}
1151 #endif
1152 
1153 		/*
1154 		 * Some other thread already has an exclusive lock, so
1155 		 * start the process of blocking.
1156 		 */
1157 		sleepq_lock(&sx->lock_object);
1158 		x = SX_READ_VALUE(sx);
1159 retry_sleepq:
1160 		if (((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) ||
1161 		    __sx_can_read(td, x, false)) {
1162 			sleepq_release(&sx->lock_object);
1163 			continue;
1164 		}
1165 
1166 #ifdef ADAPTIVE_SX
1167 		/*
1168 		 * If the owner is running on another CPU, spin until
1169 		 * the owner stops running or the state of the lock
1170 		 * changes.
1171 		 */
1172 		if (!(x & SX_LOCK_SHARED)) {
1173 			owner = (struct thread *)SX_OWNER(x);
1174 			if (TD_IS_RUNNING(owner)) {
1175 				sleepq_release(&sx->lock_object);
1176 				x = SX_READ_VALUE(sx);
1177 				continue;
1178 			}
1179 		}
1180 #endif
1181 
1182 		/*
1183 		 * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
1184 		 * fail to set it drop the sleep queue lock and loop
1185 		 * back.
1186 		 */
1187 		if (!(x & SX_LOCK_SHARED_WAITERS)) {
1188 			if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
1189 			    x | SX_LOCK_SHARED_WAITERS))
1190 				goto retry_sleepq;
1191 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1192 				CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1193 				    __func__, sx);
1194 		}
1195 
1196 		/*
1197 		 * Since we have been unable to acquire the shared lock,
1198 		 * we have to sleep.
1199 		 */
1200 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
1201 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1202 			    __func__, sx);
1203 
1204 #ifdef KDTRACE_HOOKS
1205 		sleep_time -= lockstat_nsecs(&sx->lock_object);
1206 #endif
1207 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1208 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1209 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1210 		/*
1211 		 * Hack: this can land in thread_suspend_check which will
1212 		 * conditionally take a mutex, tripping over an assert if a
1213 		 * lock we are waiting for is set.
1214 		 */
1215 		THREAD_CONTENTION_DONE(&sx->lock_object);
1216 		if (!(opts & SX_INTERRUPTIBLE))
1217 			sleepq_wait(&sx->lock_object, 0);
1218 		else
1219 			error = sleepq_wait_sig(&sx->lock_object, 0);
1220 		THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
1221 #ifdef KDTRACE_HOOKS
1222 		sleep_time += lockstat_nsecs(&sx->lock_object);
1223 		sleep_cnt++;
1224 #endif
1225 		if (error) {
1226 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1227 				CTR2(KTR_LOCK,
1228 			"%s: interruptible sleep by %p suspended by signal",
1229 				    __func__, sx);
1230 			break;
1231 		}
1232 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
1233 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1234 			    __func__, sx);
1235 		x = SX_READ_VALUE(sx);
1236 	}
1237 	THREAD_CONTENTION_DONE(&sx->lock_object);
1238 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1239 	if (__predict_true(!extra_work))
1240 		return (error);
1241 #endif
1242 #ifdef KDTRACE_HOOKS
1243 	all_time += lockstat_nsecs(&sx->lock_object);
1244 	if (sleep_time)
1245 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1246 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1247 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1248 	if (lda.spin_cnt > sleep_cnt)
1249 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1250 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1251 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1252 out_lockstat:
1253 #endif
1254 	if (error == 0) {
1255 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1256 		    contested, waittime, file, line, LOCKSTAT_READER);
1257 	}
1258 	GIANT_RESTORE();
1259 	return (error);
1260 }
1261 
1262 int
1263 _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
1264 {
1265 	struct thread *td;
1266 	uintptr_t x;
1267 	int error;
1268 
1269 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1270 	    !TD_IS_IDLETHREAD(curthread),
1271 	    ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1272 	    curthread, sx->lock_object.lo_name, file, line));
1273 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1274 	    ("sx_slock() of destroyed sx @ %s:%d", file, line));
1275 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1276 
1277 	error = 0;
1278 	td = curthread;
1279 	x = SX_READ_VALUE(sx);
1280 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__acquire) ||
1281 	    !__sx_slock_try(sx, td, &x, true LOCK_FILE_LINE_ARG)))
1282 		error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1283 	else
1284 		lock_profile_obtain_lock_success(&sx->lock_object, false, 0, 0,
1285 		    file, line);
1286 	if (error == 0) {
1287 		LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1288 		WITNESS_LOCK(&sx->lock_object, 0, file, line);
1289 		TD_LOCKS_INC(curthread);
1290 	}
1291 	return (error);
1292 }
1293 
1294 int
1295 _sx_slock(struct sx *sx, int opts, const char *file, int line)
1296 {
1297 
1298 	return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1299 }
1300 
1301 static __always_inline bool
1302 _sx_sunlock_try(struct sx *sx, struct thread *td, uintptr_t *xp)
1303 {
1304 
1305 	for (;;) {
1306 		if (SX_SHARERS(*xp) > 1 || !(*xp & SX_LOCK_WAITERS)) {
1307 			if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1308 			    *xp - SX_ONE_SHARER)) {
1309 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
1310 					CTR4(KTR_LOCK,
1311 					    "%s: %p succeeded %p -> %p",
1312 					    __func__, sx, (void *)*xp,
1313 					    (void *)(*xp - SX_ONE_SHARER));
1314 				td->td_sx_slocks--;
1315 				return (true);
1316 			}
1317 			continue;
1318 		}
1319 		break;
1320 	}
1321 	return (false);
1322 }
1323 
1324 static void __noinline
1325 _sx_sunlock_hard(struct sx *sx, struct thread *td, uintptr_t x
1326     LOCK_FILE_LINE_ARG_DEF)
1327 {
1328 	uintptr_t setx, queue;
1329 
1330 	if (SCHEDULER_STOPPED())
1331 		return;
1332 
1333 	if (_sx_sunlock_try(sx, td, &x))
1334 		goto out_lockstat;
1335 
1336 	sleepq_lock(&sx->lock_object);
1337 	x = SX_READ_VALUE(sx);
1338 	for (;;) {
1339 		if (_sx_sunlock_try(sx, td, &x))
1340 			break;
1341 
1342 		/*
1343 		 * Wake up semantic here is quite simple:
1344 		 * Just wake up all the exclusive waiters.
1345 		 * Note that the state of the lock could have changed,
1346 		 * so if it fails loop back and retry.
1347 		 */
1348 		setx = SX_LOCK_UNLOCKED;
1349 		queue = SQ_SHARED_QUEUE;
1350 		if (x & SX_LOCK_EXCLUSIVE_WAITERS) {
1351 			setx |= (x & SX_LOCK_SHARED_WAITERS);
1352 			queue = SQ_EXCLUSIVE_QUEUE;
1353 		}
1354 		setx |= (x & SX_LOCK_WRITE_SPINNER);
1355 		if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
1356 			continue;
1357 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
1358 			CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1359 			    "exclusive queue", __func__, sx);
1360 		sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0, queue);
1361 		td->td_sx_slocks--;
1362 		break;
1363 	}
1364 	sleepq_release(&sx->lock_object);
1365 out_lockstat:
1366 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1367 }
1368 
1369 void
1370 _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1371 {
1372 	struct thread *td;
1373 	uintptr_t x;
1374 
1375 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1376 	    ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1377 	_sx_assert(sx, SA_SLOCKED, file, line);
1378 	WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1379 	LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1380 
1381 	td = curthread;
1382 	x = SX_READ_VALUE(sx);
1383 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__release) ||
1384 	    !_sx_sunlock_try(sx, td, &x)))
1385 		_sx_sunlock_hard(sx, td, x LOCK_FILE_LINE_ARG);
1386 	else
1387 		lock_profile_release_lock(&sx->lock_object, false);
1388 
1389 	TD_LOCKS_DEC(curthread);
1390 }
1391 
1392 void
1393 _sx_sunlock(struct sx *sx, const char *file, int line)
1394 {
1395 
1396 	_sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1397 }
1398 
1399 #ifdef INVARIANT_SUPPORT
1400 #ifndef INVARIANTS
1401 #undef	_sx_assert
1402 #endif
1403 
1404 /*
1405  * In the non-WITNESS case, sx_assert() can only detect that at least
1406  * *some* thread owns an slock, but it cannot guarantee that *this*
1407  * thread owns an slock.
1408  */
1409 void
1410 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1411 {
1412 #ifndef WITNESS
1413 	int slocked = 0;
1414 #endif
1415 
1416 	if (SCHEDULER_STOPPED())
1417 		return;
1418 	switch (what) {
1419 	case SA_SLOCKED:
1420 	case SA_SLOCKED | SA_NOTRECURSED:
1421 	case SA_SLOCKED | SA_RECURSED:
1422 #ifndef WITNESS
1423 		slocked = 1;
1424 		/* FALLTHROUGH */
1425 #endif
1426 	case SA_LOCKED:
1427 	case SA_LOCKED | SA_NOTRECURSED:
1428 	case SA_LOCKED | SA_RECURSED:
1429 #ifdef WITNESS
1430 		witness_assert(&sx->lock_object, what, file, line);
1431 #else
1432 		/*
1433 		 * If some other thread has an exclusive lock or we
1434 		 * have one and are asserting a shared lock, fail.
1435 		 * Also, if no one has a lock at all, fail.
1436 		 */
1437 		if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1438 		    (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1439 		    sx_xholder(sx) != curthread)))
1440 			panic("Lock %s not %slocked @ %s:%d\n",
1441 			    sx->lock_object.lo_name, slocked ? "share " : "",
1442 			    file, line);
1443 
1444 		if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1445 			if (sx_recursed(sx)) {
1446 				if (what & SA_NOTRECURSED)
1447 					panic("Lock %s recursed @ %s:%d\n",
1448 					    sx->lock_object.lo_name, file,
1449 					    line);
1450 			} else if (what & SA_RECURSED)
1451 				panic("Lock %s not recursed @ %s:%d\n",
1452 				    sx->lock_object.lo_name, file, line);
1453 		}
1454 #endif
1455 		break;
1456 	case SA_XLOCKED:
1457 	case SA_XLOCKED | SA_NOTRECURSED:
1458 	case SA_XLOCKED | SA_RECURSED:
1459 		if (sx_xholder(sx) != curthread)
1460 			panic("Lock %s not exclusively locked @ %s:%d\n",
1461 			    sx->lock_object.lo_name, file, line);
1462 		if (sx_recursed(sx)) {
1463 			if (what & SA_NOTRECURSED)
1464 				panic("Lock %s recursed @ %s:%d\n",
1465 				    sx->lock_object.lo_name, file, line);
1466 		} else if (what & SA_RECURSED)
1467 			panic("Lock %s not recursed @ %s:%d\n",
1468 			    sx->lock_object.lo_name, file, line);
1469 		break;
1470 	case SA_UNLOCKED:
1471 #ifdef WITNESS
1472 		witness_assert(&sx->lock_object, what, file, line);
1473 #else
1474 		/*
1475 		 * If we hold an exclusve lock fail.  We can't
1476 		 * reliably check to see if we hold a shared lock or
1477 		 * not.
1478 		 */
1479 		if (sx_xholder(sx) == curthread)
1480 			panic("Lock %s exclusively locked @ %s:%d\n",
1481 			    sx->lock_object.lo_name, file, line);
1482 #endif
1483 		break;
1484 	default:
1485 		panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1486 		    line);
1487 	}
1488 }
1489 #endif	/* INVARIANT_SUPPORT */
1490 
1491 #ifdef DDB
1492 static void
1493 db_show_sx(const struct lock_object *lock)
1494 {
1495 	struct thread *td;
1496 	const struct sx *sx;
1497 
1498 	sx = (const struct sx *)lock;
1499 
1500 	db_printf(" state: ");
1501 	if (sx->sx_lock == SX_LOCK_UNLOCKED)
1502 		db_printf("UNLOCKED\n");
1503 	else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1504 		db_printf("DESTROYED\n");
1505 		return;
1506 	} else if (sx->sx_lock & SX_LOCK_SHARED)
1507 		db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1508 	else {
1509 		td = sx_xholder(sx);
1510 		db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1511 		    td->td_tid, td->td_proc->p_pid, td->td_name);
1512 		if (sx_recursed(sx))
1513 			db_printf(" recursed: %d\n", sx->sx_recurse);
1514 	}
1515 
1516 	db_printf(" waiters: ");
1517 	switch(sx->sx_lock &
1518 	    (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1519 	case SX_LOCK_SHARED_WAITERS:
1520 		db_printf("shared\n");
1521 		break;
1522 	case SX_LOCK_EXCLUSIVE_WAITERS:
1523 		db_printf("exclusive\n");
1524 		break;
1525 	case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1526 		db_printf("exclusive and shared\n");
1527 		break;
1528 	default:
1529 		db_printf("none\n");
1530 	}
1531 }
1532 
1533 /*
1534  * Check to see if a thread that is blocked on a sleep queue is actually
1535  * blocked on an sx lock.  If so, output some details and return true.
1536  * If the lock has an exclusive owner, return that in *ownerp.
1537  */
1538 int
1539 sx_chain(struct thread *td, struct thread **ownerp)
1540 {
1541 	const struct sx *sx;
1542 
1543 	/*
1544 	 * Check to see if this thread is blocked on an sx lock.
1545 	 * First, we check the lock class.  If that is ok, then we
1546 	 * compare the lock name against the wait message.
1547 	 */
1548 	sx = td->td_wchan;
1549 	if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1550 	    sx->lock_object.lo_name != td->td_wmesg)
1551 		return (0);
1552 
1553 	/* We think we have an sx lock, so output some details. */
1554 	db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1555 	*ownerp = sx_xholder(sx);
1556 	if (sx->sx_lock & SX_LOCK_SHARED)
1557 		db_printf("SLOCK (count %ju)\n",
1558 		    (uintmax_t)SX_SHARERS(sx->sx_lock));
1559 	else
1560 		db_printf("XLOCK\n");
1561 	return (1);
1562 }
1563 #endif
1564