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