2 * Copyright (c) 2007 Attilio Rao <attilio@freebsd.org>
3 * Copyright (c) 2001 Jason Evans <jasone@freebsd.org>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice(s), this list of conditions and the following disclaimer as
11 * the first lines of this file unmodified other than the possible
12 * addition of one or more copyright notices.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice(s), this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
31 * Shared/exclusive locks. This implementation attempts to ensure
32 * deterministic lock granting behavior, so that slocks and xlocks are
35 * Priority propagation will not generally raise the priority of lock holders,
36 * so should not be relied upon in combination with sx locks.
40 #include "opt_hwpmc_hooks.h"
41 #include "opt_no_adaptive_sx.h"
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
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)
72 CTASSERT((SX_NOADAPTIVE & LO_CLASSFLAGS) == SX_NOADAPTIVE);
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_NOADAPTIVE | 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 flags |= opts & SX_NOADAPTIVE;
254 lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
255 sx->sx_lock = SX_LOCK_UNLOCKED;
260 sx_destroy(struct sx *sx)
263 KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
264 KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
265 sx->sx_lock = SX_LOCK_DESTROYED;
266 lock_destroy(&sx->lock_object);
270 sx_try_slock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
274 if (SCHEDULER_STOPPED())
277 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
278 ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
279 curthread, sx->lock_object.lo_name, file, line));
283 KASSERT(x != SX_LOCK_DESTROYED,
284 ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
285 if (!(x & SX_LOCK_SHARED))
287 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, x + SX_ONE_SHARER)) {
288 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
289 WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
290 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
291 sx, 0, 0, file, line, LOCKSTAT_READER);
292 TD_LOCKS_INC(curthread);
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_EXCLUSIVE_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 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
453 LOCKSTAT_RECORD0(sx__upgrade, sx);
459 sx_try_upgrade_(struct sx *sx, const char *file, int line)
462 return (sx_try_upgrade_int(sx LOCK_FILE_LINE_ARG));
466 * Downgrade an unrecursed exclusive lock into a single shared lock.
469 sx_downgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
474 if (SCHEDULER_STOPPED())
477 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
478 ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
479 _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
482 panic("downgrade of a recursed lock");
485 WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
488 * Try to switch from an exclusive lock with no shared waiters
489 * to one sharer with no shared waiters. If there are
490 * exclusive waiters, we don't need to lock the sleep queue so
491 * long as we preserve the flag. We do one quick try and if
492 * that fails we grab the sleepq lock to keep the flags from
493 * changing and do it the slow way.
495 * We have to lock the sleep queue if there are shared waiters
496 * so we can wake them up.
499 if (!(x & SX_LOCK_SHARED_WAITERS) &&
500 atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
501 (x & SX_LOCK_EXCLUSIVE_WAITERS)))
505 * Lock the sleep queue so we can read the waiters bits
506 * without any races and wakeup any shared waiters.
508 sleepq_lock(&sx->lock_object);
511 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
512 * shared lock. If there are any shared waiters, wake them up.
516 atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
517 (x & SX_LOCK_EXCLUSIVE_WAITERS));
518 if (x & SX_LOCK_SHARED_WAITERS)
519 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
521 sleepq_release(&sx->lock_object);
527 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
528 LOCKSTAT_RECORD0(sx__downgrade, sx);
532 sx_downgrade_(struct sx *sx, const char *file, int line)
535 sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
539 * This function represents the so-called 'hard case' for sx_xlock
540 * operation. All 'easy case' failures are redirected to this. Note
541 * that ideally this would be a static function, but it needs to be
542 * accessible from at least sx.h.
545 _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
550 volatile struct thread *owner;
551 u_int i, n, spintries = 0;
552 enum { READERS, WRITER } sleep_reason = READERS;
555 #ifdef LOCK_PROFILING
556 uint64_t waittime = 0;
560 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
561 struct lock_delay_arg lda;
565 int64_t sleep_time = 0;
566 int64_t all_time = 0;
568 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
573 tid = (uintptr_t)curthread;
576 if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
577 while (x == SX_LOCK_UNLOCKED) {
578 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
582 all_time -= lockstat_nsecs(&sx->lock_object);
586 #ifdef LOCK_PROFILING
591 if (SCHEDULER_STOPPED())
594 #if defined(ADAPTIVE_SX)
595 lock_delay_arg_init(&lda, &sx_delay);
596 #elif defined(KDTRACE_HOOKS)
597 lock_delay_arg_init(&lda, NULL);
600 if (__predict_false(x == SX_LOCK_UNLOCKED))
601 x = SX_READ_VALUE(sx);
603 /* If we already hold an exclusive lock, then recurse. */
604 if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
605 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
606 ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
607 sx->lock_object.lo_name, file, line));
609 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
610 if (LOCK_LOG_TEST(&sx->lock_object, 0))
611 CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
615 if (LOCK_LOG_TEST(&sx->lock_object, 0))
616 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
617 sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
620 adaptive = ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0);
624 PMC_SOFT_CALL( , , lock, failed);
626 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
630 GIANT_SAVE(extra_work);
634 if (x == SX_LOCK_UNLOCKED) {
635 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
640 GIANT_SAVE(extra_work);
646 if (__predict_false(!adaptive))
649 * If the lock is write locked and the owner is
650 * running on another CPU, spin until the owner stops
651 * running or the state of the lock changes.
653 if ((x & SX_LOCK_SHARED) == 0) {
654 sleep_reason = WRITER;
655 owner = lv_sx_owner(x);
656 if (!TD_IS_RUNNING(owner))
658 if (LOCK_LOG_TEST(&sx->lock_object, 0))
659 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
660 __func__, sx, owner);
661 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
662 "spinning", "lockname:\"%s\"",
663 sx->lock_object.lo_name);
666 x = SX_READ_VALUE(sx);
667 owner = lv_sx_owner(x);
668 } while (owner != NULL && TD_IS_RUNNING(owner));
669 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
672 } else if (SX_SHARERS(x) > 0) {
673 sleep_reason = READERS;
674 if (spintries == asx_retries)
677 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
678 "spinning", "lockname:\"%s\"",
679 sx->lock_object.lo_name);
680 for (i = 0; i < asx_loops; i += n) {
683 x = SX_READ_VALUE(sx);
684 if ((x & SX_LOCK_SHARED) == 0 ||
691 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
698 sleepq_lock(&sx->lock_object);
699 x = SX_READ_VALUE(sx);
703 * If the lock was released while spinning on the
704 * sleep queue chain lock, try again.
706 if (x == SX_LOCK_UNLOCKED) {
707 sleepq_release(&sx->lock_object);
713 * The current lock owner might have started executing
714 * on another CPU (or the lock could have changed
715 * owners) while we were waiting on the sleep queue
716 * chain lock. If so, drop the sleep queue lock and try
720 if (!(x & SX_LOCK_SHARED)) {
721 owner = (struct thread *)SX_OWNER(x);
722 if (TD_IS_RUNNING(owner)) {
723 sleepq_release(&sx->lock_object);
726 } else if (SX_SHARERS(x) > 0 && sleep_reason == WRITER) {
727 sleepq_release(&sx->lock_object);
734 * If an exclusive lock was released with both shared
735 * and exclusive waiters and a shared waiter hasn't
736 * woken up and acquired the lock yet, sx_lock will be
737 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
738 * If we see that value, try to acquire it once. Note
739 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
740 * as there are other exclusive waiters still. If we
741 * fail, restart the loop.
743 if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
744 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
745 tid | SX_LOCK_EXCLUSIVE_WAITERS))
747 sleepq_release(&sx->lock_object);
748 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
754 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
755 * than loop back and retry.
757 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
758 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
759 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
762 if (LOCK_LOG_TEST(&sx->lock_object, 0))
763 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
768 * Since we have been unable to acquire the exclusive
769 * lock and the exclusive waiters flag is set, we have
772 if (LOCK_LOG_TEST(&sx->lock_object, 0))
773 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
777 sleep_time -= lockstat_nsecs(&sx->lock_object);
779 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
780 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
781 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
782 if (!(opts & SX_INTERRUPTIBLE))
783 sleepq_wait(&sx->lock_object, 0);
785 error = sleepq_wait_sig(&sx->lock_object, 0);
787 sleep_time += lockstat_nsecs(&sx->lock_object);
791 if (LOCK_LOG_TEST(&sx->lock_object, 0))
793 "%s: interruptible sleep by %p suspended by signal",
797 if (LOCK_LOG_TEST(&sx->lock_object, 0))
798 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
800 x = SX_READ_VALUE(sx);
802 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
803 if (__predict_true(!extra_work))
807 all_time += lockstat_nsecs(&sx->lock_object);
809 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
810 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
811 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
812 if (lda.spin_cnt > sleep_cnt)
813 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
814 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
815 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
819 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
820 contested, waittime, file, line, LOCKSTAT_WRITER);
826 * This function represents the so-called 'hard case' for sx_xunlock
827 * operation. All 'easy case' failures are redirected to this. Note
828 * that ideally this would be a static function, but it needs to be
829 * accessible from at least sx.h.
832 _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
835 int queue, wakeup_swapper;
837 if (SCHEDULER_STOPPED())
840 tid = (uintptr_t)curthread;
842 if (__predict_false(x == tid))
843 x = SX_READ_VALUE(sx);
845 MPASS(!(x & SX_LOCK_SHARED));
847 if (__predict_false(x & SX_LOCK_RECURSED)) {
848 /* The lock is recursed, unrecurse one level. */
849 if ((--sx->sx_recurse) == 0)
850 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
851 if (LOCK_LOG_TEST(&sx->lock_object, 0))
852 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
856 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
858 atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
861 if (LOCK_LOG_TEST(&sx->lock_object, 0))
862 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
864 sleepq_lock(&sx->lock_object);
865 x = SX_READ_VALUE(sx);
866 MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
869 * The wake up algorithm here is quite simple and probably not
870 * ideal. It gives precedence to shared waiters if they are
871 * present. For this condition, we have to preserve the
872 * state of the exclusive waiters flag.
873 * If interruptible sleeps left the shared queue empty avoid a
874 * starvation for the threads sleeping on the exclusive queue by giving
875 * them precedence and cleaning up the shared waiters bit anyway.
877 setx = SX_LOCK_UNLOCKED;
878 queue = SQ_EXCLUSIVE_QUEUE;
879 if ((x & SX_LOCK_SHARED_WAITERS) != 0 &&
880 sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
881 queue = SQ_SHARED_QUEUE;
882 setx |= (x & SX_LOCK_EXCLUSIVE_WAITERS);
884 atomic_store_rel_ptr(&sx->sx_lock, setx);
886 /* Wake up all the waiters for the specific queue. */
887 if (LOCK_LOG_TEST(&sx->lock_object, 0))
888 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
889 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
892 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
894 sleepq_release(&sx->lock_object);
899 static bool __always_inline
900 __sx_slock_try(struct sx *sx, uintptr_t *xp LOCK_FILE_LINE_ARG_DEF)
904 * If no other thread has an exclusive lock then try to bump up
905 * the count of sharers. Since we have to preserve the state
906 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
907 * shared lock loop back and retry.
909 while (*xp & SX_LOCK_SHARED) {
910 MPASS(!(*xp & SX_LOCK_SHARED_WAITERS));
911 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
912 *xp + SX_ONE_SHARER)) {
913 if (LOCK_LOG_TEST(&sx->lock_object, 0))
914 CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
915 __func__, sx, (void *)*xp,
916 (void *)(*xp + SX_ONE_SHARER));
923 static int __noinline
924 _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
928 volatile struct thread *owner;
931 #ifdef LOCK_PROFILING
932 uint64_t waittime = 0;
936 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
937 struct lock_delay_arg lda;
941 int64_t sleep_time = 0;
942 int64_t all_time = 0;
944 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
950 if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
951 if (__sx_slock_try(sx, &x LOCK_FILE_LINE_ARG))
954 all_time -= lockstat_nsecs(&sx->lock_object);
958 #ifdef LOCK_PROFILING
963 if (SCHEDULER_STOPPED())
966 #if defined(ADAPTIVE_SX)
967 lock_delay_arg_init(&lda, &sx_delay);
968 #elif defined(KDTRACE_HOOKS)
969 lock_delay_arg_init(&lda, NULL);
973 adaptive = ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0);
977 PMC_SOFT_CALL( , , lock, failed);
979 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
983 GIANT_SAVE(extra_work);
987 * As with rwlocks, we don't make any attempt to try to block
988 * shared locks once there is an exclusive waiter.
991 if (__sx_slock_try(sx, &x LOCK_FILE_LINE_ARG))
994 GIANT_SAVE(extra_work);
1001 if (__predict_false(!adaptive))
1004 * If the owner is running on another CPU, spin until
1005 * the owner stops running or the state of the lock
1008 owner = lv_sx_owner(x);
1009 if (TD_IS_RUNNING(owner)) {
1010 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1012 "%s: spinning on %p held by %p",
1013 __func__, sx, owner);
1014 KTR_STATE1(KTR_SCHED, "thread",
1015 sched_tdname(curthread), "spinning",
1016 "lockname:\"%s\"", sx->lock_object.lo_name);
1019 x = SX_READ_VALUE(sx);
1020 owner = lv_sx_owner(x);
1021 } while (owner != NULL && TD_IS_RUNNING(owner));
1022 KTR_STATE0(KTR_SCHED, "thread",
1023 sched_tdname(curthread), "running");
1030 * Some other thread already has an exclusive lock, so
1031 * start the process of blocking.
1033 sleepq_lock(&sx->lock_object);
1034 x = SX_READ_VALUE(sx);
1037 * The lock could have been released while we spun.
1038 * In this case loop back and retry.
1040 if (x & SX_LOCK_SHARED) {
1041 sleepq_release(&sx->lock_object);
1047 * If the owner is running on another CPU, spin until
1048 * the owner stops running or the state of the lock
1051 if (!(x & SX_LOCK_SHARED) && adaptive) {
1052 owner = (struct thread *)SX_OWNER(x);
1053 if (TD_IS_RUNNING(owner)) {
1054 sleepq_release(&sx->lock_object);
1055 x = SX_READ_VALUE(sx);
1062 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
1063 * fail to set it drop the sleep queue lock and loop
1066 if (!(x & SX_LOCK_SHARED_WAITERS)) {
1067 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
1068 x | SX_LOCK_SHARED_WAITERS))
1070 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1071 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1076 * Since we have been unable to acquire the shared lock,
1079 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1080 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1083 #ifdef KDTRACE_HOOKS
1084 sleep_time -= lockstat_nsecs(&sx->lock_object);
1086 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1087 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1088 SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1089 if (!(opts & SX_INTERRUPTIBLE))
1090 sleepq_wait(&sx->lock_object, 0);
1092 error = sleepq_wait_sig(&sx->lock_object, 0);
1093 #ifdef KDTRACE_HOOKS
1094 sleep_time += lockstat_nsecs(&sx->lock_object);
1098 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1100 "%s: interruptible sleep by %p suspended by signal",
1104 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1105 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1107 x = SX_READ_VALUE(sx);
1109 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1110 if (__predict_true(!extra_work))
1113 #ifdef KDTRACE_HOOKS
1114 all_time += lockstat_nsecs(&sx->lock_object);
1116 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1117 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1118 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1119 if (lda.spin_cnt > sleep_cnt)
1120 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1121 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1122 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1126 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1127 contested, waittime, file, line, LOCKSTAT_READER);
1134 _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
1139 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1140 !TD_IS_IDLETHREAD(curthread),
1141 ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1142 curthread, sx->lock_object.lo_name, file, line));
1143 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1144 ("sx_slock() of destroyed sx @ %s:%d", file, line));
1145 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1148 x = SX_READ_VALUE(sx);
1149 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__acquire) ||
1150 !__sx_slock_try(sx, &x LOCK_FILE_LINE_ARG)))
1151 error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1153 lock_profile_obtain_lock_success(&sx->lock_object, 0, 0,
1156 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1157 WITNESS_LOCK(&sx->lock_object, 0, file, line);
1158 TD_LOCKS_INC(curthread);
1164 _sx_slock(struct sx *sx, int opts, const char *file, int line)
1167 return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1170 static bool __always_inline
1171 _sx_sunlock_try(struct sx *sx, uintptr_t *xp)
1176 * We should never have sharers while at least one thread
1177 * holds a shared lock.
1179 KASSERT(!(*xp & SX_LOCK_SHARED_WAITERS),
1180 ("%s: waiting sharers", __func__));
1183 * See if there is more than one shared lock held. If
1184 * so, just drop one and return.
1186 if (SX_SHARERS(*xp) > 1) {
1187 if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1188 *xp - SX_ONE_SHARER)) {
1189 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1191 "%s: %p succeeded %p -> %p",
1192 __func__, sx, (void *)*xp,
1193 (void *)(*xp - SX_ONE_SHARER));
1200 * If there aren't any waiters for an exclusive lock,
1201 * then try to drop it quickly.
1203 if (!(*xp & SX_LOCK_EXCLUSIVE_WAITERS)) {
1204 MPASS(*xp == SX_SHARERS_LOCK(1));
1205 *xp = SX_SHARERS_LOCK(1);
1206 if (atomic_fcmpset_rel_ptr(&sx->sx_lock,
1207 xp, SX_LOCK_UNLOCKED)) {
1208 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1209 CTR2(KTR_LOCK, "%s: %p last succeeded",
1220 static void __noinline
1221 _sx_sunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
1223 int wakeup_swapper = 0;
1226 if (SCHEDULER_STOPPED())
1229 if (_sx_sunlock_try(sx, &x))
1233 * At this point, there should just be one sharer with
1234 * exclusive waiters.
1236 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1238 sleepq_lock(&sx->lock_object);
1239 x = SX_READ_VALUE(sx);
1241 MPASS(x & SX_LOCK_EXCLUSIVE_WAITERS);
1242 MPASS(!(x & SX_LOCK_SHARED_WAITERS));
1243 if (_sx_sunlock_try(sx, &x))
1247 * Wake up semantic here is quite simple:
1248 * Just wake up all the exclusive waiters.
1249 * Note that the state of the lock could have changed,
1250 * so if it fails loop back and retry.
1252 setx = x - SX_ONE_SHARER;
1253 setx &= ~SX_LOCK_EXCLUSIVE_WAITERS;
1254 if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
1256 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1257 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1258 "exclusive queue", __func__, sx);
1259 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1260 0, SQ_EXCLUSIVE_QUEUE);
1263 sleepq_release(&sx->lock_object);
1267 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1271 _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1275 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1276 ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1277 _sx_assert(sx, SA_SLOCKED, file, line);
1278 WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1279 LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1281 x = SX_READ_VALUE(sx);
1282 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__release) ||
1283 !_sx_sunlock_try(sx, &x)))
1284 _sx_sunlock_hard(sx, x LOCK_FILE_LINE_ARG);
1286 lock_profile_release_lock(&sx->lock_object);
1288 TD_LOCKS_DEC(curthread);
1292 _sx_sunlock(struct sx *sx, const char *file, int line)
1295 _sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1298 #ifdef INVARIANT_SUPPORT
1304 * In the non-WITNESS case, sx_assert() can only detect that at least
1305 * *some* thread owns an slock, but it cannot guarantee that *this*
1306 * thread owns an slock.
1309 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1315 if (SCHEDULER_STOPPED())
1319 case SA_SLOCKED | SA_NOTRECURSED:
1320 case SA_SLOCKED | SA_RECURSED:
1326 case SA_LOCKED | SA_NOTRECURSED:
1327 case SA_LOCKED | SA_RECURSED:
1329 witness_assert(&sx->lock_object, what, file, line);
1332 * If some other thread has an exclusive lock or we
1333 * have one and are asserting a shared lock, fail.
1334 * Also, if no one has a lock at all, fail.
1336 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1337 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1338 sx_xholder(sx) != curthread)))
1339 panic("Lock %s not %slocked @ %s:%d\n",
1340 sx->lock_object.lo_name, slocked ? "share " : "",
1343 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1344 if (sx_recursed(sx)) {
1345 if (what & SA_NOTRECURSED)
1346 panic("Lock %s recursed @ %s:%d\n",
1347 sx->lock_object.lo_name, file,
1349 } else if (what & SA_RECURSED)
1350 panic("Lock %s not recursed @ %s:%d\n",
1351 sx->lock_object.lo_name, file, line);
1356 case SA_XLOCKED | SA_NOTRECURSED:
1357 case SA_XLOCKED | SA_RECURSED:
1358 if (sx_xholder(sx) != curthread)
1359 panic("Lock %s not exclusively locked @ %s:%d\n",
1360 sx->lock_object.lo_name, file, line);
1361 if (sx_recursed(sx)) {
1362 if (what & SA_NOTRECURSED)
1363 panic("Lock %s recursed @ %s:%d\n",
1364 sx->lock_object.lo_name, file, line);
1365 } else if (what & SA_RECURSED)
1366 panic("Lock %s not recursed @ %s:%d\n",
1367 sx->lock_object.lo_name, file, line);
1371 witness_assert(&sx->lock_object, what, file, line);
1374 * If we hold an exclusve lock fail. We can't
1375 * reliably check to see if we hold a shared lock or
1378 if (sx_xholder(sx) == curthread)
1379 panic("Lock %s exclusively locked @ %s:%d\n",
1380 sx->lock_object.lo_name, file, line);
1384 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1388 #endif /* INVARIANT_SUPPORT */
1392 db_show_sx(const struct lock_object *lock)
1395 const struct sx *sx;
1397 sx = (const struct sx *)lock;
1399 db_printf(" state: ");
1400 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1401 db_printf("UNLOCKED\n");
1402 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1403 db_printf("DESTROYED\n");
1405 } else if (sx->sx_lock & SX_LOCK_SHARED)
1406 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1408 td = sx_xholder(sx);
1409 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1410 td->td_tid, td->td_proc->p_pid, td->td_name);
1411 if (sx_recursed(sx))
1412 db_printf(" recursed: %d\n", sx->sx_recurse);
1415 db_printf(" waiters: ");
1416 switch(sx->sx_lock &
1417 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1418 case SX_LOCK_SHARED_WAITERS:
1419 db_printf("shared\n");
1421 case SX_LOCK_EXCLUSIVE_WAITERS:
1422 db_printf("exclusive\n");
1424 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1425 db_printf("exclusive and shared\n");
1428 db_printf("none\n");
1433 * Check to see if a thread that is blocked on a sleep queue is actually
1434 * blocked on an sx lock. If so, output some details and return true.
1435 * If the lock has an exclusive owner, return that in *ownerp.
1438 sx_chain(struct thread *td, struct thread **ownerp)
1443 * Check to see if this thread is blocked on an sx lock.
1444 * First, we check the lock class. If that is ok, then we
1445 * compare the lock name against the wait message.
1448 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1449 sx->lock_object.lo_name != td->td_wmesg)
1452 /* We think we have an sx lock, so output some details. */
1453 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1454 *ownerp = sx_xholder(sx);
1455 if (sx->sx_lock & SX_LOCK_SHARED)
1456 db_printf("SLOCK (count %ju)\n",
1457 (uintmax_t)SX_SHARERS(sx->sx_lock));
1459 db_printf("XLOCK\n");