2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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 __FBSDID("$FreeBSD$");
48 #include <sys/param.h>
49 #include <sys/systm.h>
51 #include <sys/kernel.h>
54 #include <sys/mutex.h>
56 #include <sys/sched.h>
57 #include <sys/sleepqueue.h>
60 #include <sys/sysctl.h>
62 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
63 #include <machine/cpu.h>
70 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
75 #include <sys/pmckern.h>
76 PMC_SOFT_DECLARE( , , lock, failed);
79 /* Handy macros for sleep queues. */
80 #define SQ_EXCLUSIVE_QUEUE 0
81 #define SQ_SHARED_QUEUE 1
84 * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file. We
85 * drop Giant anytime we have to sleep or if we adaptively spin.
87 #define GIANT_DECLARE \
89 WITNESS_SAVE_DECL(Giant) \
91 #define GIANT_SAVE(work) do { \
92 if (__predict_false(mtx_owned(&Giant))) { \
94 WITNESS_SAVE(&Giant.lock_object, Giant); \
95 while (mtx_owned(&Giant)) { \
102 #define GIANT_RESTORE() do { \
103 if (_giantcnt > 0) { \
104 mtx_assert(&Giant, MA_NOTOWNED); \
105 while (_giantcnt--) \
107 WITNESS_RESTORE(&Giant.lock_object, Giant); \
112 * Returns true if an exclusive lock is recursed. It assumes
113 * curthread currently has an exclusive lock.
115 #define sx_recursed(sx) ((sx)->sx_recurse != 0)
117 static void assert_sx(const struct lock_object *lock, int what);
119 static void db_show_sx(const struct lock_object *lock);
121 static void lock_sx(struct lock_object *lock, uintptr_t how);
123 static int owner_sx(const struct lock_object *lock, struct thread **owner);
125 static uintptr_t unlock_sx(struct lock_object *lock);
127 struct lock_class lock_class_sx = {
129 .lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
130 .lc_assert = assert_sx,
132 .lc_ddb_show = db_show_sx,
135 .lc_unlock = unlock_sx,
137 .lc_owner = owner_sx,
142 #define _sx_assert(sx, what, file, line)
146 static __read_frequently u_int asx_retries;
147 static __read_frequently u_int asx_loops;
148 static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD, NULL, "sxlock debugging");
149 SYSCTL_UINT(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
150 SYSCTL_UINT(_debug_sx, OID_AUTO, loops, CTLFLAG_RW, &asx_loops, 0, "");
152 static struct lock_delay_config __read_frequently sx_delay;
154 SYSCTL_INT(_debug_sx, OID_AUTO, delay_base, CTLFLAG_RW, &sx_delay.base,
156 SYSCTL_INT(_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);
171 assert_sx(const struct lock_object *lock, int what)
174 sx_assert((const struct sx *)lock, what);
178 lock_sx(struct lock_object *lock, uintptr_t how)
182 sx = (struct sx *)lock;
190 unlock_sx(struct lock_object *lock)
194 sx = (struct sx *)lock;
195 sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
196 if (sx_xlocked(sx)) {
207 owner_sx(const struct lock_object *lock, struct thread **owner)
212 sx = (const struct sx *)lock;
215 return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
216 ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
221 sx_sysinit(void *arg)
223 struct sx_args *sargs = arg;
225 sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
229 sx_init_flags(struct sx *sx, const char *description, int opts)
233 MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
234 SX_NOPROFILE | SX_NEW)) == 0);
235 ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
236 ("%s: sx_lock not aligned for %s: %p", __func__, description,
239 flags = LO_SLEEPABLE | LO_UPGRADABLE;
242 if (opts & SX_NOPROFILE)
243 flags |= LO_NOPROFILE;
244 if (!(opts & SX_NOWITNESS))
246 if (opts & SX_RECURSE)
247 flags |= LO_RECURSABLE;
253 lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
254 sx->sx_lock = SX_LOCK_UNLOCKED;
259 sx_destroy(struct sx *sx)
262 KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
263 KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
264 sx->sx_lock = SX_LOCK_DESTROYED;
265 lock_destroy(&sx->lock_object);
269 sx_try_slock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
273 if (SCHEDULER_STOPPED())
276 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
277 ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
278 curthread, sx->lock_object.lo_name, file, line));
282 KASSERT(x != SX_LOCK_DESTROYED,
283 ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
284 if (!(x & SX_LOCK_SHARED))
286 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, x + SX_ONE_SHARER)) {
287 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
288 WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
289 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
290 sx, 0, 0, file, line, LOCKSTAT_READER);
291 TD_LOCKS_INC(curthread);
292 curthread->td_sx_slocks++;
297 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
302 sx_try_slock_(struct sx *sx, const char *file, int line)
305 return (sx_try_slock_int(sx LOCK_FILE_LINE_ARG));
309 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
314 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
315 !TD_IS_IDLETHREAD(curthread),
316 ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
317 curthread, sx->lock_object.lo_name, file, line));
318 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
319 ("sx_xlock() of destroyed sx @ %s:%d", file, line));
320 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
322 tid = (uintptr_t)curthread;
323 x = SX_LOCK_UNLOCKED;
324 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
325 error = _sx_xlock_hard(sx, x, opts LOCK_FILE_LINE_ARG);
327 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
328 0, 0, file, line, LOCKSTAT_WRITER);
330 LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
332 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
333 TD_LOCKS_INC(curthread);
340 sx_try_xlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
349 if (SCHEDULER_STOPPED_TD(td))
352 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
353 ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
354 curthread, sx->lock_object.lo_name, file, line));
355 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
356 ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
360 x = SX_LOCK_UNLOCKED;
362 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
364 if (x == SX_LOCK_UNLOCKED)
366 if (x == tid && (sx->lock_object.lo_flags & LO_RECURSABLE)) {
368 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
375 LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
377 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
380 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
381 sx, 0, 0, file, line, LOCKSTAT_WRITER);
382 TD_LOCKS_INC(curthread);
389 sx_try_xlock_(struct sx *sx, const char *file, int line)
392 return (sx_try_xlock_int(sx LOCK_FILE_LINE_ARG));
396 _sx_xunlock(struct sx *sx, const char *file, int line)
399 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
400 ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
401 _sx_assert(sx, SA_XLOCKED, file, line);
402 WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
403 LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
406 _sx_xunlock_hard(sx, (uintptr_t)curthread, file, line);
408 __sx_xunlock(sx, curthread, file, line);
410 TD_LOCKS_DEC(curthread);
414 * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
415 * This will only succeed if this thread holds a single shared lock.
416 * Return 1 if if the upgrade succeed, 0 otherwise.
419 sx_try_upgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
425 if (SCHEDULER_STOPPED())
428 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
429 ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
430 _sx_assert(sx, SA_SLOCKED, file, line);
433 * Try to switch from one shared lock to an exclusive lock. We need
434 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
435 * we will wake up the exclusive waiters when we drop the lock.
438 x = SX_READ_VALUE(sx);
440 if (SX_SHARERS(x) > 1)
442 waiters = (x & SX_LOCK_WAITERS);
443 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
444 (uintptr_t)curthread | waiters)) {
449 LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
451 curthread->td_sx_slocks--;
452 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
454 LOCKSTAT_RECORD0(sx__upgrade, sx);
460 sx_try_upgrade_(struct sx *sx, const char *file, int line)
463 return (sx_try_upgrade_int(sx LOCK_FILE_LINE_ARG));
467 * Downgrade an unrecursed exclusive lock into a single shared lock.
470 sx_downgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
475 if (SCHEDULER_STOPPED())
478 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
479 ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
480 _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
483 panic("downgrade of a recursed lock");
486 WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
489 * Try to switch from an exclusive lock with no shared waiters
490 * to one sharer with no shared waiters. If there are
491 * exclusive waiters, we don't need to lock the sleep queue so
492 * long as we preserve the flag. We do one quick try and if
493 * that fails we grab the sleepq lock to keep the flags from
494 * changing and do it the slow way.
496 * We have to lock the sleep queue if there are shared waiters
497 * so we can wake them up.
500 if (!(x & SX_LOCK_SHARED_WAITERS) &&
501 atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
502 (x & SX_LOCK_EXCLUSIVE_WAITERS)))
506 * Lock the sleep queue so we can read the waiters bits
507 * without any races and wakeup any shared waiters.
509 sleepq_lock(&sx->lock_object);
512 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
513 * shared lock. If there are any shared waiters, wake them up.
517 atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
518 (x & SX_LOCK_EXCLUSIVE_WAITERS));
519 if (x & SX_LOCK_SHARED_WAITERS)
520 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
522 sleepq_release(&sx->lock_object);
528 curthread->td_sx_slocks++;
529 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
530 LOCKSTAT_RECORD0(sx__downgrade, sx);
534 sx_downgrade_(struct sx *sx, const char *file, int line)
537 sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
542 sx_drop_critical(uintptr_t x, bool *in_critical, int *extra_work)
545 if (x & SX_LOCK_WRITE_SPINNER)
549 *in_critical = false;
554 #define sx_drop_critical(x, in_critical, extra_work) do { } while(0)
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.
564 _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
569 volatile struct thread *owner;
570 u_int i, n, spintries = 0;
571 enum { READERS, WRITER } sleep_reason = READERS;
572 bool in_critical = false;
574 #ifdef LOCK_PROFILING
575 uint64_t waittime = 0;
579 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
580 struct lock_delay_arg lda;
584 int64_t sleep_time = 0;
585 int64_t all_time = 0;
587 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
589 int doing_lockprof = 0;
593 tid = (uintptr_t)curthread;
596 if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
597 while (x == SX_LOCK_UNLOCKED) {
598 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
603 all_time -= lockstat_nsecs(&sx->lock_object);
607 #ifdef LOCK_PROFILING
613 if (SCHEDULER_STOPPED())
616 #if defined(ADAPTIVE_SX)
617 lock_delay_arg_init(&lda, &sx_delay);
618 #elif defined(KDTRACE_HOOKS)
619 lock_delay_arg_init(&lda, NULL);
622 if (__predict_false(x == SX_LOCK_UNLOCKED))
623 x = SX_READ_VALUE(sx);
625 /* If we already hold an exclusive lock, then recurse. */
626 if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
627 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
628 ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
629 sx->lock_object.lo_name, file, line));
631 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
632 if (LOCK_LOG_TEST(&sx->lock_object, 0))
633 CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
637 if (LOCK_LOG_TEST(&sx->lock_object, 0))
638 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
639 sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
642 PMC_SOFT_CALL( , , lock, failed);
644 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
648 GIANT_SAVE(extra_work);
652 if (x == SX_LOCK_UNLOCKED) {
653 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
658 GIANT_SAVE(extra_work);
664 if (x == (SX_LOCK_SHARED | SX_LOCK_WRITE_SPINNER)) {
665 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
671 * If the lock is write locked and the owner is
672 * running on another CPU, spin until the owner stops
673 * running or the state of the lock changes.
675 if ((x & SX_LOCK_SHARED) == 0) {
676 sx_drop_critical(x, &in_critical, &extra_work);
677 sleep_reason = WRITER;
678 owner = lv_sx_owner(x);
679 if (!TD_IS_RUNNING(owner))
681 if (LOCK_LOG_TEST(&sx->lock_object, 0))
682 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
683 __func__, sx, owner);
684 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
685 "spinning", "lockname:\"%s\"",
686 sx->lock_object.lo_name);
689 x = SX_READ_VALUE(sx);
690 owner = lv_sx_owner(x);
691 } while (owner != NULL && TD_IS_RUNNING(owner));
692 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
695 } else if (SX_SHARERS(x) > 0) {
696 sleep_reason = READERS;
697 if (spintries == asx_retries)
699 if (!(x & SX_LOCK_WRITE_SPINNER)) {
705 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
706 x | SX_LOCK_WRITE_SPINNER)) {
714 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
715 "spinning", "lockname:\"%s\"",
716 sx->lock_object.lo_name);
718 for (i = 0; i < asx_loops; i += n) {
720 x = SX_READ_VALUE(sx);
721 if (!(x & SX_LOCK_WRITE_SPINNER))
723 if (!(x & SX_LOCK_SHARED))
732 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
739 sleepq_lock(&sx->lock_object);
740 x = SX_READ_VALUE(sx);
744 * If the lock was released while spinning on the
745 * sleep queue chain lock, try again.
747 if (x == SX_LOCK_UNLOCKED) {
748 sleepq_release(&sx->lock_object);
749 sx_drop_critical(x, &in_critical, &extra_work);
755 * The current lock owner might have started executing
756 * on another CPU (or the lock could have changed
757 * owners) while we were waiting on the sleep queue
758 * chain lock. If so, drop the sleep queue lock and try
761 if (!(x & SX_LOCK_SHARED)) {
762 owner = (struct thread *)SX_OWNER(x);
763 if (TD_IS_RUNNING(owner)) {
764 sleepq_release(&sx->lock_object);
765 sx_drop_critical(x, &in_critical,
769 } else if (SX_SHARERS(x) > 0 && sleep_reason == WRITER) {
770 sleepq_release(&sx->lock_object);
771 sx_drop_critical(x, &in_critical, &extra_work);
777 * If an exclusive lock was released with both shared
778 * and exclusive waiters and a shared waiter hasn't
779 * woken up and acquired the lock yet, sx_lock will be
780 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
781 * If we see that value, try to acquire it once. Note
782 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
783 * as there are other exclusive waiters still. If we
784 * fail, restart the loop.
786 setx = x & (SX_LOCK_WAITERS | SX_LOCK_WRITE_SPINNER);
787 if ((x & ~setx) == SX_LOCK_SHARED) {
788 setx &= ~SX_LOCK_WRITE_SPINNER;
789 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid | setx))
791 sleepq_release(&sx->lock_object);
792 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
799 * It is possible we set the SX_LOCK_WRITE_SPINNER bit.
800 * It is an invariant that when the bit is set, there is
801 * a writer ready to grab the lock. Thus clear the bit since
802 * we are going to sleep.
805 if ((x & SX_LOCK_WRITE_SPINNER) ||
806 !((x & SX_LOCK_EXCLUSIVE_WAITERS))) {
807 setx = x & ~SX_LOCK_WRITE_SPINNER;
808 setx |= SX_LOCK_EXCLUSIVE_WAITERS;
809 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
819 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
820 * than loop back and retry.
822 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
823 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
824 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
827 if (LOCK_LOG_TEST(&sx->lock_object, 0))
828 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
836 * Since we have been unable to acquire the exclusive
837 * lock and the exclusive waiters flag is set, we have
840 if (LOCK_LOG_TEST(&sx->lock_object, 0))
841 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
845 sleep_time -= lockstat_nsecs(&sx->lock_object);
847 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
848 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
849 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
850 if (!(opts & SX_INTERRUPTIBLE))
851 sleepq_wait(&sx->lock_object, 0);
853 error = sleepq_wait_sig(&sx->lock_object, 0);
855 sleep_time += lockstat_nsecs(&sx->lock_object);
859 if (LOCK_LOG_TEST(&sx->lock_object, 0))
861 "%s: interruptible sleep by %p suspended by signal",
865 if (LOCK_LOG_TEST(&sx->lock_object, 0))
866 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
868 x = SX_READ_VALUE(sx);
870 if (__predict_true(!extra_work))
877 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
878 if (__predict_true(!doing_lockprof))
882 all_time += lockstat_nsecs(&sx->lock_object);
884 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
885 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
886 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
887 if (lda.spin_cnt > sleep_cnt)
888 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
889 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
890 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
894 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
895 contested, waittime, file, line, LOCKSTAT_WRITER);
900 * This function represents the so-called 'hard case' for sx_xunlock
901 * operation. All 'easy case' failures are redirected to this. Note
902 * that ideally this would be a static function, but it needs to be
903 * accessible from at least sx.h.
906 _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
909 int queue, wakeup_swapper;
911 if (SCHEDULER_STOPPED())
914 tid = (uintptr_t)curthread;
916 if (__predict_false(x == tid))
917 x = SX_READ_VALUE(sx);
919 MPASS(!(x & SX_LOCK_SHARED));
921 if (__predict_false(x & SX_LOCK_RECURSED)) {
922 /* The lock is recursed, unrecurse one level. */
923 if ((--sx->sx_recurse) == 0)
924 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
925 if (LOCK_LOG_TEST(&sx->lock_object, 0))
926 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
930 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
932 atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
935 if (LOCK_LOG_TEST(&sx->lock_object, 0))
936 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
938 sleepq_lock(&sx->lock_object);
939 x = SX_READ_VALUE(sx);
940 MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
943 * The wake up algorithm here is quite simple and probably not
944 * ideal. It gives precedence to shared waiters if they are
945 * present. For this condition, we have to preserve the
946 * state of the exclusive waiters flag.
947 * If interruptible sleeps left the shared queue empty avoid a
948 * starvation for the threads sleeping on the exclusive queue by giving
949 * them precedence and cleaning up the shared waiters bit anyway.
951 setx = SX_LOCK_UNLOCKED;
952 queue = SQ_SHARED_QUEUE;
953 if ((x & SX_LOCK_EXCLUSIVE_WAITERS) != 0 &&
954 sleepq_sleepcnt(&sx->lock_object, SQ_EXCLUSIVE_QUEUE) != 0) {
955 queue = SQ_EXCLUSIVE_QUEUE;
956 setx |= (x & SX_LOCK_SHARED_WAITERS);
958 atomic_store_rel_ptr(&sx->sx_lock, setx);
960 /* Wake up all the waiters for the specific queue. */
961 if (LOCK_LOG_TEST(&sx->lock_object, 0))
962 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
963 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
966 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
968 sleepq_release(&sx->lock_object);
973 static bool __always_inline
974 __sx_can_read(struct thread *td, uintptr_t x, bool fp)
977 if ((x & (SX_LOCK_SHARED | SX_LOCK_EXCLUSIVE_WAITERS | SX_LOCK_WRITE_SPINNER))
980 if (!fp && td->td_sx_slocks && (x & SX_LOCK_SHARED))
985 static bool __always_inline
986 __sx_slock_try(struct sx *sx, struct thread *td, uintptr_t *xp, bool fp
987 LOCK_FILE_LINE_ARG_DEF)
991 * If no other thread has an exclusive lock then try to bump up
992 * the count of sharers. Since we have to preserve the state
993 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
994 * shared lock loop back and retry.
996 while (__sx_can_read(td, *xp, fp)) {
997 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
998 *xp + SX_ONE_SHARER)) {
999 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1000 CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
1001 __func__, sx, (void *)*xp,
1002 (void *)(*xp + SX_ONE_SHARER));
1010 static int __noinline
1011 _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
1016 volatile struct thread *owner;
1017 u_int i, n, spintries = 0;
1019 #ifdef LOCK_PROFILING
1020 uint64_t waittime = 0;
1024 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
1025 struct lock_delay_arg lda;
1027 #ifdef KDTRACE_HOOKS
1028 u_int sleep_cnt = 0;
1029 int64_t sleep_time = 0;
1030 int64_t all_time = 0;
1032 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1033 uintptr_t state = 0;
1039 #ifdef KDTRACE_HOOKS
1040 if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
1041 if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
1044 all_time -= lockstat_nsecs(&sx->lock_object);
1048 #ifdef LOCK_PROFILING
1053 if (SCHEDULER_STOPPED())
1056 #if defined(ADAPTIVE_SX)
1057 lock_delay_arg_init(&lda, &sx_delay);
1058 #elif defined(KDTRACE_HOOKS)
1059 lock_delay_arg_init(&lda, NULL);
1063 PMC_SOFT_CALL( , , lock, failed);
1065 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
1069 GIANT_SAVE(extra_work);
1073 * As with rwlocks, we don't make any attempt to try to block
1074 * shared locks once there is an exclusive waiter.
1077 if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
1080 GIANT_SAVE(extra_work);
1082 #ifdef KDTRACE_HOOKS
1088 * If the owner is running on another CPU, spin until
1089 * the owner stops running or the state of the lock
1092 if ((x & SX_LOCK_SHARED) == 0) {
1093 owner = lv_sx_owner(x);
1094 if (TD_IS_RUNNING(owner)) {
1095 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1097 "%s: spinning on %p held by %p",
1098 __func__, sx, owner);
1099 KTR_STATE1(KTR_SCHED, "thread",
1100 sched_tdname(curthread), "spinning",
1101 "lockname:\"%s\"", sx->lock_object.lo_name);
1104 x = SX_READ_VALUE(sx);
1105 owner = lv_sx_owner(x);
1106 } while (owner != NULL && TD_IS_RUNNING(owner));
1107 KTR_STATE0(KTR_SCHED, "thread",
1108 sched_tdname(curthread), "running");
1112 if ((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) {
1113 MPASS(!__sx_can_read(td, x, false));
1115 x = SX_READ_VALUE(sx);
1118 if (spintries < asx_retries) {
1119 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1120 "spinning", "lockname:\"%s\"",
1121 sx->lock_object.lo_name);
1123 for (i = 0; i < asx_loops; i += n) {
1125 x = SX_READ_VALUE(sx);
1126 if (!(x & SX_LOCK_SHARED))
1131 if (__sx_can_read(td, x, false))
1134 #ifdef KDTRACE_HOOKS
1137 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1146 * Some other thread already has an exclusive lock, so
1147 * start the process of blocking.
1149 sleepq_lock(&sx->lock_object);
1150 x = SX_READ_VALUE(sx);
1152 if (((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) ||
1153 __sx_can_read(td, x, false)) {
1154 sleepq_release(&sx->lock_object);
1160 * If the owner is running on another CPU, spin until
1161 * the owner stops running or the state of the lock
1164 if (!(x & SX_LOCK_SHARED)) {
1165 owner = (struct thread *)SX_OWNER(x);
1166 if (TD_IS_RUNNING(owner)) {
1167 sleepq_release(&sx->lock_object);
1168 x = SX_READ_VALUE(sx);
1175 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
1176 * fail to set it drop the sleep queue lock and loop
1179 if (!(x & SX_LOCK_SHARED_WAITERS)) {
1180 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
1181 x | SX_LOCK_SHARED_WAITERS))
1183 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1184 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1189 * Since we have been unable to acquire the shared lock,
1192 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1193 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1196 #ifdef KDTRACE_HOOKS
1197 sleep_time -= lockstat_nsecs(&sx->lock_object);
1199 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1200 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1201 SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1202 if (!(opts & SX_INTERRUPTIBLE))
1203 sleepq_wait(&sx->lock_object, 0);
1205 error = sleepq_wait_sig(&sx->lock_object, 0);
1206 #ifdef KDTRACE_HOOKS
1207 sleep_time += lockstat_nsecs(&sx->lock_object);
1211 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1213 "%s: interruptible sleep by %p suspended by signal",
1217 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1218 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1220 x = SX_READ_VALUE(sx);
1222 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1223 if (__predict_true(!extra_work))
1226 #ifdef KDTRACE_HOOKS
1227 all_time += lockstat_nsecs(&sx->lock_object);
1229 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1230 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1231 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1232 if (lda.spin_cnt > sleep_cnt)
1233 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1234 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1235 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1239 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1240 contested, waittime, file, line, LOCKSTAT_READER);
1247 _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
1253 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1254 !TD_IS_IDLETHREAD(curthread),
1255 ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1256 curthread, sx->lock_object.lo_name, file, line));
1257 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1258 ("sx_slock() of destroyed sx @ %s:%d", file, line));
1259 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1263 x = SX_READ_VALUE(sx);
1264 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__acquire) ||
1265 !__sx_slock_try(sx, td, &x, true LOCK_FILE_LINE_ARG)))
1266 error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1268 lock_profile_obtain_lock_success(&sx->lock_object, 0, 0,
1271 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1272 WITNESS_LOCK(&sx->lock_object, 0, file, line);
1273 TD_LOCKS_INC(curthread);
1279 _sx_slock(struct sx *sx, int opts, const char *file, int line)
1282 return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1285 static bool __always_inline
1286 _sx_sunlock_try(struct sx *sx, struct thread *td, uintptr_t *xp)
1290 if (SX_SHARERS(*xp) > 1 || !(*xp & SX_LOCK_WAITERS)) {
1291 if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1292 *xp - SX_ONE_SHARER)) {
1293 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1295 "%s: %p succeeded %p -> %p",
1296 __func__, sx, (void *)*xp,
1297 (void *)(*xp - SX_ONE_SHARER));
1308 static void __noinline
1309 _sx_sunlock_hard(struct sx *sx, struct thread *td, uintptr_t x
1310 LOCK_FILE_LINE_ARG_DEF)
1312 int wakeup_swapper = 0;
1313 uintptr_t setx, queue;
1315 if (SCHEDULER_STOPPED())
1318 if (_sx_sunlock_try(sx, td, &x))
1321 sleepq_lock(&sx->lock_object);
1322 x = SX_READ_VALUE(sx);
1324 if (_sx_sunlock_try(sx, td, &x))
1328 * Wake up semantic here is quite simple:
1329 * Just wake up all the exclusive waiters.
1330 * Note that the state of the lock could have changed,
1331 * so if it fails loop back and retry.
1333 setx = SX_LOCK_UNLOCKED;
1334 queue = SQ_SHARED_QUEUE;
1335 if (x & SX_LOCK_EXCLUSIVE_WAITERS) {
1336 setx |= (x & SX_LOCK_SHARED_WAITERS);
1337 queue = SQ_EXCLUSIVE_QUEUE;
1339 setx |= (x & SX_LOCK_WRITE_SPINNER);
1340 if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
1342 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1343 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1344 "exclusive queue", __func__, sx);
1345 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1350 sleepq_release(&sx->lock_object);
1354 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1358 _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1363 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1364 ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1365 _sx_assert(sx, SA_SLOCKED, file, line);
1366 WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1367 LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1370 x = SX_READ_VALUE(sx);
1371 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__release) ||
1372 !_sx_sunlock_try(sx, td, &x)))
1373 _sx_sunlock_hard(sx, td, x LOCK_FILE_LINE_ARG);
1375 lock_profile_release_lock(&sx->lock_object);
1377 TD_LOCKS_DEC(curthread);
1381 _sx_sunlock(struct sx *sx, const char *file, int line)
1384 _sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1387 #ifdef INVARIANT_SUPPORT
1393 * In the non-WITNESS case, sx_assert() can only detect that at least
1394 * *some* thread owns an slock, but it cannot guarantee that *this*
1395 * thread owns an slock.
1398 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1404 if (SCHEDULER_STOPPED())
1408 case SA_SLOCKED | SA_NOTRECURSED:
1409 case SA_SLOCKED | SA_RECURSED:
1415 case SA_LOCKED | SA_NOTRECURSED:
1416 case SA_LOCKED | SA_RECURSED:
1418 witness_assert(&sx->lock_object, what, file, line);
1421 * If some other thread has an exclusive lock or we
1422 * have one and are asserting a shared lock, fail.
1423 * Also, if no one has a lock at all, fail.
1425 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1426 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1427 sx_xholder(sx) != curthread)))
1428 panic("Lock %s not %slocked @ %s:%d\n",
1429 sx->lock_object.lo_name, slocked ? "share " : "",
1432 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1433 if (sx_recursed(sx)) {
1434 if (what & SA_NOTRECURSED)
1435 panic("Lock %s recursed @ %s:%d\n",
1436 sx->lock_object.lo_name, file,
1438 } else if (what & SA_RECURSED)
1439 panic("Lock %s not recursed @ %s:%d\n",
1440 sx->lock_object.lo_name, file, line);
1445 case SA_XLOCKED | SA_NOTRECURSED:
1446 case SA_XLOCKED | SA_RECURSED:
1447 if (sx_xholder(sx) != curthread)
1448 panic("Lock %s not exclusively locked @ %s:%d\n",
1449 sx->lock_object.lo_name, file, line);
1450 if (sx_recursed(sx)) {
1451 if (what & SA_NOTRECURSED)
1452 panic("Lock %s recursed @ %s:%d\n",
1453 sx->lock_object.lo_name, file, line);
1454 } else if (what & SA_RECURSED)
1455 panic("Lock %s not recursed @ %s:%d\n",
1456 sx->lock_object.lo_name, file, line);
1460 witness_assert(&sx->lock_object, what, file, line);
1463 * If we hold an exclusve lock fail. We can't
1464 * reliably check to see if we hold a shared lock or
1467 if (sx_xholder(sx) == curthread)
1468 panic("Lock %s exclusively locked @ %s:%d\n",
1469 sx->lock_object.lo_name, file, line);
1473 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1477 #endif /* INVARIANT_SUPPORT */
1481 db_show_sx(const struct lock_object *lock)
1484 const struct sx *sx;
1486 sx = (const struct sx *)lock;
1488 db_printf(" state: ");
1489 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1490 db_printf("UNLOCKED\n");
1491 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1492 db_printf("DESTROYED\n");
1494 } else if (sx->sx_lock & SX_LOCK_SHARED)
1495 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1497 td = sx_xholder(sx);
1498 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1499 td->td_tid, td->td_proc->p_pid, td->td_name);
1500 if (sx_recursed(sx))
1501 db_printf(" recursed: %d\n", sx->sx_recurse);
1504 db_printf(" waiters: ");
1505 switch(sx->sx_lock &
1506 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1507 case SX_LOCK_SHARED_WAITERS:
1508 db_printf("shared\n");
1510 case SX_LOCK_EXCLUSIVE_WAITERS:
1511 db_printf("exclusive\n");
1513 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1514 db_printf("exclusive and shared\n");
1517 db_printf("none\n");
1522 * Check to see if a thread that is blocked on a sleep queue is actually
1523 * blocked on an sx lock. If so, output some details and return true.
1524 * If the lock has an exclusive owner, return that in *ownerp.
1527 sx_chain(struct thread *td, struct thread **ownerp)
1529 const struct sx *sx;
1532 * Check to see if this thread is blocked on an sx lock.
1533 * First, we check the lock class. If that is ok, then we
1534 * compare the lock name against the wait message.
1537 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1538 sx->lock_object.lo_name != td->td_wmesg)
1541 /* We think we have an sx lock, so output some details. */
1542 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1543 *ownerp = sx_xholder(sx);
1544 if (sx->sx_lock & SX_LOCK_SHARED)
1545 db_printf("SLOCK (count %ju)\n",
1546 (uintmax_t)SX_SHARERS(sx->sx_lock));
1548 db_printf("XLOCK\n");