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