2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2007 Attilio Rao <attilio@freebsd.org>
5 * Copyright (c) 2001 Jason Evans <jasone@freebsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
33 * Shared/exclusive locks. This implementation attempts to ensure
34 * deterministic lock granting behavior, so that slocks and xlocks are
37 * Priority propagation will not generally raise the priority of lock holders,
38 * so should not be relied upon in combination with sx locks.
42 #include "opt_hwpmc_hooks.h"
43 #include "opt_no_adaptive_sx.h"
45 #include <sys/cdefs.h>
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/kernel.h>
52 #include <sys/mutex.h>
54 #include <sys/sched.h>
55 #include <sys/sleepqueue.h>
58 #include <sys/sysctl.h>
60 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
61 #include <machine/cpu.h>
68 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
73 #include <sys/pmckern.h>
74 PMC_SOFT_DECLARE( , , lock, failed);
77 /* Handy macros for sleep queues. */
78 #define SQ_EXCLUSIVE_QUEUE 0
79 #define SQ_SHARED_QUEUE 1
82 * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file. We
83 * drop Giant anytime we have to sleep or if we adaptively spin.
85 #define GIANT_DECLARE \
87 WITNESS_SAVE_DECL(Giant) \
89 #define GIANT_SAVE(work) do { \
90 if (__predict_false(mtx_owned(&Giant))) { \
92 WITNESS_SAVE(&Giant.lock_object, Giant); \
93 while (mtx_owned(&Giant)) { \
100 #define GIANT_RESTORE() do { \
101 if (_giantcnt > 0) { \
102 mtx_assert(&Giant, MA_NOTOWNED); \
103 while (_giantcnt--) \
105 WITNESS_RESTORE(&Giant.lock_object, Giant); \
110 * Returns true if an exclusive lock is recursed. It assumes
111 * curthread currently has an exclusive lock.
113 #define sx_recursed(sx) ((sx)->sx_recurse != 0)
115 static void assert_sx(const struct lock_object *lock, int what);
117 static void db_show_sx(const struct lock_object *lock);
119 static void lock_sx(struct lock_object *lock, uintptr_t how);
121 static int owner_sx(const struct lock_object *lock, struct thread **owner);
123 static uintptr_t unlock_sx(struct lock_object *lock);
125 struct lock_class lock_class_sx = {
127 .lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
128 .lc_assert = assert_sx,
130 .lc_ddb_show = db_show_sx,
133 .lc_unlock = unlock_sx,
135 .lc_owner = owner_sx,
140 #define _sx_assert(sx, what, file, line)
144 #ifdef SX_CUSTOM_BACKOFF
145 static u_short __read_frequently asx_retries;
146 static u_short __read_frequently asx_loops;
147 static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
149 SYSCTL_U16(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
150 SYSCTL_U16(_debug_sx, OID_AUTO, loops, CTLFLAG_RW, &asx_loops, 0, "");
152 static struct lock_delay_config __read_frequently sx_delay;
154 SYSCTL_U16(_debug_sx, OID_AUTO, delay_base, CTLFLAG_RW, &sx_delay.base,
156 SYSCTL_U16(_debug_sx, OID_AUTO, delay_max, CTLFLAG_RW, &sx_delay.max,
160 sx_lock_delay_init(void *arg __unused)
163 lock_delay_default_init(&sx_delay);
165 asx_loops = max(10000, sx_delay.max);
167 LOCK_DELAY_SYSINIT(sx_lock_delay_init);
169 #define sx_delay locks_delay
170 #define asx_retries locks_delay_retries
171 #define asx_loops locks_delay_loops
176 assert_sx(const struct lock_object *lock, int what)
179 sx_assert((const struct sx *)lock, what);
183 lock_sx(struct lock_object *lock, uintptr_t how)
187 sx = (struct sx *)lock;
195 unlock_sx(struct lock_object *lock)
199 sx = (struct sx *)lock;
200 sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
201 if (sx_xlocked(sx)) {
212 owner_sx(const struct lock_object *lock, struct thread **owner)
217 sx = (const struct sx *)lock;
220 return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
221 ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
226 sx_sysinit(void *arg)
228 struct sx_args *sargs = arg;
230 sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
234 sx_init_flags(struct sx *sx, const char *description, int opts)
238 MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
239 SX_NOPROFILE | SX_NEW)) == 0);
240 ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
241 ("%s: sx_lock not aligned for %s: %p", __func__, description,
244 flags = LO_SLEEPABLE | LO_UPGRADABLE;
247 if (opts & SX_NOPROFILE)
248 flags |= LO_NOPROFILE;
249 if (!(opts & SX_NOWITNESS))
251 if (opts & SX_RECURSE)
252 flags |= LO_RECURSABLE;
258 lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
259 sx->sx_lock = SX_LOCK_UNLOCKED;
264 sx_destroy(struct sx *sx)
267 KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
268 KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
269 sx->sx_lock = SX_LOCK_DESTROYED;
270 lock_destroy(&sx->lock_object);
274 sx_try_slock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
278 if (SCHEDULER_STOPPED())
281 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
282 ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
283 curthread, sx->lock_object.lo_name, file, line));
287 KASSERT(x != SX_LOCK_DESTROYED,
288 ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
289 if (!(x & SX_LOCK_SHARED))
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++;
302 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
307 sx_try_slock_(struct sx *sx, const char *file, int line)
310 return (sx_try_slock_int(sx LOCK_FILE_LINE_ARG));
314 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
319 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
320 !TD_IS_IDLETHREAD(curthread),
321 ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
322 curthread, sx->lock_object.lo_name, file, line));
323 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
324 ("sx_xlock() of destroyed sx @ %s:%d", file, line));
325 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
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);
332 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
333 0, 0, file, line, LOCKSTAT_WRITER);
335 LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
337 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
338 TD_LOCKS_INC(curthread);
345 sx_try_xlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
354 if (SCHEDULER_STOPPED_TD(td))
357 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
358 ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
359 curthread, sx->lock_object.lo_name, file, line));
360 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
361 ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
365 x = SX_LOCK_UNLOCKED;
367 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
369 if (x == SX_LOCK_UNLOCKED)
371 if (x == tid && (sx->lock_object.lo_flags & LO_RECURSABLE)) {
373 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
380 LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
382 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
385 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
386 sx, 0, 0, file, line, LOCKSTAT_WRITER);
387 TD_LOCKS_INC(curthread);
394 sx_try_xlock_(struct sx *sx, const char *file, int line)
397 return (sx_try_xlock_int(sx LOCK_FILE_LINE_ARG));
401 _sx_xunlock(struct sx *sx, const char *file, int line)
404 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
405 ("sx_xunlock() of destroyed sx @ %s:%d", 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,
411 _sx_xunlock_hard(sx, (uintptr_t)curthread, file, line);
413 __sx_xunlock(sx, curthread, file, line);
415 TD_LOCKS_DEC(curthread);
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.
424 sx_try_upgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
430 if (SCHEDULER_STOPPED())
433 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
434 ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
435 _sx_assert(sx, SA_SLOCKED, file, line);
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.
443 x = SX_READ_VALUE(sx);
445 if (SX_SHARERS(x) > 1)
447 waiters = (x & SX_LOCK_WAITERS);
448 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
449 (uintptr_t)curthread | waiters)) {
454 LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
456 curthread->td_sx_slocks--;
457 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
459 LOCKSTAT_RECORD0(sx__upgrade, sx);
465 sx_try_upgrade_(struct sx *sx, const char *file, int line)
468 return (sx_try_upgrade_int(sx LOCK_FILE_LINE_ARG));
472 * Downgrade an unrecursed exclusive lock into a single shared lock.
475 sx_downgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
480 if (SCHEDULER_STOPPED())
483 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
484 ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
485 _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
488 panic("downgrade of a recursed lock");
491 WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
494 * Try to switch from an exclusive lock with no shared waiters
495 * to one sharer with no shared waiters. If there are
496 * exclusive waiters, we don't need to lock the sleep queue so
497 * long as we preserve the flag. We do one quick try and if
498 * that fails we grab the sleepq lock to keep the flags from
499 * changing and do it the slow way.
501 * We have to lock the sleep queue if there are shared waiters
502 * so we can wake them up.
505 if (!(x & SX_LOCK_SHARED_WAITERS) &&
506 atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
507 (x & SX_LOCK_EXCLUSIVE_WAITERS)))
511 * Lock the sleep queue so we can read the waiters bits
512 * without any races and wakeup any shared waiters.
514 sleepq_lock(&sx->lock_object);
517 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
518 * shared lock. If there are any shared waiters, wake them up.
522 atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
523 (x & SX_LOCK_EXCLUSIVE_WAITERS));
524 if (x & SX_LOCK_SHARED_WAITERS)
525 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
527 sleepq_release(&sx->lock_object);
533 curthread->td_sx_slocks++;
534 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
535 LOCKSTAT_RECORD0(sx__downgrade, sx);
539 sx_downgrade_(struct sx *sx, const char *file, int line)
542 sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
547 sx_drop_critical(uintptr_t x, bool *in_critical, int *extra_work)
550 if (x & SX_LOCK_WRITE_SPINNER)
554 *in_critical = false;
559 #define sx_drop_critical(x, in_critical, extra_work) do { } while(0)
563 * This function represents the so-called 'hard case' for sx_xlock
564 * operation. All 'easy case' failures are redirected to this. Note
565 * that ideally this would be a static function, but it needs to be
566 * accessible from at least sx.h.
569 _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
574 struct thread *owner;
575 u_int i, n, spintries = 0;
576 enum { READERS, WRITER } sleep_reason = READERS;
577 bool in_critical = false;
579 #ifdef LOCK_PROFILING
580 uint64_t waittime = 0;
584 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
585 struct lock_delay_arg lda;
589 int64_t sleep_time = 0;
590 int64_t all_time = 0;
592 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
594 int doing_lockprof = 0;
598 tid = (uintptr_t)curthread;
601 if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
602 while (x == SX_LOCK_UNLOCKED) {
603 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
608 all_time -= lockstat_nsecs(&sx->lock_object);
612 #ifdef LOCK_PROFILING
618 if (SCHEDULER_STOPPED())
621 if (__predict_false(x == SX_LOCK_UNLOCKED))
622 x = SX_READ_VALUE(sx);
624 /* If we already hold an exclusive lock, then recurse. */
625 if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
626 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
627 ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
628 sx->lock_object.lo_name, file, line));
630 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
631 if (LOCK_LOG_TEST(&sx->lock_object, 0))
632 CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
636 if (LOCK_LOG_TEST(&sx->lock_object, 0))
637 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
638 sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
640 #if defined(ADAPTIVE_SX)
641 lock_delay_arg_init(&lda, &sx_delay);
642 #elif defined(KDTRACE_HOOKS)
643 lock_delay_arg_init_noadapt(&lda);
647 PMC_SOFT_CALL( , , lock, failed);
649 lock_profile_obtain_lock_failed(&sx->lock_object, false, &contested,
653 GIANT_SAVE(extra_work);
657 if (x == SX_LOCK_UNLOCKED) {
658 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
663 GIANT_SAVE(extra_work);
669 if (x == (SX_LOCK_SHARED | SX_LOCK_WRITE_SPINNER)) {
670 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
676 * If the lock is write locked and the owner is
677 * running on another CPU, spin until the owner stops
678 * running or the state of the lock changes.
680 if ((x & SX_LOCK_SHARED) == 0) {
681 sx_drop_critical(x, &in_critical, &extra_work);
682 sleep_reason = WRITER;
683 owner = lv_sx_owner(x);
684 if (!TD_IS_RUNNING(owner))
686 if (LOCK_LOG_TEST(&sx->lock_object, 0))
687 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
688 __func__, sx, owner);
689 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
690 "spinning", "lockname:\"%s\"",
691 sx->lock_object.lo_name);
694 x = SX_READ_VALUE(sx);
695 owner = lv_sx_owner(x);
696 } while (owner != NULL && TD_IS_RUNNING(owner));
697 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
700 } else if (SX_SHARERS(x) > 0) {
701 sleep_reason = READERS;
702 if (spintries == asx_retries)
704 if (!(x & SX_LOCK_WRITE_SPINNER)) {
710 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
711 x | SX_LOCK_WRITE_SPINNER)) {
719 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
720 "spinning", "lockname:\"%s\"",
721 sx->lock_object.lo_name);
723 for (i = 0; i < asx_loops; i += n) {
725 x = SX_READ_VALUE(sx);
726 if (!(x & SX_LOCK_WRITE_SPINNER))
728 if (!(x & SX_LOCK_SHARED))
737 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
744 sleepq_lock(&sx->lock_object);
745 x = SX_READ_VALUE(sx);
749 * If the lock was released while spinning on the
750 * sleep queue chain lock, try again.
752 if (x == SX_LOCK_UNLOCKED) {
753 sleepq_release(&sx->lock_object);
754 sx_drop_critical(x, &in_critical, &extra_work);
760 * The current lock owner might have started executing
761 * on another CPU (or the lock could have changed
762 * owners) while we were waiting on the sleep queue
763 * chain lock. If so, drop the sleep queue lock and try
766 if (!(x & SX_LOCK_SHARED)) {
767 owner = (struct thread *)SX_OWNER(x);
768 if (TD_IS_RUNNING(owner)) {
769 sleepq_release(&sx->lock_object);
770 sx_drop_critical(x, &in_critical,
774 } else if (SX_SHARERS(x) > 0 && sleep_reason == WRITER) {
775 sleepq_release(&sx->lock_object);
776 sx_drop_critical(x, &in_critical, &extra_work);
782 * If an exclusive lock was released with both shared
783 * and exclusive waiters and a shared waiter hasn't
784 * woken up and acquired the lock yet, sx_lock will be
785 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
786 * If we see that value, try to acquire it once. Note
787 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
788 * as there are other exclusive waiters still. If we
789 * fail, restart the loop.
791 setx = x & (SX_LOCK_WAITERS | SX_LOCK_WRITE_SPINNER);
792 if ((x & ~setx) == SX_LOCK_SHARED) {
793 setx &= ~SX_LOCK_WRITE_SPINNER;
794 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid | setx))
796 sleepq_release(&sx->lock_object);
797 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
804 * It is possible we set the SX_LOCK_WRITE_SPINNER bit.
805 * It is an invariant that when the bit is set, there is
806 * a writer ready to grab the lock. Thus clear the bit since
807 * we are going to sleep.
810 if ((x & SX_LOCK_WRITE_SPINNER) ||
811 !((x & SX_LOCK_EXCLUSIVE_WAITERS))) {
812 setx = x & ~SX_LOCK_WRITE_SPINNER;
813 setx |= SX_LOCK_EXCLUSIVE_WAITERS;
814 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
824 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
825 * than loop back and retry.
827 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
828 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
829 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
832 if (LOCK_LOG_TEST(&sx->lock_object, 0))
833 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
841 * Since we have been unable to acquire the exclusive
842 * lock and the exclusive waiters flag is set, we have
845 if (LOCK_LOG_TEST(&sx->lock_object, 0))
846 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
850 sleep_time -= lockstat_nsecs(&sx->lock_object);
852 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
853 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
854 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
855 if (!(opts & SX_INTERRUPTIBLE))
856 sleepq_wait(&sx->lock_object, 0);
858 error = sleepq_wait_sig(&sx->lock_object, 0);
860 sleep_time += lockstat_nsecs(&sx->lock_object);
864 if (LOCK_LOG_TEST(&sx->lock_object, 0))
866 "%s: interruptible sleep by %p suspended by signal",
870 if (LOCK_LOG_TEST(&sx->lock_object, 0))
871 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
873 x = SX_READ_VALUE(sx);
875 if (__predict_true(!extra_work))
882 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
883 if (__predict_true(!doing_lockprof))
887 all_time += lockstat_nsecs(&sx->lock_object);
889 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
890 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
891 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
892 if (lda.spin_cnt > sleep_cnt)
893 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
894 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
895 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
899 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
900 contested, waittime, file, line, LOCKSTAT_WRITER);
905 * This function represents the so-called 'hard case' for sx_xunlock
906 * operation. All 'easy case' failures are redirected to this. Note
907 * that ideally this would be a static function, but it needs to be
908 * accessible from at least sx.h.
911 _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
914 int queue, wakeup_swapper;
916 if (SCHEDULER_STOPPED())
919 tid = (uintptr_t)curthread;
921 if (__predict_false(x == tid))
922 x = SX_READ_VALUE(sx);
924 MPASS(!(x & SX_LOCK_SHARED));
926 if (__predict_false(x & SX_LOCK_RECURSED)) {
927 /* The lock is recursed, unrecurse one level. */
928 if ((--sx->sx_recurse) == 0)
929 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
930 if (LOCK_LOG_TEST(&sx->lock_object, 0))
931 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
935 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
937 atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
940 if (LOCK_LOG_TEST(&sx->lock_object, 0))
941 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
943 sleepq_lock(&sx->lock_object);
944 x = SX_READ_VALUE(sx);
945 MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
948 * The wake up algorithm here is quite simple and probably not
949 * ideal. It gives precedence to shared waiters if they are
950 * present. For this condition, we have to preserve the
951 * state of the exclusive waiters flag.
952 * If interruptible sleeps left the shared queue empty avoid a
953 * starvation for the threads sleeping on the exclusive queue by giving
954 * them precedence and cleaning up the shared waiters bit anyway.
956 setx = SX_LOCK_UNLOCKED;
957 queue = SQ_SHARED_QUEUE;
958 if ((x & SX_LOCK_EXCLUSIVE_WAITERS) != 0 &&
959 sleepq_sleepcnt(&sx->lock_object, SQ_EXCLUSIVE_QUEUE) != 0) {
960 queue = SQ_EXCLUSIVE_QUEUE;
961 setx |= (x & SX_LOCK_SHARED_WAITERS);
963 atomic_store_rel_ptr(&sx->sx_lock, setx);
965 /* Wake up all the waiters for the specific queue. */
966 if (LOCK_LOG_TEST(&sx->lock_object, 0))
967 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
968 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
971 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
973 sleepq_release(&sx->lock_object);
978 static bool __always_inline
979 __sx_can_read(struct thread *td, uintptr_t x, bool fp)
982 if ((x & (SX_LOCK_SHARED | SX_LOCK_EXCLUSIVE_WAITERS | SX_LOCK_WRITE_SPINNER))
985 if (!fp && td->td_sx_slocks && (x & SX_LOCK_SHARED))
990 static bool __always_inline
991 __sx_slock_try(struct sx *sx, struct thread *td, uintptr_t *xp, bool fp
992 LOCK_FILE_LINE_ARG_DEF)
996 * If no other thread has an exclusive lock then try to bump up
997 * the count of sharers. Since we have to preserve the state
998 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
999 * shared lock loop back and retry.
1001 while (__sx_can_read(td, *xp, fp)) {
1002 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
1003 *xp + SX_ONE_SHARER)) {
1004 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1005 CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
1006 __func__, sx, (void *)*xp,
1007 (void *)(*xp + SX_ONE_SHARER));
1015 static int __noinline
1016 _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
1021 struct thread *owner;
1022 u_int i, n, spintries = 0;
1024 #ifdef LOCK_PROFILING
1025 uint64_t waittime = 0;
1029 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
1030 struct lock_delay_arg lda;
1032 #ifdef KDTRACE_HOOKS
1033 u_int sleep_cnt = 0;
1034 int64_t sleep_time = 0;
1035 int64_t all_time = 0;
1037 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1038 uintptr_t state = 0;
1044 #ifdef KDTRACE_HOOKS
1045 if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
1046 if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
1049 all_time -= lockstat_nsecs(&sx->lock_object);
1053 #ifdef LOCK_PROFILING
1058 if (SCHEDULER_STOPPED())
1061 #if defined(ADAPTIVE_SX)
1062 lock_delay_arg_init(&lda, &sx_delay);
1063 #elif defined(KDTRACE_HOOKS)
1064 lock_delay_arg_init_noadapt(&lda);
1068 PMC_SOFT_CALL( , , lock, failed);
1070 lock_profile_obtain_lock_failed(&sx->lock_object, false, &contested,
1074 GIANT_SAVE(extra_work);
1078 * As with rwlocks, we don't make any attempt to try to block
1079 * shared locks once there is an exclusive waiter.
1082 if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
1085 GIANT_SAVE(extra_work);
1087 #ifdef KDTRACE_HOOKS
1093 * If the owner is running on another CPU, spin until
1094 * the owner stops running or the state of the lock
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))
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);
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");
1117 if ((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) {
1118 MPASS(!__sx_can_read(td, x, false));
1120 x = SX_READ_VALUE(sx);
1123 if (spintries < asx_retries) {
1124 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1125 "spinning", "lockname:\"%s\"",
1126 sx->lock_object.lo_name);
1128 for (i = 0; i < asx_loops; i += n) {
1130 x = SX_READ_VALUE(sx);
1131 if (!(x & SX_LOCK_SHARED))
1136 if (__sx_can_read(td, x, false))
1139 #ifdef KDTRACE_HOOKS
1142 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1151 * Some other thread already has an exclusive lock, so
1152 * start the process of blocking.
1154 sleepq_lock(&sx->lock_object);
1155 x = SX_READ_VALUE(sx);
1157 if (((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) ||
1158 __sx_can_read(td, x, false)) {
1159 sleepq_release(&sx->lock_object);
1165 * If the owner is running on another CPU, spin until
1166 * the owner stops running or the state of the lock
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);
1180 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
1181 * fail to set it drop the sleep queue lock and loop
1184 if (!(x & SX_LOCK_SHARED_WAITERS)) {
1185 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
1186 x | SX_LOCK_SHARED_WAITERS))
1188 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1189 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1194 * Since we have been unable to acquire the shared lock,
1197 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1198 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1201 #ifdef KDTRACE_HOOKS
1202 sleep_time -= lockstat_nsecs(&sx->lock_object);
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 if (!(opts & SX_INTERRUPTIBLE))
1208 sleepq_wait(&sx->lock_object, 0);
1210 error = sleepq_wait_sig(&sx->lock_object, 0);
1211 #ifdef KDTRACE_HOOKS
1212 sleep_time += lockstat_nsecs(&sx->lock_object);
1216 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1218 "%s: interruptible sleep by %p suspended by signal",
1222 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1223 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1225 x = SX_READ_VALUE(sx);
1227 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1228 if (__predict_true(!extra_work))
1231 #ifdef KDTRACE_HOOKS
1232 all_time += lockstat_nsecs(&sx->lock_object);
1234 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1235 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1236 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1237 if (lda.spin_cnt > sleep_cnt)
1238 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1239 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1240 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1244 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1245 contested, waittime, file, line, LOCKSTAT_READER);
1252 _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
1258 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1259 !TD_IS_IDLETHREAD(curthread),
1260 ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1261 curthread, sx->lock_object.lo_name, file, line));
1262 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1263 ("sx_slock() of destroyed sx @ %s:%d", file, line));
1264 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1268 x = SX_READ_VALUE(sx);
1269 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__acquire) ||
1270 !__sx_slock_try(sx, td, &x, true LOCK_FILE_LINE_ARG)))
1271 error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1273 lock_profile_obtain_lock_success(&sx->lock_object, false, 0, 0,
1276 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1277 WITNESS_LOCK(&sx->lock_object, 0, file, line);
1278 TD_LOCKS_INC(curthread);
1284 _sx_slock(struct sx *sx, int opts, const char *file, int line)
1287 return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1290 static bool __always_inline
1291 _sx_sunlock_try(struct sx *sx, struct thread *td, uintptr_t *xp)
1295 if (SX_SHARERS(*xp) > 1 || !(*xp & SX_LOCK_WAITERS)) {
1296 if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1297 *xp - SX_ONE_SHARER)) {
1298 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1300 "%s: %p succeeded %p -> %p",
1301 __func__, sx, (void *)*xp,
1302 (void *)(*xp - SX_ONE_SHARER));
1313 static void __noinline
1314 _sx_sunlock_hard(struct sx *sx, struct thread *td, uintptr_t x
1315 LOCK_FILE_LINE_ARG_DEF)
1317 int wakeup_swapper = 0;
1318 uintptr_t setx, queue;
1320 if (SCHEDULER_STOPPED())
1323 if (_sx_sunlock_try(sx, td, &x))
1326 sleepq_lock(&sx->lock_object);
1327 x = SX_READ_VALUE(sx);
1329 if (_sx_sunlock_try(sx, td, &x))
1333 * Wake up semantic here is quite simple:
1334 * Just wake up all the exclusive waiters.
1335 * Note that the state of the lock could have changed,
1336 * so if it fails loop back and retry.
1338 setx = SX_LOCK_UNLOCKED;
1339 queue = SQ_SHARED_QUEUE;
1340 if (x & SX_LOCK_EXCLUSIVE_WAITERS) {
1341 setx |= (x & SX_LOCK_SHARED_WAITERS);
1342 queue = SQ_EXCLUSIVE_QUEUE;
1344 setx |= (x & SX_LOCK_WRITE_SPINNER);
1345 if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
1347 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1348 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1349 "exclusive queue", __func__, sx);
1350 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1355 sleepq_release(&sx->lock_object);
1359 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1363 _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1368 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1369 ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1370 _sx_assert(sx, SA_SLOCKED, file, line);
1371 WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1372 LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1375 x = SX_READ_VALUE(sx);
1376 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__release) ||
1377 !_sx_sunlock_try(sx, td, &x)))
1378 _sx_sunlock_hard(sx, td, x LOCK_FILE_LINE_ARG);
1380 lock_profile_release_lock(&sx->lock_object, false);
1382 TD_LOCKS_DEC(curthread);
1386 _sx_sunlock(struct sx *sx, const char *file, int line)
1389 _sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1392 #ifdef INVARIANT_SUPPORT
1398 * In the non-WITNESS case, sx_assert() can only detect that at least
1399 * *some* thread owns an slock, but it cannot guarantee that *this*
1400 * thread owns an slock.
1403 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1409 if (SCHEDULER_STOPPED())
1413 case SA_SLOCKED | SA_NOTRECURSED:
1414 case SA_SLOCKED | SA_RECURSED:
1420 case SA_LOCKED | SA_NOTRECURSED:
1421 case SA_LOCKED | SA_RECURSED:
1423 witness_assert(&sx->lock_object, what, file, line);
1426 * If some other thread has an exclusive lock or we
1427 * have one and are asserting a shared lock, fail.
1428 * Also, if no one has a lock at all, fail.
1430 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1431 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1432 sx_xholder(sx) != curthread)))
1433 panic("Lock %s not %slocked @ %s:%d\n",
1434 sx->lock_object.lo_name, slocked ? "share " : "",
1437 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1438 if (sx_recursed(sx)) {
1439 if (what & SA_NOTRECURSED)
1440 panic("Lock %s recursed @ %s:%d\n",
1441 sx->lock_object.lo_name, file,
1443 } else if (what & SA_RECURSED)
1444 panic("Lock %s not recursed @ %s:%d\n",
1445 sx->lock_object.lo_name, file, line);
1450 case SA_XLOCKED | SA_NOTRECURSED:
1451 case SA_XLOCKED | SA_RECURSED:
1452 if (sx_xholder(sx) != curthread)
1453 panic("Lock %s not exclusively locked @ %s:%d\n",
1454 sx->lock_object.lo_name, file, line);
1455 if (sx_recursed(sx)) {
1456 if (what & SA_NOTRECURSED)
1457 panic("Lock %s recursed @ %s:%d\n",
1458 sx->lock_object.lo_name, file, line);
1459 } else if (what & SA_RECURSED)
1460 panic("Lock %s not recursed @ %s:%d\n",
1461 sx->lock_object.lo_name, file, line);
1465 witness_assert(&sx->lock_object, what, file, line);
1468 * If we hold an exclusve lock fail. We can't
1469 * reliably check to see if we hold a shared lock or
1472 if (sx_xholder(sx) == curthread)
1473 panic("Lock %s exclusively locked @ %s:%d\n",
1474 sx->lock_object.lo_name, file, line);
1478 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1482 #endif /* INVARIANT_SUPPORT */
1486 db_show_sx(const struct lock_object *lock)
1489 const struct sx *sx;
1491 sx = (const struct sx *)lock;
1493 db_printf(" state: ");
1494 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1495 db_printf("UNLOCKED\n");
1496 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1497 db_printf("DESTROYED\n");
1499 } else if (sx->sx_lock & SX_LOCK_SHARED)
1500 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1502 td = sx_xholder(sx);
1503 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1504 td->td_tid, td->td_proc->p_pid, td->td_name);
1505 if (sx_recursed(sx))
1506 db_printf(" recursed: %d\n", sx->sx_recurse);
1509 db_printf(" waiters: ");
1510 switch(sx->sx_lock &
1511 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1512 case SX_LOCK_SHARED_WAITERS:
1513 db_printf("shared\n");
1515 case SX_LOCK_EXCLUSIVE_WAITERS:
1516 db_printf("exclusive\n");
1518 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1519 db_printf("exclusive and shared\n");
1522 db_printf("none\n");
1527 * Check to see if a thread that is blocked on a sleep queue is actually
1528 * blocked on an sx lock. If so, output some details and return true.
1529 * If the lock has an exclusive owner, return that in *ownerp.
1532 sx_chain(struct thread *td, struct thread **ownerp)
1534 const struct sx *sx;
1537 * Check to see if this thread is blocked on an sx lock.
1538 * First, we check the lock class. If that is ok, then we
1539 * compare the lock name against the wait message.
1542 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1543 sx->lock_object.lo_name != td->td_wmesg)
1546 /* We think we have an sx lock, so output some details. */
1547 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1548 *ownerp = sx_xholder(sx);
1549 if (sx->sx_lock & SX_LOCK_SHARED)
1550 db_printf("SLOCK (count %ju)\n",
1551 (uintmax_t)SX_SHARERS(sx->sx_lock));
1553 db_printf("XLOCK\n");