xref: /freebsd/sys/kern/kern_sx.c (revision 4d65a7c6951cea0333f1a0c1b32c38489cdfa6c5)
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_TD(td))
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 	int wakeup_swapper;
478 
479 	if (SCHEDULER_STOPPED())
480 		return;
481 
482 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
483 	    ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
484 	_sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
485 #ifndef INVARIANTS
486 	if (sx_recursed(sx))
487 		panic("downgrade of a recursed lock");
488 #endif
489 
490 	WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
491 
492 	/*
493 	 * Try to switch from an exclusive lock with no shared waiters
494 	 * to one sharer with no shared waiters.  If there are
495 	 * exclusive waiters, we don't need to lock the sleep queue so
496 	 * long as we preserve the flag.  We do one quick try and if
497 	 * that fails we grab the sleepq lock to keep the flags from
498 	 * changing and do it the slow way.
499 	 *
500 	 * We have to lock the sleep queue if there are shared waiters
501 	 * so we can wake them up.
502 	 */
503 	x = sx->sx_lock;
504 	if (!(x & SX_LOCK_SHARED_WAITERS) &&
505 	    atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
506 	    (x & SX_LOCK_EXCLUSIVE_WAITERS)))
507 		goto out;
508 
509 	/*
510 	 * Lock the sleep queue so we can read the waiters bits
511 	 * without any races and wakeup any shared waiters.
512 	 */
513 	sleepq_lock(&sx->lock_object);
514 
515 	/*
516 	 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
517 	 * shared lock.  If there are any shared waiters, wake them up.
518 	 */
519 	wakeup_swapper = 0;
520 	x = sx->sx_lock;
521 	atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
522 	    (x & SX_LOCK_EXCLUSIVE_WAITERS));
523 	if (x & SX_LOCK_SHARED_WAITERS)
524 		wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
525 		    0, SQ_SHARED_QUEUE);
526 	sleepq_release(&sx->lock_object);
527 
528 	if (wakeup_swapper)
529 		kick_proc0();
530 
531 out:
532 	curthread->td_sx_slocks++;
533 	LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
534 	LOCKSTAT_RECORD0(sx__downgrade, sx);
535 }
536 
537 void
538 sx_downgrade_(struct sx *sx, const char *file, int line)
539 {
540 
541 	sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
542 }
543 
544 #ifdef	ADAPTIVE_SX
545 static inline void
546 sx_drop_critical(uintptr_t x, bool *in_critical, int *extra_work)
547 {
548 
549 	if (x & SX_LOCK_WRITE_SPINNER)
550 		return;
551 	if (*in_critical) {
552 		critical_exit();
553 		*in_critical = false;
554 		(*extra_work)--;
555 	}
556 }
557 #else
558 #define sx_drop_critical(x, in_critical, extra_work) do { } while (0)
559 #endif
560 
561 /*
562  * This function represents the so-called 'hard case' for sx_xlock
563  * operation.  All 'easy case' failures are redirected to this.  Note
564  * that ideally this would be a static function, but it needs to be
565  * accessible from at least sx.h.
566  */
567 int
568 _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
569 {
570 	GIANT_DECLARE;
571 	uintptr_t tid, setx;
572 #ifdef ADAPTIVE_SX
573 	struct thread *owner;
574 	u_int i, n, spintries = 0;
575 	enum { READERS, WRITER } sleep_reason = READERS;
576 	bool in_critical = false;
577 #endif
578 #ifdef LOCK_PROFILING
579 	uint64_t waittime = 0;
580 	int contested = 0;
581 #endif
582 	int error = 0;
583 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
584 	struct lock_delay_arg lda;
585 #endif
586 #ifdef	KDTRACE_HOOKS
587 	u_int sleep_cnt = 0;
588 	int64_t sleep_time = 0;
589 	int64_t all_time = 0;
590 #endif
591 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
592 	uintptr_t state = 0;
593 	int doing_lockprof = 0;
594 #endif
595 	int extra_work = 0;
596 
597 	tid = (uintptr_t)curthread;
598 
599 #ifdef KDTRACE_HOOKS
600 	if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
601 		while (x == SX_LOCK_UNLOCKED) {
602 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
603 				goto out_lockstat;
604 		}
605 		extra_work = 1;
606 		doing_lockprof = 1;
607 		all_time -= lockstat_nsecs(&sx->lock_object);
608 		state = x;
609 	}
610 #endif
611 #ifdef LOCK_PROFILING
612 	extra_work = 1;
613 	doing_lockprof = 1;
614 	state = x;
615 #endif
616 
617 	if (SCHEDULER_STOPPED())
618 		return (0);
619 
620 	if (__predict_false(x == SX_LOCK_UNLOCKED))
621 		x = SX_READ_VALUE(sx);
622 
623 	/* If we already hold an exclusive lock, then recurse. */
624 	if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
625 		KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
626 	    ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
627 		    sx->lock_object.lo_name, file, line));
628 		sx->sx_recurse++;
629 		atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
630 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
631 			CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
632 		return (0);
633 	}
634 
635 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
636 		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
637 		    sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
638 
639 #if defined(ADAPTIVE_SX)
640 	lock_delay_arg_init(&lda, &sx_delay);
641 #elif defined(KDTRACE_HOOKS)
642 	lock_delay_arg_init_noadapt(&lda);
643 #endif
644 
645 #ifdef HWPMC_HOOKS
646 	PMC_SOFT_CALL( , , lock, failed);
647 #endif
648 	lock_profile_obtain_lock_failed(&sx->lock_object, false, &contested,
649 	    &waittime);
650 
651 #ifndef INVARIANTS
652 	GIANT_SAVE(extra_work);
653 #endif
654 
655 	THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
656 
657 	for (;;) {
658 		if (x == SX_LOCK_UNLOCKED) {
659 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
660 				break;
661 			continue;
662 		}
663 #ifdef INVARIANTS
664 		GIANT_SAVE(extra_work);
665 #endif
666 #ifdef KDTRACE_HOOKS
667 		lda.spin_cnt++;
668 #endif
669 #ifdef ADAPTIVE_SX
670 		if (x == (SX_LOCK_SHARED | SX_LOCK_WRITE_SPINNER)) {
671 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
672 				break;
673 			continue;
674 		}
675 
676 		/*
677 		 * If the lock is write locked and the owner is
678 		 * running on another CPU, spin until the owner stops
679 		 * running or the state of the lock changes.
680 		 */
681 		if ((x & SX_LOCK_SHARED) == 0) {
682 			sx_drop_critical(x, &in_critical, &extra_work);
683 			sleep_reason = WRITER;
684 			owner = lv_sx_owner(x);
685 			if (!TD_IS_RUNNING(owner))
686 				goto sleepq;
687 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
688 				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
689 				    __func__, sx, owner);
690 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
691 			    "spinning", "lockname:\"%s\"",
692 			    sx->lock_object.lo_name);
693 			do {
694 				lock_delay(&lda);
695 				x = SX_READ_VALUE(sx);
696 				owner = lv_sx_owner(x);
697 			} while (owner != NULL && TD_IS_RUNNING(owner));
698 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
699 			    "running");
700 			continue;
701 		} else if (SX_SHARERS(x) > 0) {
702 			sleep_reason = READERS;
703 			if (spintries == asx_retries)
704 				goto sleepq;
705 			if (!(x & SX_LOCK_WRITE_SPINNER)) {
706 				if (!in_critical) {
707 					critical_enter();
708 					in_critical = true;
709 					extra_work++;
710 				}
711 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
712 				    x | SX_LOCK_WRITE_SPINNER)) {
713 					critical_exit();
714 					in_critical = false;
715 					extra_work--;
716 					continue;
717 				}
718 			}
719 			spintries++;
720 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
721 			    "spinning", "lockname:\"%s\"",
722 			    sx->lock_object.lo_name);
723 			n = SX_SHARERS(x);
724 			for (i = 0; i < asx_loops; i += n) {
725 				lock_delay_spin(n);
726 				x = SX_READ_VALUE(sx);
727 				if (!(x & SX_LOCK_WRITE_SPINNER))
728 					break;
729 				if (!(x & SX_LOCK_SHARED))
730 					break;
731 				n = SX_SHARERS(x);
732 				if (n == 0)
733 					break;
734 			}
735 #ifdef KDTRACE_HOOKS
736 			lda.spin_cnt += i;
737 #endif
738 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
739 			    "running");
740 			if (i < asx_loops)
741 				continue;
742 		}
743 sleepq:
744 #endif
745 		sleepq_lock(&sx->lock_object);
746 		x = SX_READ_VALUE(sx);
747 retry_sleepq:
748 
749 		/*
750 		 * If the lock was released while spinning on the
751 		 * sleep queue chain lock, try again.
752 		 */
753 		if (x == SX_LOCK_UNLOCKED) {
754 			sleepq_release(&sx->lock_object);
755 			sx_drop_critical(x, &in_critical, &extra_work);
756 			continue;
757 		}
758 
759 #ifdef ADAPTIVE_SX
760 		/*
761 		 * The current lock owner might have started executing
762 		 * on another CPU (or the lock could have changed
763 		 * owners) while we were waiting on the sleep queue
764 		 * chain lock.  If so, drop the sleep queue lock and try
765 		 * again.
766 		 */
767 		if (!(x & SX_LOCK_SHARED)) {
768 			owner = (struct thread *)SX_OWNER(x);
769 			if (TD_IS_RUNNING(owner)) {
770 				sleepq_release(&sx->lock_object);
771 				sx_drop_critical(x, &in_critical,
772 				    &extra_work);
773 				continue;
774 			}
775 		} else if (SX_SHARERS(x) > 0 && sleep_reason == WRITER) {
776 			sleepq_release(&sx->lock_object);
777 			sx_drop_critical(x, &in_critical, &extra_work);
778 			continue;
779 		}
780 #endif
781 
782 		/*
783 		 * If an exclusive lock was released with both shared
784 		 * and exclusive waiters and a shared waiter hasn't
785 		 * woken up and acquired the lock yet, sx_lock will be
786 		 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
787 		 * If we see that value, try to acquire it once.  Note
788 		 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
789 		 * as there are other exclusive waiters still.  If we
790 		 * fail, restart the loop.
791 		 */
792 		setx = x & (SX_LOCK_WAITERS | SX_LOCK_WRITE_SPINNER);
793 		if ((x & ~setx) == SX_LOCK_SHARED) {
794 			setx &= ~SX_LOCK_WRITE_SPINNER;
795 			if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid | setx))
796 				goto retry_sleepq;
797 			sleepq_release(&sx->lock_object);
798 			CTR2(KTR_LOCK, "%s: %p claimed by new writer",
799 			    __func__, sx);
800 			break;
801 		}
802 
803 #ifdef ADAPTIVE_SX
804 		/*
805 		 * It is possible we set the SX_LOCK_WRITE_SPINNER bit.
806 		 * It is an invariant that when the bit is set, there is
807 		 * a writer ready to grab the lock. Thus clear the bit since
808 		 * we are going to sleep.
809 		 */
810 		if (in_critical) {
811 			if ((x & SX_LOCK_WRITE_SPINNER) ||
812 			    !((x & SX_LOCK_EXCLUSIVE_WAITERS))) {
813 				setx = x & ~SX_LOCK_WRITE_SPINNER;
814 				setx |= SX_LOCK_EXCLUSIVE_WAITERS;
815 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
816 				    setx)) {
817 					goto retry_sleepq;
818 				}
819 			}
820 			critical_exit();
821 			in_critical = false;
822 		} else {
823 #endif
824 			/*
825 			 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
826 			 * than loop back and retry.
827 			 */
828 			if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
829 				if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
830 				    x | SX_LOCK_EXCLUSIVE_WAITERS)) {
831 					goto retry_sleepq;
832 				}
833 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
834 					CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
835 					    __func__, sx);
836 			}
837 #ifdef ADAPTIVE_SX
838 		}
839 #endif
840 
841 		/*
842 		 * Since we have been unable to acquire the exclusive
843 		 * lock and the exclusive waiters flag is set, we have
844 		 * to sleep.
845 		 */
846 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
847 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
848 			    __func__, sx);
849 
850 #ifdef KDTRACE_HOOKS
851 		sleep_time -= lockstat_nsecs(&sx->lock_object);
852 #endif
853 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
854 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
855 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
856 		/*
857 		 * Hack: this can land in thread_suspend_check which will
858 		 * conditionally take a mutex, tripping over an assert if a
859 		 * lock we are waiting for is set.
860 		 */
861 		THREAD_CONTENTION_DONE(&sx->lock_object);
862 		if (!(opts & SX_INTERRUPTIBLE))
863 			sleepq_wait(&sx->lock_object, 0);
864 		else
865 			error = sleepq_wait_sig(&sx->lock_object, 0);
866 		THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
867 #ifdef KDTRACE_HOOKS
868 		sleep_time += lockstat_nsecs(&sx->lock_object);
869 		sleep_cnt++;
870 #endif
871 		if (error) {
872 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
873 				CTR2(KTR_LOCK,
874 			"%s: interruptible sleep by %p suspended by signal",
875 				    __func__, sx);
876 			break;
877 		}
878 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
879 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
880 			    __func__, sx);
881 		x = SX_READ_VALUE(sx);
882 	}
883 	THREAD_CONTENTION_DONE(&sx->lock_object);
884 	if (__predict_true(!extra_work))
885 		return (error);
886 #ifdef ADAPTIVE_SX
887 	if (in_critical)
888 		critical_exit();
889 #endif
890 	GIANT_RESTORE();
891 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
892 	if (__predict_true(!doing_lockprof))
893 		return (error);
894 #endif
895 #ifdef KDTRACE_HOOKS
896 	all_time += lockstat_nsecs(&sx->lock_object);
897 	if (sleep_time)
898 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
899 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
900 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
901 	if (lda.spin_cnt > sleep_cnt)
902 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
903 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
904 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
905 out_lockstat:
906 #endif
907 	if (!error)
908 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
909 		    contested, waittime, file, line, LOCKSTAT_WRITER);
910 	return (error);
911 }
912 
913 /*
914  * This function represents the so-called 'hard case' for sx_xunlock
915  * operation.  All 'easy case' failures are redirected to this.  Note
916  * that ideally this would be a static function, but it needs to be
917  * accessible from at least sx.h.
918  */
919 void
920 _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
921 {
922 	uintptr_t tid, setx;
923 	int queue, wakeup_swapper;
924 
925 	if (SCHEDULER_STOPPED())
926 		return;
927 
928 	tid = (uintptr_t)curthread;
929 
930 	if (__predict_false(x == tid))
931 		x = SX_READ_VALUE(sx);
932 
933 	MPASS(!(x & SX_LOCK_SHARED));
934 
935 	if (__predict_false(x & SX_LOCK_RECURSED)) {
936 		/* The lock is recursed, unrecurse one level. */
937 		if ((--sx->sx_recurse) == 0)
938 			atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
939 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
940 			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
941 		return;
942 	}
943 
944 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
945 	if (x == tid &&
946 	    atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
947 		return;
948 
949 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
950 		CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
951 
952 	sleepq_lock(&sx->lock_object);
953 	x = SX_READ_VALUE(sx);
954 	MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
955 
956 	/*
957 	 * The wake up algorithm here is quite simple and probably not
958 	 * ideal.  It gives precedence to shared waiters if they are
959 	 * present.  For this condition, we have to preserve the
960 	 * state of the exclusive waiters flag.
961 	 * If interruptible sleeps left the shared queue empty avoid a
962 	 * starvation for the threads sleeping on the exclusive queue by giving
963 	 * them precedence and cleaning up the shared waiters bit anyway.
964 	 */
965 	setx = SX_LOCK_UNLOCKED;
966 	queue = SQ_SHARED_QUEUE;
967 	if ((x & SX_LOCK_EXCLUSIVE_WAITERS) != 0 &&
968 	    sleepq_sleepcnt(&sx->lock_object, SQ_EXCLUSIVE_QUEUE) != 0) {
969 		queue = SQ_EXCLUSIVE_QUEUE;
970 		setx |= (x & SX_LOCK_SHARED_WAITERS);
971 	}
972 	atomic_store_rel_ptr(&sx->sx_lock, setx);
973 
974 	/* Wake up all the waiters for the specific queue. */
975 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
976 		CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
977 		    __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
978 		    "exclusive");
979 
980 	wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
981 	    queue);
982 	sleepq_release(&sx->lock_object);
983 	if (wakeup_swapper)
984 		kick_proc0();
985 }
986 
987 static bool __always_inline
988 __sx_can_read(struct thread *td, uintptr_t x, bool fp)
989 {
990 
991 	if ((x & (SX_LOCK_SHARED | SX_LOCK_EXCLUSIVE_WAITERS | SX_LOCK_WRITE_SPINNER))
992 			== SX_LOCK_SHARED)
993 		return (true);
994 	if (!fp && td->td_sx_slocks && (x & SX_LOCK_SHARED))
995 		return (true);
996 	return (false);
997 }
998 
999 static bool __always_inline
1000 __sx_slock_try(struct sx *sx, struct thread *td, uintptr_t *xp, bool fp
1001     LOCK_FILE_LINE_ARG_DEF)
1002 {
1003 
1004 	/*
1005 	 * If no other thread has an exclusive lock then try to bump up
1006 	 * the count of sharers.  Since we have to preserve the state
1007 	 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
1008 	 * shared lock loop back and retry.
1009 	 */
1010 	while (__sx_can_read(td, *xp, fp)) {
1011 		if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
1012 		    *xp + SX_ONE_SHARER)) {
1013 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1014 				CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
1015 				    __func__, sx, (void *)*xp,
1016 				    (void *)(*xp + SX_ONE_SHARER));
1017 			td->td_sx_slocks++;
1018 			return (true);
1019 		}
1020 	}
1021 	return (false);
1022 }
1023 
1024 static int __noinline
1025 _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
1026 {
1027 	GIANT_DECLARE;
1028 	struct thread *td;
1029 #ifdef ADAPTIVE_SX
1030 	struct thread *owner;
1031 	u_int i, n, spintries = 0;
1032 #endif
1033 #ifdef LOCK_PROFILING
1034 	uint64_t waittime = 0;
1035 	int contested = 0;
1036 #endif
1037 	int error = 0;
1038 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
1039 	struct lock_delay_arg lda;
1040 #endif
1041 #ifdef KDTRACE_HOOKS
1042 	u_int sleep_cnt = 0;
1043 	int64_t sleep_time = 0;
1044 	int64_t all_time = 0;
1045 #endif
1046 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1047 	uintptr_t state = 0;
1048 #endif
1049 	int extra_work __sdt_used = 0;
1050 
1051 	td = curthread;
1052 
1053 #ifdef KDTRACE_HOOKS
1054 	if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
1055 		if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
1056 			goto out_lockstat;
1057 		extra_work = 1;
1058 		all_time -= lockstat_nsecs(&sx->lock_object);
1059 		state = x;
1060 	}
1061 #endif
1062 #ifdef LOCK_PROFILING
1063 	extra_work = 1;
1064 	state = x;
1065 #endif
1066 
1067 	if (SCHEDULER_STOPPED())
1068 		return (0);
1069 
1070 #if defined(ADAPTIVE_SX)
1071 	lock_delay_arg_init(&lda, &sx_delay);
1072 #elif defined(KDTRACE_HOOKS)
1073 	lock_delay_arg_init_noadapt(&lda);
1074 #endif
1075 
1076 #ifdef HWPMC_HOOKS
1077 	PMC_SOFT_CALL( , , lock, failed);
1078 #endif
1079 	lock_profile_obtain_lock_failed(&sx->lock_object, false, &contested,
1080 	    &waittime);
1081 
1082 #ifndef INVARIANTS
1083 	GIANT_SAVE(extra_work);
1084 #endif
1085 
1086 	THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
1087 
1088 	/*
1089 	 * As with rwlocks, we don't make any attempt to try to block
1090 	 * shared locks once there is an exclusive waiter.
1091 	 */
1092 	for (;;) {
1093 		if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
1094 			break;
1095 #ifdef INVARIANTS
1096 		GIANT_SAVE(extra_work);
1097 #endif
1098 #ifdef KDTRACE_HOOKS
1099 		lda.spin_cnt++;
1100 #endif
1101 
1102 #ifdef ADAPTIVE_SX
1103 		/*
1104 		 * If the owner is running on another CPU, spin until
1105 		 * the owner stops running or the state of the lock
1106 		 * changes.
1107 		 */
1108 		if ((x & SX_LOCK_SHARED) == 0) {
1109 			owner = lv_sx_owner(x);
1110 			if (TD_IS_RUNNING(owner)) {
1111 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
1112 					CTR3(KTR_LOCK,
1113 					    "%s: spinning on %p held by %p",
1114 					    __func__, sx, owner);
1115 				KTR_STATE1(KTR_SCHED, "thread",
1116 				    sched_tdname(curthread), "spinning",
1117 				    "lockname:\"%s\"", sx->lock_object.lo_name);
1118 				do {
1119 					lock_delay(&lda);
1120 					x = SX_READ_VALUE(sx);
1121 					owner = lv_sx_owner(x);
1122 				} while (owner != NULL && TD_IS_RUNNING(owner));
1123 				KTR_STATE0(KTR_SCHED, "thread",
1124 				    sched_tdname(curthread), "running");
1125 				continue;
1126 			}
1127 		} else {
1128 			if ((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) {
1129 				MPASS(!__sx_can_read(td, x, false));
1130 				lock_delay_spin(2);
1131 				x = SX_READ_VALUE(sx);
1132 				continue;
1133 			}
1134 			if (spintries < asx_retries) {
1135 				KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1136 				    "spinning", "lockname:\"%s\"",
1137 				    sx->lock_object.lo_name);
1138 				n = SX_SHARERS(x);
1139 				for (i = 0; i < asx_loops; i += n) {
1140 					lock_delay_spin(n);
1141 					x = SX_READ_VALUE(sx);
1142 					if (!(x & SX_LOCK_SHARED))
1143 						break;
1144 					n = SX_SHARERS(x);
1145 					if (n == 0)
1146 						break;
1147 					if (__sx_can_read(td, x, false))
1148 						break;
1149 				}
1150 #ifdef KDTRACE_HOOKS
1151 				lda.spin_cnt += i;
1152 #endif
1153 				KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1154 				    "running");
1155 				if (i < asx_loops)
1156 					continue;
1157 			}
1158 		}
1159 #endif
1160 
1161 		/*
1162 		 * Some other thread already has an exclusive lock, so
1163 		 * start the process of blocking.
1164 		 */
1165 		sleepq_lock(&sx->lock_object);
1166 		x = SX_READ_VALUE(sx);
1167 retry_sleepq:
1168 		if (((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) ||
1169 		    __sx_can_read(td, x, false)) {
1170 			sleepq_release(&sx->lock_object);
1171 			continue;
1172 		}
1173 
1174 #ifdef ADAPTIVE_SX
1175 		/*
1176 		 * If the owner is running on another CPU, spin until
1177 		 * the owner stops running or the state of the lock
1178 		 * changes.
1179 		 */
1180 		if (!(x & SX_LOCK_SHARED)) {
1181 			owner = (struct thread *)SX_OWNER(x);
1182 			if (TD_IS_RUNNING(owner)) {
1183 				sleepq_release(&sx->lock_object);
1184 				x = SX_READ_VALUE(sx);
1185 				continue;
1186 			}
1187 		}
1188 #endif
1189 
1190 		/*
1191 		 * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
1192 		 * fail to set it drop the sleep queue lock and loop
1193 		 * back.
1194 		 */
1195 		if (!(x & SX_LOCK_SHARED_WAITERS)) {
1196 			if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
1197 			    x | SX_LOCK_SHARED_WAITERS))
1198 				goto retry_sleepq;
1199 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1200 				CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1201 				    __func__, sx);
1202 		}
1203 
1204 		/*
1205 		 * Since we have been unable to acquire the shared lock,
1206 		 * we have to sleep.
1207 		 */
1208 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
1209 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1210 			    __func__, sx);
1211 
1212 #ifdef KDTRACE_HOOKS
1213 		sleep_time -= lockstat_nsecs(&sx->lock_object);
1214 #endif
1215 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1216 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1217 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1218 		/*
1219 		 * Hack: this can land in thread_suspend_check which will
1220 		 * conditionally take a mutex, tripping over an assert if a
1221 		 * lock we are waiting for is set.
1222 		 */
1223 		THREAD_CONTENTION_DONE(&sx->lock_object);
1224 		if (!(opts & SX_INTERRUPTIBLE))
1225 			sleepq_wait(&sx->lock_object, 0);
1226 		else
1227 			error = sleepq_wait_sig(&sx->lock_object, 0);
1228 		THREAD_CONTENDS_ON_LOCK(&sx->lock_object);
1229 #ifdef KDTRACE_HOOKS
1230 		sleep_time += lockstat_nsecs(&sx->lock_object);
1231 		sleep_cnt++;
1232 #endif
1233 		if (error) {
1234 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1235 				CTR2(KTR_LOCK,
1236 			"%s: interruptible sleep by %p suspended by signal",
1237 				    __func__, sx);
1238 			break;
1239 		}
1240 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
1241 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1242 			    __func__, sx);
1243 		x = SX_READ_VALUE(sx);
1244 	}
1245 	THREAD_CONTENTION_DONE(&sx->lock_object);
1246 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1247 	if (__predict_true(!extra_work))
1248 		return (error);
1249 #endif
1250 #ifdef KDTRACE_HOOKS
1251 	all_time += lockstat_nsecs(&sx->lock_object);
1252 	if (sleep_time)
1253 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1254 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1255 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1256 	if (lda.spin_cnt > sleep_cnt)
1257 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1258 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1259 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1260 out_lockstat:
1261 #endif
1262 	if (error == 0) {
1263 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1264 		    contested, waittime, file, line, LOCKSTAT_READER);
1265 	}
1266 	GIANT_RESTORE();
1267 	return (error);
1268 }
1269 
1270 int
1271 _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
1272 {
1273 	struct thread *td;
1274 	uintptr_t x;
1275 	int error;
1276 
1277 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1278 	    !TD_IS_IDLETHREAD(curthread),
1279 	    ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1280 	    curthread, sx->lock_object.lo_name, file, line));
1281 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1282 	    ("sx_slock() of destroyed sx @ %s:%d", file, line));
1283 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1284 
1285 	error = 0;
1286 	td = curthread;
1287 	x = SX_READ_VALUE(sx);
1288 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__acquire) ||
1289 	    !__sx_slock_try(sx, td, &x, true LOCK_FILE_LINE_ARG)))
1290 		error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1291 	else
1292 		lock_profile_obtain_lock_success(&sx->lock_object, false, 0, 0,
1293 		    file, line);
1294 	if (error == 0) {
1295 		LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1296 		WITNESS_LOCK(&sx->lock_object, 0, file, line);
1297 		TD_LOCKS_INC(curthread);
1298 	}
1299 	return (error);
1300 }
1301 
1302 int
1303 _sx_slock(struct sx *sx, int opts, const char *file, int line)
1304 {
1305 
1306 	return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1307 }
1308 
1309 static bool __always_inline
1310 _sx_sunlock_try(struct sx *sx, struct thread *td, uintptr_t *xp)
1311 {
1312 
1313 	for (;;) {
1314 		if (SX_SHARERS(*xp) > 1 || !(*xp & SX_LOCK_WAITERS)) {
1315 			if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1316 			    *xp - SX_ONE_SHARER)) {
1317 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
1318 					CTR4(KTR_LOCK,
1319 					    "%s: %p succeeded %p -> %p",
1320 					    __func__, sx, (void *)*xp,
1321 					    (void *)(*xp - SX_ONE_SHARER));
1322 				td->td_sx_slocks--;
1323 				return (true);
1324 			}
1325 			continue;
1326 		}
1327 		break;
1328 	}
1329 	return (false);
1330 }
1331 
1332 static void __noinline
1333 _sx_sunlock_hard(struct sx *sx, struct thread *td, uintptr_t x
1334     LOCK_FILE_LINE_ARG_DEF)
1335 {
1336 	int wakeup_swapper = 0;
1337 	uintptr_t setx, queue;
1338 
1339 	if (SCHEDULER_STOPPED())
1340 		return;
1341 
1342 	if (_sx_sunlock_try(sx, td, &x))
1343 		goto out_lockstat;
1344 
1345 	sleepq_lock(&sx->lock_object);
1346 	x = SX_READ_VALUE(sx);
1347 	for (;;) {
1348 		if (_sx_sunlock_try(sx, td, &x))
1349 			break;
1350 
1351 		/*
1352 		 * Wake up semantic here is quite simple:
1353 		 * Just wake up all the exclusive waiters.
1354 		 * Note that the state of the lock could have changed,
1355 		 * so if it fails loop back and retry.
1356 		 */
1357 		setx = SX_LOCK_UNLOCKED;
1358 		queue = SQ_SHARED_QUEUE;
1359 		if (x & SX_LOCK_EXCLUSIVE_WAITERS) {
1360 			setx |= (x & SX_LOCK_SHARED_WAITERS);
1361 			queue = SQ_EXCLUSIVE_QUEUE;
1362 		}
1363 		setx |= (x & SX_LOCK_WRITE_SPINNER);
1364 		if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
1365 			continue;
1366 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
1367 			CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1368 			    "exclusive queue", __func__, sx);
1369 		wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1370 		    0, queue);
1371 		td->td_sx_slocks--;
1372 		break;
1373 	}
1374 	sleepq_release(&sx->lock_object);
1375 	if (wakeup_swapper)
1376 		kick_proc0();
1377 out_lockstat:
1378 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1379 }
1380 
1381 void
1382 _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1383 {
1384 	struct thread *td;
1385 	uintptr_t x;
1386 
1387 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1388 	    ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1389 	_sx_assert(sx, SA_SLOCKED, file, line);
1390 	WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1391 	LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1392 
1393 	td = curthread;
1394 	x = SX_READ_VALUE(sx);
1395 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__release) ||
1396 	    !_sx_sunlock_try(sx, td, &x)))
1397 		_sx_sunlock_hard(sx, td, x LOCK_FILE_LINE_ARG);
1398 	else
1399 		lock_profile_release_lock(&sx->lock_object, false);
1400 
1401 	TD_LOCKS_DEC(curthread);
1402 }
1403 
1404 void
1405 _sx_sunlock(struct sx *sx, const char *file, int line)
1406 {
1407 
1408 	_sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1409 }
1410 
1411 #ifdef INVARIANT_SUPPORT
1412 #ifndef INVARIANTS
1413 #undef	_sx_assert
1414 #endif
1415 
1416 /*
1417  * In the non-WITNESS case, sx_assert() can only detect that at least
1418  * *some* thread owns an slock, but it cannot guarantee that *this*
1419  * thread owns an slock.
1420  */
1421 void
1422 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1423 {
1424 #ifndef WITNESS
1425 	int slocked = 0;
1426 #endif
1427 
1428 	if (SCHEDULER_STOPPED())
1429 		return;
1430 	switch (what) {
1431 	case SA_SLOCKED:
1432 	case SA_SLOCKED | SA_NOTRECURSED:
1433 	case SA_SLOCKED | SA_RECURSED:
1434 #ifndef WITNESS
1435 		slocked = 1;
1436 		/* FALLTHROUGH */
1437 #endif
1438 	case SA_LOCKED:
1439 	case SA_LOCKED | SA_NOTRECURSED:
1440 	case SA_LOCKED | SA_RECURSED:
1441 #ifdef WITNESS
1442 		witness_assert(&sx->lock_object, what, file, line);
1443 #else
1444 		/*
1445 		 * If some other thread has an exclusive lock or we
1446 		 * have one and are asserting a shared lock, fail.
1447 		 * Also, if no one has a lock at all, fail.
1448 		 */
1449 		if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1450 		    (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1451 		    sx_xholder(sx) != curthread)))
1452 			panic("Lock %s not %slocked @ %s:%d\n",
1453 			    sx->lock_object.lo_name, slocked ? "share " : "",
1454 			    file, line);
1455 
1456 		if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1457 			if (sx_recursed(sx)) {
1458 				if (what & SA_NOTRECURSED)
1459 					panic("Lock %s recursed @ %s:%d\n",
1460 					    sx->lock_object.lo_name, file,
1461 					    line);
1462 			} else if (what & SA_RECURSED)
1463 				panic("Lock %s not recursed @ %s:%d\n",
1464 				    sx->lock_object.lo_name, file, line);
1465 		}
1466 #endif
1467 		break;
1468 	case SA_XLOCKED:
1469 	case SA_XLOCKED | SA_NOTRECURSED:
1470 	case SA_XLOCKED | SA_RECURSED:
1471 		if (sx_xholder(sx) != curthread)
1472 			panic("Lock %s not exclusively locked @ %s:%d\n",
1473 			    sx->lock_object.lo_name, file, line);
1474 		if (sx_recursed(sx)) {
1475 			if (what & SA_NOTRECURSED)
1476 				panic("Lock %s recursed @ %s:%d\n",
1477 				    sx->lock_object.lo_name, file, line);
1478 		} else if (what & SA_RECURSED)
1479 			panic("Lock %s not recursed @ %s:%d\n",
1480 			    sx->lock_object.lo_name, file, line);
1481 		break;
1482 	case SA_UNLOCKED:
1483 #ifdef WITNESS
1484 		witness_assert(&sx->lock_object, what, file, line);
1485 #else
1486 		/*
1487 		 * If we hold an exclusve lock fail.  We can't
1488 		 * reliably check to see if we hold a shared lock or
1489 		 * not.
1490 		 */
1491 		if (sx_xholder(sx) == curthread)
1492 			panic("Lock %s exclusively locked @ %s:%d\n",
1493 			    sx->lock_object.lo_name, file, line);
1494 #endif
1495 		break;
1496 	default:
1497 		panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1498 		    line);
1499 	}
1500 }
1501 #endif	/* INVARIANT_SUPPORT */
1502 
1503 #ifdef DDB
1504 static void
1505 db_show_sx(const struct lock_object *lock)
1506 {
1507 	struct thread *td;
1508 	const struct sx *sx;
1509 
1510 	sx = (const struct sx *)lock;
1511 
1512 	db_printf(" state: ");
1513 	if (sx->sx_lock == SX_LOCK_UNLOCKED)
1514 		db_printf("UNLOCKED\n");
1515 	else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1516 		db_printf("DESTROYED\n");
1517 		return;
1518 	} else if (sx->sx_lock & SX_LOCK_SHARED)
1519 		db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1520 	else {
1521 		td = sx_xholder(sx);
1522 		db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1523 		    td->td_tid, td->td_proc->p_pid, td->td_name);
1524 		if (sx_recursed(sx))
1525 			db_printf(" recursed: %d\n", sx->sx_recurse);
1526 	}
1527 
1528 	db_printf(" waiters: ");
1529 	switch(sx->sx_lock &
1530 	    (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1531 	case SX_LOCK_SHARED_WAITERS:
1532 		db_printf("shared\n");
1533 		break;
1534 	case SX_LOCK_EXCLUSIVE_WAITERS:
1535 		db_printf("exclusive\n");
1536 		break;
1537 	case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1538 		db_printf("exclusive and shared\n");
1539 		break;
1540 	default:
1541 		db_printf("none\n");
1542 	}
1543 }
1544 
1545 /*
1546  * Check to see if a thread that is blocked on a sleep queue is actually
1547  * blocked on an sx lock.  If so, output some details and return true.
1548  * If the lock has an exclusive owner, return that in *ownerp.
1549  */
1550 int
1551 sx_chain(struct thread *td, struct thread **ownerp)
1552 {
1553 	const struct sx *sx;
1554 
1555 	/*
1556 	 * Check to see if this thread is blocked on an sx lock.
1557 	 * First, we check the lock class.  If that is ok, then we
1558 	 * compare the lock name against the wait message.
1559 	 */
1560 	sx = td->td_wchan;
1561 	if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1562 	    sx->lock_object.lo_name != td->td_wmesg)
1563 		return (0);
1564 
1565 	/* We think we have an sx lock, so output some details. */
1566 	db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1567 	*ownerp = sx_xholder(sx);
1568 	if (sx->sx_lock & SX_LOCK_SHARED)
1569 		db_printf("SLOCK (count %ju)\n",
1570 		    (uintmax_t)SX_SHARERS(sx->sx_lock));
1571 	else
1572 		db_printf("XLOCK\n");
1573 	return (1);
1574 }
1575 #endif
1576