xref: /freebsd/sys/kern/kern_sx.c (revision 721351876cd4d3a8a700f62d2061331fa951a488)
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_adaptive_sx.h"
40 #include "opt_ddb.h"
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include <sys/param.h>
46 #include <sys/ktr.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/proc.h>
50 #include <sys/sleepqueue.h>
51 #include <sys/sx.h>
52 #include <sys/systm.h>
53 
54 #ifdef ADAPTIVE_SX
55 #include <machine/cpu.h>
56 #endif
57 
58 #ifdef DDB
59 #include <ddb/ddb.h>
60 #endif
61 
62 #if !defined(SMP) && defined(ADAPTIVE_SX)
63 #error "You must have SMP to enable the ADAPTIVE_SX option"
64 #endif
65 
66 CTASSERT(((SX_ADAPTIVESPIN | SX_RECURSE) & LO_CLASSFLAGS) ==
67     (SX_ADAPTIVESPIN | SX_RECURSE));
68 
69 /* Handy macros for sleep queues. */
70 #define	SQ_EXCLUSIVE_QUEUE	0
71 #define	SQ_SHARED_QUEUE		1
72 
73 /*
74  * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file.  We
75  * drop Giant anytime we have to sleep or if we adaptively spin.
76  */
77 #define	GIANT_DECLARE							\
78 	int _giantcnt = 0;						\
79 	WITNESS_SAVE_DECL(Giant)					\
80 
81 #define	GIANT_SAVE() do {						\
82 	if (mtx_owned(&Giant)) {					\
83 		WITNESS_SAVE(&Giant.lock_object, Giant);		\
84 		while (mtx_owned(&Giant)) {				\
85 			_giantcnt++;					\
86 			mtx_unlock(&Giant);				\
87 		}							\
88 	}								\
89 } while (0)
90 
91 #define GIANT_RESTORE() do {						\
92 	if (_giantcnt > 0) {						\
93 		mtx_assert(&Giant, MA_NOTOWNED);			\
94 		while (_giantcnt--)					\
95 			mtx_lock(&Giant);				\
96 		WITNESS_RESTORE(&Giant.lock_object, Giant);		\
97 	}								\
98 } while (0)
99 
100 /*
101  * Returns true if an exclusive lock is recursed.  It assumes
102  * curthread currently has an exclusive lock.
103  */
104 #define	sx_recurse		lock_object.lo_data
105 #define	sx_recursed(sx)		((sx)->sx_recurse != 0)
106 
107 static void	assert_sx(struct lock_object *lock, int what);
108 #ifdef DDB
109 static void	db_show_sx(struct lock_object *lock);
110 #endif
111 static void	lock_sx(struct lock_object *lock, int how);
112 static int	unlock_sx(struct lock_object *lock);
113 
114 struct lock_class lock_class_sx = {
115 	.lc_name = "sx",
116 	.lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
117 	.lc_assert = assert_sx,
118 #ifdef DDB
119 	.lc_ddb_show = db_show_sx,
120 #endif
121 	.lc_lock = lock_sx,
122 	.lc_unlock = unlock_sx,
123 };
124 
125 #ifndef INVARIANTS
126 #define	_sx_assert(sx, what, file, line)
127 #endif
128 
129 void
130 assert_sx(struct lock_object *lock, int what)
131 {
132 
133 	sx_assert((struct sx *)lock, what);
134 }
135 
136 void
137 lock_sx(struct lock_object *lock, int how)
138 {
139 	struct sx *sx;
140 
141 	sx = (struct sx *)lock;
142 	if (how)
143 		sx_xlock(sx);
144 	else
145 		sx_slock(sx);
146 }
147 
148 int
149 unlock_sx(struct lock_object *lock)
150 {
151 	struct sx *sx;
152 
153 	sx = (struct sx *)lock;
154 	sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
155 	if (sx_xlocked(sx)) {
156 		sx_xunlock(sx);
157 		return (1);
158 	} else {
159 		sx_sunlock(sx);
160 		return (0);
161 	}
162 }
163 
164 void
165 sx_sysinit(void *arg)
166 {
167 	struct sx_args *sargs = arg;
168 
169 	sx_init(sargs->sa_sx, sargs->sa_desc);
170 }
171 
172 void
173 sx_init_flags(struct sx *sx, const char *description, int opts)
174 {
175 	int flags;
176 
177 	MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
178 	    SX_NOPROFILE | SX_ADAPTIVESPIN)) == 0);
179 
180 	flags = LO_RECURSABLE | LO_SLEEPABLE | LO_UPGRADABLE;
181 	if (opts & SX_DUPOK)
182 		flags |= LO_DUPOK;
183 	if (opts & SX_NOPROFILE)
184 		flags |= LO_NOPROFILE;
185 	if (!(opts & SX_NOWITNESS))
186 		flags |= LO_WITNESS;
187 	if (opts & SX_QUIET)
188 		flags |= LO_QUIET;
189 
190 	flags |= opts & (SX_ADAPTIVESPIN | SX_RECURSE);
191 	sx->sx_lock = SX_LOCK_UNLOCKED;
192 	sx->sx_recurse = 0;
193 	lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
194 }
195 
196 void
197 sx_destroy(struct sx *sx)
198 {
199 
200 	KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
201 	KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
202 	sx->sx_lock = SX_LOCK_DESTROYED;
203 	lock_destroy(&sx->lock_object);
204 }
205 
206 int
207 _sx_slock(struct sx *sx, int opts, const char *file, int line)
208 {
209 	int error = 0;
210 
211 	MPASS(curthread != NULL);
212 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
213 	    ("sx_slock() of destroyed sx @ %s:%d", file, line));
214 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line);
215 	error = __sx_slock(sx, opts, file, line);
216 	if (!error) {
217 		LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
218 		WITNESS_LOCK(&sx->lock_object, 0, file, line);
219 		curthread->td_locks++;
220 	}
221 
222 	return (error);
223 }
224 
225 int
226 _sx_try_slock(struct sx *sx, const char *file, int line)
227 {
228 	uintptr_t x;
229 
230 	for (;;) {
231 		x = sx->sx_lock;
232 		KASSERT(x != SX_LOCK_DESTROYED,
233 		    ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
234 		if (!(x & SX_LOCK_SHARED))
235 			break;
236 		if (atomic_cmpset_acq_ptr(&sx->sx_lock, x, x + SX_ONE_SHARER)) {
237 			LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
238 			WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
239 			curthread->td_locks++;
240 			return (1);
241 		}
242 	}
243 
244 	LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
245 	return (0);
246 }
247 
248 int
249 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
250 {
251 	int error = 0;
252 
253 	MPASS(curthread != NULL);
254 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
255 	    ("sx_xlock() of destroyed sx @ %s:%d", file, line));
256 	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
257 	    line);
258 	error = __sx_xlock(sx, curthread, opts, file, line);
259 	if (!error) {
260 		LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
261 		    file, line);
262 		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
263 		curthread->td_locks++;
264 	}
265 
266 	return (error);
267 }
268 
269 int
270 _sx_try_xlock(struct sx *sx, const char *file, int line)
271 {
272 	int rval;
273 
274 	MPASS(curthread != NULL);
275 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
276 	    ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
277 
278 	if (sx_xlocked(sx) && (sx->lock_object.lo_flags & SX_RECURSE) != 0) {
279 		sx->sx_recurse++;
280 		atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
281 		rval = 1;
282 	} else
283 		rval = atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED,
284 		    (uintptr_t)curthread);
285 	LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
286 	if (rval) {
287 		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
288 		    file, line);
289 		curthread->td_locks++;
290 	}
291 
292 	return (rval);
293 }
294 
295 void
296 _sx_sunlock(struct sx *sx, const char *file, int line)
297 {
298 
299 	MPASS(curthread != NULL);
300 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
301 	    ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
302 	_sx_assert(sx, SA_SLOCKED, file, line);
303 	curthread->td_locks--;
304 	WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
305 	LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
306 	__sx_sunlock(sx, file, line);
307 	lock_profile_release_lock(&sx->lock_object);
308 }
309 
310 void
311 _sx_xunlock(struct sx *sx, const char *file, int line)
312 {
313 
314 	MPASS(curthread != NULL);
315 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
316 	    ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
317 	_sx_assert(sx, SA_XLOCKED, file, line);
318 	curthread->td_locks--;
319 	WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
320 	LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
321 	    line);
322 	if (!sx_recursed(sx))
323 		lock_profile_release_lock(&sx->lock_object);
324 	__sx_xunlock(sx, curthread, file, line);
325 }
326 
327 /*
328  * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
329  * This will only succeed if this thread holds a single shared lock.
330  * Return 1 if if the upgrade succeed, 0 otherwise.
331  */
332 int
333 _sx_try_upgrade(struct sx *sx, const char *file, int line)
334 {
335 	uintptr_t x;
336 	int success;
337 
338 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
339 	    ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
340 	_sx_assert(sx, SA_SLOCKED, file, line);
341 
342 	/*
343 	 * Try to switch from one shared lock to an exclusive lock.  We need
344 	 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
345 	 * we will wake up the exclusive waiters when we drop the lock.
346 	 */
347 	x = sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS;
348 	success = atomic_cmpset_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) | x,
349 	    (uintptr_t)curthread | x);
350 	LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
351 	if (success)
352 		WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
353 		    file, line);
354 	return (success);
355 }
356 
357 /*
358  * Downgrade an unrecursed exclusive lock into a single shared lock.
359  */
360 void
361 _sx_downgrade(struct sx *sx, const char *file, int line)
362 {
363 	uintptr_t x;
364 
365 	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
366 	    ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
367 	_sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
368 #ifndef INVARIANTS
369 	if (sx_recursed(sx))
370 		panic("downgrade of a recursed lock");
371 #endif
372 
373 	WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
374 
375 	/*
376 	 * Try to switch from an exclusive lock with no shared waiters
377 	 * to one sharer with no shared waiters.  If there are
378 	 * exclusive waiters, we don't need to lock the sleep queue so
379 	 * long as we preserve the flag.  We do one quick try and if
380 	 * that fails we grab the sleepq lock to keep the flags from
381 	 * changing and do it the slow way.
382 	 *
383 	 * We have to lock the sleep queue if there are shared waiters
384 	 * so we can wake them up.
385 	 */
386 	x = sx->sx_lock;
387 	if (!(x & SX_LOCK_SHARED_WAITERS) &&
388 	    atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
389 	    (x & SX_LOCK_EXCLUSIVE_WAITERS))) {
390 		LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
391 		return;
392 	}
393 
394 	/*
395 	 * Lock the sleep queue so we can read the waiters bits
396 	 * without any races and wakeup any shared waiters.
397 	 */
398 	sleepq_lock(&sx->lock_object);
399 
400 	/*
401 	 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
402 	 * shared lock.  If there are any shared waiters, wake them up.
403 	 */
404 	x = sx->sx_lock;
405 	atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
406 	    (x & SX_LOCK_EXCLUSIVE_WAITERS));
407 	if (x & SX_LOCK_SHARED_WAITERS)
408 		sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
409 		    SQ_SHARED_QUEUE);
410 	sleepq_release(&sx->lock_object);
411 
412 	LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
413 }
414 
415 /*
416  * This function represents the so-called 'hard case' for sx_xlock
417  * operation.  All 'easy case' failures are redirected to this.  Note
418  * that ideally this would be a static function, but it needs to be
419  * accessible from at least sx.h.
420  */
421 int
422 _sx_xlock_hard(struct sx *sx, uintptr_t tid, int opts, const char *file,
423     int line)
424 {
425 	GIANT_DECLARE;
426 #ifdef ADAPTIVE_SX
427 	volatile struct thread *owner;
428 #endif
429 	uint64_t waittime = 0;
430 	uintptr_t x;
431 	int contested = 0, error = 0;
432 
433 	/* If we already hold an exclusive lock, then recurse. */
434 	if (sx_xlocked(sx)) {
435 		KASSERT((sx->lock_object.lo_flags & SX_RECURSE) != 0,
436 	    ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
437 		    sx->lock_object.lo_name, file, line));
438 		sx->sx_recurse++;
439 		atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
440 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
441 			CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
442 		return (0);
443 	}
444 
445 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
446 		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
447 		    sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
448 
449 	while (!atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED, tid)) {
450 		lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
451 		    &waittime);
452 #ifdef ADAPTIVE_SX
453 		/*
454 		 * If the lock is write locked and the owner is
455 		 * running on another CPU, spin until the owner stops
456 		 * running or the state of the lock changes.
457 		 */
458 		x = sx->sx_lock;
459 		if (!(x & SX_LOCK_SHARED) &&
460 		    (sx->lock_object.lo_flags & SX_ADAPTIVESPIN)) {
461 			x = SX_OWNER(x);
462 			owner = (struct thread *)x;
463 			if (TD_IS_RUNNING(owner)) {
464 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
465 					CTR3(KTR_LOCK,
466 					    "%s: spinning on %p held by %p",
467 					    __func__, sx, owner);
468 				GIANT_SAVE();
469 				while (SX_OWNER(sx->sx_lock) == x &&
470 				    TD_IS_RUNNING(owner))
471 					cpu_spinwait();
472 				continue;
473 			}
474 		}
475 #endif
476 
477 		sleepq_lock(&sx->lock_object);
478 		x = sx->sx_lock;
479 
480 		/*
481 		 * If the lock was released while spinning on the
482 		 * sleep queue chain lock, try again.
483 		 */
484 		if (x == SX_LOCK_UNLOCKED) {
485 			sleepq_release(&sx->lock_object);
486 			continue;
487 		}
488 
489 #ifdef ADAPTIVE_SX
490 		/*
491 		 * The current lock owner might have started executing
492 		 * on another CPU (or the lock could have changed
493 		 * owners) while we were waiting on the sleep queue
494 		 * chain lock.  If so, drop the sleep queue lock and try
495 		 * again.
496 		 */
497 		if (!(x & SX_LOCK_SHARED) &&
498 		    (sx->lock_object.lo_flags & SX_ADAPTIVESPIN)) {
499 			owner = (struct thread *)SX_OWNER(x);
500 			if (TD_IS_RUNNING(owner)) {
501 				sleepq_release(&sx->lock_object);
502 				continue;
503 			}
504 		}
505 #endif
506 
507 		/*
508 		 * If an exclusive lock was released with both shared
509 		 * and exclusive waiters and a shared waiter hasn't
510 		 * woken up and acquired the lock yet, sx_lock will be
511 		 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
512 		 * If we see that value, try to acquire it once.  Note
513 		 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
514 		 * as there are other exclusive waiters still.  If we
515 		 * fail, restart the loop.
516 		 */
517 		if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
518 			if (atomic_cmpset_acq_ptr(&sx->sx_lock,
519 			    SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
520 			    tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
521 				sleepq_release(&sx->lock_object);
522 				CTR2(KTR_LOCK, "%s: %p claimed by new writer",
523 				    __func__, sx);
524 				break;
525 			}
526 			sleepq_release(&sx->lock_object);
527 			continue;
528 		}
529 
530 		/*
531 		 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
532 		 * than loop back and retry.
533 		 */
534 		if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
535 			if (!atomic_cmpset_ptr(&sx->sx_lock, x,
536 			    x | SX_LOCK_EXCLUSIVE_WAITERS)) {
537 				sleepq_release(&sx->lock_object);
538 				continue;
539 			}
540 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
541 				CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
542 				    __func__, sx);
543 		}
544 
545 		/*
546 		 * Since we have been unable to acquire the exclusive
547 		 * lock and the exclusive waiters flag is set, we have
548 		 * to sleep.
549 		 */
550 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
551 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
552 			    __func__, sx);
553 
554 		GIANT_SAVE();
555 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
556 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
557 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
558 		if (!(opts & SX_INTERRUPTIBLE))
559 			sleepq_wait(&sx->lock_object, 0);
560 		else
561 			error = sleepq_wait_sig(&sx->lock_object, 0);
562 
563 		if (error) {
564 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
565 				CTR2(KTR_LOCK,
566 			"%s: interruptible sleep by %p suspended by signal",
567 				    __func__, sx);
568 			break;
569 		}
570 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
571 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
572 			    __func__, sx);
573 	}
574 
575 	GIANT_RESTORE();
576 	if (!error)
577 		lock_profile_obtain_lock_success(&sx->lock_object, contested,
578 		    waittime, file, line);
579 	return (error);
580 }
581 
582 /*
583  * This function represents the so-called 'hard case' for sx_xunlock
584  * operation.  All 'easy case' failures are redirected to this.  Note
585  * that ideally this would be a static function, but it needs to be
586  * accessible from at least sx.h.
587  */
588 void
589 _sx_xunlock_hard(struct sx *sx, uintptr_t tid, const char *file, int line)
590 {
591 	uintptr_t x;
592 	int queue;
593 
594 	MPASS(!(sx->sx_lock & SX_LOCK_SHARED));
595 
596 	/* If the lock is recursed, then unrecurse one level. */
597 	if (sx_xlocked(sx) && sx_recursed(sx)) {
598 		if ((--sx->sx_recurse) == 0)
599 			atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
600 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
601 			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
602 		return;
603 	}
604 	MPASS(sx->sx_lock & (SX_LOCK_SHARED_WAITERS |
605 	    SX_LOCK_EXCLUSIVE_WAITERS));
606 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
607 		CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
608 
609 	sleepq_lock(&sx->lock_object);
610 	x = SX_LOCK_UNLOCKED;
611 
612 	/*
613 	 * The wake up algorithm here is quite simple and probably not
614 	 * ideal.  It gives precedence to shared waiters if they are
615 	 * present.  For this condition, we have to preserve the
616 	 * state of the exclusive waiters flag.
617 	 */
618 	if (sx->sx_lock & SX_LOCK_SHARED_WAITERS) {
619 		queue = SQ_SHARED_QUEUE;
620 		x |= (sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS);
621 	} else
622 		queue = SQ_EXCLUSIVE_QUEUE;
623 
624 	/* Wake up all the waiters for the specific queue. */
625 	if (LOCK_LOG_TEST(&sx->lock_object, 0))
626 		CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
627 		    __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
628 		    "exclusive");
629 	atomic_store_rel_ptr(&sx->sx_lock, x);
630 	sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0, queue);
631 	sleepq_release(&sx->lock_object);
632 }
633 
634 /*
635  * This function represents the so-called 'hard case' for sx_slock
636  * operation.  All 'easy case' failures are redirected to this.  Note
637  * that ideally this would be a static function, but it needs to be
638  * accessible from at least sx.h.
639  */
640 int
641 _sx_slock_hard(struct sx *sx, int opts, const char *file, int line)
642 {
643 	GIANT_DECLARE;
644 #ifdef ADAPTIVE_SX
645 	volatile struct thread *owner;
646 #endif
647 	uint64_t waittime = 0;
648 	int contested = 0;
649 	uintptr_t x;
650 	int error = 0;
651 
652 	/*
653 	 * As with rwlocks, we don't make any attempt to try to block
654 	 * shared locks once there is an exclusive waiter.
655 	 */
656 	for (;;) {
657 		x = sx->sx_lock;
658 
659 		/*
660 		 * If no other thread has an exclusive lock then try to bump up
661 		 * the count of sharers.  Since we have to preserve the state
662 		 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
663 		 * shared lock loop back and retry.
664 		 */
665 		if (x & SX_LOCK_SHARED) {
666 			MPASS(!(x & SX_LOCK_SHARED_WAITERS));
667 			if (atomic_cmpset_acq_ptr(&sx->sx_lock, x,
668 			    x + SX_ONE_SHARER)) {
669 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
670 					CTR4(KTR_LOCK,
671 					    "%s: %p succeed %p -> %p", __func__,
672 					    sx, (void *)x,
673 					    (void *)(x + SX_ONE_SHARER));
674 				break;
675 			}
676 			continue;
677 		}
678 		lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
679 		    &waittime);
680 
681 #ifdef ADAPTIVE_SX
682 		/*
683 		 * If the owner is running on another CPU, spin until
684 		 * the owner stops running or the state of the lock
685 		 * changes.
686 		 */
687 		if (sx->lock_object.lo_flags & SX_ADAPTIVESPIN) {
688 			x = SX_OWNER(x);
689 			owner = (struct thread *)x;
690 			if (TD_IS_RUNNING(owner)) {
691 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
692 					CTR3(KTR_LOCK,
693 					    "%s: spinning on %p held by %p",
694 					    __func__, sx, owner);
695 				GIANT_SAVE();
696 				while (SX_OWNER(sx->sx_lock) == x &&
697 				    TD_IS_RUNNING(owner))
698 					cpu_spinwait();
699 				continue;
700 			}
701 		}
702 #endif
703 
704 		/*
705 		 * Some other thread already has an exclusive lock, so
706 		 * start the process of blocking.
707 		 */
708 		sleepq_lock(&sx->lock_object);
709 		x = sx->sx_lock;
710 
711 		/*
712 		 * The lock could have been released while we spun.
713 		 * In this case loop back and retry.
714 		 */
715 		if (x & SX_LOCK_SHARED) {
716 			sleepq_release(&sx->lock_object);
717 			continue;
718 		}
719 
720 #ifdef ADAPTIVE_SX
721 		/*
722 		 * If the owner is running on another CPU, spin until
723 		 * the owner stops running or the state of the lock
724 		 * changes.
725 		 */
726 		if (!(x & SX_LOCK_SHARED) &&
727 		    (sx->lock_object.lo_flags & SX_ADAPTIVESPIN)) {
728 			owner = (struct thread *)SX_OWNER(x);
729 			if (TD_IS_RUNNING(owner)) {
730 				sleepq_release(&sx->lock_object);
731 				continue;
732 			}
733 		}
734 #endif
735 
736 		/*
737 		 * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
738 		 * fail to set it drop the sleep queue lock and loop
739 		 * back.
740 		 */
741 		if (!(x & SX_LOCK_SHARED_WAITERS)) {
742 			if (!atomic_cmpset_ptr(&sx->sx_lock, x,
743 			    x | SX_LOCK_SHARED_WAITERS)) {
744 				sleepq_release(&sx->lock_object);
745 				continue;
746 			}
747 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
748 				CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
749 				    __func__, sx);
750 		}
751 
752 		/*
753 		 * Since we have been unable to acquire the shared lock,
754 		 * we have to sleep.
755 		 */
756 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
757 			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
758 			    __func__, sx);
759 
760 		GIANT_SAVE();
761 		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
762 		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
763 		    SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
764 		if (!(opts & SX_INTERRUPTIBLE))
765 			sleepq_wait(&sx->lock_object, 0);
766 		else
767 			error = sleepq_wait_sig(&sx->lock_object, 0);
768 
769 		if (error) {
770 			if (LOCK_LOG_TEST(&sx->lock_object, 0))
771 				CTR2(KTR_LOCK,
772 			"%s: interruptible sleep by %p suspended by signal",
773 				    __func__, sx);
774 			break;
775 		}
776 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
777 			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
778 			    __func__, sx);
779 	}
780 	if (error == 0)
781 		lock_profile_obtain_lock_success(&sx->lock_object, contested,
782 		    waittime, file, line);
783 
784 	GIANT_RESTORE();
785 	return (error);
786 }
787 
788 /*
789  * This function represents the so-called 'hard case' for sx_sunlock
790  * operation.  All 'easy case' failures are redirected to this.  Note
791  * that ideally this would be a static function, but it needs to be
792  * accessible from at least sx.h.
793  */
794 void
795 _sx_sunlock_hard(struct sx *sx, const char *file, int line)
796 {
797 	uintptr_t x;
798 
799 	for (;;) {
800 		x = sx->sx_lock;
801 
802 		/*
803 		 * We should never have sharers while at least one thread
804 		 * holds a shared lock.
805 		 */
806 		KASSERT(!(x & SX_LOCK_SHARED_WAITERS),
807 		    ("%s: waiting sharers", __func__));
808 
809 		/*
810 		 * See if there is more than one shared lock held.  If
811 		 * so, just drop one and return.
812 		 */
813 		if (SX_SHARERS(x) > 1) {
814 			if (atomic_cmpset_ptr(&sx->sx_lock, x,
815 			    x - SX_ONE_SHARER)) {
816 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
817 					CTR4(KTR_LOCK,
818 					    "%s: %p succeeded %p -> %p",
819 					    __func__, sx, (void *)x,
820 					    (void *)(x - SX_ONE_SHARER));
821 				break;
822 			}
823 			continue;
824 		}
825 
826 		/*
827 		 * If there aren't any waiters for an exclusive lock,
828 		 * then try to drop it quickly.
829 		 */
830 		if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
831 			MPASS(x == SX_SHARERS_LOCK(1));
832 			if (atomic_cmpset_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1),
833 			    SX_LOCK_UNLOCKED)) {
834 				if (LOCK_LOG_TEST(&sx->lock_object, 0))
835 					CTR2(KTR_LOCK, "%s: %p last succeeded",
836 					    __func__, sx);
837 				break;
838 			}
839 			continue;
840 		}
841 
842 		/*
843 		 * At this point, there should just be one sharer with
844 		 * exclusive waiters.
845 		 */
846 		MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
847 
848 		sleepq_lock(&sx->lock_object);
849 
850 		/*
851 		 * Wake up semantic here is quite simple:
852 		 * Just wake up all the exclusive waiters.
853 		 * Note that the state of the lock could have changed,
854 		 * so if it fails loop back and retry.
855 		 */
856 		if (!atomic_cmpset_ptr(&sx->sx_lock,
857 		    SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
858 		    SX_LOCK_UNLOCKED)) {
859 			sleepq_release(&sx->lock_object);
860 			continue;
861 		}
862 		if (LOCK_LOG_TEST(&sx->lock_object, 0))
863 			CTR2(KTR_LOCK, "%s: %p waking up all thread on"
864 			    "exclusive queue", __func__, sx);
865 		sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
866 		    SQ_EXCLUSIVE_QUEUE);
867 		sleepq_release(&sx->lock_object);
868 		break;
869 	}
870 }
871 
872 #ifdef INVARIANT_SUPPORT
873 #ifndef INVARIANTS
874 #undef	_sx_assert
875 #endif
876 
877 /*
878  * In the non-WITNESS case, sx_assert() can only detect that at least
879  * *some* thread owns an slock, but it cannot guarantee that *this*
880  * thread owns an slock.
881  */
882 void
883 _sx_assert(struct sx *sx, int what, const char *file, int line)
884 {
885 #ifndef WITNESS
886 	int slocked = 0;
887 #endif
888 
889 	if (panicstr != NULL)
890 		return;
891 	switch (what) {
892 	case SA_SLOCKED:
893 	case SA_SLOCKED | SA_NOTRECURSED:
894 	case SA_SLOCKED | SA_RECURSED:
895 #ifndef WITNESS
896 		slocked = 1;
897 		/* FALLTHROUGH */
898 #endif
899 	case SA_LOCKED:
900 	case SA_LOCKED | SA_NOTRECURSED:
901 	case SA_LOCKED | SA_RECURSED:
902 #ifdef WITNESS
903 		witness_assert(&sx->lock_object, what, file, line);
904 #else
905 		/*
906 		 * If some other thread has an exclusive lock or we
907 		 * have one and are asserting a shared lock, fail.
908 		 * Also, if no one has a lock at all, fail.
909 		 */
910 		if (sx->sx_lock == SX_LOCK_UNLOCKED ||
911 		    (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
912 		    sx_xholder(sx) != curthread)))
913 			panic("Lock %s not %slocked @ %s:%d\n",
914 			    sx->lock_object.lo_name, slocked ? "share " : "",
915 			    file, line);
916 
917 		if (!(sx->sx_lock & SX_LOCK_SHARED)) {
918 			if (sx_recursed(sx)) {
919 				if (what & SA_NOTRECURSED)
920 					panic("Lock %s recursed @ %s:%d\n",
921 					    sx->lock_object.lo_name, file,
922 					    line);
923 			} else if (what & SA_RECURSED)
924 				panic("Lock %s not recursed @ %s:%d\n",
925 				    sx->lock_object.lo_name, file, line);
926 		}
927 #endif
928 		break;
929 	case SA_XLOCKED:
930 	case SA_XLOCKED | SA_NOTRECURSED:
931 	case SA_XLOCKED | SA_RECURSED:
932 		if (sx_xholder(sx) != curthread)
933 			panic("Lock %s not exclusively locked @ %s:%d\n",
934 			    sx->lock_object.lo_name, file, line);
935 		if (sx_recursed(sx)) {
936 			if (what & SA_NOTRECURSED)
937 				panic("Lock %s recursed @ %s:%d\n",
938 				    sx->lock_object.lo_name, file, line);
939 		} else if (what & SA_RECURSED)
940 			panic("Lock %s not recursed @ %s:%d\n",
941 			    sx->lock_object.lo_name, file, line);
942 		break;
943 	case SA_UNLOCKED:
944 #ifdef WITNESS
945 		witness_assert(&sx->lock_object, what, file, line);
946 #else
947 		/*
948 		 * If we hold an exclusve lock fail.  We can't
949 		 * reliably check to see if we hold a shared lock or
950 		 * not.
951 		 */
952 		if (sx_xholder(sx) == curthread)
953 			panic("Lock %s exclusively locked @ %s:%d\n",
954 			    sx->lock_object.lo_name, file, line);
955 #endif
956 		break;
957 	default:
958 		panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
959 		    line);
960 	}
961 }
962 #endif	/* INVARIANT_SUPPORT */
963 
964 #ifdef DDB
965 static void
966 db_show_sx(struct lock_object *lock)
967 {
968 	struct thread *td;
969 	struct sx *sx;
970 
971 	sx = (struct sx *)lock;
972 
973 	db_printf(" state: ");
974 	if (sx->sx_lock == SX_LOCK_UNLOCKED)
975 		db_printf("UNLOCKED\n");
976 	else if (sx->sx_lock == SX_LOCK_DESTROYED) {
977 		db_printf("DESTROYED\n");
978 		return;
979 	} else if (sx->sx_lock & SX_LOCK_SHARED)
980 		db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
981 	else {
982 		td = sx_xholder(sx);
983 		db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
984 		    td->td_tid, td->td_proc->p_pid, td->td_name);
985 		if (sx_recursed(sx))
986 			db_printf(" recursed: %d\n", sx->sx_recurse);
987 	}
988 
989 	db_printf(" waiters: ");
990 	switch(sx->sx_lock &
991 	    (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
992 	case SX_LOCK_SHARED_WAITERS:
993 		db_printf("shared\n");
994 		break;
995 	case SX_LOCK_EXCLUSIVE_WAITERS:
996 		db_printf("exclusive\n");
997 		break;
998 	case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
999 		db_printf("exclusive and shared\n");
1000 		break;
1001 	default:
1002 		db_printf("none\n");
1003 	}
1004 }
1005 
1006 /*
1007  * Check to see if a thread that is blocked on a sleep queue is actually
1008  * blocked on an sx lock.  If so, output some details and return true.
1009  * If the lock has an exclusive owner, return that in *ownerp.
1010  */
1011 int
1012 sx_chain(struct thread *td, struct thread **ownerp)
1013 {
1014 	struct sx *sx;
1015 
1016 	/*
1017 	 * Check to see if this thread is blocked on an sx lock.
1018 	 * First, we check the lock class.  If that is ok, then we
1019 	 * compare the lock name against the wait message.
1020 	 */
1021 	sx = td->td_wchan;
1022 	if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1023 	    sx->lock_object.lo_name != td->td_wmesg)
1024 		return (0);
1025 
1026 	/* We think we have an sx lock, so output some details. */
1027 	db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1028 	*ownerp = sx_xholder(sx);
1029 	if (sx->sx_lock & SX_LOCK_SHARED)
1030 		db_printf("SLOCK (count %ju)\n",
1031 		    (uintmax_t)SX_SHARERS(sx->sx_lock));
1032 	else
1033 		db_printf("XLOCK\n");
1034 	return (1);
1035 }
1036 #endif
1037