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() do { \
92 if (mtx_owned(&Giant)) { \
93 WITNESS_SAVE(&Giant.lock_object, Giant); \
94 while (mtx_owned(&Giant)) { \
101 #define GIANT_RESTORE() do { \
102 if (_giantcnt > 0) { \
103 mtx_assert(&Giant, MA_NOTOWNED); \
104 while (_giantcnt--) \
106 WITNESS_RESTORE(&Giant.lock_object, Giant); \
111 * Returns true if an exclusive lock is recursed. It assumes
112 * curthread currently has an exclusive lock.
114 #define sx_recursed(sx) ((sx)->sx_recurse != 0)
116 static void assert_sx(const struct lock_object *lock, int what);
118 static void db_show_sx(const struct lock_object *lock);
120 static void lock_sx(struct lock_object *lock, uintptr_t how);
122 static int owner_sx(const struct lock_object *lock, struct thread **owner);
124 static uintptr_t unlock_sx(struct lock_object *lock);
126 struct lock_class lock_class_sx = {
128 .lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
129 .lc_assert = assert_sx,
131 .lc_ddb_show = db_show_sx,
134 .lc_unlock = unlock_sx,
136 .lc_owner = owner_sx,
141 #define _sx_assert(sx, what, file, line)
145 static u_int asx_retries = 10;
146 static u_int asx_loops = 10000;
147 static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD, NULL, "sxlock debugging");
148 SYSCTL_UINT(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
149 SYSCTL_UINT(_debug_sx, OID_AUTO, loops, CTLFLAG_RW, &asx_loops, 0, "");
151 static struct lock_delay_config __read_mostly sx_delay;
153 SYSCTL_INT(_debug_sx, OID_AUTO, delay_base, CTLFLAG_RW, &sx_delay.base,
155 SYSCTL_INT(_debug_sx, OID_AUTO, delay_max, CTLFLAG_RW, &sx_delay.max,
158 LOCK_DELAY_SYSINIT_DEFAULT(sx_delay);
162 assert_sx(const struct lock_object *lock, int what)
165 sx_assert((const struct sx *)lock, what);
169 lock_sx(struct lock_object *lock, uintptr_t how)
173 sx = (struct sx *)lock;
181 unlock_sx(struct lock_object *lock)
185 sx = (struct sx *)lock;
186 sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
187 if (sx_xlocked(sx)) {
198 owner_sx(const struct lock_object *lock, struct thread **owner)
203 sx = (const struct sx *)lock;
206 return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
207 ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
212 sx_sysinit(void *arg)
214 struct sx_args *sargs = arg;
216 sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
220 sx_init_flags(struct sx *sx, const char *description, int opts)
224 MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
225 SX_NOPROFILE | SX_NOADAPTIVE | SX_NEW)) == 0);
226 ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
227 ("%s: sx_lock not aligned for %s: %p", __func__, description,
230 flags = LO_SLEEPABLE | LO_UPGRADABLE;
233 if (opts & SX_NOPROFILE)
234 flags |= LO_NOPROFILE;
235 if (!(opts & SX_NOWITNESS))
237 if (opts & SX_RECURSE)
238 flags |= LO_RECURSABLE;
244 flags |= opts & SX_NOADAPTIVE;
245 lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
246 sx->sx_lock = SX_LOCK_UNLOCKED;
251 sx_destroy(struct sx *sx)
254 KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
255 KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
256 sx->sx_lock = SX_LOCK_DESTROYED;
257 lock_destroy(&sx->lock_object);
261 sx_try_slock_(struct sx *sx, const char *file, int line)
265 if (SCHEDULER_STOPPED())
268 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
269 ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
270 curthread, sx->lock_object.lo_name, file, line));
274 KASSERT(x != SX_LOCK_DESTROYED,
275 ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
276 if (!(x & SX_LOCK_SHARED))
278 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, x + SX_ONE_SHARER)) {
279 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
280 WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
281 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
282 sx, 0, 0, file, line, LOCKSTAT_READER);
283 TD_LOCKS_INC(curthread);
288 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
293 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
298 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
299 ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
300 curthread, sx->lock_object.lo_name, file, line));
301 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
302 ("sx_xlock() of destroyed sx @ %s:%d", file, line));
303 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
305 tid = (uintptr_t)curthread;
306 x = SX_LOCK_UNLOCKED;
307 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
308 error = _sx_xlock_hard(sx, x, tid, opts, file, line);
310 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
311 0, 0, file, line, LOCKSTAT_WRITER);
313 LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
315 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
316 TD_LOCKS_INC(curthread);
323 sx_try_xlock_(struct sx *sx, const char *file, int line)
332 if (SCHEDULER_STOPPED_TD(td))
335 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
336 ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
337 curthread, sx->lock_object.lo_name, file, line));
338 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
339 ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
343 x = SX_LOCK_UNLOCKED;
345 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
347 if (x == SX_LOCK_UNLOCKED)
349 if (x == tid && (sx->lock_object.lo_flags & LO_RECURSABLE)) {
351 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
358 LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
360 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
363 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
364 sx, 0, 0, file, line, LOCKSTAT_WRITER);
365 TD_LOCKS_INC(curthread);
372 _sx_xunlock(struct sx *sx, const char *file, int line)
375 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
376 ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
377 _sx_assert(sx, SA_XLOCKED, file, line);
378 WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
379 LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
382 _sx_xunlock_hard(sx, (uintptr_t)curthread, file, line);
384 __sx_xunlock(sx, curthread, file, line);
386 TD_LOCKS_DEC(curthread);
390 * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
391 * This will only succeed if this thread holds a single shared lock.
392 * Return 1 if if the upgrade succeed, 0 otherwise.
395 sx_try_upgrade_(struct sx *sx, const char *file, int line)
400 if (SCHEDULER_STOPPED())
403 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
404 ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
405 _sx_assert(sx, SA_SLOCKED, file, line);
408 * Try to switch from one shared lock to an exclusive lock. We need
409 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
410 * we will wake up the exclusive waiters when we drop the lock.
412 x = sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS;
413 success = atomic_cmpset_acq_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) | x,
414 (uintptr_t)curthread | x);
415 LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
417 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
419 LOCKSTAT_RECORD0(sx__upgrade, sx);
425 * Downgrade an unrecursed exclusive lock into a single shared lock.
428 sx_downgrade_(struct sx *sx, const char *file, int line)
433 if (SCHEDULER_STOPPED())
436 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
437 ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
438 _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
441 panic("downgrade of a recursed lock");
444 WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
447 * Try to switch from an exclusive lock with no shared waiters
448 * to one sharer with no shared waiters. If there are
449 * exclusive waiters, we don't need to lock the sleep queue so
450 * long as we preserve the flag. We do one quick try and if
451 * that fails we grab the sleepq lock to keep the flags from
452 * changing and do it the slow way.
454 * We have to lock the sleep queue if there are shared waiters
455 * so we can wake them up.
458 if (!(x & SX_LOCK_SHARED_WAITERS) &&
459 atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
460 (x & SX_LOCK_EXCLUSIVE_WAITERS))) {
461 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
466 * Lock the sleep queue so we can read the waiters bits
467 * without any races and wakeup any shared waiters.
469 sleepq_lock(&sx->lock_object);
472 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
473 * shared lock. If there are any shared waiters, wake them up.
477 atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
478 (x & SX_LOCK_EXCLUSIVE_WAITERS));
479 if (x & SX_LOCK_SHARED_WAITERS)
480 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
482 sleepq_release(&sx->lock_object);
484 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
485 LOCKSTAT_RECORD0(sx__downgrade, sx);
492 * This function represents the so-called 'hard case' for sx_xlock
493 * operation. All 'easy case' failures are redirected to this. Note
494 * that ideally this would be a static function, but it needs to be
495 * accessible from at least sx.h.
498 _sx_xlock_hard(struct sx *sx, uintptr_t x, uintptr_t tid, int opts,
499 const char *file, int line)
503 volatile struct thread *owner;
504 u_int i, spintries = 0;
506 #ifdef LOCK_PROFILING
507 uint64_t waittime = 0;
511 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
512 struct lock_delay_arg lda;
517 int64_t sleep_time = 0;
518 int64_t all_time = 0;
521 if (SCHEDULER_STOPPED())
524 #if defined(ADAPTIVE_SX)
525 lock_delay_arg_init(&lda, &sx_delay);
526 #elif defined(KDTRACE_HOOKS)
527 lock_delay_arg_init(&lda, NULL);
530 if (__predict_false(x == SX_LOCK_UNLOCKED))
531 x = SX_READ_VALUE(sx);
533 /* If we already hold an exclusive lock, then recurse. */
534 if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
535 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
536 ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
537 sx->lock_object.lo_name, file, line));
539 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
540 if (LOCK_LOG_TEST(&sx->lock_object, 0))
541 CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
545 if (LOCK_LOG_TEST(&sx->lock_object, 0))
546 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
547 sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
550 all_time -= lockstat_nsecs(&sx->lock_object);
554 if (x == SX_LOCK_UNLOCKED) {
555 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
563 PMC_SOFT_CALL( , , lock, failed);
565 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
569 * If the lock is write locked and the owner is
570 * running on another CPU, spin until the owner stops
571 * running or the state of the lock changes.
573 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
574 if ((x & SX_LOCK_SHARED) == 0) {
575 owner = lv_sx_owner(x);
576 if (TD_IS_RUNNING(owner)) {
577 if (LOCK_LOG_TEST(&sx->lock_object, 0))
579 "%s: spinning on %p held by %p",
580 __func__, sx, owner);
581 KTR_STATE1(KTR_SCHED, "thread",
582 sched_tdname(curthread), "spinning",
584 sx->lock_object.lo_name);
588 x = SX_READ_VALUE(sx);
589 owner = lv_sx_owner(x);
590 } while (owner != NULL &&
591 TD_IS_RUNNING(owner));
592 KTR_STATE0(KTR_SCHED, "thread",
593 sched_tdname(curthread), "running");
596 } else if (SX_SHARERS(x) && spintries < asx_retries) {
597 KTR_STATE1(KTR_SCHED, "thread",
598 sched_tdname(curthread), "spinning",
599 "lockname:\"%s\"", sx->lock_object.lo_name);
602 for (i = 0; i < asx_loops; i++) {
603 if (LOCK_LOG_TEST(&sx->lock_object, 0))
605 "%s: shared spinning on %p with %u and %u",
606 __func__, sx, spintries, i);
608 if ((x & SX_LOCK_SHARED) == 0 ||
616 KTR_STATE0(KTR_SCHED, "thread",
617 sched_tdname(curthread), "running");
618 x = SX_READ_VALUE(sx);
625 sleepq_lock(&sx->lock_object);
626 x = SX_READ_VALUE(sx);
629 * If the lock was released while spinning on the
630 * sleep queue chain lock, try again.
632 if (x == SX_LOCK_UNLOCKED) {
633 sleepq_release(&sx->lock_object);
639 * The current lock owner might have started executing
640 * on another CPU (or the lock could have changed
641 * owners) while we were waiting on the sleep queue
642 * chain lock. If so, drop the sleep queue lock and try
645 if (!(x & SX_LOCK_SHARED) &&
646 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
647 owner = (struct thread *)SX_OWNER(x);
648 if (TD_IS_RUNNING(owner)) {
649 sleepq_release(&sx->lock_object);
656 * If an exclusive lock was released with both shared
657 * and exclusive waiters and a shared waiter hasn't
658 * woken up and acquired the lock yet, sx_lock will be
659 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
660 * If we see that value, try to acquire it once. Note
661 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
662 * as there are other exclusive waiters still. If we
663 * fail, restart the loop.
665 if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
666 if (atomic_cmpset_acq_ptr(&sx->sx_lock,
667 SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
668 tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
669 sleepq_release(&sx->lock_object);
670 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
674 sleepq_release(&sx->lock_object);
675 x = SX_READ_VALUE(sx);
680 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
681 * than loop back and retry.
683 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
684 if (!atomic_cmpset_ptr(&sx->sx_lock, x,
685 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
686 sleepq_release(&sx->lock_object);
687 x = SX_READ_VALUE(sx);
690 if (LOCK_LOG_TEST(&sx->lock_object, 0))
691 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
696 * Since we have been unable to acquire the exclusive
697 * lock and the exclusive waiters flag is set, we have
700 if (LOCK_LOG_TEST(&sx->lock_object, 0))
701 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
705 sleep_time -= lockstat_nsecs(&sx->lock_object);
708 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
709 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
710 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
711 if (!(opts & SX_INTERRUPTIBLE))
712 sleepq_wait(&sx->lock_object, 0);
714 error = sleepq_wait_sig(&sx->lock_object, 0);
716 sleep_time += lockstat_nsecs(&sx->lock_object);
720 if (LOCK_LOG_TEST(&sx->lock_object, 0))
722 "%s: interruptible sleep by %p suspended by signal",
726 if (LOCK_LOG_TEST(&sx->lock_object, 0))
727 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
729 x = SX_READ_VALUE(sx);
732 all_time += lockstat_nsecs(&sx->lock_object);
734 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
735 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
736 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
737 if (lda.spin_cnt > sleep_cnt)
738 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
739 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
740 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
743 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
744 contested, waittime, file, line, LOCKSTAT_WRITER);
750 * This function represents the so-called 'hard case' for sx_xunlock
751 * operation. All 'easy case' failures are redirected to this. Note
752 * that ideally this would be a static function, but it needs to be
753 * accessible from at least sx.h.
756 _sx_xunlock_hard(struct sx *sx, uintptr_t tid, const char *file, int line)
759 int queue, wakeup_swapper;
761 if (SCHEDULER_STOPPED())
764 MPASS(!(sx->sx_lock & SX_LOCK_SHARED));
766 x = SX_READ_VALUE(sx);
767 if (x & SX_LOCK_RECURSED) {
768 /* The lock is recursed, unrecurse one level. */
769 if ((--sx->sx_recurse) == 0)
770 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
771 if (LOCK_LOG_TEST(&sx->lock_object, 0))
772 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
776 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
778 atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
781 MPASS(sx->sx_lock & (SX_LOCK_SHARED_WAITERS |
782 SX_LOCK_EXCLUSIVE_WAITERS));
783 if (LOCK_LOG_TEST(&sx->lock_object, 0))
784 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
786 sleepq_lock(&sx->lock_object);
787 x = SX_LOCK_UNLOCKED;
790 * The wake up algorithm here is quite simple and probably not
791 * ideal. It gives precedence to shared waiters if they are
792 * present. For this condition, we have to preserve the
793 * state of the exclusive waiters flag.
794 * If interruptible sleeps left the shared queue empty avoid a
795 * starvation for the threads sleeping on the exclusive queue by giving
796 * them precedence and cleaning up the shared waiters bit anyway.
798 if ((sx->sx_lock & SX_LOCK_SHARED_WAITERS) != 0 &&
799 sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
800 queue = SQ_SHARED_QUEUE;
801 x |= (sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS);
803 queue = SQ_EXCLUSIVE_QUEUE;
805 /* Wake up all the waiters for the specific queue. */
806 if (LOCK_LOG_TEST(&sx->lock_object, 0))
807 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
808 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
810 atomic_store_rel_ptr(&sx->sx_lock, x);
811 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
813 sleepq_release(&sx->lock_object);
818 static bool __always_inline
819 __sx_slock_try(struct sx *sx, uintptr_t *xp, const char *file, int line)
823 * If no other thread has an exclusive lock then try to bump up
824 * the count of sharers. Since we have to preserve the state
825 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
826 * shared lock loop back and retry.
828 while (*xp & SX_LOCK_SHARED) {
829 MPASS(!(*xp & SX_LOCK_SHARED_WAITERS));
830 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
831 *xp + SX_ONE_SHARER)) {
832 if (LOCK_LOG_TEST(&sx->lock_object, 0))
833 CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
834 __func__, sx, (void *)*xp,
835 (void *)(*xp + SX_ONE_SHARER));
842 static int __noinline
843 _sx_slock_hard(struct sx *sx, int opts, const char *file, int line, uintptr_t x)
847 volatile struct thread *owner;
849 #ifdef LOCK_PROFILING
850 uint64_t waittime = 0;
854 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
855 struct lock_delay_arg lda;
860 int64_t sleep_time = 0;
861 int64_t all_time = 0;
864 if (SCHEDULER_STOPPED())
867 #if defined(ADAPTIVE_SX)
868 lock_delay_arg_init(&lda, &sx_delay);
869 #elif defined(KDTRACE_HOOKS)
870 lock_delay_arg_init(&lda, NULL);
873 all_time -= lockstat_nsecs(&sx->lock_object);
878 * As with rwlocks, we don't make any attempt to try to block
879 * shared locks once there is an exclusive waiter.
882 if (__sx_slock_try(sx, &x, file, line))
889 PMC_SOFT_CALL( , , lock, failed);
891 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
896 * If the owner is running on another CPU, spin until
897 * the owner stops running or the state of the lock
900 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
901 owner = lv_sx_owner(x);
902 if (TD_IS_RUNNING(owner)) {
903 if (LOCK_LOG_TEST(&sx->lock_object, 0))
905 "%s: spinning on %p held by %p",
906 __func__, sx, owner);
907 KTR_STATE1(KTR_SCHED, "thread",
908 sched_tdname(curthread), "spinning",
909 "lockname:\"%s\"", sx->lock_object.lo_name);
913 x = SX_READ_VALUE(sx);
914 owner = lv_sx_owner(x);
915 } while (owner != NULL && TD_IS_RUNNING(owner));
916 KTR_STATE0(KTR_SCHED, "thread",
917 sched_tdname(curthread), "running");
924 * Some other thread already has an exclusive lock, so
925 * start the process of blocking.
927 sleepq_lock(&sx->lock_object);
928 x = SX_READ_VALUE(sx);
931 * The lock could have been released while we spun.
932 * In this case loop back and retry.
934 if (x & SX_LOCK_SHARED) {
935 sleepq_release(&sx->lock_object);
941 * If the owner is running on another CPU, spin until
942 * the owner stops running or the state of the lock
945 if (!(x & SX_LOCK_SHARED) &&
946 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
947 owner = (struct thread *)SX_OWNER(x);
948 if (TD_IS_RUNNING(owner)) {
949 sleepq_release(&sx->lock_object);
950 x = SX_READ_VALUE(sx);
957 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
958 * fail to set it drop the sleep queue lock and loop
961 if (!(x & SX_LOCK_SHARED_WAITERS)) {
962 if (!atomic_cmpset_ptr(&sx->sx_lock, x,
963 x | SX_LOCK_SHARED_WAITERS)) {
964 sleepq_release(&sx->lock_object);
965 x = SX_READ_VALUE(sx);
968 if (LOCK_LOG_TEST(&sx->lock_object, 0))
969 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
974 * Since we have been unable to acquire the shared lock,
977 if (LOCK_LOG_TEST(&sx->lock_object, 0))
978 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
982 sleep_time -= lockstat_nsecs(&sx->lock_object);
985 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
986 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
987 SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
988 if (!(opts & SX_INTERRUPTIBLE))
989 sleepq_wait(&sx->lock_object, 0);
991 error = sleepq_wait_sig(&sx->lock_object, 0);
993 sleep_time += lockstat_nsecs(&sx->lock_object);
997 if (LOCK_LOG_TEST(&sx->lock_object, 0))
999 "%s: interruptible sleep by %p suspended by signal",
1003 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1004 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1006 x = SX_READ_VALUE(sx);
1008 #ifdef KDTRACE_HOOKS
1009 all_time += lockstat_nsecs(&sx->lock_object);
1011 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1012 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1013 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1014 if (lda.spin_cnt > sleep_cnt)
1015 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1016 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1017 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1020 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1021 contested, waittime, file, line, LOCKSTAT_READER);
1028 _sx_slock(struct sx *sx, int opts, const char *file, int line)
1033 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
1034 ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1035 curthread, sx->lock_object.lo_name, file, line));
1036 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1037 ("sx_slock() of destroyed sx @ %s:%d", file, line));
1038 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1041 x = SX_READ_VALUE(sx);
1042 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(sx__acquire) ||
1043 !__sx_slock_try(sx, &x, file, line)))
1044 error = _sx_slock_hard(sx, opts, file, line, x);
1046 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1047 WITNESS_LOCK(&sx->lock_object, 0, file, line);
1048 TD_LOCKS_INC(curthread);
1053 static bool __always_inline
1054 _sx_sunlock_try(struct sx *sx, uintptr_t *xp)
1059 * We should never have sharers while at least one thread
1060 * holds a shared lock.
1062 KASSERT(!(*xp & SX_LOCK_SHARED_WAITERS),
1063 ("%s: waiting sharers", __func__));
1066 * See if there is more than one shared lock held. If
1067 * so, just drop one and return.
1069 if (SX_SHARERS(*xp) > 1) {
1070 if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1071 *xp - SX_ONE_SHARER)) {
1072 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1074 "%s: %p succeeded %p -> %p",
1075 __func__, sx, (void *)*xp,
1076 (void *)(*xp - SX_ONE_SHARER));
1083 * If there aren't any waiters for an exclusive lock,
1084 * then try to drop it quickly.
1086 if (!(*xp & SX_LOCK_EXCLUSIVE_WAITERS)) {
1087 MPASS(*xp == SX_SHARERS_LOCK(1));
1088 *xp = SX_SHARERS_LOCK(1);
1089 if (atomic_fcmpset_rel_ptr(&sx->sx_lock,
1090 xp, SX_LOCK_UNLOCKED)) {
1091 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1092 CTR2(KTR_LOCK, "%s: %p last succeeded",
1103 static void __noinline
1104 _sx_sunlock_hard(struct sx *sx, uintptr_t x, const char *file, int line)
1108 if (SCHEDULER_STOPPED())
1111 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1114 if (_sx_sunlock_try(sx, &x))
1118 * At this point, there should just be one sharer with
1119 * exclusive waiters.
1121 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1123 sleepq_lock(&sx->lock_object);
1126 * Wake up semantic here is quite simple:
1127 * Just wake up all the exclusive waiters.
1128 * Note that the state of the lock could have changed,
1129 * so if it fails loop back and retry.
1131 if (!atomic_cmpset_rel_ptr(&sx->sx_lock,
1132 SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
1133 SX_LOCK_UNLOCKED)) {
1134 sleepq_release(&sx->lock_object);
1135 x = SX_READ_VALUE(sx);
1138 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1139 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1140 "exclusive queue", __func__, sx);
1141 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1142 0, SQ_EXCLUSIVE_QUEUE);
1143 sleepq_release(&sx->lock_object);
1151 _sx_sunlock(struct sx *sx, const char *file, int line)
1155 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1156 ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1157 _sx_assert(sx, SA_SLOCKED, file, line);
1158 WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1159 LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1161 x = SX_READ_VALUE(sx);
1162 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(sx__release) ||
1163 !_sx_sunlock_try(sx, &x)))
1164 _sx_sunlock_hard(sx, x, file, line);
1166 TD_LOCKS_DEC(curthread);
1169 #ifdef INVARIANT_SUPPORT
1175 * In the non-WITNESS case, sx_assert() can only detect that at least
1176 * *some* thread owns an slock, but it cannot guarantee that *this*
1177 * thread owns an slock.
1180 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1186 if (panicstr != NULL)
1190 case SA_SLOCKED | SA_NOTRECURSED:
1191 case SA_SLOCKED | SA_RECURSED:
1197 case SA_LOCKED | SA_NOTRECURSED:
1198 case SA_LOCKED | SA_RECURSED:
1200 witness_assert(&sx->lock_object, what, file, line);
1203 * If some other thread has an exclusive lock or we
1204 * have one and are asserting a shared lock, fail.
1205 * Also, if no one has a lock at all, fail.
1207 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1208 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1209 sx_xholder(sx) != curthread)))
1210 panic("Lock %s not %slocked @ %s:%d\n",
1211 sx->lock_object.lo_name, slocked ? "share " : "",
1214 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1215 if (sx_recursed(sx)) {
1216 if (what & SA_NOTRECURSED)
1217 panic("Lock %s recursed @ %s:%d\n",
1218 sx->lock_object.lo_name, file,
1220 } else if (what & SA_RECURSED)
1221 panic("Lock %s not recursed @ %s:%d\n",
1222 sx->lock_object.lo_name, file, line);
1227 case SA_XLOCKED | SA_NOTRECURSED:
1228 case SA_XLOCKED | SA_RECURSED:
1229 if (sx_xholder(sx) != curthread)
1230 panic("Lock %s not exclusively locked @ %s:%d\n",
1231 sx->lock_object.lo_name, file, line);
1232 if (sx_recursed(sx)) {
1233 if (what & SA_NOTRECURSED)
1234 panic("Lock %s recursed @ %s:%d\n",
1235 sx->lock_object.lo_name, file, line);
1236 } else if (what & SA_RECURSED)
1237 panic("Lock %s not recursed @ %s:%d\n",
1238 sx->lock_object.lo_name, file, line);
1242 witness_assert(&sx->lock_object, what, file, line);
1245 * If we hold an exclusve lock fail. We can't
1246 * reliably check to see if we hold a shared lock or
1249 if (sx_xholder(sx) == curthread)
1250 panic("Lock %s exclusively locked @ %s:%d\n",
1251 sx->lock_object.lo_name, file, line);
1255 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1259 #endif /* INVARIANT_SUPPORT */
1263 db_show_sx(const struct lock_object *lock)
1266 const struct sx *sx;
1268 sx = (const struct sx *)lock;
1270 db_printf(" state: ");
1271 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1272 db_printf("UNLOCKED\n");
1273 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1274 db_printf("DESTROYED\n");
1276 } else if (sx->sx_lock & SX_LOCK_SHARED)
1277 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1279 td = sx_xholder(sx);
1280 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1281 td->td_tid, td->td_proc->p_pid, td->td_name);
1282 if (sx_recursed(sx))
1283 db_printf(" recursed: %d\n", sx->sx_recurse);
1286 db_printf(" waiters: ");
1287 switch(sx->sx_lock &
1288 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1289 case SX_LOCK_SHARED_WAITERS:
1290 db_printf("shared\n");
1292 case SX_LOCK_EXCLUSIVE_WAITERS:
1293 db_printf("exclusive\n");
1295 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1296 db_printf("exclusive and shared\n");
1299 db_printf("none\n");
1304 * Check to see if a thread that is blocked on a sleep queue is actually
1305 * blocked on an sx lock. If so, output some details and return true.
1306 * If the lock has an exclusive owner, return that in *ownerp.
1309 sx_chain(struct thread *td, struct thread **ownerp)
1314 * Check to see if this thread is blocked on an sx lock.
1315 * First, we check the lock class. If that is ok, then we
1316 * compare the lock name against the wait message.
1319 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1320 sx->lock_object.lo_name != td->td_wmesg)
1323 /* We think we have an sx lock, so output some details. */
1324 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1325 *ownerp = sx_xholder(sx);
1326 if (sx->sx_lock & SX_LOCK_SHARED)
1327 db_printf("SLOCK (count %ju)\n",
1328 (uintmax_t)SX_SHARERS(sx->sx_lock));
1330 db_printf("XLOCK\n");