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_kdtrace.h"
42 #include "opt_no_adaptive_sx.h"
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
47 #include <sys/param.h>
48 #include <sys/systm.h>
50 #include <sys/kernel.h>
53 #include <sys/mutex.h>
55 #include <sys/sched.h>
56 #include <sys/sleepqueue.h>
59 #include <sys/sysctl.h>
61 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
62 #include <machine/cpu.h>
69 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
73 CTASSERT((SX_NOADAPTIVE & LO_CLASSFLAGS) == SX_NOADAPTIVE);
76 #include <sys/pmckern.h>
77 PMC_SOFT_DECLARE( , , lock, failed);
80 /* Handy macros for sleep queues. */
81 #define SQ_EXCLUSIVE_QUEUE 0
82 #define SQ_SHARED_QUEUE 1
85 * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file. We
86 * drop Giant anytime we have to sleep or if we adaptively spin.
88 #define GIANT_DECLARE \
90 WITNESS_SAVE_DECL(Giant) \
92 #define GIANT_SAVE() do { \
93 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_recurse lock_object.lo_data
116 #define sx_recursed(sx) ((sx)->sx_recurse != 0)
118 static void assert_sx(const struct lock_object *lock, int what);
120 static void db_show_sx(const struct lock_object *lock);
122 static void lock_sx(struct lock_object *lock, uintptr_t how);
124 static int owner_sx(const struct lock_object *lock, struct thread **owner);
126 static uintptr_t unlock_sx(struct lock_object *lock);
128 struct lock_class lock_class_sx = {
130 .lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
131 .lc_assert = assert_sx,
133 .lc_ddb_show = db_show_sx,
136 .lc_unlock = unlock_sx,
138 .lc_owner = owner_sx,
143 #define _sx_assert(sx, what, file, line)
147 static u_int asx_retries = 10;
148 static u_int asx_loops = 10000;
149 static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD, NULL, "sxlock debugging");
150 SYSCTL_UINT(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
151 SYSCTL_UINT(_debug_sx, OID_AUTO, loops, CTLFLAG_RW, &asx_loops, 0, "");
153 static struct lock_delay_config sx_delay = {
160 SYSCTL_INT(_debug_sx, OID_AUTO, delay_initial, CTLFLAG_RW, &sx_delay.initial,
162 SYSCTL_INT(_debug_sx, OID_AUTO, delay_step, CTLFLAG_RW, &sx_delay.step,
164 SYSCTL_INT(_debug_sx, OID_AUTO, delay_min, CTLFLAG_RW, &sx_delay.min,
166 SYSCTL_INT(_debug_sx, OID_AUTO, delay_max, CTLFLAG_RW, &sx_delay.max,
170 sx_delay_sysinit(void *dummy)
173 sx_delay.initial = mp_ncpus * 25;
174 sx_delay.step = (mp_ncpus * 25) / 2;
175 sx_delay.min = mp_ncpus * 5;
176 sx_delay.max = mp_ncpus * 25 * 10;
178 LOCK_DELAY_SYSINIT(sx_delay_sysinit);
182 assert_sx(const struct lock_object *lock, int what)
185 sx_assert((const struct sx *)lock, what);
189 lock_sx(struct lock_object *lock, uintptr_t how)
193 sx = (struct sx *)lock;
201 unlock_sx(struct lock_object *lock)
205 sx = (struct sx *)lock;
206 sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
207 if (sx_xlocked(sx)) {
218 owner_sx(const struct lock_object *lock, struct thread **owner)
220 const struct sx *sx = (const struct sx *)lock;
221 uintptr_t x = sx->sx_lock;
223 *owner = (struct thread *)SX_OWNER(x);
224 return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
230 sx_sysinit(void *arg)
232 struct sx_args *sargs = arg;
234 sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
238 sx_init_flags(struct sx *sx, const char *description, int opts)
242 MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
243 SX_NOPROFILE | SX_NOADAPTIVE | SX_NEW)) == 0);
244 ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
245 ("%s: sx_lock not aligned for %s: %p", __func__, description,
248 flags = LO_SLEEPABLE | LO_UPGRADABLE;
251 if (opts & SX_NOPROFILE)
252 flags |= LO_NOPROFILE;
253 if (!(opts & SX_NOWITNESS))
255 if (opts & SX_RECURSE)
256 flags |= LO_RECURSABLE;
262 flags |= opts & SX_NOADAPTIVE;
263 lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
264 sx->sx_lock = SX_LOCK_UNLOCKED;
269 sx_destroy(struct sx *sx)
272 KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
273 KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
274 sx->sx_lock = SX_LOCK_DESTROYED;
275 lock_destroy(&sx->lock_object);
279 _sx_slock(struct sx *sx, int opts, const char *file, int line)
283 if (SCHEDULER_STOPPED())
285 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
286 ("sx_slock() by idle thread %p on sx %s @ %s:%d",
287 curthread, sx->lock_object.lo_name, file, line));
288 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
289 ("sx_slock() of destroyed sx @ %s:%d", file, line));
290 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
291 error = __sx_slock(sx, opts, file, line);
293 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
294 WITNESS_LOCK(&sx->lock_object, 0, file, line);
295 curthread->td_locks++;
302 sx_try_slock_(struct sx *sx, const char *file, int line)
306 if (SCHEDULER_STOPPED())
309 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
310 ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
311 curthread, sx->lock_object.lo_name, file, line));
315 KASSERT(x != SX_LOCK_DESTROYED,
316 ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
317 if (!(x & SX_LOCK_SHARED))
319 if (atomic_cmpset_acq_ptr(&sx->sx_lock, x, x + SX_ONE_SHARER)) {
320 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
321 WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
322 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_SLOCK_ACQUIRE,
323 sx, 0, 0, file, line);
324 curthread->td_locks++;
329 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
334 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
338 if (SCHEDULER_STOPPED())
340 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
341 ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
342 curthread, sx->lock_object.lo_name, file, line));
343 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
344 ("sx_xlock() of destroyed sx @ %s:%d", file, line));
345 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
347 error = __sx_xlock(sx, curthread, opts, file, line);
349 LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
351 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
352 curthread->td_locks++;
359 sx_try_xlock_(struct sx *sx, const char *file, int line)
363 if (SCHEDULER_STOPPED())
366 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
367 ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
368 curthread, sx->lock_object.lo_name, file, line));
369 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
370 ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
372 if (sx_xlocked(sx) &&
373 (sx->lock_object.lo_flags & LO_RECURSABLE) != 0) {
375 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
378 rval = atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED,
379 (uintptr_t)curthread);
380 LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
382 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
384 if (!sx_recursed(sx))
385 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_XLOCK_ACQUIRE,
386 sx, 0, 0, file, line);
387 curthread->td_locks++;
394 _sx_sunlock(struct sx *sx, const char *file, int line)
397 if (SCHEDULER_STOPPED())
399 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
400 ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
401 _sx_assert(sx, SA_SLOCKED, file, line);
402 WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
403 LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
404 __sx_sunlock(sx, file, line);
405 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_SX_SUNLOCK_RELEASE, sx);
406 curthread->td_locks--;
410 _sx_xunlock(struct sx *sx, const char *file, int line)
413 if (SCHEDULER_STOPPED())
415 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
416 ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
417 _sx_assert(sx, SA_XLOCKED, file, line);
418 WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
419 LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
421 if (!sx_recursed(sx))
422 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_SX_XUNLOCK_RELEASE, sx);
423 __sx_xunlock(sx, curthread, file, line);
424 curthread->td_locks--;
428 * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
429 * This will only succeed if this thread holds a single shared lock.
430 * Return 1 if if the upgrade succeed, 0 otherwise.
433 sx_try_upgrade_(struct sx *sx, const char *file, int line)
438 if (SCHEDULER_STOPPED())
441 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
442 ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
443 _sx_assert(sx, SA_SLOCKED, file, line);
446 * Try to switch from one shared lock to an exclusive lock. We need
447 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
448 * we will wake up the exclusive waiters when we drop the lock.
450 x = sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS;
451 success = atomic_cmpset_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) | x,
452 (uintptr_t)curthread | x);
453 LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
455 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
457 LOCKSTAT_RECORD0(LS_SX_TRYUPGRADE_UPGRADE, sx);
463 * Downgrade an unrecursed exclusive lock into a single shared lock.
466 sx_downgrade_(struct sx *sx, const char *file, int line)
471 if (SCHEDULER_STOPPED())
474 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
475 ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
476 _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
479 panic("downgrade of a recursed lock");
482 WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
485 * Try to switch from an exclusive lock with no shared waiters
486 * to one sharer with no shared waiters. If there are
487 * exclusive waiters, we don't need to lock the sleep queue so
488 * long as we preserve the flag. We do one quick try and if
489 * that fails we grab the sleepq lock to keep the flags from
490 * changing and do it the slow way.
492 * We have to lock the sleep queue if there are shared waiters
493 * so we can wake them up.
496 if (!(x & SX_LOCK_SHARED_WAITERS) &&
497 atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
498 (x & SX_LOCK_EXCLUSIVE_WAITERS))) {
499 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
504 * Lock the sleep queue so we can read the waiters bits
505 * without any races and wakeup any shared waiters.
507 sleepq_lock(&sx->lock_object);
510 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
511 * shared lock. If there are any shared waiters, wake them up.
515 atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
516 (x & SX_LOCK_EXCLUSIVE_WAITERS));
517 if (x & SX_LOCK_SHARED_WAITERS)
518 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
520 sleepq_release(&sx->lock_object);
522 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
523 LOCKSTAT_RECORD0(LS_SX_DOWNGRADE_DOWNGRADE, sx);
530 * This function represents the so-called 'hard case' for sx_xlock
531 * operation. All 'easy case' failures are redirected to this. Note
532 * that ideally this would be a static function, but it needs to be
533 * accessible from at least sx.h.
536 _sx_xlock_hard(struct sx *sx, uintptr_t tid, int opts, const char *file,
541 volatile struct thread *owner;
542 u_int i, spintries = 0;
545 #ifdef LOCK_PROFILING
546 uint64_t waittime = 0;
550 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
551 struct lock_delay_arg lda;
556 int64_t sleep_time = 0;
557 int64_t all_time = 0;
560 if (SCHEDULER_STOPPED())
563 #if defined(ADAPTIVE_SX)
564 lock_delay_arg_init(&lda, &sx_delay);
565 #elif defined(KDTRACE_HOOKS)
566 lock_delay_arg_init(&lda, NULL);
569 /* If we already hold an exclusive lock, then recurse. */
570 if (sx_xlocked(sx)) {
571 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
572 ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
573 sx->lock_object.lo_name, file, line));
575 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
576 if (LOCK_LOG_TEST(&sx->lock_object, 0))
577 CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
581 if (LOCK_LOG_TEST(&sx->lock_object, 0))
582 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
583 sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
586 all_time -= lockstat_nsecs(&sx->lock_object);
590 if (sx->sx_lock == SX_LOCK_UNLOCKED &&
591 atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED, tid))
597 PMC_SOFT_CALL( , , lock, failed);
599 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
603 * If the lock is write locked and the owner is
604 * running on another CPU, spin until the owner stops
605 * running or the state of the lock changes.
608 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
609 if ((x & SX_LOCK_SHARED) == 0) {
611 owner = (struct thread *)x;
612 if (TD_IS_RUNNING(owner)) {
613 if (LOCK_LOG_TEST(&sx->lock_object, 0))
615 "%s: spinning on %p held by %p",
616 __func__, sx, owner);
617 KTR_STATE1(KTR_SCHED, "thread",
618 sched_tdname(curthread), "spinning",
620 sx->lock_object.lo_name);
622 while (SX_OWNER(sx->sx_lock) == x &&
623 TD_IS_RUNNING(owner))
625 KTR_STATE0(KTR_SCHED, "thread",
626 sched_tdname(curthread), "running");
629 } else if (SX_SHARERS(x) && spintries < asx_retries) {
630 KTR_STATE1(KTR_SCHED, "thread",
631 sched_tdname(curthread), "spinning",
632 "lockname:\"%s\"", sx->lock_object.lo_name);
635 for (i = 0; i < asx_loops; i++) {
636 if (LOCK_LOG_TEST(&sx->lock_object, 0))
638 "%s: shared spinning on %p with %u and %u",
639 __func__, sx, spintries, i);
641 if ((x & SX_LOCK_SHARED) == 0 ||
649 KTR_STATE0(KTR_SCHED, "thread",
650 sched_tdname(curthread), "running");
657 sleepq_lock(&sx->lock_object);
661 * If the lock was released while spinning on the
662 * sleep queue chain lock, try again.
664 if (x == SX_LOCK_UNLOCKED) {
665 sleepq_release(&sx->lock_object);
671 * The current lock owner might have started executing
672 * on another CPU (or the lock could have changed
673 * owners) while we were waiting on the sleep queue
674 * chain lock. If so, drop the sleep queue lock and try
677 if (!(x & SX_LOCK_SHARED) &&
678 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
679 owner = (struct thread *)SX_OWNER(x);
680 if (TD_IS_RUNNING(owner)) {
681 sleepq_release(&sx->lock_object);
688 * If an exclusive lock was released with both shared
689 * and exclusive waiters and a shared waiter hasn't
690 * woken up and acquired the lock yet, sx_lock will be
691 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
692 * If we see that value, try to acquire it once. Note
693 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
694 * as there are other exclusive waiters still. If we
695 * fail, restart the loop.
697 if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
698 if (atomic_cmpset_acq_ptr(&sx->sx_lock,
699 SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
700 tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
701 sleepq_release(&sx->lock_object);
702 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
706 sleepq_release(&sx->lock_object);
711 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
712 * than loop back and retry.
714 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
715 if (!atomic_cmpset_ptr(&sx->sx_lock, x,
716 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
717 sleepq_release(&sx->lock_object);
720 if (LOCK_LOG_TEST(&sx->lock_object, 0))
721 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
726 * Since we have been unable to acquire the exclusive
727 * lock and the exclusive waiters flag is set, we have
730 if (LOCK_LOG_TEST(&sx->lock_object, 0))
731 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
735 sleep_time -= lockstat_nsecs(&sx->lock_object);
738 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
739 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
740 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
741 if (!(opts & SX_INTERRUPTIBLE))
742 sleepq_wait(&sx->lock_object, 0);
744 error = sleepq_wait_sig(&sx->lock_object, 0);
746 sleep_time += lockstat_nsecs(&sx->lock_object);
750 if (LOCK_LOG_TEST(&sx->lock_object, 0))
752 "%s: interruptible sleep by %p suspended by signal",
756 if (LOCK_LOG_TEST(&sx->lock_object, 0))
757 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
761 all_time += lockstat_nsecs(&sx->lock_object);
763 LOCKSTAT_RECORD4(LS_SX_XLOCK_BLOCK, sx, sleep_time,
764 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
765 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
766 if (lda.spin_cnt > sleep_cnt)
767 LOCKSTAT_RECORD4(LS_SX_XLOCK_SPIN, sx, all_time - sleep_time,
768 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
769 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
772 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_XLOCK_ACQUIRE, sx,
773 contested, waittime, file, line);
779 * This function represents the so-called 'hard case' for sx_xunlock
780 * operation. All 'easy case' failures are redirected to this. Note
781 * that ideally this would be a static function, but it needs to be
782 * accessible from at least sx.h.
785 _sx_xunlock_hard(struct sx *sx, uintptr_t tid, const char *file, int line)
788 int queue, wakeup_swapper;
790 if (SCHEDULER_STOPPED())
793 MPASS(!(sx->sx_lock & SX_LOCK_SHARED));
795 /* If the lock is recursed, then unrecurse one level. */
796 if (sx_xlocked(sx) && sx_recursed(sx)) {
797 if ((--sx->sx_recurse) == 0)
798 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
799 if (LOCK_LOG_TEST(&sx->lock_object, 0))
800 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
803 MPASS(sx->sx_lock & (SX_LOCK_SHARED_WAITERS |
804 SX_LOCK_EXCLUSIVE_WAITERS));
805 if (LOCK_LOG_TEST(&sx->lock_object, 0))
806 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
808 sleepq_lock(&sx->lock_object);
809 x = SX_LOCK_UNLOCKED;
812 * The wake up algorithm here is quite simple and probably not
813 * ideal. It gives precedence to shared waiters if they are
814 * present. For this condition, we have to preserve the
815 * state of the exclusive waiters flag.
816 * If interruptible sleeps left the shared queue empty avoid a
817 * starvation for the threads sleeping on the exclusive queue by giving
818 * them precedence and cleaning up the shared waiters bit anyway.
820 if ((sx->sx_lock & SX_LOCK_SHARED_WAITERS) != 0 &&
821 sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
822 queue = SQ_SHARED_QUEUE;
823 x |= (sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS);
825 queue = SQ_EXCLUSIVE_QUEUE;
827 /* Wake up all the waiters for the specific queue. */
828 if (LOCK_LOG_TEST(&sx->lock_object, 0))
829 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
830 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
832 atomic_store_rel_ptr(&sx->sx_lock, x);
833 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
835 sleepq_release(&sx->lock_object);
841 * This function represents the so-called 'hard case' for sx_slock
842 * operation. All 'easy case' failures are redirected to this. Note
843 * that ideally this would be a static function, but it needs to be
844 * accessible from at least sx.h.
847 _sx_slock_hard(struct sx *sx, int opts, const char *file, int line)
851 volatile struct thread *owner;
853 #ifdef LOCK_PROFILING
854 uint64_t waittime = 0;
859 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
860 struct lock_delay_arg lda;
865 int64_t sleep_time = 0;
866 int64_t all_time = 0;
869 if (SCHEDULER_STOPPED())
872 #if defined(ADAPTIVE_SX)
873 lock_delay_arg_init(&lda, &sx_delay);
874 #elif defined(KDTRACE_HOOKS)
875 lock_delay_arg_init(&lda, NULL);
879 all_time -= lockstat_nsecs(&sx->lock_object);
883 * As with rwlocks, we don't make any attempt to try to block
884 * shared locks once there is an exclusive waiter.
893 * If no other thread has an exclusive lock then try to bump up
894 * the count of sharers. Since we have to preserve the state
895 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
896 * shared lock loop back and retry.
898 if (x & SX_LOCK_SHARED) {
899 MPASS(!(x & SX_LOCK_SHARED_WAITERS));
900 if (atomic_cmpset_acq_ptr(&sx->sx_lock, x,
901 x + SX_ONE_SHARER)) {
902 if (LOCK_LOG_TEST(&sx->lock_object, 0))
904 "%s: %p succeed %p -> %p", __func__,
906 (void *)(x + SX_ONE_SHARER));
912 PMC_SOFT_CALL( , , lock, failed);
914 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
919 * If the owner is running on another CPU, spin until
920 * the owner stops running or the state of the lock
923 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
925 owner = (struct thread *)x;
926 if (TD_IS_RUNNING(owner)) {
927 if (LOCK_LOG_TEST(&sx->lock_object, 0))
929 "%s: spinning on %p held by %p",
930 __func__, sx, owner);
931 KTR_STATE1(KTR_SCHED, "thread",
932 sched_tdname(curthread), "spinning",
933 "lockname:\"%s\"", sx->lock_object.lo_name);
935 while (SX_OWNER(sx->sx_lock) == x &&
936 TD_IS_RUNNING(owner))
938 KTR_STATE0(KTR_SCHED, "thread",
939 sched_tdname(curthread), "running");
946 * Some other thread already has an exclusive lock, so
947 * start the process of blocking.
949 sleepq_lock(&sx->lock_object);
953 * The lock could have been released while we spun.
954 * In this case loop back and retry.
956 if (x & SX_LOCK_SHARED) {
957 sleepq_release(&sx->lock_object);
963 * If the owner is running on another CPU, spin until
964 * the owner stops running or the state of the lock
967 if (!(x & SX_LOCK_SHARED) &&
968 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
969 owner = (struct thread *)SX_OWNER(x);
970 if (TD_IS_RUNNING(owner)) {
971 sleepq_release(&sx->lock_object);
978 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
979 * fail to set it drop the sleep queue lock and loop
982 if (!(x & SX_LOCK_SHARED_WAITERS)) {
983 if (!atomic_cmpset_ptr(&sx->sx_lock, x,
984 x | SX_LOCK_SHARED_WAITERS)) {
985 sleepq_release(&sx->lock_object);
988 if (LOCK_LOG_TEST(&sx->lock_object, 0))
989 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
994 * Since we have been unable to acquire the shared lock,
997 if (LOCK_LOG_TEST(&sx->lock_object, 0))
998 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1001 #ifdef KDTRACE_HOOKS
1002 sleep_time -= lockstat_nsecs(&sx->lock_object);
1005 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1006 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1007 SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1008 if (!(opts & SX_INTERRUPTIBLE))
1009 sleepq_wait(&sx->lock_object, 0);
1011 error = sleepq_wait_sig(&sx->lock_object, 0);
1012 #ifdef KDTRACE_HOOKS
1013 sleep_time += lockstat_nsecs(&sx->lock_object);
1017 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1019 "%s: interruptible sleep by %p suspended by signal",
1023 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1024 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1027 #ifdef KDTRACE_HOOKS
1028 all_time += lockstat_nsecs(&sx->lock_object);
1030 LOCKSTAT_RECORD4(LS_SX_SLOCK_BLOCK, sx, sleep_time,
1031 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1032 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1033 if (lda.spin_cnt > sleep_cnt)
1034 LOCKSTAT_RECORD4(LS_SX_SLOCK_SPIN, sx, all_time - sleep_time,
1035 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1036 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1039 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_SLOCK_ACQUIRE, sx,
1040 contested, waittime, file, line);
1046 * This function represents the so-called 'hard case' for sx_sunlock
1047 * operation. All 'easy case' failures are redirected to this. Note
1048 * that ideally this would be a static function, but it needs to be
1049 * accessible from at least sx.h.
1052 _sx_sunlock_hard(struct sx *sx, const char *file, int line)
1057 if (SCHEDULER_STOPPED())
1064 * We should never have sharers while at least one thread
1065 * holds a shared lock.
1067 KASSERT(!(x & SX_LOCK_SHARED_WAITERS),
1068 ("%s: waiting sharers", __func__));
1071 * See if there is more than one shared lock held. If
1072 * so, just drop one and return.
1074 if (SX_SHARERS(x) > 1) {
1075 if (atomic_cmpset_rel_ptr(&sx->sx_lock, x,
1076 x - SX_ONE_SHARER)) {
1077 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1079 "%s: %p succeeded %p -> %p",
1080 __func__, sx, (void *)x,
1081 (void *)(x - SX_ONE_SHARER));
1088 * If there aren't any waiters for an exclusive lock,
1089 * then try to drop it quickly.
1091 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
1092 MPASS(x == SX_SHARERS_LOCK(1));
1093 if (atomic_cmpset_rel_ptr(&sx->sx_lock,
1094 SX_SHARERS_LOCK(1), SX_LOCK_UNLOCKED)) {
1095 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1096 CTR2(KTR_LOCK, "%s: %p last succeeded",
1104 * At this point, there should just be one sharer with
1105 * exclusive waiters.
1107 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1109 sleepq_lock(&sx->lock_object);
1112 * Wake up semantic here is quite simple:
1113 * Just wake up all the exclusive waiters.
1114 * Note that the state of the lock could have changed,
1115 * so if it fails loop back and retry.
1117 if (!atomic_cmpset_rel_ptr(&sx->sx_lock,
1118 SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
1119 SX_LOCK_UNLOCKED)) {
1120 sleepq_release(&sx->lock_object);
1123 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1124 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1125 "exclusive queue", __func__, sx);
1126 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1127 0, SQ_EXCLUSIVE_QUEUE);
1128 sleepq_release(&sx->lock_object);
1135 #ifdef INVARIANT_SUPPORT
1141 * In the non-WITNESS case, sx_assert() can only detect that at least
1142 * *some* thread owns an slock, but it cannot guarantee that *this*
1143 * thread owns an slock.
1146 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1152 if (panicstr != NULL)
1156 case SA_SLOCKED | SA_NOTRECURSED:
1157 case SA_SLOCKED | SA_RECURSED:
1163 case SA_LOCKED | SA_NOTRECURSED:
1164 case SA_LOCKED | SA_RECURSED:
1166 witness_assert(&sx->lock_object, what, file, line);
1169 * If some other thread has an exclusive lock or we
1170 * have one and are asserting a shared lock, fail.
1171 * Also, if no one has a lock at all, fail.
1173 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1174 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1175 sx_xholder(sx) != curthread)))
1176 panic("Lock %s not %slocked @ %s:%d\n",
1177 sx->lock_object.lo_name, slocked ? "share " : "",
1180 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1181 if (sx_recursed(sx)) {
1182 if (what & SA_NOTRECURSED)
1183 panic("Lock %s recursed @ %s:%d\n",
1184 sx->lock_object.lo_name, file,
1186 } else if (what & SA_RECURSED)
1187 panic("Lock %s not recursed @ %s:%d\n",
1188 sx->lock_object.lo_name, file, line);
1193 case SA_XLOCKED | SA_NOTRECURSED:
1194 case SA_XLOCKED | SA_RECURSED:
1195 if (sx_xholder(sx) != curthread)
1196 panic("Lock %s not exclusively locked @ %s:%d\n",
1197 sx->lock_object.lo_name, file, line);
1198 if (sx_recursed(sx)) {
1199 if (what & SA_NOTRECURSED)
1200 panic("Lock %s recursed @ %s:%d\n",
1201 sx->lock_object.lo_name, file, line);
1202 } else if (what & SA_RECURSED)
1203 panic("Lock %s not recursed @ %s:%d\n",
1204 sx->lock_object.lo_name, file, line);
1208 witness_assert(&sx->lock_object, what, file, line);
1211 * If we hold an exclusve lock fail. We can't
1212 * reliably check to see if we hold a shared lock or
1215 if (sx_xholder(sx) == curthread)
1216 panic("Lock %s exclusively locked @ %s:%d\n",
1217 sx->lock_object.lo_name, file, line);
1221 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1225 #endif /* INVARIANT_SUPPORT */
1229 db_show_sx(const struct lock_object *lock)
1232 const struct sx *sx;
1234 sx = (const struct sx *)lock;
1236 db_printf(" state: ");
1237 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1238 db_printf("UNLOCKED\n");
1239 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1240 db_printf("DESTROYED\n");
1242 } else if (sx->sx_lock & SX_LOCK_SHARED)
1243 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1245 td = sx_xholder(sx);
1246 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1247 td->td_tid, td->td_proc->p_pid, td->td_name);
1248 if (sx_recursed(sx))
1249 db_printf(" recursed: %d\n", sx->sx_recurse);
1252 db_printf(" waiters: ");
1253 switch(sx->sx_lock &
1254 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1255 case SX_LOCK_SHARED_WAITERS:
1256 db_printf("shared\n");
1258 case SX_LOCK_EXCLUSIVE_WAITERS:
1259 db_printf("exclusive\n");
1261 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1262 db_printf("exclusive and shared\n");
1265 db_printf("none\n");
1270 * Check to see if a thread that is blocked on a sleep queue is actually
1271 * blocked on an sx lock. If so, output some details and return true.
1272 * If the lock has an exclusive owner, return that in *ownerp.
1275 sx_chain(struct thread *td, struct thread **ownerp)
1280 * Check to see if this thread is blocked on an sx lock.
1281 * First, we check the lock class. If that is ok, then we
1282 * compare the lock name against the wait message.
1285 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1286 sx->lock_object.lo_name != td->td_wmesg)
1289 /* We think we have an sx lock, so output some details. */
1290 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1291 *ownerp = sx_xholder(sx);
1292 if (sx->sx_lock & SX_LOCK_SHARED)
1293 db_printf("SLOCK (count %ju)\n",
1294 (uintmax_t)SX_SHARERS(sx->sx_lock));
1296 db_printf("XLOCK\n");