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