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))) {
484 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
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);
507 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
508 LOCKSTAT_RECORD0(sx__downgrade, sx);
515 sx_downgrade_(struct sx *sx, const char *file, int line)
518 sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
522 * This function represents the so-called 'hard case' for sx_xlock
523 * operation. All 'easy case' failures are redirected to this. Note
524 * that ideally this would be a static function, but it needs to be
525 * accessible from at least sx.h.
528 _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
533 volatile struct thread *owner;
534 u_int i, n, spintries = 0;
536 #ifdef LOCK_PROFILING
537 uint64_t waittime = 0;
541 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
542 struct lock_delay_arg lda;
546 int64_t sleep_time = 0;
547 int64_t all_time = 0;
549 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
554 tid = (uintptr_t)curthread;
555 if (SCHEDULER_STOPPED())
558 #if defined(ADAPTIVE_SX)
559 lock_delay_arg_init(&lda, &sx_delay);
560 #elif defined(KDTRACE_HOOKS)
561 lock_delay_arg_init(&lda, NULL);
564 if (__predict_false(x == SX_LOCK_UNLOCKED))
565 x = SX_READ_VALUE(sx);
567 /* If we already hold an exclusive lock, then recurse. */
568 if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
569 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
570 ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
571 sx->lock_object.lo_name, file, line));
573 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
574 if (LOCK_LOG_TEST(&sx->lock_object, 0))
575 CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
579 if (LOCK_LOG_TEST(&sx->lock_object, 0))
580 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
581 sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
584 PMC_SOFT_CALL( , , lock, failed);
586 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
589 #ifdef LOCK_PROFILING
592 #elif defined(KDTRACE_HOOKS)
593 extra_work = lockstat_enabled;
594 if (__predict_false(extra_work)) {
595 all_time -= lockstat_nsecs(&sx->lock_object);
601 if (x == SX_LOCK_UNLOCKED) {
602 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
611 * If the lock is write locked and the owner is
612 * running on another CPU, spin until the owner stops
613 * running or the state of the lock changes.
615 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
616 if ((x & SX_LOCK_SHARED) == 0) {
617 owner = lv_sx_owner(x);
618 if (TD_IS_RUNNING(owner)) {
619 if (LOCK_LOG_TEST(&sx->lock_object, 0))
621 "%s: spinning on %p held by %p",
622 __func__, sx, owner);
623 KTR_STATE1(KTR_SCHED, "thread",
624 sched_tdname(curthread), "spinning",
626 sx->lock_object.lo_name);
627 GIANT_SAVE(extra_work);
630 x = SX_READ_VALUE(sx);
631 owner = lv_sx_owner(x);
632 } while (owner != NULL &&
633 TD_IS_RUNNING(owner));
634 KTR_STATE0(KTR_SCHED, "thread",
635 sched_tdname(curthread), "running");
638 } else if (SX_SHARERS(x) && spintries < asx_retries) {
639 KTR_STATE1(KTR_SCHED, "thread",
640 sched_tdname(curthread), "spinning",
641 "lockname:\"%s\"", sx->lock_object.lo_name);
642 GIANT_SAVE(extra_work);
644 for (i = 0; i < asx_loops; i += n) {
645 if (LOCK_LOG_TEST(&sx->lock_object, 0))
647 "%s: shared spinning on %p with %u and %u",
648 __func__, sx, spintries, i);
651 x = SX_READ_VALUE(sx);
652 if ((x & SX_LOCK_SHARED) == 0 ||
659 KTR_STATE0(KTR_SCHED, "thread",
660 sched_tdname(curthread), "running");
667 sleepq_lock(&sx->lock_object);
668 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_cmpset_acq_ptr(&sx->sx_lock,
709 SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
710 tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
711 sleepq_release(&sx->lock_object);
712 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
716 sleepq_release(&sx->lock_object);
717 x = SX_READ_VALUE(sx);
722 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
723 * than loop back and retry.
725 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
726 if (!atomic_cmpset_ptr(&sx->sx_lock, x,
727 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
728 sleepq_release(&sx->lock_object);
729 x = SX_READ_VALUE(sx);
732 if (LOCK_LOG_TEST(&sx->lock_object, 0))
733 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
738 * Since we have been unable to acquire the exclusive
739 * lock and the exclusive waiters flag is set, we have
742 if (LOCK_LOG_TEST(&sx->lock_object, 0))
743 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
747 sleep_time -= lockstat_nsecs(&sx->lock_object);
749 GIANT_SAVE(extra_work);
750 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
751 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
752 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
753 if (!(opts & SX_INTERRUPTIBLE))
754 sleepq_wait(&sx->lock_object, 0);
756 error = sleepq_wait_sig(&sx->lock_object, 0);
758 sleep_time += lockstat_nsecs(&sx->lock_object);
762 if (LOCK_LOG_TEST(&sx->lock_object, 0))
764 "%s: interruptible sleep by %p suspended by signal",
768 if (LOCK_LOG_TEST(&sx->lock_object, 0))
769 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
771 x = SX_READ_VALUE(sx);
773 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
774 if (__predict_true(!extra_work))
778 all_time += lockstat_nsecs(&sx->lock_object);
780 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
781 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
782 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
783 if (lda.spin_cnt > sleep_cnt)
784 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
785 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
786 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
789 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
790 contested, waittime, file, line, LOCKSTAT_WRITER);
796 * This function represents the so-called 'hard case' for sx_xunlock
797 * operation. All 'easy case' failures are redirected to this. Note
798 * that ideally this would be a static function, but it needs to be
799 * accessible from at least sx.h.
802 _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
805 int queue, wakeup_swapper;
807 if (SCHEDULER_STOPPED())
810 tid = (uintptr_t)curthread;
812 if (__predict_false(x == tid))
813 x = SX_READ_VALUE(sx);
815 MPASS(!(x & SX_LOCK_SHARED));
817 if (__predict_false(x & SX_LOCK_RECURSED)) {
818 /* The lock is recursed, unrecurse one level. */
819 if ((--sx->sx_recurse) == 0)
820 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
821 if (LOCK_LOG_TEST(&sx->lock_object, 0))
822 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
826 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
828 atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
831 if (LOCK_LOG_TEST(&sx->lock_object, 0))
832 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
834 sleepq_lock(&sx->lock_object);
835 x = SX_READ_VALUE(sx);
836 MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
839 * The wake up algorithm here is quite simple and probably not
840 * ideal. It gives precedence to shared waiters if they are
841 * present. For this condition, we have to preserve the
842 * state of the exclusive waiters flag.
843 * If interruptible sleeps left the shared queue empty avoid a
844 * starvation for the threads sleeping on the exclusive queue by giving
845 * them precedence and cleaning up the shared waiters bit anyway.
847 setx = SX_LOCK_UNLOCKED;
848 queue = SQ_EXCLUSIVE_QUEUE;
849 if ((x & SX_LOCK_SHARED_WAITERS) != 0 &&
850 sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
851 queue = SQ_SHARED_QUEUE;
852 setx |= (x & SX_LOCK_EXCLUSIVE_WAITERS);
854 atomic_store_rel_ptr(&sx->sx_lock, setx);
856 /* Wake up all the waiters for the specific queue. */
857 if (LOCK_LOG_TEST(&sx->lock_object, 0))
858 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
859 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
862 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
864 sleepq_release(&sx->lock_object);
869 static bool __always_inline
870 __sx_slock_try(struct sx *sx, uintptr_t *xp LOCK_FILE_LINE_ARG_DEF)
874 * If no other thread has an exclusive lock then try to bump up
875 * the count of sharers. Since we have to preserve the state
876 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
877 * shared lock loop back and retry.
879 while (*xp & SX_LOCK_SHARED) {
880 MPASS(!(*xp & SX_LOCK_SHARED_WAITERS));
881 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
882 *xp + SX_ONE_SHARER)) {
883 if (LOCK_LOG_TEST(&sx->lock_object, 0))
884 CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
885 __func__, sx, (void *)*xp,
886 (void *)(*xp + SX_ONE_SHARER));
893 static int __noinline
894 _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
898 volatile struct thread *owner;
900 #ifdef LOCK_PROFILING
901 uint64_t waittime = 0;
905 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
906 struct lock_delay_arg lda;
910 int64_t sleep_time = 0;
911 int64_t all_time = 0;
913 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
918 if (SCHEDULER_STOPPED())
921 #if defined(ADAPTIVE_SX)
922 lock_delay_arg_init(&lda, &sx_delay);
923 #elif defined(KDTRACE_HOOKS)
924 lock_delay_arg_init(&lda, NULL);
928 PMC_SOFT_CALL( , , lock, failed);
930 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
933 #ifdef LOCK_PROFILING
936 #elif defined(KDTRACE_HOOKS)
937 extra_work = lockstat_enabled;
938 if (__predict_false(extra_work)) {
939 all_time -= lockstat_nsecs(&sx->lock_object);
945 * As with rwlocks, we don't make any attempt to try to block
946 * shared locks once there is an exclusive waiter.
949 if (__sx_slock_try(sx, &x LOCK_FILE_LINE_ARG))
957 * If the owner is running on another CPU, spin until
958 * the owner stops running or the state of the lock
961 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
962 owner = lv_sx_owner(x);
963 if (TD_IS_RUNNING(owner)) {
964 if (LOCK_LOG_TEST(&sx->lock_object, 0))
966 "%s: spinning on %p held by %p",
967 __func__, sx, owner);
968 KTR_STATE1(KTR_SCHED, "thread",
969 sched_tdname(curthread), "spinning",
970 "lockname:\"%s\"", sx->lock_object.lo_name);
971 GIANT_SAVE(extra_work);
974 x = SX_READ_VALUE(sx);
975 owner = lv_sx_owner(x);
976 } while (owner != NULL && TD_IS_RUNNING(owner));
977 KTR_STATE0(KTR_SCHED, "thread",
978 sched_tdname(curthread), "running");
985 * Some other thread already has an exclusive lock, so
986 * start the process of blocking.
988 sleepq_lock(&sx->lock_object);
989 x = SX_READ_VALUE(sx);
992 * The lock could have been released while we spun.
993 * In this case loop back and retry.
995 if (x & SX_LOCK_SHARED) {
996 sleepq_release(&sx->lock_object);
1002 * If the owner is running on another CPU, spin until
1003 * the owner stops running or the state of the lock
1006 if (!(x & SX_LOCK_SHARED) &&
1007 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
1008 owner = (struct thread *)SX_OWNER(x);
1009 if (TD_IS_RUNNING(owner)) {
1010 sleepq_release(&sx->lock_object);
1011 x = SX_READ_VALUE(sx);
1018 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
1019 * fail to set it drop the sleep queue lock and loop
1022 if (!(x & SX_LOCK_SHARED_WAITERS)) {
1023 if (!atomic_cmpset_ptr(&sx->sx_lock, x,
1024 x | SX_LOCK_SHARED_WAITERS)) {
1025 sleepq_release(&sx->lock_object);
1026 x = SX_READ_VALUE(sx);
1029 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1030 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1035 * Since we have been unable to acquire the shared lock,
1038 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1039 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1042 #ifdef KDTRACE_HOOKS
1043 sleep_time -= lockstat_nsecs(&sx->lock_object);
1045 GIANT_SAVE(extra_work);
1046 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1047 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1048 SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1049 if (!(opts & SX_INTERRUPTIBLE))
1050 sleepq_wait(&sx->lock_object, 0);
1052 error = sleepq_wait_sig(&sx->lock_object, 0);
1053 #ifdef KDTRACE_HOOKS
1054 sleep_time += lockstat_nsecs(&sx->lock_object);
1058 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1060 "%s: interruptible sleep by %p suspended by signal",
1064 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1065 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1067 x = SX_READ_VALUE(sx);
1069 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1070 if (__predict_true(!extra_work))
1073 #ifdef KDTRACE_HOOKS
1074 all_time += lockstat_nsecs(&sx->lock_object);
1076 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1077 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1078 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1079 if (lda.spin_cnt > sleep_cnt)
1080 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1081 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1082 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1085 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1086 contested, waittime, file, line, LOCKSTAT_READER);
1093 _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
1098 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1099 !TD_IS_IDLETHREAD(curthread),
1100 ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1101 curthread, sx->lock_object.lo_name, file, line));
1102 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1103 ("sx_slock() of destroyed sx @ %s:%d", file, line));
1104 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1107 x = SX_READ_VALUE(sx);
1108 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(sx__acquire) ||
1109 !__sx_slock_try(sx, &x LOCK_FILE_LINE_ARG)))
1110 error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1112 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1113 WITNESS_LOCK(&sx->lock_object, 0, file, line);
1114 TD_LOCKS_INC(curthread);
1120 _sx_slock(struct sx *sx, int opts, const char *file, int line)
1123 return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1126 static bool __always_inline
1127 _sx_sunlock_try(struct sx *sx, uintptr_t *xp)
1132 * We should never have sharers while at least one thread
1133 * holds a shared lock.
1135 KASSERT(!(*xp & SX_LOCK_SHARED_WAITERS),
1136 ("%s: waiting sharers", __func__));
1139 * See if there is more than one shared lock held. If
1140 * so, just drop one and return.
1142 if (SX_SHARERS(*xp) > 1) {
1143 if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1144 *xp - SX_ONE_SHARER)) {
1145 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1147 "%s: %p succeeded %p -> %p",
1148 __func__, sx, (void *)*xp,
1149 (void *)(*xp - SX_ONE_SHARER));
1156 * If there aren't any waiters for an exclusive lock,
1157 * then try to drop it quickly.
1159 if (!(*xp & SX_LOCK_EXCLUSIVE_WAITERS)) {
1160 MPASS(*xp == SX_SHARERS_LOCK(1));
1161 *xp = SX_SHARERS_LOCK(1);
1162 if (atomic_fcmpset_rel_ptr(&sx->sx_lock,
1163 xp, SX_LOCK_UNLOCKED)) {
1164 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1165 CTR2(KTR_LOCK, "%s: %p last succeeded",
1176 static void __noinline
1177 _sx_sunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
1181 if (SCHEDULER_STOPPED())
1184 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1187 if (_sx_sunlock_try(sx, &x))
1191 * At this point, there should just be one sharer with
1192 * exclusive waiters.
1194 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1196 sleepq_lock(&sx->lock_object);
1199 * Wake up semantic here is quite simple:
1200 * Just wake up all the exclusive waiters.
1201 * Note that the state of the lock could have changed,
1202 * so if it fails loop back and retry.
1204 if (!atomic_cmpset_rel_ptr(&sx->sx_lock,
1205 SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
1206 SX_LOCK_UNLOCKED)) {
1207 sleepq_release(&sx->lock_object);
1208 x = SX_READ_VALUE(sx);
1211 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1212 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1213 "exclusive queue", __func__, sx);
1214 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1215 0, SQ_EXCLUSIVE_QUEUE);
1216 sleepq_release(&sx->lock_object);
1224 _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1228 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1229 ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1230 _sx_assert(sx, SA_SLOCKED, file, line);
1231 WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1232 LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1234 x = SX_READ_VALUE(sx);
1235 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(sx__release) ||
1236 !_sx_sunlock_try(sx, &x)))
1237 _sx_sunlock_hard(sx, x LOCK_FILE_LINE_ARG);
1239 TD_LOCKS_DEC(curthread);
1243 _sx_sunlock(struct sx *sx, const char *file, int line)
1246 _sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1249 #ifdef INVARIANT_SUPPORT
1255 * In the non-WITNESS case, sx_assert() can only detect that at least
1256 * *some* thread owns an slock, but it cannot guarantee that *this*
1257 * thread owns an slock.
1260 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1266 if (panicstr != NULL)
1270 case SA_SLOCKED | SA_NOTRECURSED:
1271 case SA_SLOCKED | SA_RECURSED:
1277 case SA_LOCKED | SA_NOTRECURSED:
1278 case SA_LOCKED | SA_RECURSED:
1280 witness_assert(&sx->lock_object, what, file, line);
1283 * If some other thread has an exclusive lock or we
1284 * have one and are asserting a shared lock, fail.
1285 * Also, if no one has a lock at all, fail.
1287 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1288 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1289 sx_xholder(sx) != curthread)))
1290 panic("Lock %s not %slocked @ %s:%d\n",
1291 sx->lock_object.lo_name, slocked ? "share " : "",
1294 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1295 if (sx_recursed(sx)) {
1296 if (what & SA_NOTRECURSED)
1297 panic("Lock %s recursed @ %s:%d\n",
1298 sx->lock_object.lo_name, file,
1300 } else if (what & SA_RECURSED)
1301 panic("Lock %s not recursed @ %s:%d\n",
1302 sx->lock_object.lo_name, file, line);
1307 case SA_XLOCKED | SA_NOTRECURSED:
1308 case SA_XLOCKED | SA_RECURSED:
1309 if (sx_xholder(sx) != curthread)
1310 panic("Lock %s not exclusively locked @ %s:%d\n",
1311 sx->lock_object.lo_name, file, line);
1312 if (sx_recursed(sx)) {
1313 if (what & SA_NOTRECURSED)
1314 panic("Lock %s recursed @ %s:%d\n",
1315 sx->lock_object.lo_name, file, line);
1316 } else if (what & SA_RECURSED)
1317 panic("Lock %s not recursed @ %s:%d\n",
1318 sx->lock_object.lo_name, file, line);
1322 witness_assert(&sx->lock_object, what, file, line);
1325 * If we hold an exclusve lock fail. We can't
1326 * reliably check to see if we hold a shared lock or
1329 if (sx_xholder(sx) == curthread)
1330 panic("Lock %s exclusively locked @ %s:%d\n",
1331 sx->lock_object.lo_name, file, line);
1335 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1339 #endif /* INVARIANT_SUPPORT */
1343 db_show_sx(const struct lock_object *lock)
1346 const struct sx *sx;
1348 sx = (const struct sx *)lock;
1350 db_printf(" state: ");
1351 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1352 db_printf("UNLOCKED\n");
1353 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1354 db_printf("DESTROYED\n");
1356 } else if (sx->sx_lock & SX_LOCK_SHARED)
1357 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1359 td = sx_xholder(sx);
1360 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1361 td->td_tid, td->td_proc->p_pid, td->td_name);
1362 if (sx_recursed(sx))
1363 db_printf(" recursed: %d\n", sx->sx_recurse);
1366 db_printf(" waiters: ");
1367 switch(sx->sx_lock &
1368 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1369 case SX_LOCK_SHARED_WAITERS:
1370 db_printf("shared\n");
1372 case SX_LOCK_EXCLUSIVE_WAITERS:
1373 db_printf("exclusive\n");
1375 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1376 db_printf("exclusive and shared\n");
1379 db_printf("none\n");
1384 * Check to see if a thread that is blocked on a sleep queue is actually
1385 * blocked on an sx lock. If so, output some details and return true.
1386 * If the lock has an exclusive owner, return that in *ownerp.
1389 sx_chain(struct thread *td, struct thread **ownerp)
1394 * Check to see if this thread is blocked on an sx lock.
1395 * First, we check the lock class. If that is ok, then we
1396 * compare the lock name against the wait message.
1399 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1400 sx->lock_object.lo_name != td->td_wmesg)
1403 /* We think we have an sx lock, so output some details. */
1404 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1405 *ownerp = sx_xholder(sx);
1406 if (sx->sx_lock & SX_LOCK_SHARED)
1407 db_printf("SLOCK (count %ju)\n",
1408 (uintmax_t)SX_SHARERS(sx->sx_lock));
1410 db_printf("XLOCK\n");