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)
74 CTASSERT((SX_NOADAPTIVE & LO_CLASSFLAGS) == SX_NOADAPTIVE);
77 #include <sys/pmckern.h>
78 PMC_SOFT_DECLARE( , , lock, failed);
81 /* Handy macros for sleep queues. */
82 #define SQ_EXCLUSIVE_QUEUE 0
83 #define SQ_SHARED_QUEUE 1
86 * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file. We
87 * drop Giant anytime we have to sleep or if we adaptively spin.
89 #define GIANT_DECLARE \
91 WITNESS_SAVE_DECL(Giant) \
93 #define GIANT_SAVE(work) do { \
94 if (mtx_owned(&Giant)) { \
96 WITNESS_SAVE(&Giant.lock_object, Giant); \
97 while (mtx_owned(&Giant)) { \
104 #define GIANT_RESTORE() do { \
105 if (_giantcnt > 0) { \
106 mtx_assert(&Giant, MA_NOTOWNED); \
107 while (_giantcnt--) \
109 WITNESS_RESTORE(&Giant.lock_object, Giant); \
114 * Returns true if an exclusive lock is recursed. It assumes
115 * curthread currently has an exclusive lock.
117 #define sx_recursed(sx) ((sx)->sx_recurse != 0)
119 static void assert_sx(const struct lock_object *lock, int what);
121 static void db_show_sx(const struct lock_object *lock);
123 static void lock_sx(struct lock_object *lock, uintptr_t how);
125 static int owner_sx(const struct lock_object *lock, struct thread **owner);
127 static uintptr_t unlock_sx(struct lock_object *lock);
129 struct lock_class lock_class_sx = {
131 .lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
132 .lc_assert = assert_sx,
134 .lc_ddb_show = db_show_sx,
137 .lc_unlock = unlock_sx,
139 .lc_owner = owner_sx,
144 #define _sx_assert(sx, what, file, line)
148 static __read_frequently u_int asx_retries = 10;
149 static __read_frequently u_int asx_loops = 10000;
150 static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD, NULL, "sxlock debugging");
151 SYSCTL_UINT(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
152 SYSCTL_UINT(_debug_sx, OID_AUTO, loops, CTLFLAG_RW, &asx_loops, 0, "");
154 static struct lock_delay_config __read_frequently sx_delay;
156 SYSCTL_INT(_debug_sx, OID_AUTO, delay_base, CTLFLAG_RW, &sx_delay.base,
158 SYSCTL_INT(_debug_sx, OID_AUTO, delay_max, CTLFLAG_RW, &sx_delay.max,
161 LOCK_DELAY_SYSINIT_DEFAULT(sx_delay);
165 assert_sx(const struct lock_object *lock, int what)
168 sx_assert((const struct sx *)lock, what);
172 lock_sx(struct lock_object *lock, uintptr_t how)
176 sx = (struct sx *)lock;
184 unlock_sx(struct lock_object *lock)
188 sx = (struct sx *)lock;
189 sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
190 if (sx_xlocked(sx)) {
201 owner_sx(const struct lock_object *lock, struct thread **owner)
206 sx = (const struct sx *)lock;
209 return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
210 ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
215 sx_sysinit(void *arg)
217 struct sx_args *sargs = arg;
219 sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
223 sx_init_flags(struct sx *sx, const char *description, int opts)
227 MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
228 SX_NOPROFILE | SX_NOADAPTIVE | SX_NEW)) == 0);
229 ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
230 ("%s: sx_lock not aligned for %s: %p", __func__, description,
233 flags = LO_SLEEPABLE | LO_UPGRADABLE;
236 if (opts & SX_NOPROFILE)
237 flags |= LO_NOPROFILE;
238 if (!(opts & SX_NOWITNESS))
240 if (opts & SX_RECURSE)
241 flags |= LO_RECURSABLE;
247 flags |= opts & SX_NOADAPTIVE;
248 lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
249 sx->sx_lock = SX_LOCK_UNLOCKED;
254 sx_destroy(struct sx *sx)
257 KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
258 KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
259 sx->sx_lock = SX_LOCK_DESTROYED;
260 lock_destroy(&sx->lock_object);
264 sx_try_slock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
268 if (SCHEDULER_STOPPED())
271 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
272 ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
273 curthread, sx->lock_object.lo_name, file, line));
277 KASSERT(x != SX_LOCK_DESTROYED,
278 ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
279 if (!(x & SX_LOCK_SHARED))
281 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, x + SX_ONE_SHARER)) {
282 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
283 WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
284 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
285 sx, 0, 0, file, line, LOCKSTAT_READER);
286 TD_LOCKS_INC(curthread);
291 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
296 sx_try_slock_(struct sx *sx, const char *file, int line)
299 return (sx_try_slock_int(sx LOCK_FILE_LINE_ARG));
303 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
308 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
309 !TD_IS_IDLETHREAD(curthread),
310 ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
311 curthread, sx->lock_object.lo_name, file, line));
312 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
313 ("sx_xlock() of destroyed sx @ %s:%d", file, line));
314 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
316 tid = (uintptr_t)curthread;
317 x = SX_LOCK_UNLOCKED;
318 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
319 error = _sx_xlock_hard(sx, x, opts LOCK_FILE_LINE_ARG);
321 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
322 0, 0, file, line, LOCKSTAT_WRITER);
324 LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
326 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
327 TD_LOCKS_INC(curthread);
334 sx_try_xlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
343 if (SCHEDULER_STOPPED_TD(td))
346 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
347 ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
348 curthread, sx->lock_object.lo_name, file, line));
349 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
350 ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
354 x = SX_LOCK_UNLOCKED;
356 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
358 if (x == SX_LOCK_UNLOCKED)
360 if (x == tid && (sx->lock_object.lo_flags & LO_RECURSABLE)) {
362 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
369 LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
371 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
374 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
375 sx, 0, 0, file, line, LOCKSTAT_WRITER);
376 TD_LOCKS_INC(curthread);
383 sx_try_xlock_(struct sx *sx, const char *file, int line)
386 return (sx_try_xlock_int(sx LOCK_FILE_LINE_ARG));
390 _sx_xunlock(struct sx *sx, const char *file, int line)
393 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
394 ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
395 _sx_assert(sx, SA_XLOCKED, file, line);
396 WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
397 LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
400 _sx_xunlock_hard(sx, (uintptr_t)curthread, file, line);
402 __sx_xunlock(sx, curthread, file, line);
404 TD_LOCKS_DEC(curthread);
408 * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
409 * This will only succeed if this thread holds a single shared lock.
410 * Return 1 if if the upgrade succeed, 0 otherwise.
413 sx_try_upgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
418 if (SCHEDULER_STOPPED())
421 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
422 ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
423 _sx_assert(sx, SA_SLOCKED, file, line);
426 * Try to switch from one shared lock to an exclusive lock. We need
427 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
428 * we will wake up the exclusive waiters when we drop the lock.
430 x = sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS;
431 success = atomic_cmpset_acq_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) | x,
432 (uintptr_t)curthread | x);
433 LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
435 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
437 LOCKSTAT_RECORD0(sx__upgrade, sx);
443 sx_try_upgrade_(struct sx *sx, const char *file, int line)
446 return (sx_try_upgrade_int(sx LOCK_FILE_LINE_ARG));
450 * Downgrade an unrecursed exclusive lock into a single shared lock.
453 sx_downgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
458 if (SCHEDULER_STOPPED())
461 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
462 ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
463 _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
466 panic("downgrade of a recursed lock");
469 WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
472 * Try to switch from an exclusive lock with no shared waiters
473 * to one sharer with no shared waiters. If there are
474 * exclusive waiters, we don't need to lock the sleep queue so
475 * long as we preserve the flag. We do one quick try and if
476 * that fails we grab the sleepq lock to keep the flags from
477 * changing and do it the slow way.
479 * We have to lock the sleep queue if there are shared waiters
480 * so we can wake them up.
483 if (!(x & SX_LOCK_SHARED_WAITERS) &&
484 atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
485 (x & SX_LOCK_EXCLUSIVE_WAITERS)))
489 * Lock the sleep queue so we can read the waiters bits
490 * without any races and wakeup any shared waiters.
492 sleepq_lock(&sx->lock_object);
495 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
496 * shared lock. If there are any shared waiters, wake them up.
500 atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
501 (x & SX_LOCK_EXCLUSIVE_WAITERS));
502 if (x & SX_LOCK_SHARED_WAITERS)
503 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
505 sleepq_release(&sx->lock_object);
511 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
512 LOCKSTAT_RECORD0(sx__downgrade, sx);
516 sx_downgrade_(struct sx *sx, const char *file, int line)
519 sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
523 * This function represents the so-called 'hard case' for sx_xlock
524 * operation. All 'easy case' failures are redirected to this. Note
525 * that ideally this would be a static function, but it needs to be
526 * accessible from at least sx.h.
529 _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
534 volatile struct thread *owner;
535 u_int i, n, spintries = 0;
537 #ifdef LOCK_PROFILING
538 uint64_t waittime = 0;
542 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
543 struct lock_delay_arg lda;
547 int64_t sleep_time = 0;
548 int64_t all_time = 0;
550 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
555 tid = (uintptr_t)curthread;
556 if (SCHEDULER_STOPPED())
559 #if defined(ADAPTIVE_SX)
560 lock_delay_arg_init(&lda, &sx_delay);
561 #elif defined(KDTRACE_HOOKS)
562 lock_delay_arg_init(&lda, NULL);
565 if (__predict_false(x == SX_LOCK_UNLOCKED))
566 x = SX_READ_VALUE(sx);
568 /* If we already hold an exclusive lock, then recurse. */
569 if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
570 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
571 ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
572 sx->lock_object.lo_name, file, line));
574 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
575 if (LOCK_LOG_TEST(&sx->lock_object, 0))
576 CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
580 if (LOCK_LOG_TEST(&sx->lock_object, 0))
581 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
582 sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
585 PMC_SOFT_CALL( , , lock, failed);
587 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
590 #ifdef LOCK_PROFILING
593 #elif defined(KDTRACE_HOOKS)
594 extra_work = lockstat_enabled;
595 if (__predict_false(extra_work)) {
596 all_time -= lockstat_nsecs(&sx->lock_object);
602 if (x == SX_LOCK_UNLOCKED) {
603 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
612 * If the lock is write locked and the owner is
613 * running on another CPU, spin until the owner stops
614 * running or the state of the lock changes.
616 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
617 if ((x & SX_LOCK_SHARED) == 0) {
618 owner = lv_sx_owner(x);
619 if (TD_IS_RUNNING(owner)) {
620 if (LOCK_LOG_TEST(&sx->lock_object, 0))
622 "%s: spinning on %p held by %p",
623 __func__, sx, owner);
624 KTR_STATE1(KTR_SCHED, "thread",
625 sched_tdname(curthread), "spinning",
627 sx->lock_object.lo_name);
628 GIANT_SAVE(extra_work);
631 x = SX_READ_VALUE(sx);
632 owner = lv_sx_owner(x);
633 } while (owner != NULL &&
634 TD_IS_RUNNING(owner));
635 KTR_STATE0(KTR_SCHED, "thread",
636 sched_tdname(curthread), "running");
639 } else if (SX_SHARERS(x) && spintries < asx_retries) {
640 KTR_STATE1(KTR_SCHED, "thread",
641 sched_tdname(curthread), "spinning",
642 "lockname:\"%s\"", sx->lock_object.lo_name);
643 GIANT_SAVE(extra_work);
645 for (i = 0; i < asx_loops; i += n) {
646 if (LOCK_LOG_TEST(&sx->lock_object, 0))
648 "%s: shared spinning on %p with %u and %u",
649 __func__, sx, spintries, i);
652 x = SX_READ_VALUE(sx);
653 if ((x & SX_LOCK_SHARED) == 0 ||
660 KTR_STATE0(KTR_SCHED, "thread",
661 sched_tdname(curthread), "running");
668 sleepq_lock(&sx->lock_object);
669 x = SX_READ_VALUE(sx);
673 * If the lock was released while spinning on the
674 * sleep queue chain lock, try again.
676 if (x == SX_LOCK_UNLOCKED) {
677 sleepq_release(&sx->lock_object);
683 * The current lock owner might have started executing
684 * on another CPU (or the lock could have changed
685 * owners) while we were waiting on the sleep queue
686 * chain lock. If so, drop the sleep queue lock and try
689 if (!(x & SX_LOCK_SHARED) &&
690 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
691 owner = (struct thread *)SX_OWNER(x);
692 if (TD_IS_RUNNING(owner)) {
693 sleepq_release(&sx->lock_object);
700 * If an exclusive lock was released with both shared
701 * and exclusive waiters and a shared waiter hasn't
702 * woken up and acquired the lock yet, sx_lock will be
703 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
704 * If we see that value, try to acquire it once. Note
705 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
706 * as there are other exclusive waiters still. If we
707 * fail, restart the loop.
709 if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
710 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
711 tid | SX_LOCK_EXCLUSIVE_WAITERS))
713 sleepq_release(&sx->lock_object);
714 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
720 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
721 * than loop back and retry.
723 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
724 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
725 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
728 if (LOCK_LOG_TEST(&sx->lock_object, 0))
729 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
734 * Since we have been unable to acquire the exclusive
735 * lock and the exclusive waiters flag is set, we have
738 if (LOCK_LOG_TEST(&sx->lock_object, 0))
739 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
743 sleep_time -= lockstat_nsecs(&sx->lock_object);
745 GIANT_SAVE(extra_work);
746 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
747 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
748 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
749 if (!(opts & SX_INTERRUPTIBLE))
750 sleepq_wait(&sx->lock_object, 0);
752 error = sleepq_wait_sig(&sx->lock_object, 0);
754 sleep_time += lockstat_nsecs(&sx->lock_object);
758 if (LOCK_LOG_TEST(&sx->lock_object, 0))
760 "%s: interruptible sleep by %p suspended by signal",
764 if (LOCK_LOG_TEST(&sx->lock_object, 0))
765 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
767 x = SX_READ_VALUE(sx);
769 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
770 if (__predict_true(!extra_work))
774 all_time += lockstat_nsecs(&sx->lock_object);
776 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
777 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
778 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
779 if (lda.spin_cnt > sleep_cnt)
780 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
781 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
782 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
785 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
786 contested, waittime, file, line, LOCKSTAT_WRITER);
792 * This function represents the so-called 'hard case' for sx_xunlock
793 * operation. All 'easy case' failures are redirected to this. Note
794 * that ideally this would be a static function, but it needs to be
795 * accessible from at least sx.h.
798 _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
801 int queue, wakeup_swapper;
803 if (SCHEDULER_STOPPED())
806 tid = (uintptr_t)curthread;
808 if (__predict_false(x == tid))
809 x = SX_READ_VALUE(sx);
811 MPASS(!(x & SX_LOCK_SHARED));
813 if (__predict_false(x & SX_LOCK_RECURSED)) {
814 /* The lock is recursed, unrecurse one level. */
815 if ((--sx->sx_recurse) == 0)
816 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
817 if (LOCK_LOG_TEST(&sx->lock_object, 0))
818 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
822 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
824 atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
827 if (LOCK_LOG_TEST(&sx->lock_object, 0))
828 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
830 sleepq_lock(&sx->lock_object);
831 x = SX_READ_VALUE(sx);
832 MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
835 * The wake up algorithm here is quite simple and probably not
836 * ideal. It gives precedence to shared waiters if they are
837 * present. For this condition, we have to preserve the
838 * state of the exclusive waiters flag.
839 * If interruptible sleeps left the shared queue empty avoid a
840 * starvation for the threads sleeping on the exclusive queue by giving
841 * them precedence and cleaning up the shared waiters bit anyway.
843 setx = SX_LOCK_UNLOCKED;
844 queue = SQ_EXCLUSIVE_QUEUE;
845 if ((x & SX_LOCK_SHARED_WAITERS) != 0 &&
846 sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
847 queue = SQ_SHARED_QUEUE;
848 setx |= (x & SX_LOCK_EXCLUSIVE_WAITERS);
850 atomic_store_rel_ptr(&sx->sx_lock, setx);
852 /* Wake up all the waiters for the specific queue. */
853 if (LOCK_LOG_TEST(&sx->lock_object, 0))
854 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
855 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
858 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
860 sleepq_release(&sx->lock_object);
865 static bool __always_inline
866 __sx_slock_try(struct sx *sx, uintptr_t *xp LOCK_FILE_LINE_ARG_DEF)
870 * If no other thread has an exclusive lock then try to bump up
871 * the count of sharers. Since we have to preserve the state
872 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
873 * shared lock loop back and retry.
875 while (*xp & SX_LOCK_SHARED) {
876 MPASS(!(*xp & SX_LOCK_SHARED_WAITERS));
877 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
878 *xp + SX_ONE_SHARER)) {
879 if (LOCK_LOG_TEST(&sx->lock_object, 0))
880 CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
881 __func__, sx, (void *)*xp,
882 (void *)(*xp + SX_ONE_SHARER));
889 static int __noinline
890 _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
894 volatile struct thread *owner;
896 #ifdef LOCK_PROFILING
897 uint64_t waittime = 0;
901 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
902 struct lock_delay_arg lda;
906 int64_t sleep_time = 0;
907 int64_t all_time = 0;
909 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
914 if (SCHEDULER_STOPPED())
917 #if defined(ADAPTIVE_SX)
918 lock_delay_arg_init(&lda, &sx_delay);
919 #elif defined(KDTRACE_HOOKS)
920 lock_delay_arg_init(&lda, NULL);
924 PMC_SOFT_CALL( , , lock, failed);
926 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
929 #ifdef LOCK_PROFILING
932 #elif defined(KDTRACE_HOOKS)
933 extra_work = lockstat_enabled;
934 if (__predict_false(extra_work)) {
935 all_time -= lockstat_nsecs(&sx->lock_object);
941 * As with rwlocks, we don't make any attempt to try to block
942 * shared locks once there is an exclusive waiter.
945 if (__sx_slock_try(sx, &x LOCK_FILE_LINE_ARG))
953 * If the owner is running on another CPU, spin until
954 * the owner stops running or the state of the lock
957 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
958 owner = lv_sx_owner(x);
959 if (TD_IS_RUNNING(owner)) {
960 if (LOCK_LOG_TEST(&sx->lock_object, 0))
962 "%s: spinning on %p held by %p",
963 __func__, sx, owner);
964 KTR_STATE1(KTR_SCHED, "thread",
965 sched_tdname(curthread), "spinning",
966 "lockname:\"%s\"", sx->lock_object.lo_name);
967 GIANT_SAVE(extra_work);
970 x = SX_READ_VALUE(sx);
971 owner = lv_sx_owner(x);
972 } while (owner != NULL && TD_IS_RUNNING(owner));
973 KTR_STATE0(KTR_SCHED, "thread",
974 sched_tdname(curthread), "running");
981 * Some other thread already has an exclusive lock, so
982 * start the process of blocking.
984 sleepq_lock(&sx->lock_object);
985 x = SX_READ_VALUE(sx);
988 * The lock could have been released while we spun.
989 * In this case loop back and retry.
991 if (x & SX_LOCK_SHARED) {
992 sleepq_release(&sx->lock_object);
998 * If the owner is running on another CPU, spin until
999 * the owner stops running or the state of the lock
1002 if (!(x & SX_LOCK_SHARED) &&
1003 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
1004 owner = (struct thread *)SX_OWNER(x);
1005 if (TD_IS_RUNNING(owner)) {
1006 sleepq_release(&sx->lock_object);
1007 x = SX_READ_VALUE(sx);
1014 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
1015 * fail to set it drop the sleep queue lock and loop
1018 if (!(x & SX_LOCK_SHARED_WAITERS)) {
1019 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
1020 x | SX_LOCK_SHARED_WAITERS))
1022 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1023 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1028 * Since we have been unable to acquire the shared lock,
1031 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1032 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1035 #ifdef KDTRACE_HOOKS
1036 sleep_time -= lockstat_nsecs(&sx->lock_object);
1038 GIANT_SAVE(extra_work);
1039 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1040 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1041 SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1042 if (!(opts & SX_INTERRUPTIBLE))
1043 sleepq_wait(&sx->lock_object, 0);
1045 error = sleepq_wait_sig(&sx->lock_object, 0);
1046 #ifdef KDTRACE_HOOKS
1047 sleep_time += lockstat_nsecs(&sx->lock_object);
1051 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1053 "%s: interruptible sleep by %p suspended by signal",
1057 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1058 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1060 x = SX_READ_VALUE(sx);
1062 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1063 if (__predict_true(!extra_work))
1066 #ifdef KDTRACE_HOOKS
1067 all_time += lockstat_nsecs(&sx->lock_object);
1069 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1070 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1071 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1072 if (lda.spin_cnt > sleep_cnt)
1073 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1074 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1075 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1078 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1079 contested, waittime, file, line, LOCKSTAT_READER);
1086 _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
1091 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1092 !TD_IS_IDLETHREAD(curthread),
1093 ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1094 curthread, sx->lock_object.lo_name, file, line));
1095 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1096 ("sx_slock() of destroyed sx @ %s:%d", file, line));
1097 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1100 x = SX_READ_VALUE(sx);
1101 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(sx__acquire) ||
1102 !__sx_slock_try(sx, &x LOCK_FILE_LINE_ARG)))
1103 error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1105 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1106 WITNESS_LOCK(&sx->lock_object, 0, file, line);
1107 TD_LOCKS_INC(curthread);
1113 _sx_slock(struct sx *sx, int opts, const char *file, int line)
1116 return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1119 static bool __always_inline
1120 _sx_sunlock_try(struct sx *sx, uintptr_t *xp)
1125 * We should never have sharers while at least one thread
1126 * holds a shared lock.
1128 KASSERT(!(*xp & SX_LOCK_SHARED_WAITERS),
1129 ("%s: waiting sharers", __func__));
1132 * See if there is more than one shared lock held. If
1133 * so, just drop one and return.
1135 if (SX_SHARERS(*xp) > 1) {
1136 if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1137 *xp - SX_ONE_SHARER)) {
1138 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1140 "%s: %p succeeded %p -> %p",
1141 __func__, sx, (void *)*xp,
1142 (void *)(*xp - SX_ONE_SHARER));
1149 * If there aren't any waiters for an exclusive lock,
1150 * then try to drop it quickly.
1152 if (!(*xp & SX_LOCK_EXCLUSIVE_WAITERS)) {
1153 MPASS(*xp == SX_SHARERS_LOCK(1));
1154 *xp = SX_SHARERS_LOCK(1);
1155 if (atomic_fcmpset_rel_ptr(&sx->sx_lock,
1156 xp, SX_LOCK_UNLOCKED)) {
1157 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1158 CTR2(KTR_LOCK, "%s: %p last succeeded",
1169 static void __noinline
1170 _sx_sunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
1175 if (SCHEDULER_STOPPED())
1178 if (_sx_sunlock_try(sx, &x))
1182 * At this point, there should just be one sharer with
1183 * exclusive waiters.
1185 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1187 sleepq_lock(&sx->lock_object);
1188 x = SX_READ_VALUE(sx);
1190 MPASS(x & SX_LOCK_EXCLUSIVE_WAITERS);
1191 MPASS(!(x & SX_LOCK_SHARED_WAITERS));
1193 * Wake up semantic here is quite simple:
1194 * Just wake up all the exclusive waiters.
1195 * Note that the state of the lock could have changed,
1196 * so if it fails loop back and retry.
1198 setx = x - SX_ONE_SHARER;
1199 setx &= ~SX_LOCK_EXCLUSIVE_WAITERS;
1200 if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
1202 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1203 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1204 "exclusive queue", __func__, sx);
1205 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1206 0, SQ_EXCLUSIVE_QUEUE);
1209 sleepq_release(&sx->lock_object);
1213 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1217 _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1221 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1222 ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1223 _sx_assert(sx, SA_SLOCKED, file, line);
1224 WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1225 LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1227 x = SX_READ_VALUE(sx);
1228 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(sx__release) ||
1229 !_sx_sunlock_try(sx, &x)))
1230 _sx_sunlock_hard(sx, x LOCK_FILE_LINE_ARG);
1232 TD_LOCKS_DEC(curthread);
1236 _sx_sunlock(struct sx *sx, const char *file, int line)
1239 _sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1242 #ifdef INVARIANT_SUPPORT
1248 * In the non-WITNESS case, sx_assert() can only detect that at least
1249 * *some* thread owns an slock, but it cannot guarantee that *this*
1250 * thread owns an slock.
1253 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1259 if (panicstr != NULL)
1263 case SA_SLOCKED | SA_NOTRECURSED:
1264 case SA_SLOCKED | SA_RECURSED:
1270 case SA_LOCKED | SA_NOTRECURSED:
1271 case SA_LOCKED | SA_RECURSED:
1273 witness_assert(&sx->lock_object, what, file, line);
1276 * If some other thread has an exclusive lock or we
1277 * have one and are asserting a shared lock, fail.
1278 * Also, if no one has a lock at all, fail.
1280 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1281 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1282 sx_xholder(sx) != curthread)))
1283 panic("Lock %s not %slocked @ %s:%d\n",
1284 sx->lock_object.lo_name, slocked ? "share " : "",
1287 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1288 if (sx_recursed(sx)) {
1289 if (what & SA_NOTRECURSED)
1290 panic("Lock %s recursed @ %s:%d\n",
1291 sx->lock_object.lo_name, file,
1293 } else if (what & SA_RECURSED)
1294 panic("Lock %s not recursed @ %s:%d\n",
1295 sx->lock_object.lo_name, file, line);
1300 case SA_XLOCKED | SA_NOTRECURSED:
1301 case SA_XLOCKED | SA_RECURSED:
1302 if (sx_xholder(sx) != curthread)
1303 panic("Lock %s not exclusively locked @ %s:%d\n",
1304 sx->lock_object.lo_name, file, line);
1305 if (sx_recursed(sx)) {
1306 if (what & SA_NOTRECURSED)
1307 panic("Lock %s recursed @ %s:%d\n",
1308 sx->lock_object.lo_name, file, line);
1309 } else if (what & SA_RECURSED)
1310 panic("Lock %s not recursed @ %s:%d\n",
1311 sx->lock_object.lo_name, file, line);
1315 witness_assert(&sx->lock_object, what, file, line);
1318 * If we hold an exclusve lock fail. We can't
1319 * reliably check to see if we hold a shared lock or
1322 if (sx_xholder(sx) == curthread)
1323 panic("Lock %s exclusively locked @ %s:%d\n",
1324 sx->lock_object.lo_name, file, line);
1328 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1332 #endif /* INVARIANT_SUPPORT */
1336 db_show_sx(const struct lock_object *lock)
1339 const struct sx *sx;
1341 sx = (const struct sx *)lock;
1343 db_printf(" state: ");
1344 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1345 db_printf("UNLOCKED\n");
1346 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1347 db_printf("DESTROYED\n");
1349 } else if (sx->sx_lock & SX_LOCK_SHARED)
1350 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1352 td = sx_xholder(sx);
1353 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1354 td->td_tid, td->td_proc->p_pid, td->td_name);
1355 if (sx_recursed(sx))
1356 db_printf(" recursed: %d\n", sx->sx_recurse);
1359 db_printf(" waiters: ");
1360 switch(sx->sx_lock &
1361 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1362 case SX_LOCK_SHARED_WAITERS:
1363 db_printf("shared\n");
1365 case SX_LOCK_EXCLUSIVE_WAITERS:
1366 db_printf("exclusive\n");
1368 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1369 db_printf("exclusive and shared\n");
1372 db_printf("none\n");
1377 * Check to see if a thread that is blocked on a sleep queue is actually
1378 * blocked on an sx lock. If so, output some details and return true.
1379 * If the lock has an exclusive owner, return that in *ownerp.
1382 sx_chain(struct thread *td, struct thread **ownerp)
1387 * Check to see if this thread is blocked on an sx lock.
1388 * First, we check the lock class. If that is ok, then we
1389 * compare the lock name against the wait message.
1392 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1393 sx->lock_object.lo_name != td->td_wmesg)
1396 /* We think we have an sx lock, so output some details. */
1397 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1398 *ownerp = sx_xholder(sx);
1399 if (sx->sx_lock & SX_LOCK_SHARED)
1400 db_printf("SLOCK (count %ju)\n",
1401 (uintmax_t)SX_SHARERS(sx->sx_lock));
1403 db_printf("XLOCK\n");