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 (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 = 10;
147 static __read_frequently u_int asx_loops = 10000;
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,
159 LOCK_DELAY_SYSINIT_DEFAULT(sx_delay);
163 assert_sx(const struct lock_object *lock, int what)
166 sx_assert((const struct sx *)lock, what);
170 lock_sx(struct lock_object *lock, uintptr_t how)
174 sx = (struct sx *)lock;
182 unlock_sx(struct lock_object *lock)
186 sx = (struct sx *)lock;
187 sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
188 if (sx_xlocked(sx)) {
199 owner_sx(const struct lock_object *lock, struct thread **owner)
204 sx = (const struct sx *)lock;
207 return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
208 ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
213 sx_sysinit(void *arg)
215 struct sx_args *sargs = arg;
217 sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
221 sx_init_flags(struct sx *sx, const char *description, int opts)
225 MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
226 SX_NOPROFILE | SX_NOADAPTIVE | SX_NEW)) == 0);
227 ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
228 ("%s: sx_lock not aligned for %s: %p", __func__, description,
231 flags = LO_SLEEPABLE | LO_UPGRADABLE;
234 if (opts & SX_NOPROFILE)
235 flags |= LO_NOPROFILE;
236 if (!(opts & SX_NOWITNESS))
238 if (opts & SX_RECURSE)
239 flags |= LO_RECURSABLE;
245 flags |= opts & SX_NOADAPTIVE;
246 lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
247 sx->sx_lock = SX_LOCK_UNLOCKED;
252 sx_destroy(struct sx *sx)
255 KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
256 KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
257 sx->sx_lock = SX_LOCK_DESTROYED;
258 lock_destroy(&sx->lock_object);
262 sx_try_slock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
266 if (SCHEDULER_STOPPED())
269 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
270 ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
271 curthread, sx->lock_object.lo_name, file, line));
275 KASSERT(x != SX_LOCK_DESTROYED,
276 ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
277 if (!(x & SX_LOCK_SHARED))
279 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, x + SX_ONE_SHARER)) {
280 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
281 WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
282 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
283 sx, 0, 0, file, line, LOCKSTAT_READER);
284 TD_LOCKS_INC(curthread);
289 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
294 sx_try_slock_(struct sx *sx, const char *file, int line)
297 return (sx_try_slock_int(sx LOCK_FILE_LINE_ARG));
301 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
306 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
307 !TD_IS_IDLETHREAD(curthread),
308 ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
309 curthread, sx->lock_object.lo_name, file, line));
310 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
311 ("sx_xlock() of destroyed sx @ %s:%d", file, line));
312 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
314 tid = (uintptr_t)curthread;
315 x = SX_LOCK_UNLOCKED;
316 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
317 error = _sx_xlock_hard(sx, x, opts LOCK_FILE_LINE_ARG);
319 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
320 0, 0, file, line, LOCKSTAT_WRITER);
322 LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
324 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
325 TD_LOCKS_INC(curthread);
332 sx_try_xlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
341 if (SCHEDULER_STOPPED_TD(td))
344 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
345 ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
346 curthread, sx->lock_object.lo_name, file, line));
347 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
348 ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
352 x = SX_LOCK_UNLOCKED;
354 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
356 if (x == SX_LOCK_UNLOCKED)
358 if (x == tid && (sx->lock_object.lo_flags & LO_RECURSABLE)) {
360 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
367 LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
369 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
372 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
373 sx, 0, 0, file, line, LOCKSTAT_WRITER);
374 TD_LOCKS_INC(curthread);
381 sx_try_xlock_(struct sx *sx, const char *file, int line)
384 return (sx_try_xlock_int(sx LOCK_FILE_LINE_ARG));
388 _sx_xunlock(struct sx *sx, const char *file, int line)
391 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
392 ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
393 _sx_assert(sx, SA_XLOCKED, file, line);
394 WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
395 LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
398 _sx_xunlock_hard(sx, (uintptr_t)curthread, file, line);
400 __sx_xunlock(sx, curthread, file, line);
402 TD_LOCKS_DEC(curthread);
406 * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
407 * This will only succeed if this thread holds a single shared lock.
408 * Return 1 if if the upgrade succeed, 0 otherwise.
411 sx_try_upgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
416 if (SCHEDULER_STOPPED())
419 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
420 ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
421 _sx_assert(sx, SA_SLOCKED, file, line);
424 * Try to switch from one shared lock to an exclusive lock. We need
425 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
426 * we will wake up the exclusive waiters when we drop the lock.
428 x = sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS;
429 success = atomic_cmpset_acq_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) | x,
430 (uintptr_t)curthread | x);
431 LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
433 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
435 LOCKSTAT_RECORD0(sx__upgrade, sx);
441 sx_try_upgrade_(struct sx *sx, const char *file, int line)
444 return (sx_try_upgrade_int(sx LOCK_FILE_LINE_ARG));
448 * Downgrade an unrecursed exclusive lock into a single shared lock.
451 sx_downgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
456 if (SCHEDULER_STOPPED())
459 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
460 ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
461 _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
464 panic("downgrade of a recursed lock");
467 WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
470 * Try to switch from an exclusive lock with no shared waiters
471 * to one sharer with no shared waiters. If there are
472 * exclusive waiters, we don't need to lock the sleep queue so
473 * long as we preserve the flag. We do one quick try and if
474 * that fails we grab the sleepq lock to keep the flags from
475 * changing and do it the slow way.
477 * We have to lock the sleep queue if there are shared waiters
478 * so we can wake them up.
481 if (!(x & SX_LOCK_SHARED_WAITERS) &&
482 atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
483 (x & SX_LOCK_EXCLUSIVE_WAITERS)))
487 * Lock the sleep queue so we can read the waiters bits
488 * without any races and wakeup any shared waiters.
490 sleepq_lock(&sx->lock_object);
493 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
494 * shared lock. If there are any shared waiters, wake them up.
498 atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
499 (x & SX_LOCK_EXCLUSIVE_WAITERS));
500 if (x & SX_LOCK_SHARED_WAITERS)
501 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
503 sleepq_release(&sx->lock_object);
509 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
510 LOCKSTAT_RECORD0(sx__downgrade, sx);
514 sx_downgrade_(struct sx *sx, const char *file, int line)
517 sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
521 * This function represents the so-called 'hard case' for sx_xlock
522 * operation. All 'easy case' failures are redirected to this. Note
523 * that ideally this would be a static function, but it needs to be
524 * accessible from at least sx.h.
527 _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
532 volatile struct thread *owner;
533 u_int i, n, spintries = 0;
535 #ifdef LOCK_PROFILING
536 uint64_t waittime = 0;
540 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
541 struct lock_delay_arg lda;
545 int64_t sleep_time = 0;
546 int64_t all_time = 0;
548 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
553 tid = (uintptr_t)curthread;
554 if (SCHEDULER_STOPPED())
557 #if defined(ADAPTIVE_SX)
558 lock_delay_arg_init(&lda, &sx_delay);
559 #elif defined(KDTRACE_HOOKS)
560 lock_delay_arg_init(&lda, NULL);
563 if (__predict_false(x == SX_LOCK_UNLOCKED))
564 x = SX_READ_VALUE(sx);
566 /* If we already hold an exclusive lock, then recurse. */
567 if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
568 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
569 ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
570 sx->lock_object.lo_name, file, line));
572 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
573 if (LOCK_LOG_TEST(&sx->lock_object, 0))
574 CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
578 if (LOCK_LOG_TEST(&sx->lock_object, 0))
579 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
580 sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
583 PMC_SOFT_CALL( , , lock, failed);
585 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
588 #ifdef LOCK_PROFILING
591 #elif defined(KDTRACE_HOOKS)
592 extra_work = lockstat_enabled;
593 if (__predict_false(extra_work)) {
594 all_time -= lockstat_nsecs(&sx->lock_object);
600 if (x == SX_LOCK_UNLOCKED) {
601 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
610 * If the lock is write locked and the owner is
611 * running on another CPU, spin until the owner stops
612 * running or the state of the lock changes.
614 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
615 if ((x & SX_LOCK_SHARED) == 0) {
616 owner = lv_sx_owner(x);
617 if (TD_IS_RUNNING(owner)) {
618 if (LOCK_LOG_TEST(&sx->lock_object, 0))
620 "%s: spinning on %p held by %p",
621 __func__, sx, owner);
622 KTR_STATE1(KTR_SCHED, "thread",
623 sched_tdname(curthread), "spinning",
625 sx->lock_object.lo_name);
626 GIANT_SAVE(extra_work);
629 x = SX_READ_VALUE(sx);
630 owner = lv_sx_owner(x);
631 } while (owner != NULL &&
632 TD_IS_RUNNING(owner));
633 KTR_STATE0(KTR_SCHED, "thread",
634 sched_tdname(curthread), "running");
637 } else if (SX_SHARERS(x) && spintries < asx_retries) {
638 KTR_STATE1(KTR_SCHED, "thread",
639 sched_tdname(curthread), "spinning",
640 "lockname:\"%s\"", sx->lock_object.lo_name);
641 GIANT_SAVE(extra_work);
643 for (i = 0; i < asx_loops; i += n) {
644 if (LOCK_LOG_TEST(&sx->lock_object, 0))
646 "%s: shared spinning on %p with %u and %u",
647 __func__, sx, spintries, i);
650 x = SX_READ_VALUE(sx);
651 if ((x & SX_LOCK_SHARED) == 0 ||
658 KTR_STATE0(KTR_SCHED, "thread",
659 sched_tdname(curthread), "running");
666 sleepq_lock(&sx->lock_object);
667 x = SX_READ_VALUE(sx);
671 * If the lock was released while spinning on the
672 * sleep queue chain lock, try again.
674 if (x == SX_LOCK_UNLOCKED) {
675 sleepq_release(&sx->lock_object);
681 * The current lock owner might have started executing
682 * on another CPU (or the lock could have changed
683 * owners) while we were waiting on the sleep queue
684 * chain lock. If so, drop the sleep queue lock and try
687 if (!(x & SX_LOCK_SHARED) &&
688 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
689 owner = (struct thread *)SX_OWNER(x);
690 if (TD_IS_RUNNING(owner)) {
691 sleepq_release(&sx->lock_object);
698 * If an exclusive lock was released with both shared
699 * and exclusive waiters and a shared waiter hasn't
700 * woken up and acquired the lock yet, sx_lock will be
701 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
702 * If we see that value, try to acquire it once. Note
703 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
704 * as there are other exclusive waiters still. If we
705 * fail, restart the loop.
707 if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
708 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
709 tid | SX_LOCK_EXCLUSIVE_WAITERS))
711 sleepq_release(&sx->lock_object);
712 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
718 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
719 * than loop back and retry.
721 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
722 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
723 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
726 if (LOCK_LOG_TEST(&sx->lock_object, 0))
727 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
732 * Since we have been unable to acquire the exclusive
733 * lock and the exclusive waiters flag is set, we have
736 if (LOCK_LOG_TEST(&sx->lock_object, 0))
737 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
741 sleep_time -= lockstat_nsecs(&sx->lock_object);
743 GIANT_SAVE(extra_work);
744 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
745 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
746 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
747 if (!(opts & SX_INTERRUPTIBLE))
748 sleepq_wait(&sx->lock_object, 0);
750 error = sleepq_wait_sig(&sx->lock_object, 0);
752 sleep_time += lockstat_nsecs(&sx->lock_object);
756 if (LOCK_LOG_TEST(&sx->lock_object, 0))
758 "%s: interruptible sleep by %p suspended by signal",
762 if (LOCK_LOG_TEST(&sx->lock_object, 0))
763 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
765 x = SX_READ_VALUE(sx);
767 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
768 if (__predict_true(!extra_work))
772 all_time += lockstat_nsecs(&sx->lock_object);
774 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
775 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
776 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
777 if (lda.spin_cnt > sleep_cnt)
778 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
779 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
780 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
783 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
784 contested, waittime, file, line, LOCKSTAT_WRITER);
790 * This function represents the so-called 'hard case' for sx_xunlock
791 * operation. All 'easy case' failures are redirected to this. Note
792 * that ideally this would be a static function, but it needs to be
793 * accessible from at least sx.h.
796 _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
799 int queue, wakeup_swapper;
801 if (SCHEDULER_STOPPED())
804 tid = (uintptr_t)curthread;
806 if (__predict_false(x == tid))
807 x = SX_READ_VALUE(sx);
809 MPASS(!(x & SX_LOCK_SHARED));
811 if (__predict_false(x & SX_LOCK_RECURSED)) {
812 /* The lock is recursed, unrecurse one level. */
813 if ((--sx->sx_recurse) == 0)
814 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
815 if (LOCK_LOG_TEST(&sx->lock_object, 0))
816 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
820 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
822 atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
825 if (LOCK_LOG_TEST(&sx->lock_object, 0))
826 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
828 sleepq_lock(&sx->lock_object);
829 x = SX_READ_VALUE(sx);
830 MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
833 * The wake up algorithm here is quite simple and probably not
834 * ideal. It gives precedence to shared waiters if they are
835 * present. For this condition, we have to preserve the
836 * state of the exclusive waiters flag.
837 * If interruptible sleeps left the shared queue empty avoid a
838 * starvation for the threads sleeping on the exclusive queue by giving
839 * them precedence and cleaning up the shared waiters bit anyway.
841 setx = SX_LOCK_UNLOCKED;
842 queue = SQ_EXCLUSIVE_QUEUE;
843 if ((x & SX_LOCK_SHARED_WAITERS) != 0 &&
844 sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
845 queue = SQ_SHARED_QUEUE;
846 setx |= (x & SX_LOCK_EXCLUSIVE_WAITERS);
848 atomic_store_rel_ptr(&sx->sx_lock, setx);
850 /* Wake up all the waiters for the specific queue. */
851 if (LOCK_LOG_TEST(&sx->lock_object, 0))
852 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
853 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
856 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
858 sleepq_release(&sx->lock_object);
863 static bool __always_inline
864 __sx_slock_try(struct sx *sx, uintptr_t *xp LOCK_FILE_LINE_ARG_DEF)
868 * If no other thread has an exclusive lock then try to bump up
869 * the count of sharers. Since we have to preserve the state
870 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
871 * shared lock loop back and retry.
873 while (*xp & SX_LOCK_SHARED) {
874 MPASS(!(*xp & SX_LOCK_SHARED_WAITERS));
875 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
876 *xp + SX_ONE_SHARER)) {
877 if (LOCK_LOG_TEST(&sx->lock_object, 0))
878 CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
879 __func__, sx, (void *)*xp,
880 (void *)(*xp + SX_ONE_SHARER));
887 static int __noinline
888 _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
892 volatile struct thread *owner;
894 #ifdef LOCK_PROFILING
895 uint64_t waittime = 0;
899 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
900 struct lock_delay_arg lda;
904 int64_t sleep_time = 0;
905 int64_t all_time = 0;
907 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
912 if (SCHEDULER_STOPPED())
915 #if defined(ADAPTIVE_SX)
916 lock_delay_arg_init(&lda, &sx_delay);
917 #elif defined(KDTRACE_HOOKS)
918 lock_delay_arg_init(&lda, NULL);
922 PMC_SOFT_CALL( , , lock, failed);
924 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
927 #ifdef LOCK_PROFILING
930 #elif defined(KDTRACE_HOOKS)
931 extra_work = lockstat_enabled;
932 if (__predict_false(extra_work)) {
933 all_time -= lockstat_nsecs(&sx->lock_object);
939 * As with rwlocks, we don't make any attempt to try to block
940 * shared locks once there is an exclusive waiter.
943 if (__sx_slock_try(sx, &x LOCK_FILE_LINE_ARG))
951 * If the owner is running on another CPU, spin until
952 * the owner stops running or the state of the lock
955 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
956 owner = lv_sx_owner(x);
957 if (TD_IS_RUNNING(owner)) {
958 if (LOCK_LOG_TEST(&sx->lock_object, 0))
960 "%s: spinning on %p held by %p",
961 __func__, sx, owner);
962 KTR_STATE1(KTR_SCHED, "thread",
963 sched_tdname(curthread), "spinning",
964 "lockname:\"%s\"", sx->lock_object.lo_name);
965 GIANT_SAVE(extra_work);
968 x = SX_READ_VALUE(sx);
969 owner = lv_sx_owner(x);
970 } while (owner != NULL && TD_IS_RUNNING(owner));
971 KTR_STATE0(KTR_SCHED, "thread",
972 sched_tdname(curthread), "running");
979 * Some other thread already has an exclusive lock, so
980 * start the process of blocking.
982 sleepq_lock(&sx->lock_object);
983 x = SX_READ_VALUE(sx);
986 * The lock could have been released while we spun.
987 * In this case loop back and retry.
989 if (x & SX_LOCK_SHARED) {
990 sleepq_release(&sx->lock_object);
996 * If the owner is running on another CPU, spin until
997 * the owner stops running or the state of the lock
1000 if (!(x & SX_LOCK_SHARED) &&
1001 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
1002 owner = (struct thread *)SX_OWNER(x);
1003 if (TD_IS_RUNNING(owner)) {
1004 sleepq_release(&sx->lock_object);
1005 x = SX_READ_VALUE(sx);
1012 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
1013 * fail to set it drop the sleep queue lock and loop
1016 if (!(x & SX_LOCK_SHARED_WAITERS)) {
1017 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
1018 x | SX_LOCK_SHARED_WAITERS))
1020 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1021 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1026 * Since we have been unable to acquire the shared lock,
1029 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1030 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1033 #ifdef KDTRACE_HOOKS
1034 sleep_time -= lockstat_nsecs(&sx->lock_object);
1036 GIANT_SAVE(extra_work);
1037 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1038 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1039 SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1040 if (!(opts & SX_INTERRUPTIBLE))
1041 sleepq_wait(&sx->lock_object, 0);
1043 error = sleepq_wait_sig(&sx->lock_object, 0);
1044 #ifdef KDTRACE_HOOKS
1045 sleep_time += lockstat_nsecs(&sx->lock_object);
1049 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1051 "%s: interruptible sleep by %p suspended by signal",
1055 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1056 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1058 x = SX_READ_VALUE(sx);
1060 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1061 if (__predict_true(!extra_work))
1064 #ifdef KDTRACE_HOOKS
1065 all_time += lockstat_nsecs(&sx->lock_object);
1067 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1068 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1069 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1070 if (lda.spin_cnt > sleep_cnt)
1071 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1072 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1073 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1076 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1077 contested, waittime, file, line, LOCKSTAT_READER);
1084 _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
1089 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1090 !TD_IS_IDLETHREAD(curthread),
1091 ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1092 curthread, sx->lock_object.lo_name, file, line));
1093 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1094 ("sx_slock() of destroyed sx @ %s:%d", file, line));
1095 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1098 x = SX_READ_VALUE(sx);
1099 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(sx__acquire) ||
1100 !__sx_slock_try(sx, &x LOCK_FILE_LINE_ARG)))
1101 error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1103 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1104 WITNESS_LOCK(&sx->lock_object, 0, file, line);
1105 TD_LOCKS_INC(curthread);
1111 _sx_slock(struct sx *sx, int opts, const char *file, int line)
1114 return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1117 static bool __always_inline
1118 _sx_sunlock_try(struct sx *sx, uintptr_t *xp)
1123 * We should never have sharers while at least one thread
1124 * holds a shared lock.
1126 KASSERT(!(*xp & SX_LOCK_SHARED_WAITERS),
1127 ("%s: waiting sharers", __func__));
1130 * See if there is more than one shared lock held. If
1131 * so, just drop one and return.
1133 if (SX_SHARERS(*xp) > 1) {
1134 if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1135 *xp - SX_ONE_SHARER)) {
1136 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1138 "%s: %p succeeded %p -> %p",
1139 __func__, sx, (void *)*xp,
1140 (void *)(*xp - SX_ONE_SHARER));
1147 * If there aren't any waiters for an exclusive lock,
1148 * then try to drop it quickly.
1150 if (!(*xp & SX_LOCK_EXCLUSIVE_WAITERS)) {
1151 MPASS(*xp == SX_SHARERS_LOCK(1));
1152 *xp = SX_SHARERS_LOCK(1);
1153 if (atomic_fcmpset_rel_ptr(&sx->sx_lock,
1154 xp, SX_LOCK_UNLOCKED)) {
1155 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1156 CTR2(KTR_LOCK, "%s: %p last succeeded",
1167 static void __noinline
1168 _sx_sunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
1173 if (SCHEDULER_STOPPED())
1176 if (_sx_sunlock_try(sx, &x))
1180 * At this point, there should just be one sharer with
1181 * exclusive waiters.
1183 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1185 sleepq_lock(&sx->lock_object);
1186 x = SX_READ_VALUE(sx);
1188 MPASS(x & SX_LOCK_EXCLUSIVE_WAITERS);
1189 MPASS(!(x & SX_LOCK_SHARED_WAITERS));
1191 * Wake up semantic here is quite simple:
1192 * Just wake up all the exclusive waiters.
1193 * Note that the state of the lock could have changed,
1194 * so if it fails loop back and retry.
1196 setx = x - SX_ONE_SHARER;
1197 setx &= ~SX_LOCK_EXCLUSIVE_WAITERS;
1198 if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
1200 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1201 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1202 "exclusive queue", __func__, sx);
1203 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1204 0, SQ_EXCLUSIVE_QUEUE);
1207 sleepq_release(&sx->lock_object);
1211 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1215 _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1219 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1220 ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1221 _sx_assert(sx, SA_SLOCKED, file, line);
1222 WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1223 LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1225 x = SX_READ_VALUE(sx);
1226 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(sx__release) ||
1227 !_sx_sunlock_try(sx, &x)))
1228 _sx_sunlock_hard(sx, x LOCK_FILE_LINE_ARG);
1230 TD_LOCKS_DEC(curthread);
1234 _sx_sunlock(struct sx *sx, const char *file, int line)
1237 _sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1240 #ifdef INVARIANT_SUPPORT
1246 * In the non-WITNESS case, sx_assert() can only detect that at least
1247 * *some* thread owns an slock, but it cannot guarantee that *this*
1248 * thread owns an slock.
1251 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1257 if (panicstr != NULL)
1261 case SA_SLOCKED | SA_NOTRECURSED:
1262 case SA_SLOCKED | SA_RECURSED:
1268 case SA_LOCKED | SA_NOTRECURSED:
1269 case SA_LOCKED | SA_RECURSED:
1271 witness_assert(&sx->lock_object, what, file, line);
1274 * If some other thread has an exclusive lock or we
1275 * have one and are asserting a shared lock, fail.
1276 * Also, if no one has a lock at all, fail.
1278 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1279 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1280 sx_xholder(sx) != curthread)))
1281 panic("Lock %s not %slocked @ %s:%d\n",
1282 sx->lock_object.lo_name, slocked ? "share " : "",
1285 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1286 if (sx_recursed(sx)) {
1287 if (what & SA_NOTRECURSED)
1288 panic("Lock %s recursed @ %s:%d\n",
1289 sx->lock_object.lo_name, file,
1291 } else if (what & SA_RECURSED)
1292 panic("Lock %s not recursed @ %s:%d\n",
1293 sx->lock_object.lo_name, file, line);
1298 case SA_XLOCKED | SA_NOTRECURSED:
1299 case SA_XLOCKED | SA_RECURSED:
1300 if (sx_xholder(sx) != curthread)
1301 panic("Lock %s not exclusively locked @ %s:%d\n",
1302 sx->lock_object.lo_name, file, line);
1303 if (sx_recursed(sx)) {
1304 if (what & SA_NOTRECURSED)
1305 panic("Lock %s recursed @ %s:%d\n",
1306 sx->lock_object.lo_name, file, line);
1307 } else if (what & SA_RECURSED)
1308 panic("Lock %s not recursed @ %s:%d\n",
1309 sx->lock_object.lo_name, file, line);
1313 witness_assert(&sx->lock_object, what, file, line);
1316 * If we hold an exclusve lock fail. We can't
1317 * reliably check to see if we hold a shared lock or
1320 if (sx_xholder(sx) == curthread)
1321 panic("Lock %s exclusively locked @ %s:%d\n",
1322 sx->lock_object.lo_name, file, line);
1326 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1330 #endif /* INVARIANT_SUPPORT */
1334 db_show_sx(const struct lock_object *lock)
1337 const struct sx *sx;
1339 sx = (const struct sx *)lock;
1341 db_printf(" state: ");
1342 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1343 db_printf("UNLOCKED\n");
1344 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1345 db_printf("DESTROYED\n");
1347 } else if (sx->sx_lock & SX_LOCK_SHARED)
1348 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1350 td = sx_xholder(sx);
1351 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1352 td->td_tid, td->td_proc->p_pid, td->td_name);
1353 if (sx_recursed(sx))
1354 db_printf(" recursed: %d\n", sx->sx_recurse);
1357 db_printf(" waiters: ");
1358 switch(sx->sx_lock &
1359 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1360 case SX_LOCK_SHARED_WAITERS:
1361 db_printf("shared\n");
1363 case SX_LOCK_EXCLUSIVE_WAITERS:
1364 db_printf("exclusive\n");
1366 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1367 db_printf("exclusive and shared\n");
1370 db_printf("none\n");
1375 * Check to see if a thread that is blocked on a sleep queue is actually
1376 * blocked on an sx lock. If so, output some details and return true.
1377 * If the lock has an exclusive owner, return that in *ownerp.
1380 sx_chain(struct thread *td, struct thread **ownerp)
1385 * Check to see if this thread is blocked on an sx lock.
1386 * First, we check the lock class. If that is ok, then we
1387 * compare the lock name against the wait message.
1390 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1391 sx->lock_object.lo_name != td->td_wmesg)
1394 /* We think we have an sx lock, so output some details. */
1395 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1396 *ownerp = sx_xholder(sx);
1397 if (sx->sx_lock & SX_LOCK_SHARED)
1398 db_printf("SLOCK (count %ju)\n",
1399 (uintmax_t)SX_SHARERS(sx->sx_lock));
1401 db_printf("XLOCK\n");