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