xref: /freebsd/sys/kern/kern_sx.c (revision a678f77962278b50da97a88aac8abe77c192a4f1)
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 (__predict_false(x == SX_LOCK_UNLOCKED))
535 		x = SX_READ_VALUE(sx);
536 
537 	/* If we already hold an exclusive lock, then recurse. */
538 	if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
539 		KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
540 	    ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
541 		    sx->lock_object.lo_name, file, line));
542 		sx->sx_recurse++;
543 		atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
544 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
545 			CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
546 		return (0);
547 	}
548 
549 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
550 		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
551 		    sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
552 
553 #ifdef KDTRACE_HOOKS
554 	all_time -= lockstat_nsecs(&sx->lock_object);
555 	state = x;
556 #endif
557 	for (;;) {
558 		if (x == SX_LOCK_UNLOCKED) {
559 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
560 				break;
561 			continue;
562 		}
563 #ifdef KDTRACE_HOOKS
564 		lda.spin_cnt++;
565 #endif
566 #ifdef HWPMC_HOOKS
567 		PMC_SOFT_CALL( , , lock, failed);
568 #endif
569 		lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
570 		    &waittime);
571 #ifdef ADAPTIVE_SX
572 		/*
573 		 * If the lock is write locked and the owner is
574 		 * running on another CPU, spin until the owner stops
575 		 * running or the state of the lock changes.
576 		 */
577 		if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
578 			if ((x & SX_LOCK_SHARED) == 0) {
579 				owner = lv_sx_owner(x);
580 				if (TD_IS_RUNNING(owner)) {
581 					if (LOCK_LOG_TEST(&sx->lock_object, 0))
582 						CTR3(KTR_LOCK,
583 					    "%s: spinning on %p held by %p",
584 						    __func__, sx, owner);
585 					KTR_STATE1(KTR_SCHED, "thread",
586 					    sched_tdname(curthread), "spinning",
587 					    "lockname:\"%s\"",
588 					    sx->lock_object.lo_name);
589 					GIANT_SAVE();
590 					do {
591 						lock_delay(&lda);
592 						x = SX_READ_VALUE(sx);
593 						owner = lv_sx_owner(x);
594 					} while (owner != NULL &&
595 						    TD_IS_RUNNING(owner));
596 					KTR_STATE0(KTR_SCHED, "thread",
597 					    sched_tdname(curthread), "running");
598 					continue;
599 				}
600 			} else if (SX_SHARERS(x) && spintries < asx_retries) {
601 				KTR_STATE1(KTR_SCHED, "thread",
602 				    sched_tdname(curthread), "spinning",
603 				    "lockname:\"%s\"", sx->lock_object.lo_name);
604 				GIANT_SAVE();
605 				spintries++;
606 				for (i = 0; i < asx_loops; i++) {
607 					if (LOCK_LOG_TEST(&sx->lock_object, 0))
608 						CTR4(KTR_LOCK,
609 				    "%s: shared spinning on %p with %u and %u",
610 						    __func__, sx, spintries, i);
611 					x = sx->sx_lock;
612 					if ((x & SX_LOCK_SHARED) == 0 ||
613 					    SX_SHARERS(x) == 0)
614 						break;
615 					cpu_spinwait();
616 #ifdef KDTRACE_HOOKS
617 					lda.spin_cnt++;
618 #endif
619 				}
620 				KTR_STATE0(KTR_SCHED, "thread",
621 				    sched_tdname(curthread), "running");
622 				x = SX_READ_VALUE(sx);
623 				if (i != asx_loops)
624 					continue;
625 			}
626 		}
627 #endif
628 
629 		sleepq_lock(&sx->lock_object);
630 		x = SX_READ_VALUE(sx);
631 
632 		/*
633 		 * If the lock was released while spinning on the
634 		 * sleep queue chain lock, try again.
635 		 */
636 		if (x == SX_LOCK_UNLOCKED) {
637 			sleepq_release(&sx->lock_object);
638 			continue;
639 		}
640 
641 #ifdef ADAPTIVE_SX
642 		/*
643 		 * The current lock owner might have started executing
644 		 * on another CPU (or the lock could have changed
645 		 * owners) while we were waiting on the sleep queue
646 		 * chain lock.  If so, drop the sleep queue lock and try
647 		 * again.
648 		 */
649 		if (!(x & SX_LOCK_SHARED) &&
650 		    (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
651 			owner = (struct thread *)SX_OWNER(x);
652 			if (TD_IS_RUNNING(owner)) {
653 				sleepq_release(&sx->lock_object);
654 				continue;
655 			}
656 		}
657 #endif
658 
659 		/*
660 		 * If an exclusive lock was released with both shared
661 		 * and exclusive waiters and a shared waiter hasn't
662 		 * woken up and acquired the lock yet, sx_lock will be
663 		 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
664 		 * If we see that value, try to acquire it once.  Note
665 		 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
666 		 * as there are other exclusive waiters still.  If we
667 		 * fail, restart the loop.
668 		 */
669 		if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
670 			if (atomic_cmpset_acq_ptr(&sx->sx_lock,
671 			    SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
672 			    tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
673 				sleepq_release(&sx->lock_object);
674 				CTR2(KTR_LOCK, "%s: %p claimed by new writer",
675 				    __func__, sx);
676 				break;
677 			}
678 			sleepq_release(&sx->lock_object);
679 			x = SX_READ_VALUE(sx);
680 			continue;
681 		}
682 
683 		/*
684 		 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
685 		 * than loop back and retry.
686 		 */
687 		if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
688 			if (!atomic_cmpset_ptr(&sx->sx_lock, x,
689 			    x | SX_LOCK_EXCLUSIVE_WAITERS)) {
690 				sleepq_release(&sx->lock_object);
691 				x = SX_READ_VALUE(sx);
692 				continue;
693 			}
694 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
695 				CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
696 				    __func__, sx);
697 		}
698 
699 		/*
700 		 * Since we have been unable to acquire the exclusive
701 		 * lock and the exclusive waiters flag is set, we have
702 		 * to sleep.
703 		 */
704 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
705 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
706 			    __func__, sx);
707 
708 #ifdef KDTRACE_HOOKS
709 		sleep_time -= lockstat_nsecs(&sx->lock_object);
710 #endif
711 		GIANT_SAVE();
712 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
713 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
714 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
715 		if (!(opts & SX_INTERRUPTIBLE))
716 			sleepq_wait(&sx->lock_object, 0);
717 		else
718 			error = sleepq_wait_sig(&sx->lock_object, 0);
719 #ifdef KDTRACE_HOOKS
720 		sleep_time += lockstat_nsecs(&sx->lock_object);
721 		sleep_cnt++;
722 #endif
723 		if (error) {
724 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
725 				CTR2(KTR_LOCK,
726 			"%s: interruptible sleep by %p suspended by signal",
727 				    __func__, sx);
728 			break;
729 		}
730 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
731 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
732 			    __func__, sx);
733 		x = SX_READ_VALUE(sx);
734 	}
735 #ifdef KDTRACE_HOOKS
736 	all_time += lockstat_nsecs(&sx->lock_object);
737 	if (sleep_time)
738 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
739 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
740 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
741 	if (lda.spin_cnt > sleep_cnt)
742 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
743 		    LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
744 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
745 #endif
746 	if (!error)
747 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
748 		    contested, waittime, file, line, LOCKSTAT_WRITER);
749 	GIANT_RESTORE();
750 	return (error);
751 }
752 
753 /*
754  * This function represents the so-called 'hard case' for sx_xunlock
755  * operation.  All 'easy case' failures are redirected to this.  Note
756  * that ideally this would be a static function, but it needs to be
757  * accessible from at least sx.h.
758  */
759 void
760 _sx_xunlock_hard(struct sx *sx, uintptr_t tid, const char *file, int line)
761 {
762 	uintptr_t x;
763 	int queue, wakeup_swapper;
764 
765 	if (SCHEDULER_STOPPED())
766 		return;
767 
768 	MPASS(!(sx->sx_lock & SX_LOCK_SHARED));
769 
770 	if (!sx_recursed(sx)) {
771 		LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx,
772 		    LOCKSTAT_WRITER);
773 		if (atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
774 			return;
775 	} else {
776 		/* The lock is recursed, unrecurse one level. */
777 		if ((--sx->sx_recurse) == 0)
778 			atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
779 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
780 			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
781 		return;
782 	}
783 	MPASS(sx->sx_lock & (SX_LOCK_SHARED_WAITERS |
784 	    SX_LOCK_EXCLUSIVE_WAITERS));
785 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
786 		CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
787 
788 	sleepq_lock(&sx->lock_object);
789 	x = SX_LOCK_UNLOCKED;
790 
791 	/*
792 	 * The wake up algorithm here is quite simple and probably not
793 	 * ideal.  It gives precedence to shared waiters if they are
794 	 * present.  For this condition, we have to preserve the
795 	 * state of the exclusive waiters flag.
796 	 * If interruptible sleeps left the shared queue empty avoid a
797 	 * starvation for the threads sleeping on the exclusive queue by giving
798 	 * them precedence and cleaning up the shared waiters bit anyway.
799 	 */
800 	if ((sx->sx_lock & SX_LOCK_SHARED_WAITERS) != 0 &&
801 	    sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
802 		queue = SQ_SHARED_QUEUE;
803 		x |= (sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS);
804 	} else
805 		queue = SQ_EXCLUSIVE_QUEUE;
806 
807 	/* Wake up all the waiters for the specific queue. */
808 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
809 		CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
810 		    __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
811 		    "exclusive");
812 	atomic_store_rel_ptr(&sx->sx_lock, x);
813 	wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
814 	    queue);
815 	sleepq_release(&sx->lock_object);
816 	if (wakeup_swapper)
817 		kick_proc0();
818 }
819 
820 int
821 _sx_slock(struct sx *sx, int opts, const char *file, int line)
822 {
823 	GIANT_DECLARE;
824 #ifdef ADAPTIVE_SX
825 	volatile struct thread *owner;
826 #endif
827 #ifdef LOCK_PROFILING
828 	uint64_t waittime = 0;
829 	int contested = 0;
830 #endif
831 	uintptr_t x;
832 	int error = 0;
833 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
834 	struct lock_delay_arg lda;
835 #endif
836 #ifdef KDTRACE_HOOKS
837 	uintptr_t state;
838 	u_int sleep_cnt = 0;
839 	int64_t sleep_time = 0;
840 	int64_t all_time = 0;
841 #endif
842 
843 	if (SCHEDULER_STOPPED())
844 		return (0);
845 
846 #if defined(ADAPTIVE_SX)
847 	lock_delay_arg_init(&lda, &sx_delay);
848 #elif defined(KDTRACE_HOOKS)
849 	lock_delay_arg_init(&lda, NULL);
850 #endif
851 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
852 	    ("sx_slock() by idle thread %p on sx %s @ %s:%d",
853 	    curthread, sx->lock_object.lo_name, file, line));
854 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
855 	    ("sx_slock() of destroyed sx @ %s:%d", file, line));
856 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
857 #ifdef KDTRACE_HOOKS
858 	all_time -= lockstat_nsecs(&sx->lock_object);
859 #endif
860 	x = SX_READ_VALUE(sx);
861 #ifdef KDTRACE_HOOKS
862 	state = x;
863 #endif
864 
865 	/*
866 	 * As with rwlocks, we don't make any attempt to try to block
867 	 * shared locks once there is an exclusive waiter.
868 	 */
869 	for (;;) {
870 		/*
871 		 * If no other thread has an exclusive lock then try to bump up
872 		 * the count of sharers.  Since we have to preserve the state
873 		 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
874 		 * shared lock loop back and retry.
875 		 */
876 		if (x & SX_LOCK_SHARED) {
877 			MPASS(!(x & SX_LOCK_SHARED_WAITERS));
878 			if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
879 			    x + SX_ONE_SHARER)) {
880 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
881 					CTR4(KTR_LOCK,
882 					    "%s: %p succeed %p -> %p", __func__,
883 					    sx, (void *)x,
884 					    (void *)(x + SX_ONE_SHARER));
885 				break;
886 			}
887 			continue;
888 		}
889 #ifdef KDTRACE_HOOKS
890 		lda.spin_cnt++;
891 #endif
892 
893 #ifdef HWPMC_HOOKS
894 		PMC_SOFT_CALL( , , lock, failed);
895 #endif
896 		lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
897 		    &waittime);
898 
899 #ifdef ADAPTIVE_SX
900 		/*
901 		 * If the owner is running on another CPU, spin until
902 		 * the owner stops running or the state of the lock
903 		 * changes.
904 		 */
905 		if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
906 			owner = lv_sx_owner(x);
907 			if (TD_IS_RUNNING(owner)) {
908 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
909 					CTR3(KTR_LOCK,
910 					    "%s: spinning on %p held by %p",
911 					    __func__, sx, owner);
912 				KTR_STATE1(KTR_SCHED, "thread",
913 				    sched_tdname(curthread), "spinning",
914 				    "lockname:\"%s\"", sx->lock_object.lo_name);
915 				GIANT_SAVE();
916 				do {
917 					lock_delay(&lda);
918 					x = SX_READ_VALUE(sx);
919 					owner = lv_sx_owner(x);
920 				} while (owner != NULL && TD_IS_RUNNING(owner));
921 				KTR_STATE0(KTR_SCHED, "thread",
922 				    sched_tdname(curthread), "running");
923 				continue;
924 			}
925 		}
926 #endif
927 
928 		/*
929 		 * Some other thread already has an exclusive lock, so
930 		 * start the process of blocking.
931 		 */
932 		sleepq_lock(&sx->lock_object);
933 		x = SX_READ_VALUE(sx);
934 
935 		/*
936 		 * The lock could have been released while we spun.
937 		 * In this case loop back and retry.
938 		 */
939 		if (x & SX_LOCK_SHARED) {
940 			sleepq_release(&sx->lock_object);
941 			continue;
942 		}
943 
944 #ifdef ADAPTIVE_SX
945 		/*
946 		 * If the owner is running on another CPU, spin until
947 		 * the owner stops running or the state of the lock
948 		 * changes.
949 		 */
950 		if (!(x & SX_LOCK_SHARED) &&
951 		    (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
952 			owner = (struct thread *)SX_OWNER(x);
953 			if (TD_IS_RUNNING(owner)) {
954 				sleepq_release(&sx->lock_object);
955 				x = SX_READ_VALUE(sx);
956 				continue;
957 			}
958 		}
959 #endif
960 
961 		/*
962 		 * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
963 		 * fail to set it drop the sleep queue lock and loop
964 		 * back.
965 		 */
966 		if (!(x & SX_LOCK_SHARED_WAITERS)) {
967 			if (!atomic_cmpset_ptr(&sx->sx_lock, x,
968 			    x | SX_LOCK_SHARED_WAITERS)) {
969 				sleepq_release(&sx->lock_object);
970 				x = SX_READ_VALUE(sx);
971 				continue;
972 			}
973 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
974 				CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
975 				    __func__, sx);
976 		}
977 
978 		/*
979 		 * Since we have been unable to acquire the shared lock,
980 		 * we have to sleep.
981 		 */
982 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
983 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
984 			    __func__, sx);
985 
986 #ifdef KDTRACE_HOOKS
987 		sleep_time -= lockstat_nsecs(&sx->lock_object);
988 #endif
989 		GIANT_SAVE();
990 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
991 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
992 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
993 		if (!(opts & SX_INTERRUPTIBLE))
994 			sleepq_wait(&sx->lock_object, 0);
995 		else
996 			error = sleepq_wait_sig(&sx->lock_object, 0);
997 #ifdef KDTRACE_HOOKS
998 		sleep_time += lockstat_nsecs(&sx->lock_object);
999 		sleep_cnt++;
1000 #endif
1001 		if (error) {
1002 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
1003 				CTR2(KTR_LOCK,
1004 			"%s: interruptible sleep by %p suspended by signal",
1005 				    __func__, sx);
1006 			break;
1007 		}
1008 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
1009 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1010 			    __func__, sx);
1011 		x = SX_READ_VALUE(sx);
1012 	}
1013 #ifdef KDTRACE_HOOKS
1014 	all_time += lockstat_nsecs(&sx->lock_object);
1015 	if (sleep_time)
1016 		LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1017 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1018 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1019 	if (lda.spin_cnt > sleep_cnt)
1020 		LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1021 		    LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1022 		    (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1023 #endif
1024 	if (error == 0) {
1025 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1026 		    contested, waittime, file, line, LOCKSTAT_READER);
1027 		LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1028 		WITNESS_LOCK(&sx->lock_object, 0, file, line);
1029 		TD_LOCKS_INC(curthread);
1030 	}
1031 	GIANT_RESTORE();
1032 	return (error);
1033 }
1034 
1035 void
1036 _sx_sunlock(struct sx *sx, const char *file, int line)
1037 {
1038 	uintptr_t x;
1039 	int wakeup_swapper;
1040 
1041 	if (SCHEDULER_STOPPED())
1042 		return;
1043 
1044 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1045 	    ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1046 	_sx_assert(sx, SA_SLOCKED, file, line);
1047 	WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1048 	LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1049 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1050 	x = SX_READ_VALUE(sx);
1051 	for (;;) {
1052 		/*
1053 		 * We should never have sharers while at least one thread
1054 		 * holds a shared lock.
1055 		 */
1056 		KASSERT(!(x & SX_LOCK_SHARED_WAITERS),
1057 		    ("%s: waiting sharers", __func__));
1058 
1059 		/*
1060 		 * See if there is more than one shared lock held.  If
1061 		 * so, just drop one and return.
1062 		 */
1063 		if (SX_SHARERS(x) > 1) {
1064 			if (atomic_fcmpset_rel_ptr(&sx->sx_lock, &x,
1065 			    x - SX_ONE_SHARER)) {
1066 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
1067 					CTR4(KTR_LOCK,
1068 					    "%s: %p succeeded %p -> %p",
1069 					    __func__, sx, (void *)x,
1070 					    (void *)(x - SX_ONE_SHARER));
1071 				break;
1072 			}
1073 			continue;
1074 		}
1075 
1076 		/*
1077 		 * If there aren't any waiters for an exclusive lock,
1078 		 * then try to drop it quickly.
1079 		 */
1080 		if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
1081 			MPASS(x == SX_SHARERS_LOCK(1));
1082 			x = SX_SHARERS_LOCK(1);
1083 			if (atomic_fcmpset_rel_ptr(&sx->sx_lock,
1084 			    &x, SX_LOCK_UNLOCKED)) {
1085 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
1086 					CTR2(KTR_LOCK, "%s: %p last succeeded",
1087 					    __func__, sx);
1088 				break;
1089 			}
1090 			continue;
1091 		}
1092 
1093 		/*
1094 		 * At this point, there should just be one sharer with
1095 		 * exclusive waiters.
1096 		 */
1097 		MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1098 
1099 		sleepq_lock(&sx->lock_object);
1100 
1101 		/*
1102 		 * Wake up semantic here is quite simple:
1103 		 * Just wake up all the exclusive waiters.
1104 		 * Note that the state of the lock could have changed,
1105 		 * so if it fails loop back and retry.
1106 		 */
1107 		if (!atomic_cmpset_rel_ptr(&sx->sx_lock,
1108 		    SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
1109 		    SX_LOCK_UNLOCKED)) {
1110 			sleepq_release(&sx->lock_object);
1111 			x = SX_READ_VALUE(sx);
1112 			continue;
1113 		}
1114 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
1115 			CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1116 			    "exclusive queue", __func__, sx);
1117 		wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1118 		    0, SQ_EXCLUSIVE_QUEUE);
1119 		sleepq_release(&sx->lock_object);
1120 		if (wakeup_swapper)
1121 			kick_proc0();
1122 		break;
1123 	}
1124 	TD_LOCKS_DEC(curthread);
1125 }
1126 
1127 #ifdef INVARIANT_SUPPORT
1128 #ifndef INVARIANTS
1129 #undef	_sx_assert
1130 #endif
1131 
1132 /*
1133  * In the non-WITNESS case, sx_assert() can only detect that at least
1134  * *some* thread owns an slock, but it cannot guarantee that *this*
1135  * thread owns an slock.
1136  */
1137 void
1138 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1139 {
1140 #ifndef WITNESS
1141 	int slocked = 0;
1142 #endif
1143 
1144 	if (panicstr != NULL)
1145 		return;
1146 	switch (what) {
1147 	case SA_SLOCKED:
1148 	case SA_SLOCKED | SA_NOTRECURSED:
1149 	case SA_SLOCKED | SA_RECURSED:
1150 #ifndef WITNESS
1151 		slocked = 1;
1152 		/* FALLTHROUGH */
1153 #endif
1154 	case SA_LOCKED:
1155 	case SA_LOCKED | SA_NOTRECURSED:
1156 	case SA_LOCKED | SA_RECURSED:
1157 #ifdef WITNESS
1158 		witness_assert(&sx->lock_object, what, file, line);
1159 #else
1160 		/*
1161 		 * If some other thread has an exclusive lock or we
1162 		 * have one and are asserting a shared lock, fail.
1163 		 * Also, if no one has a lock at all, fail.
1164 		 */
1165 		if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1166 		    (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1167 		    sx_xholder(sx) != curthread)))
1168 			panic("Lock %s not %slocked @ %s:%d\n",
1169 			    sx->lock_object.lo_name, slocked ? "share " : "",
1170 			    file, line);
1171 
1172 		if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1173 			if (sx_recursed(sx)) {
1174 				if (what & SA_NOTRECURSED)
1175 					panic("Lock %s recursed @ %s:%d\n",
1176 					    sx->lock_object.lo_name, file,
1177 					    line);
1178 			} else if (what & SA_RECURSED)
1179 				panic("Lock %s not recursed @ %s:%d\n",
1180 				    sx->lock_object.lo_name, file, line);
1181 		}
1182 #endif
1183 		break;
1184 	case SA_XLOCKED:
1185 	case SA_XLOCKED | SA_NOTRECURSED:
1186 	case SA_XLOCKED | SA_RECURSED:
1187 		if (sx_xholder(sx) != curthread)
1188 			panic("Lock %s not exclusively locked @ %s:%d\n",
1189 			    sx->lock_object.lo_name, file, line);
1190 		if (sx_recursed(sx)) {
1191 			if (what & SA_NOTRECURSED)
1192 				panic("Lock %s recursed @ %s:%d\n",
1193 				    sx->lock_object.lo_name, file, line);
1194 		} else if (what & SA_RECURSED)
1195 			panic("Lock %s not recursed @ %s:%d\n",
1196 			    sx->lock_object.lo_name, file, line);
1197 		break;
1198 	case SA_UNLOCKED:
1199 #ifdef WITNESS
1200 		witness_assert(&sx->lock_object, what, file, line);
1201 #else
1202 		/*
1203 		 * If we hold an exclusve lock fail.  We can't
1204 		 * reliably check to see if we hold a shared lock or
1205 		 * not.
1206 		 */
1207 		if (sx_xholder(sx) == curthread)
1208 			panic("Lock %s exclusively locked @ %s:%d\n",
1209 			    sx->lock_object.lo_name, file, line);
1210 #endif
1211 		break;
1212 	default:
1213 		panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1214 		    line);
1215 	}
1216 }
1217 #endif	/* INVARIANT_SUPPORT */
1218 
1219 #ifdef DDB
1220 static void
1221 db_show_sx(const struct lock_object *lock)
1222 {
1223 	struct thread *td;
1224 	const struct sx *sx;
1225 
1226 	sx = (const struct sx *)lock;
1227 
1228 	db_printf(" state: ");
1229 	if (sx->sx_lock == SX_LOCK_UNLOCKED)
1230 		db_printf("UNLOCKED\n");
1231 	else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1232 		db_printf("DESTROYED\n");
1233 		return;
1234 	} else if (sx->sx_lock & SX_LOCK_SHARED)
1235 		db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1236 	else {
1237 		td = sx_xholder(sx);
1238 		db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1239 		    td->td_tid, td->td_proc->p_pid, td->td_name);
1240 		if (sx_recursed(sx))
1241 			db_printf(" recursed: %d\n", sx->sx_recurse);
1242 	}
1243 
1244 	db_printf(" waiters: ");
1245 	switch(sx->sx_lock &
1246 	    (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1247 	case SX_LOCK_SHARED_WAITERS:
1248 		db_printf("shared\n");
1249 		break;
1250 	case SX_LOCK_EXCLUSIVE_WAITERS:
1251 		db_printf("exclusive\n");
1252 		break;
1253 	case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1254 		db_printf("exclusive and shared\n");
1255 		break;
1256 	default:
1257 		db_printf("none\n");
1258 	}
1259 }
1260 
1261 /*
1262  * Check to see if a thread that is blocked on a sleep queue is actually
1263  * blocked on an sx lock.  If so, output some details and return true.
1264  * If the lock has an exclusive owner, return that in *ownerp.
1265  */
1266 int
1267 sx_chain(struct thread *td, struct thread **ownerp)
1268 {
1269 	struct sx *sx;
1270 
1271 	/*
1272 	 * Check to see if this thread is blocked on an sx lock.
1273 	 * First, we check the lock class.  If that is ok, then we
1274 	 * compare the lock name against the wait message.
1275 	 */
1276 	sx = td->td_wchan;
1277 	if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1278 	    sx->lock_object.lo_name != td->td_wmesg)
1279 		return (0);
1280 
1281 	/* We think we have an sx lock, so output some details. */
1282 	db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1283 	*ownerp = sx_xholder(sx);
1284 	if (sx->sx_lock & SX_LOCK_SHARED)
1285 		db_printf("SLOCK (count %ju)\n",
1286 		    (uintmax_t)SX_SHARERS(sx->sx_lock));
1287 	else
1288 		db_printf("XLOCK\n");
1289 	return (1);
1290 }
1291 #endif
1292