2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2007 Attilio Rao <attilio@freebsd.org>
5 * Copyright (c) 2001 Jason Evans <jasone@freebsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice(s), this list of conditions and the following disclaimer as
13 * the first lines of this file unmodified other than the possible
14 * addition of one or more copyright notices.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice(s), this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
20 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
23 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
33 * Shared/exclusive locks. This implementation attempts to ensure
34 * deterministic lock granting behavior, so that slocks and xlocks are
37 * Priority propagation will not generally raise the priority of lock holders,
38 * so should not be relied upon in combination with sx locks.
42 #include "opt_hwpmc_hooks.h"
43 #include "opt_no_adaptive_sx.h"
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
48 #include <sys/param.h>
49 #include <sys/systm.h>
51 #include <sys/kernel.h>
54 #include <sys/mutex.h>
56 #include <sys/sched.h>
57 #include <sys/sleepqueue.h>
60 #include <sys/sysctl.h>
62 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
63 #include <machine/cpu.h>
70 #if defined(SMP) && !defined(NO_ADAPTIVE_SX)
75 #include <sys/pmckern.h>
76 PMC_SOFT_DECLARE( , , lock, failed);
79 /* Handy macros for sleep queues. */
80 #define SQ_EXCLUSIVE_QUEUE 0
81 #define SQ_SHARED_QUEUE 1
84 * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file. We
85 * drop Giant anytime we have to sleep or if we adaptively spin.
87 #define GIANT_DECLARE \
89 WITNESS_SAVE_DECL(Giant) \
91 #define GIANT_SAVE(work) do { \
92 if (__predict_false(mtx_owned(&Giant))) { \
94 WITNESS_SAVE(&Giant.lock_object, Giant); \
95 while (mtx_owned(&Giant)) { \
102 #define GIANT_RESTORE() do { \
103 if (_giantcnt > 0) { \
104 mtx_assert(&Giant, MA_NOTOWNED); \
105 while (_giantcnt--) \
107 WITNESS_RESTORE(&Giant.lock_object, Giant); \
112 * Returns true if an exclusive lock is recursed. It assumes
113 * curthread currently has an exclusive lock.
115 #define sx_recursed(sx) ((sx)->sx_recurse != 0)
117 static void assert_sx(const struct lock_object *lock, int what);
119 static void db_show_sx(const struct lock_object *lock);
121 static void lock_sx(struct lock_object *lock, uintptr_t how);
123 static int owner_sx(const struct lock_object *lock, struct thread **owner);
125 static uintptr_t unlock_sx(struct lock_object *lock);
127 struct lock_class lock_class_sx = {
129 .lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
130 .lc_assert = assert_sx,
132 .lc_ddb_show = db_show_sx,
135 .lc_unlock = unlock_sx,
137 .lc_owner = owner_sx,
142 #define _sx_assert(sx, what, file, line)
146 #ifdef SX_CUSTOM_BACKOFF
147 static u_short __read_frequently asx_retries;
148 static u_short __read_frequently asx_loops;
149 static SYSCTL_NODE(_debug, OID_AUTO, sx, CTLFLAG_RD, NULL, "sxlock debugging");
150 SYSCTL_U16(_debug_sx, OID_AUTO, retries, CTLFLAG_RW, &asx_retries, 0, "");
151 SYSCTL_U16(_debug_sx, OID_AUTO, loops, CTLFLAG_RW, &asx_loops, 0, "");
153 static struct lock_delay_config __read_frequently sx_delay;
155 SYSCTL_U16(_debug_sx, OID_AUTO, delay_base, CTLFLAG_RW, &sx_delay.base,
157 SYSCTL_U16(_debug_sx, OID_AUTO, delay_max, CTLFLAG_RW, &sx_delay.max,
161 sx_lock_delay_init(void *arg __unused)
164 lock_delay_default_init(&sx_delay);
166 asx_loops = max(10000, sx_delay.max);
168 LOCK_DELAY_SYSINIT(sx_lock_delay_init);
170 #define sx_delay locks_delay
171 #define asx_retries locks_delay_retries
172 #define asx_loops locks_delay_loops
177 assert_sx(const struct lock_object *lock, int what)
180 sx_assert((const struct sx *)lock, what);
184 lock_sx(struct lock_object *lock, uintptr_t how)
188 sx = (struct sx *)lock;
196 unlock_sx(struct lock_object *lock)
200 sx = (struct sx *)lock;
201 sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
202 if (sx_xlocked(sx)) {
213 owner_sx(const struct lock_object *lock, struct thread **owner)
218 sx = (const struct sx *)lock;
221 return ((x & SX_LOCK_SHARED) != 0 ? (SX_SHARERS(x) != 0) :
222 ((*owner = (struct thread *)SX_OWNER(x)) != NULL));
227 sx_sysinit(void *arg)
229 struct sx_args *sargs = arg;
231 sx_init_flags(sargs->sa_sx, sargs->sa_desc, sargs->sa_flags);
235 sx_init_flags(struct sx *sx, const char *description, int opts)
239 MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
240 SX_NOPROFILE | SX_NEW)) == 0);
241 ASSERT_ATOMIC_LOAD_PTR(sx->sx_lock,
242 ("%s: sx_lock not aligned for %s: %p", __func__, description,
245 flags = LO_SLEEPABLE | LO_UPGRADABLE;
248 if (opts & SX_NOPROFILE)
249 flags |= LO_NOPROFILE;
250 if (!(opts & SX_NOWITNESS))
252 if (opts & SX_RECURSE)
253 flags |= LO_RECURSABLE;
259 lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
260 sx->sx_lock = SX_LOCK_UNLOCKED;
265 sx_destroy(struct sx *sx)
268 KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
269 KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
270 sx->sx_lock = SX_LOCK_DESTROYED;
271 lock_destroy(&sx->lock_object);
275 sx_try_slock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
279 if (SCHEDULER_STOPPED())
282 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
283 ("sx_try_slock() by idle thread %p on sx %s @ %s:%d",
284 curthread, sx->lock_object.lo_name, file, line));
288 KASSERT(x != SX_LOCK_DESTROYED,
289 ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
290 if (!(x & SX_LOCK_SHARED))
292 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, x + SX_ONE_SHARER)) {
293 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
294 WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
295 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
296 sx, 0, 0, file, line, LOCKSTAT_READER);
297 TD_LOCKS_INC(curthread);
298 curthread->td_sx_slocks++;
303 LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
308 sx_try_slock_(struct sx *sx, const char *file, int line)
311 return (sx_try_slock_int(sx LOCK_FILE_LINE_ARG));
315 _sx_xlock(struct sx *sx, int opts, const char *file, int line)
320 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
321 !TD_IS_IDLETHREAD(curthread),
322 ("sx_xlock() by idle thread %p on sx %s @ %s:%d",
323 curthread, sx->lock_object.lo_name, file, line));
324 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
325 ("sx_xlock() of destroyed sx @ %s:%d", file, line));
326 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
328 tid = (uintptr_t)curthread;
329 x = SX_LOCK_UNLOCKED;
330 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
331 error = _sx_xlock_hard(sx, x, opts LOCK_FILE_LINE_ARG);
333 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
334 0, 0, file, line, LOCKSTAT_WRITER);
336 LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
338 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
339 TD_LOCKS_INC(curthread);
346 sx_try_xlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
355 if (SCHEDULER_STOPPED_TD(td))
358 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
359 ("sx_try_xlock() by idle thread %p on sx %s @ %s:%d",
360 curthread, sx->lock_object.lo_name, file, line));
361 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
362 ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
366 x = SX_LOCK_UNLOCKED;
368 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
370 if (x == SX_LOCK_UNLOCKED)
372 if (x == tid && (sx->lock_object.lo_flags & LO_RECURSABLE)) {
374 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
381 LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
383 WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
386 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire,
387 sx, 0, 0, file, line, LOCKSTAT_WRITER);
388 TD_LOCKS_INC(curthread);
395 sx_try_xlock_(struct sx *sx, const char *file, int line)
398 return (sx_try_xlock_int(sx LOCK_FILE_LINE_ARG));
402 _sx_xunlock(struct sx *sx, const char *file, int line)
405 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
406 ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
407 _sx_assert(sx, SA_XLOCKED, file, line);
408 WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
409 LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
412 _sx_xunlock_hard(sx, (uintptr_t)curthread, file, line);
414 __sx_xunlock(sx, curthread, file, line);
416 TD_LOCKS_DEC(curthread);
420 * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
421 * This will only succeed if this thread holds a single shared lock.
422 * Return 1 if if the upgrade succeed, 0 otherwise.
425 sx_try_upgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
431 if (SCHEDULER_STOPPED())
434 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
435 ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
436 _sx_assert(sx, SA_SLOCKED, file, line);
439 * Try to switch from one shared lock to an exclusive lock. We need
440 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
441 * we will wake up the exclusive waiters when we drop the lock.
444 x = SX_READ_VALUE(sx);
446 if (SX_SHARERS(x) > 1)
448 waiters = (x & SX_LOCK_WAITERS);
449 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x,
450 (uintptr_t)curthread | waiters)) {
455 LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
457 curthread->td_sx_slocks--;
458 WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
460 LOCKSTAT_RECORD0(sx__upgrade, sx);
466 sx_try_upgrade_(struct sx *sx, const char *file, int line)
469 return (sx_try_upgrade_int(sx LOCK_FILE_LINE_ARG));
473 * Downgrade an unrecursed exclusive lock into a single shared lock.
476 sx_downgrade_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
481 if (SCHEDULER_STOPPED())
484 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
485 ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
486 _sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
489 panic("downgrade of a recursed lock");
492 WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
495 * Try to switch from an exclusive lock with no shared waiters
496 * to one sharer with no shared waiters. If there are
497 * exclusive waiters, we don't need to lock the sleep queue so
498 * long as we preserve the flag. We do one quick try and if
499 * that fails we grab the sleepq lock to keep the flags from
500 * changing and do it the slow way.
502 * We have to lock the sleep queue if there are shared waiters
503 * so we can wake them up.
506 if (!(x & SX_LOCK_SHARED_WAITERS) &&
507 atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
508 (x & SX_LOCK_EXCLUSIVE_WAITERS)))
512 * Lock the sleep queue so we can read the waiters bits
513 * without any races and wakeup any shared waiters.
515 sleepq_lock(&sx->lock_object);
518 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
519 * shared lock. If there are any shared waiters, wake them up.
523 atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
524 (x & SX_LOCK_EXCLUSIVE_WAITERS));
525 if (x & SX_LOCK_SHARED_WAITERS)
526 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
528 sleepq_release(&sx->lock_object);
534 curthread->td_sx_slocks++;
535 LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
536 LOCKSTAT_RECORD0(sx__downgrade, sx);
540 sx_downgrade_(struct sx *sx, const char *file, int line)
543 sx_downgrade_int(sx LOCK_FILE_LINE_ARG);
548 sx_drop_critical(uintptr_t x, bool *in_critical, int *extra_work)
551 if (x & SX_LOCK_WRITE_SPINNER)
555 *in_critical = false;
560 #define sx_drop_critical(x, in_critical, extra_work) do { } while(0)
564 * This function represents the so-called 'hard case' for sx_xlock
565 * operation. All 'easy case' failures are redirected to this. Note
566 * that ideally this would be a static function, but it needs to be
567 * accessible from at least sx.h.
570 _sx_xlock_hard(struct sx *sx, uintptr_t x, int opts LOCK_FILE_LINE_ARG_DEF)
575 volatile struct thread *owner;
576 u_int i, n, spintries = 0;
577 enum { READERS, WRITER } sleep_reason = READERS;
578 bool in_critical = false;
580 #ifdef LOCK_PROFILING
581 uint64_t waittime = 0;
585 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
586 struct lock_delay_arg lda;
590 int64_t sleep_time = 0;
591 int64_t all_time = 0;
593 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
595 int doing_lockprof = 0;
599 tid = (uintptr_t)curthread;
602 if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
603 while (x == SX_LOCK_UNLOCKED) {
604 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
609 all_time -= lockstat_nsecs(&sx->lock_object);
613 #ifdef LOCK_PROFILING
619 if (SCHEDULER_STOPPED())
622 #if defined(ADAPTIVE_SX)
623 lock_delay_arg_init(&lda, &sx_delay);
624 #elif defined(KDTRACE_HOOKS)
625 lock_delay_arg_init(&lda, NULL);
628 if (__predict_false(x == SX_LOCK_UNLOCKED))
629 x = SX_READ_VALUE(sx);
631 /* If we already hold an exclusive lock, then recurse. */
632 if (__predict_false(lv_sx_owner(x) == (struct thread *)tid)) {
633 KASSERT((sx->lock_object.lo_flags & LO_RECURSABLE) != 0,
634 ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
635 sx->lock_object.lo_name, file, line));
637 atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
638 if (LOCK_LOG_TEST(&sx->lock_object, 0))
639 CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
643 if (LOCK_LOG_TEST(&sx->lock_object, 0))
644 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
645 sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
648 PMC_SOFT_CALL( , , lock, failed);
650 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
654 GIANT_SAVE(extra_work);
658 if (x == SX_LOCK_UNLOCKED) {
659 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
664 GIANT_SAVE(extra_work);
670 if (x == (SX_LOCK_SHARED | SX_LOCK_WRITE_SPINNER)) {
671 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid))
677 * If the lock is write locked and the owner is
678 * running on another CPU, spin until the owner stops
679 * running or the state of the lock changes.
681 if ((x & SX_LOCK_SHARED) == 0) {
682 sx_drop_critical(x, &in_critical, &extra_work);
683 sleep_reason = WRITER;
684 owner = lv_sx_owner(x);
685 if (!TD_IS_RUNNING(owner))
687 if (LOCK_LOG_TEST(&sx->lock_object, 0))
688 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
689 __func__, sx, owner);
690 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
691 "spinning", "lockname:\"%s\"",
692 sx->lock_object.lo_name);
695 x = SX_READ_VALUE(sx);
696 owner = lv_sx_owner(x);
697 } while (owner != NULL && TD_IS_RUNNING(owner));
698 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
701 } else if (SX_SHARERS(x) > 0) {
702 sleep_reason = READERS;
703 if (spintries == asx_retries)
705 if (!(x & SX_LOCK_WRITE_SPINNER)) {
711 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
712 x | SX_LOCK_WRITE_SPINNER)) {
720 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
721 "spinning", "lockname:\"%s\"",
722 sx->lock_object.lo_name);
724 for (i = 0; i < asx_loops; i += n) {
726 x = SX_READ_VALUE(sx);
727 if (!(x & SX_LOCK_WRITE_SPINNER))
729 if (!(x & SX_LOCK_SHARED))
738 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
745 sleepq_lock(&sx->lock_object);
746 x = SX_READ_VALUE(sx);
750 * If the lock was released while spinning on the
751 * sleep queue chain lock, try again.
753 if (x == SX_LOCK_UNLOCKED) {
754 sleepq_release(&sx->lock_object);
755 sx_drop_critical(x, &in_critical, &extra_work);
761 * The current lock owner might have started executing
762 * on another CPU (or the lock could have changed
763 * owners) while we were waiting on the sleep queue
764 * chain lock. If so, drop the sleep queue lock and try
767 if (!(x & SX_LOCK_SHARED)) {
768 owner = (struct thread *)SX_OWNER(x);
769 if (TD_IS_RUNNING(owner)) {
770 sleepq_release(&sx->lock_object);
771 sx_drop_critical(x, &in_critical,
775 } else if (SX_SHARERS(x) > 0 && sleep_reason == WRITER) {
776 sleepq_release(&sx->lock_object);
777 sx_drop_critical(x, &in_critical, &extra_work);
783 * If an exclusive lock was released with both shared
784 * and exclusive waiters and a shared waiter hasn't
785 * woken up and acquired the lock yet, sx_lock will be
786 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
787 * If we see that value, try to acquire it once. Note
788 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
789 * as there are other exclusive waiters still. If we
790 * fail, restart the loop.
792 setx = x & (SX_LOCK_WAITERS | SX_LOCK_WRITE_SPINNER);
793 if ((x & ~setx) == SX_LOCK_SHARED) {
794 setx &= ~SX_LOCK_WRITE_SPINNER;
795 if (!atomic_fcmpset_acq_ptr(&sx->sx_lock, &x, tid | setx))
797 sleepq_release(&sx->lock_object);
798 CTR2(KTR_LOCK, "%s: %p claimed by new writer",
805 * It is possible we set the SX_LOCK_WRITE_SPINNER bit.
806 * It is an invariant that when the bit is set, there is
807 * a writer ready to grab the lock. Thus clear the bit since
808 * we are going to sleep.
811 if ((x & SX_LOCK_WRITE_SPINNER) ||
812 !((x & SX_LOCK_EXCLUSIVE_WAITERS))) {
813 setx = x & ~SX_LOCK_WRITE_SPINNER;
814 setx |= SX_LOCK_EXCLUSIVE_WAITERS;
815 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
825 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS. If we fail,
826 * than loop back and retry.
828 if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
829 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
830 x | SX_LOCK_EXCLUSIVE_WAITERS)) {
833 if (LOCK_LOG_TEST(&sx->lock_object, 0))
834 CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
842 * Since we have been unable to acquire the exclusive
843 * lock and the exclusive waiters flag is set, we have
846 if (LOCK_LOG_TEST(&sx->lock_object, 0))
847 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
851 sleep_time -= lockstat_nsecs(&sx->lock_object);
853 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
854 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
855 SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
856 if (!(opts & SX_INTERRUPTIBLE))
857 sleepq_wait(&sx->lock_object, 0);
859 error = sleepq_wait_sig(&sx->lock_object, 0);
861 sleep_time += lockstat_nsecs(&sx->lock_object);
865 if (LOCK_LOG_TEST(&sx->lock_object, 0))
867 "%s: interruptible sleep by %p suspended by signal",
871 if (LOCK_LOG_TEST(&sx->lock_object, 0))
872 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
874 x = SX_READ_VALUE(sx);
876 if (__predict_true(!extra_work))
883 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
884 if (__predict_true(!doing_lockprof))
888 all_time += lockstat_nsecs(&sx->lock_object);
890 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
891 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
892 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
893 if (lda.spin_cnt > sleep_cnt)
894 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
895 LOCKSTAT_WRITER, (state & SX_LOCK_SHARED) == 0,
896 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
900 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
901 contested, waittime, file, line, LOCKSTAT_WRITER);
906 * This function represents the so-called 'hard case' for sx_xunlock
907 * operation. All 'easy case' failures are redirected to this. Note
908 * that ideally this would be a static function, but it needs to be
909 * accessible from at least sx.h.
912 _sx_xunlock_hard(struct sx *sx, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
915 int queue, wakeup_swapper;
917 if (SCHEDULER_STOPPED())
920 tid = (uintptr_t)curthread;
922 if (__predict_false(x == tid))
923 x = SX_READ_VALUE(sx);
925 MPASS(!(x & SX_LOCK_SHARED));
927 if (__predict_false(x & SX_LOCK_RECURSED)) {
928 /* The lock is recursed, unrecurse one level. */
929 if ((--sx->sx_recurse) == 0)
930 atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
931 if (LOCK_LOG_TEST(&sx->lock_object, 0))
932 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
936 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_WRITER);
938 atomic_cmpset_rel_ptr(&sx->sx_lock, tid, SX_LOCK_UNLOCKED))
941 if (LOCK_LOG_TEST(&sx->lock_object, 0))
942 CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
944 sleepq_lock(&sx->lock_object);
945 x = SX_READ_VALUE(sx);
946 MPASS(x & (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS));
949 * The wake up algorithm here is quite simple and probably not
950 * ideal. It gives precedence to shared waiters if they are
951 * present. For this condition, we have to preserve the
952 * state of the exclusive waiters flag.
953 * If interruptible sleeps left the shared queue empty avoid a
954 * starvation for the threads sleeping on the exclusive queue by giving
955 * them precedence and cleaning up the shared waiters bit anyway.
957 setx = SX_LOCK_UNLOCKED;
958 queue = SQ_SHARED_QUEUE;
959 if ((x & SX_LOCK_EXCLUSIVE_WAITERS) != 0 &&
960 sleepq_sleepcnt(&sx->lock_object, SQ_EXCLUSIVE_QUEUE) != 0) {
961 queue = SQ_EXCLUSIVE_QUEUE;
962 setx |= (x & SX_LOCK_SHARED_WAITERS);
964 atomic_store_rel_ptr(&sx->sx_lock, setx);
966 /* Wake up all the waiters for the specific queue. */
967 if (LOCK_LOG_TEST(&sx->lock_object, 0))
968 CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
969 __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
972 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
974 sleepq_release(&sx->lock_object);
979 static bool __always_inline
980 __sx_can_read(struct thread *td, uintptr_t x, bool fp)
983 if ((x & (SX_LOCK_SHARED | SX_LOCK_EXCLUSIVE_WAITERS | SX_LOCK_WRITE_SPINNER))
986 if (!fp && td->td_sx_slocks && (x & SX_LOCK_SHARED))
991 static bool __always_inline
992 __sx_slock_try(struct sx *sx, struct thread *td, uintptr_t *xp, bool fp
993 LOCK_FILE_LINE_ARG_DEF)
997 * If no other thread has an exclusive lock then try to bump up
998 * the count of sharers. Since we have to preserve the state
999 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
1000 * shared lock loop back and retry.
1002 while (__sx_can_read(td, *xp, fp)) {
1003 if (atomic_fcmpset_acq_ptr(&sx->sx_lock, xp,
1004 *xp + SX_ONE_SHARER)) {
1005 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1006 CTR4(KTR_LOCK, "%s: %p succeed %p -> %p",
1007 __func__, sx, (void *)*xp,
1008 (void *)(*xp + SX_ONE_SHARER));
1016 static int __noinline
1017 _sx_slock_hard(struct sx *sx, int opts, uintptr_t x LOCK_FILE_LINE_ARG_DEF)
1022 volatile struct thread *owner;
1023 u_int i, n, spintries = 0;
1025 #ifdef LOCK_PROFILING
1026 uint64_t waittime = 0;
1030 #if defined(ADAPTIVE_SX) || defined(KDTRACE_HOOKS)
1031 struct lock_delay_arg lda;
1033 #ifdef KDTRACE_HOOKS
1034 u_int sleep_cnt = 0;
1035 int64_t sleep_time = 0;
1036 int64_t all_time = 0;
1038 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1039 uintptr_t state = 0;
1045 #ifdef KDTRACE_HOOKS
1046 if (LOCKSTAT_PROFILE_ENABLED(sx__acquire)) {
1047 if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
1050 all_time -= lockstat_nsecs(&sx->lock_object);
1054 #ifdef LOCK_PROFILING
1059 if (SCHEDULER_STOPPED())
1062 #if defined(ADAPTIVE_SX)
1063 lock_delay_arg_init(&lda, &sx_delay);
1064 #elif defined(KDTRACE_HOOKS)
1065 lock_delay_arg_init(&lda, NULL);
1069 PMC_SOFT_CALL( , , lock, failed);
1071 lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
1075 GIANT_SAVE(extra_work);
1079 * As with rwlocks, we don't make any attempt to try to block
1080 * shared locks once there is an exclusive waiter.
1083 if (__sx_slock_try(sx, td, &x, false LOCK_FILE_LINE_ARG))
1086 GIANT_SAVE(extra_work);
1088 #ifdef KDTRACE_HOOKS
1094 * If the owner is running on another CPU, spin until
1095 * the owner stops running or the state of the lock
1098 if ((x & SX_LOCK_SHARED) == 0) {
1099 owner = lv_sx_owner(x);
1100 if (TD_IS_RUNNING(owner)) {
1101 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1103 "%s: spinning on %p held by %p",
1104 __func__, sx, owner);
1105 KTR_STATE1(KTR_SCHED, "thread",
1106 sched_tdname(curthread), "spinning",
1107 "lockname:\"%s\"", sx->lock_object.lo_name);
1110 x = SX_READ_VALUE(sx);
1111 owner = lv_sx_owner(x);
1112 } while (owner != NULL && TD_IS_RUNNING(owner));
1113 KTR_STATE0(KTR_SCHED, "thread",
1114 sched_tdname(curthread), "running");
1118 if ((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) {
1119 MPASS(!__sx_can_read(td, x, false));
1121 x = SX_READ_VALUE(sx);
1124 if (spintries < asx_retries) {
1125 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1126 "spinning", "lockname:\"%s\"",
1127 sx->lock_object.lo_name);
1129 for (i = 0; i < asx_loops; i += n) {
1131 x = SX_READ_VALUE(sx);
1132 if (!(x & SX_LOCK_SHARED))
1137 if (__sx_can_read(td, x, false))
1140 #ifdef KDTRACE_HOOKS
1143 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1152 * Some other thread already has an exclusive lock, so
1153 * start the process of blocking.
1155 sleepq_lock(&sx->lock_object);
1156 x = SX_READ_VALUE(sx);
1158 if (((x & SX_LOCK_WRITE_SPINNER) && SX_SHARERS(x) == 0) ||
1159 __sx_can_read(td, x, false)) {
1160 sleepq_release(&sx->lock_object);
1166 * If the owner is running on another CPU, spin until
1167 * the owner stops running or the state of the lock
1170 if (!(x & SX_LOCK_SHARED)) {
1171 owner = (struct thread *)SX_OWNER(x);
1172 if (TD_IS_RUNNING(owner)) {
1173 sleepq_release(&sx->lock_object);
1174 x = SX_READ_VALUE(sx);
1181 * Try to set the SX_LOCK_SHARED_WAITERS flag. If we
1182 * fail to set it drop the sleep queue lock and loop
1185 if (!(x & SX_LOCK_SHARED_WAITERS)) {
1186 if (!atomic_fcmpset_ptr(&sx->sx_lock, &x,
1187 x | SX_LOCK_SHARED_WAITERS))
1189 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1190 CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
1195 * Since we have been unable to acquire the shared lock,
1198 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1199 CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
1202 #ifdef KDTRACE_HOOKS
1203 sleep_time -= lockstat_nsecs(&sx->lock_object);
1205 sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
1206 SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
1207 SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
1208 if (!(opts & SX_INTERRUPTIBLE))
1209 sleepq_wait(&sx->lock_object, 0);
1211 error = sleepq_wait_sig(&sx->lock_object, 0);
1212 #ifdef KDTRACE_HOOKS
1213 sleep_time += lockstat_nsecs(&sx->lock_object);
1217 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1219 "%s: interruptible sleep by %p suspended by signal",
1223 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1224 CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
1226 x = SX_READ_VALUE(sx);
1228 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1229 if (__predict_true(!extra_work))
1232 #ifdef KDTRACE_HOOKS
1233 all_time += lockstat_nsecs(&sx->lock_object);
1235 LOCKSTAT_RECORD4(sx__block, sx, sleep_time,
1236 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1237 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1238 if (lda.spin_cnt > sleep_cnt)
1239 LOCKSTAT_RECORD4(sx__spin, sx, all_time - sleep_time,
1240 LOCKSTAT_READER, (state & SX_LOCK_SHARED) == 0,
1241 (state & SX_LOCK_SHARED) == 0 ? 0 : SX_SHARERS(state));
1245 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(sx__acquire, sx,
1246 contested, waittime, file, line, LOCKSTAT_READER);
1253 _sx_slock_int(struct sx *sx, int opts LOCK_FILE_LINE_ARG_DEF)
1259 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
1260 !TD_IS_IDLETHREAD(curthread),
1261 ("sx_slock() by idle thread %p on sx %s @ %s:%d",
1262 curthread, sx->lock_object.lo_name, file, line));
1263 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1264 ("sx_slock() of destroyed sx @ %s:%d", file, line));
1265 WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
1269 x = SX_READ_VALUE(sx);
1270 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__acquire) ||
1271 !__sx_slock_try(sx, td, &x, true LOCK_FILE_LINE_ARG)))
1272 error = _sx_slock_hard(sx, opts, x LOCK_FILE_LINE_ARG);
1274 lock_profile_obtain_lock_success(&sx->lock_object, 0, 0,
1277 LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
1278 WITNESS_LOCK(&sx->lock_object, 0, file, line);
1279 TD_LOCKS_INC(curthread);
1285 _sx_slock(struct sx *sx, int opts, const char *file, int line)
1288 return (_sx_slock_int(sx, opts LOCK_FILE_LINE_ARG));
1291 static bool __always_inline
1292 _sx_sunlock_try(struct sx *sx, struct thread *td, uintptr_t *xp)
1296 if (SX_SHARERS(*xp) > 1 || !(*xp & SX_LOCK_WAITERS)) {
1297 if (atomic_fcmpset_rel_ptr(&sx->sx_lock, xp,
1298 *xp - SX_ONE_SHARER)) {
1299 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1301 "%s: %p succeeded %p -> %p",
1302 __func__, sx, (void *)*xp,
1303 (void *)(*xp - SX_ONE_SHARER));
1314 static void __noinline
1315 _sx_sunlock_hard(struct sx *sx, struct thread *td, uintptr_t x
1316 LOCK_FILE_LINE_ARG_DEF)
1318 int wakeup_swapper = 0;
1319 uintptr_t setx, queue;
1321 if (SCHEDULER_STOPPED())
1324 if (_sx_sunlock_try(sx, td, &x))
1327 sleepq_lock(&sx->lock_object);
1328 x = SX_READ_VALUE(sx);
1330 if (_sx_sunlock_try(sx, td, &x))
1334 * Wake up semantic here is quite simple:
1335 * Just wake up all the exclusive waiters.
1336 * Note that the state of the lock could have changed,
1337 * so if it fails loop back and retry.
1339 setx = SX_LOCK_UNLOCKED;
1340 queue = SQ_SHARED_QUEUE;
1341 if (x & SX_LOCK_EXCLUSIVE_WAITERS) {
1342 setx |= (x & SX_LOCK_SHARED_WAITERS);
1343 queue = SQ_EXCLUSIVE_QUEUE;
1345 setx |= (x & SX_LOCK_WRITE_SPINNER);
1346 if (!atomic_fcmpset_rel_ptr(&sx->sx_lock, &x, setx))
1348 if (LOCK_LOG_TEST(&sx->lock_object, 0))
1349 CTR2(KTR_LOCK, "%s: %p waking up all thread on"
1350 "exclusive queue", __func__, sx);
1351 wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
1356 sleepq_release(&sx->lock_object);
1360 LOCKSTAT_PROFILE_RELEASE_RWLOCK(sx__release, sx, LOCKSTAT_READER);
1364 _sx_sunlock_int(struct sx *sx LOCK_FILE_LINE_ARG_DEF)
1369 KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
1370 ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
1371 _sx_assert(sx, SA_SLOCKED, file, line);
1372 WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
1373 LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
1376 x = SX_READ_VALUE(sx);
1377 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(sx__release) ||
1378 !_sx_sunlock_try(sx, td, &x)))
1379 _sx_sunlock_hard(sx, td, x LOCK_FILE_LINE_ARG);
1381 lock_profile_release_lock(&sx->lock_object);
1383 TD_LOCKS_DEC(curthread);
1387 _sx_sunlock(struct sx *sx, const char *file, int line)
1390 _sx_sunlock_int(sx LOCK_FILE_LINE_ARG);
1393 #ifdef INVARIANT_SUPPORT
1399 * In the non-WITNESS case, sx_assert() can only detect that at least
1400 * *some* thread owns an slock, but it cannot guarantee that *this*
1401 * thread owns an slock.
1404 _sx_assert(const struct sx *sx, int what, const char *file, int line)
1410 if (SCHEDULER_STOPPED())
1414 case SA_SLOCKED | SA_NOTRECURSED:
1415 case SA_SLOCKED | SA_RECURSED:
1421 case SA_LOCKED | SA_NOTRECURSED:
1422 case SA_LOCKED | SA_RECURSED:
1424 witness_assert(&sx->lock_object, what, file, line);
1427 * If some other thread has an exclusive lock or we
1428 * have one and are asserting a shared lock, fail.
1429 * Also, if no one has a lock at all, fail.
1431 if (sx->sx_lock == SX_LOCK_UNLOCKED ||
1432 (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
1433 sx_xholder(sx) != curthread)))
1434 panic("Lock %s not %slocked @ %s:%d\n",
1435 sx->lock_object.lo_name, slocked ? "share " : "",
1438 if (!(sx->sx_lock & SX_LOCK_SHARED)) {
1439 if (sx_recursed(sx)) {
1440 if (what & SA_NOTRECURSED)
1441 panic("Lock %s recursed @ %s:%d\n",
1442 sx->lock_object.lo_name, file,
1444 } else if (what & SA_RECURSED)
1445 panic("Lock %s not recursed @ %s:%d\n",
1446 sx->lock_object.lo_name, file, line);
1451 case SA_XLOCKED | SA_NOTRECURSED:
1452 case SA_XLOCKED | SA_RECURSED:
1453 if (sx_xholder(sx) != curthread)
1454 panic("Lock %s not exclusively locked @ %s:%d\n",
1455 sx->lock_object.lo_name, file, line);
1456 if (sx_recursed(sx)) {
1457 if (what & SA_NOTRECURSED)
1458 panic("Lock %s recursed @ %s:%d\n",
1459 sx->lock_object.lo_name, file, line);
1460 } else if (what & SA_RECURSED)
1461 panic("Lock %s not recursed @ %s:%d\n",
1462 sx->lock_object.lo_name, file, line);
1466 witness_assert(&sx->lock_object, what, file, line);
1469 * If we hold an exclusve lock fail. We can't
1470 * reliably check to see if we hold a shared lock or
1473 if (sx_xholder(sx) == curthread)
1474 panic("Lock %s exclusively locked @ %s:%d\n",
1475 sx->lock_object.lo_name, file, line);
1479 panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
1483 #endif /* INVARIANT_SUPPORT */
1487 db_show_sx(const struct lock_object *lock)
1490 const struct sx *sx;
1492 sx = (const struct sx *)lock;
1494 db_printf(" state: ");
1495 if (sx->sx_lock == SX_LOCK_UNLOCKED)
1496 db_printf("UNLOCKED\n");
1497 else if (sx->sx_lock == SX_LOCK_DESTROYED) {
1498 db_printf("DESTROYED\n");
1500 } else if (sx->sx_lock & SX_LOCK_SHARED)
1501 db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
1503 td = sx_xholder(sx);
1504 db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1505 td->td_tid, td->td_proc->p_pid, td->td_name);
1506 if (sx_recursed(sx))
1507 db_printf(" recursed: %d\n", sx->sx_recurse);
1510 db_printf(" waiters: ");
1511 switch(sx->sx_lock &
1512 (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1513 case SX_LOCK_SHARED_WAITERS:
1514 db_printf("shared\n");
1516 case SX_LOCK_EXCLUSIVE_WAITERS:
1517 db_printf("exclusive\n");
1519 case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1520 db_printf("exclusive and shared\n");
1523 db_printf("none\n");
1528 * Check to see if a thread that is blocked on a sleep queue is actually
1529 * blocked on an sx lock. If so, output some details and return true.
1530 * If the lock has an exclusive owner, return that in *ownerp.
1533 sx_chain(struct thread *td, struct thread **ownerp)
1535 const struct sx *sx;
1538 * Check to see if this thread is blocked on an sx lock.
1539 * First, we check the lock class. If that is ok, then we
1540 * compare the lock name against the wait message.
1543 if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1544 sx->lock_object.lo_name != td->td_wmesg)
1547 /* We think we have an sx lock, so output some details. */
1548 db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1549 *ownerp = sx_xholder(sx);
1550 if (sx->sx_lock & SX_LOCK_SHARED)
1551 db_printf("SLOCK (count %ju)\n",
1552 (uintmax_t)SX_SHARERS(sx->sx_lock));
1554 db_printf("XLOCK\n");