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 = {
158 SYSCTL_INT(_debug_sx, OID_AUTO, delay_initial, CTLFLAG_RW, &sx_delay.initial,
160 SYSCTL_INT(_debug_sx, OID_AUTO, delay_step, CTLFLAG_RW, &sx_delay.step,
162 SYSCTL_INT(_debug_sx, OID_AUTO, delay_min, CTLFLAG_RW, &sx_delay.min,
164 SYSCTL_INT(_debug_sx, OID_AUTO, delay_max, CTLFLAG_RW, &sx_delay.max,
168 sx_delay_sysinit(void *dummy)
171 sx_delay.initial = mp_ncpus * 25;
172 sx_delay.step = (mp_ncpus * 25) / 2;
173 sx_delay.min = mp_ncpus * 5;
174 sx_delay.max = mp_ncpus * 25 * 10;
176 LOCK_DELAY_SYSINIT(sx_delay_sysinit);
180 assert_sx(const struct lock_object *lock, int what)
183 sx_assert((const struct sx *)lock, what);
187 lock_sx(struct lock_object *lock, uintptr_t how)
191 sx = (struct sx *)lock;
199 unlock_sx(struct lock_object *lock)
203 sx = (struct sx *)lock;
204 sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
205 if (sx_xlocked(sx)) {
216 owner_sx(const struct lock_object *lock, struct thread **owner)
221 sx = (const struct sx *)lock;
224 return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
225 ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
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 TD_LOCKS_INC(curthread);
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_RWLOCK_SUCCESS(sx__acquire,
323 sx, 0, 0, file, line, LOCKSTAT_READER);
324 TD_LOCKS_INC(curthread);
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 TD_LOCKS_INC(curthread);
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_RWLOCK_SUCCESS(sx__acquire,
386 sx, 0, 0, file, line, LOCKSTAT_WRITER);
387 TD_LOCKS_INC(curthread);
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 TD_LOCKS_DEC(curthread);
409 _sx_xunlock(struct sx *sx, const char *file, int line)
412 if (SCHEDULER_STOPPED())
414 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
415 ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
416 _sx_assert(sx, SA_XLOCKED, file, line);
417 WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
418 LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
420 __sx_xunlock(sx, curthread, file, line);
421 TD_LOCKS_DEC(curthread);
425 * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
426 * This will only succeed if this thread holds a single shared lock.
427 * Return 1 if if the upgrade succeed, 0 otherwise.
430 sx_try_upgrade_(struct sx *sx, const char *file, int line)
435 if (SCHEDULER_STOPPED())
438 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
439 ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
440 _sx_assert(sx, SA_SLOCKED, file, line);
443 * Try to switch from one shared lock to an exclusive lock. We need
444 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
445 * we will wake up the exclusive waiters when we drop the lock.
447 x = sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS;
448 success = atomic_cmpset_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) | x,
449 (uintptr_t)curthread | x);
450 LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
452 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
454 LOCKSTAT_RECORD0(sx__upgrade, sx);
460 * Downgrade an unrecursed exclusive lock into a single shared lock.
463 sx_downgrade_(struct sx *sx, const char *file, int line)
468 if (SCHEDULER_STOPPED())
471 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
472 ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
473 _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
476 panic("downgrade of a recursed lock");
479 WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
482 * Try to switch from an exclusive lock with no shared waiters
483 * to one sharer with no shared waiters. If there are
484 * exclusive waiters, we don't need to lock the sleep queue so
485 * long as we preserve the flag. We do one quick try and if
486 * that fails we grab the sleepq lock to keep the flags from
487 * changing and do it the slow way.
489 * We have to lock the sleep queue if there are shared waiters
490 * so we can wake them up.
493 if (!(x & SX_LOCK_SHARED_WAITERS) &&
494 atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
495 (x & SX_LOCK_EXCLUSIVE_WAITERS))) {
496 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
501 * Lock the sleep queue so we can read the waiters bits
502 * without any races and wakeup any shared waiters.
504 sleepq_lock(&sx->lock_object);
507 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
508 * shared lock. If there are any shared waiters, wake them up.
512 atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
513 (x & SX_LOCK_EXCLUSIVE_WAITERS));
514 if (x & SX_LOCK_SHARED_WAITERS)
515 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
517 sleepq_release(&sx->lock_object);
519 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
520 LOCKSTAT_RECORD0(sx__downgrade, sx);
527 * This function represents the so-called 'hard case' for sx_xlock
528 * operation. All 'easy case' failures are redirected to this. Note
529 * that ideally this would be a static function, but it needs to be
530 * accessible from at least sx.h.
533 _sx_xlock_hard(struct sx *sx, uintptr_t tid, int opts, const char *file,
538 volatile struct thread *owner;
539 u_int i, spintries = 0;
542 #ifdef LOCK_PROFILING
543 uint64_t waittime = 0;
547 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
548 struct lock_delay_arg lda;
553 int64_t sleep_time = 0;
554 int64_t all_time = 0;
557 if (SCHEDULER_STOPPED())
560 #if defined(ADAPTIVE_SX)
561 lock_delay_arg_init(&lda, &sx_delay);
562 #elif defined(KDTRACE_HOOKS)
563 lock_delay_arg_init(&lda, NULL);
566 x = SX_READ_VALUE(sx);
568 /* If we already hold an exclusive lock, then recurse. */
569 if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
570 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
571 ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
572 sx->lock_object.lo_name, file, line));
574 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
575 if (LOCK_LOG_TEST(&sx->lock_object, 0))
576 CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
580 if (LOCK_LOG_TEST(&sx->lock_object, 0))
581 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
582 sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
585 all_time -= lockstat_nsecs(&sx->lock_object);
589 if (x == SX_LOCK_UNLOCKED) {
590 if (atomic_cmpset_acq_ptr(&sx->sx_lock, x, tid))
592 x = SX_READ_VALUE(sx);
599 PMC_SOFT_CALL( , , lock, failed);
601 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
605 * If the lock is write locked and the owner is
606 * running on another CPU, spin until the owner stops
607 * running or the state of the lock changes.
609 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
610 if ((x & SX_LOCK_SHARED) == 0) {
611 owner = lv_sx_owner(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);
624 x = SX_READ_VALUE(sx);
625 owner = lv_sx_owner(x);
626 } while (owner != NULL &&
627 TD_IS_RUNNING(owner));
628 KTR_STATE0(KTR_SCHED, "thread",
629 sched_tdname(curthread), "running");
632 } else if (SX_SHARERS(x) && spintries < asx_retries) {
633 KTR_STATE1(KTR_SCHED, "thread",
634 sched_tdname(curthread), "spinning",
635 "lockname:\"%s\"", sx->lock_object.lo_name);
638 for (i = 0; i < asx_loops; i++) {
639 if (LOCK_LOG_TEST(&sx->lock_object, 0))
641 "%s: shared spinning on %p with %u and %u",
642 __func__, sx, spintries, i);
644 if ((x & SX_LOCK_SHARED) == 0 ||
652 KTR_STATE0(KTR_SCHED, "thread",
653 sched_tdname(curthread), "running");
654 x = SX_READ_VALUE(sx);
661 sleepq_lock(&sx->lock_object);
662 x = SX_READ_VALUE(sx);
665 * If the lock was released while spinning on the
666 * sleep queue chain lock, try again.
668 if (x == SX_LOCK_UNLOCKED) {
669 sleepq_release(&sx->lock_object);
675 * The current lock owner might have started executing
676 * on another CPU (or the lock could have changed
677 * owners) while we were waiting on the sleep queue
678 * chain lock. If so, drop the sleep queue lock and try
681 if (!(x & SX_LOCK_SHARED) &&
682 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
683 owner = (struct thread *)SX_OWNER(x);
684 if (TD_IS_RUNNING(owner)) {
685 sleepq_release(&sx->lock_object);
692 * If an exclusive lock was released with both shared
693 * and exclusive waiters and a shared waiter hasn't
694 * woken up and acquired the lock yet, sx_lock will be
695 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
696 * If we see that value, try to acquire it once. Note
697 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
698 * as there are other exclusive waiters still. If we
699 * fail, restart the loop.
701 if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
702 if (atomic_cmpset_acq_ptr(&sx->sx_lock,
703 SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
704 tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
705 sleepq_release(&sx->lock_object);
706 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
710 sleepq_release(&sx->lock_object);
711 x = SX_READ_VALUE(sx);
716 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
717 * than loop back and retry.
719 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
720 if (!atomic_cmpset_ptr(&sx->sx_lock, x,
721 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
722 sleepq_release(&sx->lock_object);
723 x = SX_READ_VALUE(sx);
726 if (LOCK_LOG_TEST(&sx->lock_object, 0))
727 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
732 * Since we have been unable to acquire the exclusive
733 * lock and the exclusive waiters flag is set, we have
736 if (LOCK_LOG_TEST(&sx->lock_object, 0))
737 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
741 sleep_time -= lockstat_nsecs(&sx->lock_object);
744 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
745 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
746 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
747 if (!(opts & SX_INTERRUPTIBLE))
748 sleepq_wait(&sx->lock_object, 0);
750 error = sleepq_wait_sig(&sx->lock_object, 0);
752 sleep_time += lockstat_nsecs(&sx->lock_object);
756 if (LOCK_LOG_TEST(&sx->lock_object, 0))
758 "%s: interruptible sleep by %p suspended by signal",
762 if (LOCK_LOG_TEST(&sx->lock_object, 0))
763 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
765 x = SX_READ_VALUE(sx);
768 all_time += lockstat_nsecs(&sx->lock_object);
770 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
771 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
772 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
773 if (lda.spin_cnt > sleep_cnt)
774 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
775 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
776 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
779 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
780 contested, waittime, file, line, LOCKSTAT_WRITER);
786 * This function represents the so-called 'hard case' for sx_xunlock
787 * operation. All 'easy case' failures are redirected to this. Note
788 * that ideally this would be a static function, but it needs to be
789 * accessible from at least sx.h.
792 _sx_xunlock_hard(struct sx *sx, uintptr_t tid, const char *file, int line)
795 int queue, wakeup_swapper;
797 if (SCHEDULER_STOPPED())
800 MPASS(!(sx->sx_lock & SX_LOCK_SHARED));
802 /* If the lock is recursed, then unrecurse one level. */
803 if (sx_xlocked(sx) && sx_recursed(sx)) {
804 if ((--sx->sx_recurse) == 0)
805 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
806 if (LOCK_LOG_TEST(&sx->lock_object, 0))
807 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
810 MPASS(sx->sx_lock & (SX_LOCK_SHARED_WAITERS |
811 SX_LOCK_EXCLUSIVE_WAITERS));
812 if (LOCK_LOG_TEST(&sx->lock_object, 0))
813 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
815 sleepq_lock(&sx->lock_object);
816 x = SX_LOCK_UNLOCKED;
819 * The wake up algorithm here is quite simple and probably not
820 * ideal. It gives precedence to shared waiters if they are
821 * present. For this condition, we have to preserve the
822 * state of the exclusive waiters flag.
823 * If interruptible sleeps left the shared queue empty avoid a
824 * starvation for the threads sleeping on the exclusive queue by giving
825 * them precedence and cleaning up the shared waiters bit anyway.
827 if ((sx->sx_lock & SX_LOCK_SHARED_WAITERS) != 0 &&
828 sleepq_sleepcnt(&sx->lock_object, SQ_SHARED_QUEUE) != 0) {
829 queue = SQ_SHARED_QUEUE;
830 x |= (sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS);
832 queue = SQ_EXCLUSIVE_QUEUE;
834 /* Wake up all the waiters for the specific queue. */
835 if (LOCK_LOG_TEST(&sx->lock_object, 0))
836 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
837 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
839 atomic_store_rel_ptr(&sx->sx_lock, x);
840 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
842 sleepq_release(&sx->lock_object);
848 * This function represents the so-called 'hard case' for sx_slock
849 * operation. All 'easy case' failures are redirected to this. Note
850 * that ideally this would be a static function, but it needs to be
851 * accessible from at least sx.h.
854 _sx_slock_hard(struct sx *sx, int opts, const char *file, int line)
858 volatile struct thread *owner;
860 #ifdef LOCK_PROFILING
861 uint64_t waittime = 0;
866 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
867 struct lock_delay_arg lda;
872 int64_t sleep_time = 0;
873 int64_t all_time = 0;
876 if (SCHEDULER_STOPPED())
879 #if defined(ADAPTIVE_SX)
880 lock_delay_arg_init(&lda, &sx_delay);
881 #elif defined(KDTRACE_HOOKS)
882 lock_delay_arg_init(&lda, NULL);
885 all_time -= lockstat_nsecs(&sx->lock_object);
887 x = SX_READ_VALUE(sx);
893 * As with rwlocks, we don't make any attempt to try to block
894 * shared locks once there is an exclusive waiter.
898 * If no other thread has an exclusive lock then try to bump up
899 * the count of sharers. Since we have to preserve the state
900 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
901 * shared lock loop back and retry.
903 if (x & SX_LOCK_SHARED) {
904 MPASS(!(x & SX_LOCK_SHARED_WAITERS));
905 if (atomic_cmpset_acq_ptr(&sx->sx_lock, x,
906 x + SX_ONE_SHARER)) {
907 if (LOCK_LOG_TEST(&sx->lock_object, 0))
909 "%s: %p succeed %p -> %p", __func__,
911 (void *)(x + SX_ONE_SHARER));
914 x = SX_READ_VALUE(sx);
922 PMC_SOFT_CALL( , , lock, failed);
924 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
929 * If the owner is running on another CPU, spin until
930 * the owner stops running or the state of the lock
933 if ((sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
934 owner = lv_sx_owner(x);
935 if (TD_IS_RUNNING(owner)) {
936 if (LOCK_LOG_TEST(&sx->lock_object, 0))
938 "%s: spinning on %p held by %p",
939 __func__, sx, owner);
940 KTR_STATE1(KTR_SCHED, "thread",
941 sched_tdname(curthread), "spinning",
942 "lockname:\"%s\"", sx->lock_object.lo_name);
946 x = SX_READ_VALUE(sx);
947 owner = lv_sx_owner(x);
948 } while (owner != NULL && TD_IS_RUNNING(owner));
949 KTR_STATE0(KTR_SCHED, "thread",
950 sched_tdname(curthread), "running");
957 * Some other thread already has an exclusive lock, so
958 * start the process of blocking.
960 sleepq_lock(&sx->lock_object);
961 x = SX_READ_VALUE(sx);
964 * The lock could have been released while we spun.
965 * In this case loop back and retry.
967 if (x & SX_LOCK_SHARED) {
968 sleepq_release(&sx->lock_object);
974 * If the owner is running on another CPU, spin until
975 * the owner stops running or the state of the lock
978 if (!(x & SX_LOCK_SHARED) &&
979 (sx->lock_object.lo_flags & SX_NOADAPTIVE) == 0) {
980 owner = (struct thread *)SX_OWNER(x);
981 if (TD_IS_RUNNING(owner)) {
982 sleepq_release(&sx->lock_object);
983 x = SX_READ_VALUE(sx);
990 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
991 * fail to set it drop the sleep queue lock and loop
994 if (!(x & SX_LOCK_SHARED_WAITERS)) {
995 if (!atomic_cmpset_ptr(&sx->sx_lock, x,
996 x | SX_LOCK_SHARED_WAITERS)) {
997 sleepq_release(&sx->lock_object);
998 x = SX_READ_VALUE(sx);
1001 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1002 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1007 * Since we have been unable to acquire the shared lock,
1010 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1011 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1014 #ifdef KDTRACE_HOOKS
1015 sleep_time -= lockstat_nsecs(&sx->lock_object);
1018 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1019 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1020 SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1021 if (!(opts & SX_INTERRUPTIBLE))
1022 sleepq_wait(&sx->lock_object, 0);
1024 error = sleepq_wait_sig(&sx->lock_object, 0);
1025 #ifdef KDTRACE_HOOKS
1026 sleep_time += lockstat_nsecs(&sx->lock_object);
1030 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1032 "%s: interruptible sleep by %p suspended by signal",
1036 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1037 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1039 x = SX_READ_VALUE(sx);
1041 #ifdef KDTRACE_HOOKS
1042 all_time += lockstat_nsecs(&sx->lock_object);
1044 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1045 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1046 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1047 if (lda.spin_cnt > sleep_cnt)
1048 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1049 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1050 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1053 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1054 contested, waittime, file, line, LOCKSTAT_READER);
1060 * This function represents the so-called 'hard case' for sx_sunlock
1061 * operation. All 'easy case' failures are redirected to this. Note
1062 * that ideally this would be a static function, but it needs to be
1063 * accessible from at least sx.h.
1066 _sx_sunlock_hard(struct sx *sx, const char *file, int line)
1071 if (SCHEDULER_STOPPED())
1074 x = SX_READ_VALUE(sx);
1077 * We should never have sharers while at least one thread
1078 * holds a shared lock.
1080 KASSERT(!(x & SX_LOCK_SHARED_WAITERS),
1081 ("%s: waiting sharers", __func__));
1084 * See if there is more than one shared lock held. If
1085 * so, just drop one and return.
1087 if (SX_SHARERS(x) > 1) {
1088 if (atomic_cmpset_rel_ptr(&sx->sx_lock, x,
1089 x - SX_ONE_SHARER)) {
1090 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1092 "%s: %p succeeded %p -> %p",
1093 __func__, sx, (void *)x,
1094 (void *)(x - SX_ONE_SHARER));
1098 x = SX_READ_VALUE(sx);
1103 * If there aren't any waiters for an exclusive lock,
1104 * then try to drop it quickly.
1106 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
1107 MPASS(x == SX_SHARERS_LOCK(1));
1108 if (atomic_cmpset_rel_ptr(&sx->sx_lock,
1109 SX_SHARERS_LOCK(1), SX_LOCK_UNLOCKED)) {
1110 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1111 CTR2(KTR_LOCK, "%s: %p last succeeded",
1115 x = SX_READ_VALUE(sx);
1120 * At this point, there should just be one sharer with
1121 * exclusive waiters.
1123 MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
1125 sleepq_lock(&sx->lock_object);
1128 * Wake up semantic here is quite simple:
1129 * Just wake up all the exclusive waiters.
1130 * Note that the state of the lock could have changed,
1131 * so if it fails loop back and retry.
1133 if (!atomic_cmpset_rel_ptr(&sx->sx_lock,
1134 SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
1135 SX_LOCK_UNLOCKED)) {
1136 sleepq_release(&sx->lock_object);
1137 x = SX_READ_VALUE(sx);
1140 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1141 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1142 "exclusive queue", __func__, sx);
1143 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1144 0, SQ_EXCLUSIVE_QUEUE);
1145 sleepq_release(&sx->lock_object);
1152 #ifdef INVARIANT_SUPPORT
1158 * In the non-WITNESS case, sx_assert() can only detect that at least
1159 * *some* thread owns an slock, but it cannot guarantee that *this*
1160 * thread owns an slock.
1163 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1169 if (panicstr != NULL)
1173 case SA_SLOCKED | SA_NOTRECURSED:
1174 case SA_SLOCKED | SA_RECURSED:
1180 case SA_LOCKED | SA_NOTRECURSED:
1181 case SA_LOCKED | SA_RECURSED:
1183 witness_assert(&sx->lock_object, what, file, line);
1186 * If some other thread has an exclusive lock or we
1187 * have one and are asserting a shared lock, fail.
1188 * Also, if no one has a lock at all, fail.
1190 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1191 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1192 sx_xholder(sx) != curthread)))
1193 panic("Lock %s not %slocked @ %s:%d\n",
1194 sx->lock_object.lo_name, slocked ? "share " : "",
1197 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
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,
1203 } else if (what & SA_RECURSED)
1204 panic("Lock %s not recursed @ %s:%d\n",
1205 sx->lock_object.lo_name, file, line);
1210 case SA_XLOCKED | SA_NOTRECURSED:
1211 case SA_XLOCKED | SA_RECURSED:
1212 if (sx_xholder(sx) != curthread)
1213 panic("Lock %s not exclusively locked @ %s:%d\n",
1214 sx->lock_object.lo_name, file, line);
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, line);
1219 } else if (what & SA_RECURSED)
1220 panic("Lock %s not recursed @ %s:%d\n",
1221 sx->lock_object.lo_name, file, line);
1225 witness_assert(&sx->lock_object, what, file, line);
1228 * If we hold an exclusve lock fail. We can't
1229 * reliably check to see if we hold a shared lock or
1232 if (sx_xholder(sx) == curthread)
1233 panic("Lock %s exclusively locked @ %s:%d\n",
1234 sx->lock_object.lo_name, file, line);
1238 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1242 #endif /* INVARIANT_SUPPORT */
1246 db_show_sx(const struct lock_object *lock)
1249 const struct sx *sx;
1251 sx = (const struct sx *)lock;
1253 db_printf(" state: ");
1254 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1255 db_printf("UNLOCKED\n");
1256 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1257 db_printf("DESTROYED\n");
1259 } else if (sx->sx_lock & SX_LOCK_SHARED)
1260 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1262 td = sx_xholder(sx);
1263 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1264 td->td_tid, td->td_proc->p_pid, td->td_name);
1265 if (sx_recursed(sx))
1266 db_printf(" recursed: %d\n", sx->sx_recurse);
1269 db_printf(" waiters: ");
1270 switch(sx->sx_lock &
1271 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1272 case SX_LOCK_SHARED_WAITERS:
1273 db_printf("shared\n");
1275 case SX_LOCK_EXCLUSIVE_WAITERS:
1276 db_printf("exclusive\n");
1278 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1279 db_printf("exclusive and shared\n");
1282 db_printf("none\n");
1287 * Check to see if a thread that is blocked on a sleep queue is actually
1288 * blocked on an sx lock. If so, output some details and return true.
1289 * If the lock has an exclusive owner, return that in *ownerp.
1292 sx_chain(struct thread *td, struct thread **ownerp)
1297 * Check to see if this thread is blocked on an sx lock.
1298 * First, we check the lock class. If that is ok, then we
1299 * compare the lock name against the wait message.
1302 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1303 sx->lock_object.lo_name != td->td_wmesg)
1306 /* We think we have an sx lock, so output some details. */
1307 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1308 *ownerp = sx_xholder(sx);
1309 if (sx->sx_lock & SX_LOCK_SHARED)
1310 db_printf("SLOCK (count %ju)\n",
1311 (uintmax_t)SX_SHARERS(sx->sx_lock));
1313 db_printf("XLOCK\n");