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)) == 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;
260 flags |= opts & SX_NOADAPTIVE;
261 lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
262 sx->sx_lock = SX_LOCK_UNLOCKED;
267 sx_destroy(struct sx *sx)
270 KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
271 KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
272 sx->sx_lock = SX_LOCK_DESTROYED;
273 lock_destroy(&sx->lock_object);
277 _sx_slock(struct sx *sx, int opts, const char *file, int line)
281 if (SCHEDULER_STOPPED())
283 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
284 ("sx_slock() by idle thread %p on sx %s @ %s:%d",
285 curthread, sx->lock_object.lo_name, file, line));
286 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
287 ("sx_slock() of destroyed sx @ %s:%d", file, line));
288 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
289 error = __sx_slock(sx, opts, file, line);
291 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
292 WITNESS_LOCK(&sx->lock_object, 0, file, line);
293 curthread->td_locks++;
300 sx_try_slock_(struct sx *sx, const char *file, int line)
304 if (SCHEDULER_STOPPED())
307 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
308 ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
309 curthread, sx->lock_object.lo_name, file, line));
313 KASSERT(x != SX_LOCK_DESTROYED,
314 ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
315 if (!(x & SX_LOCK_SHARED))
317 if (atomic_cmpset_acq_ptr(&sx->sx_lock, x, x + SX_ONE_SHARER)) {
318 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
319 WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
320 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_SLOCK_ACQUIRE,
321 sx, 0, 0, file, line);
322 curthread->td_locks++;
327 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
332 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
336 if (SCHEDULER_STOPPED())
338 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
339 ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
340 curthread, sx->lock_object.lo_name, file, line));
341 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
342 ("sx_xlock() of destroyed sx @ %s:%d", file, line));
343 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
345 error = __sx_xlock(sx, curthread, opts, file, line);
347 LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
349 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
350 curthread->td_locks++;
357 sx_try_xlock_(struct sx *sx, const char *file, int line)
361 if (SCHEDULER_STOPPED())
364 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
365 ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
366 curthread, sx->lock_object.lo_name, file, line));
367 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
368 ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
370 if (sx_xlocked(sx) &&
371 (sx->lock_object.lo_flags & LO_RECURSABLE) != 0) {
373 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
376 rval = atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED,
377 (uintptr_t)curthread);
378 LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
380 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
382 if (!sx_recursed(sx))
383 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_XLOCK_ACQUIRE,
384 sx, 0, 0, file, line);
385 curthread->td_locks++;
392 _sx_sunlock(struct sx *sx, const char *file, int line)
395 if (SCHEDULER_STOPPED())
397 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
398 ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
399 _sx_assert(sx, SA_SLOCKED, file, line);
400 WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
401 LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
402 __sx_sunlock(sx, file, line);
403 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_SX_SUNLOCK_RELEASE, sx);
404 curthread->td_locks--;
408 _sx_xunlock(struct sx *sx, const char *file, int line)
411 if (SCHEDULER_STOPPED())
413 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
414 ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
415 _sx_assert(sx, SA_XLOCKED, file, line);
416 WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
417 LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
419 if (!sx_recursed(sx))
420 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_SX_XUNLOCK_RELEASE, sx);
421 __sx_xunlock(sx, curthread, file, line);
422 curthread->td_locks--;
426 * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
427 * This will only succeed if this thread holds a single shared lock.
428 * Return 1 if if the upgrade succeed, 0 otherwise.
431 sx_try_upgrade_(struct sx *sx, const char *file, int line)
436 if (SCHEDULER_STOPPED())
439 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
440 ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
441 _sx_assert(sx, SA_SLOCKED, file, line);
444 * Try to switch from one shared lock to an exclusive lock. We need
445 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
446 * we will wake up the exclusive waiters when we drop the lock.
448 x = sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS;
449 success = atomic_cmpset_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) | x,
450 (uintptr_t)curthread | x);
451 LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
453 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
455 LOCKSTAT_RECORD0(LS_SX_TRYUPGRADE_UPGRADE, sx);
461 * Downgrade an unrecursed exclusive lock into a single shared lock.
464 sx_downgrade_(struct sx *sx, const char *file, int line)
469 if (SCHEDULER_STOPPED())
472 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
473 ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
474 _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
477 panic("downgrade of a recursed lock");
480 WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
483 * Try to switch from an exclusive lock with no shared waiters
484 * to one sharer with no shared waiters. If there are
485 * exclusive waiters, we don't need to lock the sleep queue so
486 * long as we preserve the flag. We do one quick try and if
487 * that fails we grab the sleepq lock to keep the flags from
488 * changing and do it the slow way.
490 * We have to lock the sleep queue if there are shared waiters
491 * so we can wake them up.
494 if (!(x & SX_LOCK_SHARED_WAITERS) &&
495 atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
496 (x & SX_LOCK_EXCLUSIVE_WAITERS))) {
497 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
502 * Lock the sleep queue so we can read the waiters bits
503 * without any races and wakeup any shared waiters.
505 sleepq_lock(&sx->lock_object);
508 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
509 * shared lock. If there are any shared waiters, wake them up.
513 atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
514 (x & SX_LOCK_EXCLUSIVE_WAITERS));
515 if (x & SX_LOCK_SHARED_WAITERS)
516 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
518 sleepq_release(&sx->lock_object);
520 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
521 LOCKSTAT_RECORD0(LS_SX_DOWNGRADE_DOWNGRADE, sx);
528 * This function represents the so-called 'hard case' for sx_xlock
529 * operation. All 'easy case' failures are redirected to this. Note
530 * that ideally this would be a static function, but it needs to be
531 * accessible from at least sx.h.
534 _sx_xlock_hard(struct sx *sx, uintptr_t tid, int opts, const char *file,
539 volatile struct thread *owner;
540 u_int i, spintries = 0;
543 #ifdef LOCK_PROFILING
544 uint64_t waittime = 0;
548 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
549 struct lock_delay_arg lda;
554 int64_t sleep_time = 0;
555 int64_t all_time = 0;
558 if (SCHEDULER_STOPPED())
561 #if defined(ADAPTIVE_SX)
562 lock_delay_arg_init(&lda, &sx_delay);
563 #elif defined(KDTRACE_HOOKS)
564 lock_delay_arg_init(&lda, NULL);
567 /* If we already hold an exclusive lock, then recurse. */
568 if (sx_xlocked(sx)) {
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 all_time -= lockstat_nsecs(&sx->lock_object);
588 if (sx->sx_lock == SX_LOCK_UNLOCKED &&
589 atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED, tid))
595 PMC_SOFT_CALL( , , lock, failed);
597 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
601 * If the lock is write locked and the owner is
602 * running on another CPU, spin until the owner stops
603 * running or the state of the lock changes.
606 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
607 if ((x & SX_LOCK_SHARED) == 0) {
609 owner = (struct thread *)x;
610 if (TD_IS_RUNNING(owner)) {
611 if (LOCK_LOG_TEST(&sx->lock_object, 0))
613 "%s: spinning on %p held by %p",
614 __func__, sx, owner);
615 KTR_STATE1(KTR_SCHED, "thread",
616 sched_tdname(curthread), "spinning",
618 sx->lock_object.lo_name);
620 while (SX_OWNER(sx->sx_lock) == x &&
621 TD_IS_RUNNING(owner))
623 KTR_STATE0(KTR_SCHED, "thread",
624 sched_tdname(curthread), "running");
627 } else if (SX_SHARERS(x) && spintries < asx_retries) {
628 KTR_STATE1(KTR_SCHED, "thread",
629 sched_tdname(curthread), "spinning",
630 "lockname:\"%s\"", sx->lock_object.lo_name);
633 for (i = 0; i < asx_loops; i++) {
634 if (LOCK_LOG_TEST(&sx->lock_object, 0))
636 "%s: shared spinning on %p with %u and %u",
637 __func__, sx, spintries, i);
639 if ((x & SX_LOCK_SHARED) == 0 ||
647 KTR_STATE0(KTR_SCHED, "thread",
648 sched_tdname(curthread), "running");
655 sleepq_lock(&sx->lock_object);
659 * If the lock was released while spinning on the
660 * sleep queue chain lock, try again.
662 if (x == SX_LOCK_UNLOCKED) {
663 sleepq_release(&sx->lock_object);
669 * The current lock owner might have started executing
670 * on another CPU (or the lock could have changed
671 * owners) while we were waiting on the sleep queue
672 * chain lock. If so, drop the sleep queue lock and try
675 if (!(x & SX_LOCK_SHARED) &&
676 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
677 owner = (struct thread *)SX_OWNER(x);
678 if (TD_IS_RUNNING(owner)) {
679 sleepq_release(&sx->lock_object);
686 * If an exclusive lock was released with both shared
687 * and exclusive waiters and a shared waiter hasn't
688 * woken up and acquired the lock yet, sx_lock will be
689 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
690 * If we see that value, try to acquire it once. Note
691 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
692 * as there are other exclusive waiters still. If we
693 * fail, restart the loop.
695 if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
696 if (atomic_cmpset_acq_ptr(&sx->sx_lock,
697 SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
698 tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
699 sleepq_release(&sx->lock_object);
700 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
704 sleepq_release(&sx->lock_object);
709 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
710 * than loop back and retry.
712 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
713 if (!atomic_cmpset_ptr(&sx->sx_lock, x,
714 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
715 sleepq_release(&sx->lock_object);
718 if (LOCK_LOG_TEST(&sx->lock_object, 0))
719 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
724 * Since we have been unable to acquire the exclusive
725 * lock and the exclusive waiters flag is set, we have
728 if (LOCK_LOG_TEST(&sx->lock_object, 0))
729 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
733 sleep_time -= lockstat_nsecs(&sx->lock_object);
736 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
737 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
738 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
739 if (!(opts & SX_INTERRUPTIBLE))
740 sleepq_wait(&sx->lock_object, 0);
742 error = sleepq_wait_sig(&sx->lock_object, 0);
744 sleep_time += lockstat_nsecs(&sx->lock_object);
748 if (LOCK_LOG_TEST(&sx->lock_object, 0))
750 "%s: interruptible sleep by %p suspended by signal",
754 if (LOCK_LOG_TEST(&sx->lock_object, 0))
755 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
759 all_time += lockstat_nsecs(&sx->lock_object);
761 LOCKSTAT_RECORD4(LS_SX_XLOCK_BLOCK, sx, sleep_time,
762 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
763 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
764 if (lda.spin_cnt > sleep_cnt)
765 LOCKSTAT_RECORD4(LS_SX_XLOCK_SPIN, sx, all_time - sleep_time,
766 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
767 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
770 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_XLOCK_ACQUIRE, sx,
771 contested, waittime, file, line);
777 * This function represents the so-called 'hard case' for sx_xunlock
778 * operation. All 'easy case' failures are redirected to this. Note
779 * that ideally this would be a static function, but it needs to be
780 * accessible from at least sx.h.
783 _sx_xunlock_hard(struct sx *sx, uintptr_t tid, const char *file, int line)
786 int queue, wakeup_swapper;
788 if (SCHEDULER_STOPPED())
791 MPASS(!(sx->sx_lock & SX_LOCK_SHARED));
793 /* If the lock is recursed, then unrecurse one level. */
794 if (sx_xlocked(sx) && sx_recursed(sx)) {
795 if ((--sx->sx_recurse) == 0)
796 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
797 if (LOCK_LOG_TEST(&sx->lock_object, 0))
798 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
801 MPASS(sx->sx_lock & (SX_LOCK_SHARED_WAITERS |
802 SX_LOCK_EXCLUSIVE_WAITERS));
803 if (LOCK_LOG_TEST(&sx->lock_object, 0))
804 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
806 sleepq_lock(&sx->lock_object);
807 x = SX_LOCK_UNLOCKED;
810 * The wake up algorithm here is quite simple and probably not
811 * ideal. It gives precedence to shared waiters if they are
812 * present. For this condition, we have to preserve the
813 * state of the exclusive waiters flag.
814 * If interruptible sleeps left the shared queue empty avoid a
815 * starvation for the threads sleeping on the exclusive queue by giving
816 * them precedence and cleaning up the shared waiters bit anyway.
818 if ((sx->sx_lock & SX_LOCK_SHARED_WAITERS) != 0 &&
819 sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
820 queue = SQ_SHARED_QUEUE;
821 x |= (sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS);
823 queue = SQ_EXCLUSIVE_QUEUE;
825 /* Wake up all the waiters for the specific queue. */
826 if (LOCK_LOG_TEST(&sx->lock_object, 0))
827 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
828 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
830 atomic_store_rel_ptr(&sx->sx_lock, x);
831 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
833 sleepq_release(&sx->lock_object);
839 * This function represents the so-called 'hard case' for sx_slock
840 * operation. All 'easy case' failures are redirected to this. Note
841 * that ideally this would be a static function, but it needs to be
842 * accessible from at least sx.h.
845 _sx_slock_hard(struct sx *sx, int opts, const char *file, int line)
849 volatile struct thread *owner;
851 #ifdef LOCK_PROFILING
852 uint64_t waittime = 0;
857 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
858 struct lock_delay_arg lda;
863 int64_t sleep_time = 0;
864 int64_t all_time = 0;
867 if (SCHEDULER_STOPPED())
870 #if defined(ADAPTIVE_SX)
871 lock_delay_arg_init(&lda, &sx_delay);
872 #elif defined(KDTRACE_HOOKS)
873 lock_delay_arg_init(&lda, NULL);
877 all_time -= lockstat_nsecs(&sx->lock_object);
881 * As with rwlocks, we don't make any attempt to try to block
882 * shared locks once there is an exclusive waiter.
891 * If no other thread has an exclusive lock then try to bump up
892 * the count of sharers. Since we have to preserve the state
893 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
894 * shared lock loop back and retry.
896 if (x & SX_LOCK_SHARED) {
897 MPASS(!(x & SX_LOCK_SHARED_WAITERS));
898 if (atomic_cmpset_acq_ptr(&sx->sx_lock, x,
899 x + SX_ONE_SHARER)) {
900 if (LOCK_LOG_TEST(&sx->lock_object, 0))
902 "%s: %p succeed %p -> %p", __func__,
904 (void *)(x + SX_ONE_SHARER));
910 PMC_SOFT_CALL( , , lock, failed);
912 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
917 * If the owner is running on another CPU, spin until
918 * the owner stops running or the state of the lock
921 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
923 owner = (struct thread *)x;
924 if (TD_IS_RUNNING(owner)) {
925 if (LOCK_LOG_TEST(&sx->lock_object, 0))
927 "%s: spinning on %p held by %p",
928 __func__, sx, owner);
929 KTR_STATE1(KTR_SCHED, "thread",
930 sched_tdname(curthread), "spinning",
931 "lockname:\"%s\"", sx->lock_object.lo_name);
933 while (SX_OWNER(sx->sx_lock) == x &&
934 TD_IS_RUNNING(owner))
936 KTR_STATE0(KTR_SCHED, "thread",
937 sched_tdname(curthread), "running");
944 * Some other thread already has an exclusive lock, so
945 * start the process of blocking.
947 sleepq_lock(&sx->lock_object);
951 * The lock could have been released while we spun.
952 * In this case loop back and retry.
954 if (x & SX_LOCK_SHARED) {
955 sleepq_release(&sx->lock_object);
961 * If the owner is running on another CPU, spin until
962 * the owner stops running or the state of the lock
965 if (!(x & SX_LOCK_SHARED) &&
966 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
967 owner = (struct thread *)SX_OWNER(x);
968 if (TD_IS_RUNNING(owner)) {
969 sleepq_release(&sx->lock_object);
976 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
977 * fail to set it drop the sleep queue lock and loop
980 if (!(x & SX_LOCK_SHARED_WAITERS)) {
981 if (!atomic_cmpset_ptr(&sx->sx_lock, x,
982 x | SX_LOCK_SHARED_WAITERS)) {
983 sleepq_release(&sx->lock_object);
986 if (LOCK_LOG_TEST(&sx->lock_object, 0))
987 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
992 * Since we have been unable to acquire the shared lock,
995 if (LOCK_LOG_TEST(&sx->lock_object, 0))
996 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1000 sleep_time -= lockstat_nsecs(&sx->lock_object);
1003 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1004 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1005 SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1006 if (!(opts & SX_INTERRUPTIBLE))
1007 sleepq_wait(&sx->lock_object, 0);
1009 error = sleepq_wait_sig(&sx->lock_object, 0);
1010 #ifdef KDTRACE_HOOKS
1011 sleep_time += lockstat_nsecs(&sx->lock_object);
1015 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1017 "%s: interruptible sleep by %p suspended by signal",
1021 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1022 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1025 #ifdef KDTRACE_HOOKS
1026 all_time += lockstat_nsecs(&sx->lock_object);
1028 LOCKSTAT_RECORD4(LS_SX_SLOCK_BLOCK, sx, sleep_time,
1029 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1030 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1031 if (lda.spin_cnt > sleep_cnt)
1032 LOCKSTAT_RECORD4(LS_SX_SLOCK_SPIN, sx, all_time - sleep_time,
1033 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1034 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1037 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_SX_SLOCK_ACQUIRE, sx,
1038 contested, waittime, file, line);
1044 * This function represents the so-called 'hard case' for sx_sunlock
1045 * operation. All 'easy case' failures are redirected to this. Note
1046 * that ideally this would be a static function, but it needs to be
1047 * accessible from at least sx.h.
1050 _sx_sunlock_hard(struct sx *sx, const char *file, int line)
1055 if (SCHEDULER_STOPPED())
1062 * We should never have sharers while at least one thread
1063 * holds a shared lock.
1065 KASSERT(!(x & SX_LOCK_SHARED_WAITERS),
1066 ("%s: waiting sharers", __func__));
1069 * See if there is more than one shared lock held. If
1070 * so, just drop one and return.
1072 if (SX_SHARERS(x) > 1) {
1073 if (atomic_cmpset_rel_ptr(&sx->sx_lock, x,
1074 x - SX_ONE_SHARER)) {
1075 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1077 "%s: %p succeeded %p -> %p",
1078 __func__, sx, (void *)x,
1079 (void *)(x - SX_ONE_SHARER));
1086 * If there aren't any waiters for an exclusive lock,
1087 * then try to drop it quickly.
1089 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
1090 MPASS(x == SX_SHARERS_LOCK(1));
1091 if (atomic_cmpset_rel_ptr(&sx->sx_lock,
1092 SX_SHARERS_LOCK(1), SX_LOCK_UNLOCKED)) {
1093 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1094 CTR2(KTR_LOCK, "%s: %p last succeeded",
1102 * At this point, there should just be one sharer with
1103 * exclusive waiters.
1105 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1107 sleepq_lock(&sx->lock_object);
1110 * Wake up semantic here is quite simple:
1111 * Just wake up all the exclusive waiters.
1112 * Note that the state of the lock could have changed,
1113 * so if it fails loop back and retry.
1115 if (!atomic_cmpset_rel_ptr(&sx->sx_lock,
1116 SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
1117 SX_LOCK_UNLOCKED)) {
1118 sleepq_release(&sx->lock_object);
1121 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1122 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1123 "exclusive queue", __func__, sx);
1124 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1125 0, SQ_EXCLUSIVE_QUEUE);
1126 sleepq_release(&sx->lock_object);
1133 #ifdef INVARIANT_SUPPORT
1139 * In the non-WITNESS case, sx_assert() can only detect that at least
1140 * *some* thread owns an slock, but it cannot guarantee that *this*
1141 * thread owns an slock.
1144 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1150 if (panicstr != NULL)
1154 case SA_SLOCKED | SA_NOTRECURSED:
1155 case SA_SLOCKED | SA_RECURSED:
1161 case SA_LOCKED | SA_NOTRECURSED:
1162 case SA_LOCKED | SA_RECURSED:
1164 witness_assert(&sx->lock_object, what, file, line);
1167 * If some other thread has an exclusive lock or we
1168 * have one and are asserting a shared lock, fail.
1169 * Also, if no one has a lock at all, fail.
1171 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1172 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1173 sx_xholder(sx) != curthread)))
1174 panic("Lock %s not %slocked @ %s:%d\n",
1175 sx->lock_object.lo_name, slocked ? "share " : "",
1178 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1179 if (sx_recursed(sx)) {
1180 if (what & SA_NOTRECURSED)
1181 panic("Lock %s recursed @ %s:%d\n",
1182 sx->lock_object.lo_name, file,
1184 } else if (what & SA_RECURSED)
1185 panic("Lock %s not recursed @ %s:%d\n",
1186 sx->lock_object.lo_name, file, line);
1191 case SA_XLOCKED | SA_NOTRECURSED:
1192 case SA_XLOCKED | SA_RECURSED:
1193 if (sx_xholder(sx) != curthread)
1194 panic("Lock %s not exclusively locked @ %s:%d\n",
1195 sx->lock_object.lo_name, file, line);
1196 if (sx_recursed(sx)) {
1197 if (what & SA_NOTRECURSED)
1198 panic("Lock %s recursed @ %s:%d\n",
1199 sx->lock_object.lo_name, file, line);
1200 } else if (what & SA_RECURSED)
1201 panic("Lock %s not recursed @ %s:%d\n",
1202 sx->lock_object.lo_name, file, line);
1206 witness_assert(&sx->lock_object, what, file, line);
1209 * If we hold an exclusve lock fail. We can't
1210 * reliably check to see if we hold a shared lock or
1213 if (sx_xholder(sx) == curthread)
1214 panic("Lock %s exclusively locked @ %s:%d\n",
1215 sx->lock_object.lo_name, file, line);
1219 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1223 #endif /* INVARIANT_SUPPORT */
1227 db_show_sx(const struct lock_object *lock)
1230 const struct sx *sx;
1232 sx = (const struct sx *)lock;
1234 db_printf(" state: ");
1235 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1236 db_printf("UNLOCKED\n");
1237 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1238 db_printf("DESTROYED\n");
1240 } else if (sx->sx_lock & SX_LOCK_SHARED)
1241 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1243 td = sx_xholder(sx);
1244 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1245 td->td_tid, td->td_proc->p_pid, td->td_name);
1246 if (sx_recursed(sx))
1247 db_printf(" recursed: %d\n", sx->sx_recurse);
1250 db_printf(" waiters: ");
1251 switch(sx->sx_lock &
1252 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1253 case SX_LOCK_SHARED_WAITERS:
1254 db_printf("shared\n");
1256 case SX_LOCK_EXCLUSIVE_WAITERS:
1257 db_printf("exclusive\n");
1259 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1260 db_printf("exclusive and shared\n");
1263 db_printf("none\n");
1268 * Check to see if a thread that is blocked on a sleep queue is actually
1269 * blocked on an sx lock. If so, output some details and return true.
1270 * If the lock has an exclusive owner, return that in *ownerp.
1273 sx_chain(struct thread *td, struct thread **ownerp)
1278 * Check to see if this thread is blocked on an sx lock.
1279 * First, we check the lock class. If that is ok, then we
1280 * compare the lock name against the wait message.
1283 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1284 sx->lock_object.lo_name != td->td_wmesg)
1287 /* We think we have an sx lock, so output some details. */
1288 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1289 *ownerp = sx_xholder(sx);
1290 if (sx->sx_lock & SX_LOCK_SHARED)
1291 db_printf("SLOCK (count %ju)\n",
1292 (uintmax_t)SX_SHARERS(sx->sx_lock));
1294 db_printf("XLOCK\n");