2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2006 John Baldwin <jhb@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, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * Machine independent bits of reader/writer lock implementation.
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
36 #include "opt_hwpmc_hooks.h"
37 #include "opt_no_adaptive_rwlocks.h"
39 #include <sys/param.h>
42 #include <sys/kernel.h>
44 #include <sys/mutex.h>
46 #include <sys/rwlock.h>
47 #include <sys/sched.h>
49 #include <sys/sysctl.h>
50 #include <sys/systm.h>
51 #include <sys/turnstile.h>
53 #include <machine/cpu.h>
55 #if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
56 #define ADAPTIVE_RWLOCKS
60 #include <sys/pmckern.h>
61 PMC_SOFT_DECLARE( , , lock, failed);
65 * Return the rwlock address when the lock cookie address is provided.
66 * This functionality assumes that struct rwlock* have a member named rw_lock.
68 #define rwlock2rw(c) (__containerof(c, struct rwlock, rw_lock))
73 static void db_show_rwlock(const struct lock_object *lock);
75 static void assert_rw(const struct lock_object *lock, int what);
76 static void lock_rw(struct lock_object *lock, uintptr_t how);
78 static int owner_rw(const struct lock_object *lock, struct thread **owner);
80 static uintptr_t unlock_rw(struct lock_object *lock);
82 struct lock_class lock_class_rw = {
84 .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
85 .lc_assert = assert_rw,
87 .lc_ddb_show = db_show_rwlock,
90 .lc_unlock = unlock_rw,
96 #ifdef ADAPTIVE_RWLOCKS
97 #ifdef RWLOCK_CUSTOM_BACKOFF
98 static u_short __read_frequently rowner_retries;
99 static u_short __read_frequently rowner_loops;
100 static SYSCTL_NODE(_debug, OID_AUTO, rwlock,
101 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
103 SYSCTL_U16(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
104 SYSCTL_U16(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
106 static struct lock_delay_config __read_frequently rw_delay;
108 SYSCTL_U16(_debug_rwlock, OID_AUTO, delay_base, CTLFLAG_RW, &rw_delay.base,
110 SYSCTL_U16(_debug_rwlock, OID_AUTO, delay_max, CTLFLAG_RW, &rw_delay.max,
114 rw_lock_delay_init(void *arg __unused)
117 lock_delay_default_init(&rw_delay);
119 rowner_loops = max(10000, rw_delay.max);
121 LOCK_DELAY_SYSINIT(rw_lock_delay_init);
123 #define rw_delay locks_delay
124 #define rowner_retries locks_delay_retries
125 #define rowner_loops locks_delay_loops
130 * Return a pointer to the owning thread if the lock is write-locked or
131 * NULL if the lock is unlocked or read-locked.
134 #define lv_rw_wowner(v) \
135 ((v) & RW_LOCK_READ ? NULL : \
136 (struct thread *)RW_OWNER((v)))
138 #define rw_wowner(rw) lv_rw_wowner(RW_READ_VALUE(rw))
141 * Returns if a write owner is recursed. Write ownership is not assured
142 * here and should be previously checked.
144 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
147 * Return true if curthread helds the lock.
149 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
152 * Return a pointer to the owning thread for this lock who should receive
153 * any priority lent by threads that block on this lock. Currently this
154 * is identical to rw_wowner().
156 #define rw_owner(rw) rw_wowner(rw)
159 #define __rw_assert(c, what, file, line)
163 assert_rw(const struct lock_object *lock, int what)
166 rw_assert((const struct rwlock *)lock, what);
170 lock_rw(struct lock_object *lock, uintptr_t how)
174 rw = (struct rwlock *)lock;
182 unlock_rw(struct lock_object *lock)
186 rw = (struct rwlock *)lock;
187 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
188 if (rw->rw_lock & RW_LOCK_READ) {
199 owner_rw(const struct lock_object *lock, struct thread **owner)
201 const struct rwlock *rw = (const struct rwlock *)lock;
202 uintptr_t x = rw->rw_lock;
204 *owner = rw_wowner(rw);
205 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
211 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
218 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
219 RW_RECURSE | RW_NEW)) == 0);
220 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
221 ("%s: rw_lock not aligned for %s: %p", __func__, name,
224 flags = LO_UPGRADABLE;
227 if (opts & RW_NOPROFILE)
228 flags |= LO_NOPROFILE;
229 if (!(opts & RW_NOWITNESS))
231 if (opts & RW_RECURSE)
232 flags |= LO_RECURSABLE;
238 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
239 rw->rw_lock = RW_UNLOCKED;
244 _rw_destroy(volatile uintptr_t *c)
250 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
251 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
252 rw->rw_lock = RW_DESTROYED;
253 lock_destroy(&rw->lock_object);
257 rw_sysinit(void *arg)
259 struct rw_args *args;
262 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
267 _rw_wowned(const volatile uintptr_t *c)
270 return (rw_wowner(rwlock2rw(c)) == curthread);
274 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
281 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
282 !TD_IS_IDLETHREAD(curthread),
283 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
284 curthread, rw->lock_object.lo_name, file, line));
285 KASSERT(rw->rw_lock != RW_DESTROYED,
286 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
287 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
289 tid = (uintptr_t)curthread;
291 if (!_rw_write_lock_fetch(rw, &v, tid))
292 _rw_wlock_hard(rw, v, file, line);
294 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
295 0, 0, file, line, LOCKSTAT_WRITER);
297 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
298 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
299 TD_LOCKS_INC(curthread);
303 __rw_try_wlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
312 if (SCHEDULER_STOPPED_TD(td))
315 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
316 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
317 curthread, rw->lock_object.lo_name, file, line));
318 KASSERT(rw->rw_lock != RW_DESTROYED,
319 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
325 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
327 if (v == RW_UNLOCKED)
329 if (v == tid && (rw->lock_object.lo_flags & LO_RECURSABLE)) {
331 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
338 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
340 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
343 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
344 rw, 0, 0, file, line, LOCKSTAT_WRITER);
345 TD_LOCKS_INC(curthread);
351 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
356 return (__rw_try_wlock_int(rw LOCK_FILE_LINE_ARG));
360 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
366 KASSERT(rw->rw_lock != RW_DESTROYED,
367 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
368 __rw_assert(c, RA_WLOCKED, file, line);
369 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
370 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
373 #ifdef LOCK_PROFILING
374 _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
376 __rw_wunlock(rw, curthread, file, line);
379 TD_LOCKS_DEC(curthread);
383 * Determines whether a new reader can acquire a lock. Succeeds if the
384 * reader already owns a read lock and the lock is locked for read to
385 * prevent deadlock from reader recursion. Also succeeds if the lock
386 * is unlocked and has no writer waiters or spinners. Failing otherwise
387 * prioritizes writers before readers.
389 static bool __always_inline
390 __rw_can_read(struct thread *td, uintptr_t v, bool fp)
393 if ((v & (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER))
396 if (!fp && td->td_rw_rlocks && (v & RW_LOCK_READ))
401 static bool __always_inline
402 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp, bool fp
403 LOCK_FILE_LINE_ARG_DEF)
407 * Handle the easy case. If no other thread has a write
408 * lock, then try to bump up the count of read locks. Note
409 * that we have to preserve the current state of the
410 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
411 * read lock, then rw_lock must have changed, so restart
412 * the loop. Note that this handles the case of a
413 * completely unlocked rwlock since such a lock is encoded
414 * as a read lock with no waiters.
416 while (__rw_can_read(td, *vp, fp)) {
417 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
418 *vp + RW_ONE_READER)) {
419 if (LOCK_LOG_TEST(&rw->lock_object, 0))
421 "%s: %p succeed %p -> %p", __func__,
423 (void *)(*vp + RW_ONE_READER));
431 static void __noinline
432 __rw_rlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
433 LOCK_FILE_LINE_ARG_DEF)
435 struct turnstile *ts;
436 struct thread *owner;
437 #ifdef ADAPTIVE_RWLOCKS
441 #ifdef LOCK_PROFILING
442 uint64_t waittime = 0;
445 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
446 struct lock_delay_arg lda;
450 int64_t sleep_time = 0;
451 int64_t all_time = 0;
453 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
455 int doing_lockprof = 0;
459 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
460 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
463 all_time -= lockstat_nsecs(&rw->lock_object);
467 #ifdef LOCK_PROFILING
472 if (SCHEDULER_STOPPED())
475 #if defined(ADAPTIVE_RWLOCKS)
476 lock_delay_arg_init(&lda, &rw_delay);
477 #elif defined(KDTRACE_HOOKS)
478 lock_delay_arg_init_noadapt(&lda);
482 PMC_SOFT_CALL( , , lock, failed);
484 lock_profile_obtain_lock_failed(&rw->lock_object,
485 &contested, &waittime);
488 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
494 #ifdef ADAPTIVE_RWLOCKS
496 * If the owner is running on another CPU, spin until
497 * the owner stops running or the state of the lock
500 if ((v & RW_LOCK_READ) == 0) {
501 owner = (struct thread *)RW_OWNER(v);
502 if (TD_IS_RUNNING(owner)) {
503 if (LOCK_LOG_TEST(&rw->lock_object, 0))
505 "%s: spinning on %p held by %p",
506 __func__, rw, owner);
507 KTR_STATE1(KTR_SCHED, "thread",
508 sched_tdname(curthread), "spinning",
509 "lockname:\"%s\"", rw->lock_object.lo_name);
512 v = RW_READ_VALUE(rw);
513 owner = lv_rw_wowner(v);
514 } while (owner != NULL && TD_IS_RUNNING(owner));
515 KTR_STATE0(KTR_SCHED, "thread",
516 sched_tdname(curthread), "running");
520 if ((v & RW_LOCK_WRITE_SPINNER) && RW_READERS(v) == 0) {
521 MPASS(!__rw_can_read(td, v, false));
523 v = RW_READ_VALUE(rw);
526 if (spintries < rowner_retries) {
528 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
529 "spinning", "lockname:\"%s\"",
530 rw->lock_object.lo_name);
532 for (i = 0; i < rowner_loops; i += n) {
534 v = RW_READ_VALUE(rw);
535 if (!(v & RW_LOCK_READ))
540 if (__rw_can_read(td, v, false))
544 lda.spin_cnt += rowner_loops - i;
546 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
548 if (i < rowner_loops)
555 * Okay, now it's the hard case. Some other thread already
556 * has a write lock or there are write waiters present,
557 * acquire the turnstile lock so we can begin the process
560 ts = turnstile_trywait(&rw->lock_object);
563 * The lock might have been released while we spun, so
564 * recheck its state and restart the loop if needed.
566 v = RW_READ_VALUE(rw);
568 if (((v & RW_LOCK_WRITE_SPINNER) && RW_READERS(v) == 0) ||
569 __rw_can_read(td, v, false)) {
570 turnstile_cancel(ts);
574 owner = lv_rw_wowner(v);
576 #ifdef ADAPTIVE_RWLOCKS
578 * The current lock owner might have started executing
579 * on another CPU (or the lock could have changed
580 * owners) while we were waiting on the turnstile
581 * chain lock. If so, drop the turnstile lock and try
585 if (TD_IS_RUNNING(owner)) {
586 turnstile_cancel(ts);
593 * The lock is held in write mode or it already has waiters.
595 MPASS(!__rw_can_read(td, v, false));
598 * If the RW_LOCK_READ_WAITERS flag is already set, then
599 * we can go ahead and block. If it is not set then try
600 * to set it. If we fail to set it drop the turnstile
601 * lock and restart the loop.
603 if (!(v & RW_LOCK_READ_WAITERS)) {
604 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
605 v | RW_LOCK_READ_WAITERS))
607 if (LOCK_LOG_TEST(&rw->lock_object, 0))
608 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
613 * We were unable to acquire the lock and the read waiters
614 * flag is set, so we must block on the turnstile.
616 if (LOCK_LOG_TEST(&rw->lock_object, 0))
617 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
620 sleep_time -= lockstat_nsecs(&rw->lock_object);
622 MPASS(owner == rw_owner(rw));
623 turnstile_wait(ts, owner, TS_SHARED_QUEUE);
625 sleep_time += lockstat_nsecs(&rw->lock_object);
628 if (LOCK_LOG_TEST(&rw->lock_object, 0))
629 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
631 v = RW_READ_VALUE(rw);
633 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
634 if (__predict_true(!doing_lockprof))
638 all_time += lockstat_nsecs(&rw->lock_object);
640 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
641 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
642 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
644 /* Record only the loops spinning and not sleeping. */
645 if (lda.spin_cnt > sleep_cnt)
646 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
647 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
648 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
652 * TODO: acquire "owner of record" here. Here be turnstile dragons
653 * however. turnstiles don't like owners changing between calls to
654 * turnstile_wait() currently.
656 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
657 waittime, file, line, LOCKSTAT_READER);
661 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
668 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
669 !TD_IS_IDLETHREAD(td),
670 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
671 td, rw->lock_object.lo_name, file, line));
672 KASSERT(rw->rw_lock != RW_DESTROYED,
673 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
674 KASSERT(rw_wowner(rw) != td,
675 ("rw_rlock: wlock already held for %s @ %s:%d",
676 rw->lock_object.lo_name, file, line));
677 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
679 v = RW_READ_VALUE(rw);
680 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__acquire) ||
681 !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
682 __rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
684 lock_profile_obtain_lock_success(&rw->lock_object, 0, 0,
687 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
688 WITNESS_LOCK(&rw->lock_object, 0, file, line);
689 TD_LOCKS_INC(curthread);
693 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
698 __rw_rlock_int(rw LOCK_FILE_LINE_ARG);
702 __rw_try_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
706 if (SCHEDULER_STOPPED())
709 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
710 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
711 curthread, rw->lock_object.lo_name, file, line));
715 KASSERT(rw->rw_lock != RW_DESTROYED,
716 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
717 if (!(x & RW_LOCK_READ))
719 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
720 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
722 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
723 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
724 rw, 0, 0, file, line, LOCKSTAT_READER);
725 TD_LOCKS_INC(curthread);
726 curthread->td_rw_rlocks++;
731 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
736 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
741 return (__rw_try_rlock_int(rw LOCK_FILE_LINE_ARG));
744 static bool __always_inline
745 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
749 if (RW_READERS(*vp) > 1 || !(*vp & RW_LOCK_WAITERS)) {
750 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
751 *vp - RW_ONE_READER)) {
752 if (LOCK_LOG_TEST(&rw->lock_object, 0))
754 "%s: %p succeeded %p -> %p",
755 __func__, rw, (void *)*vp,
756 (void *)(*vp - RW_ONE_READER));
767 static void __noinline
768 __rw_runlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
769 LOCK_FILE_LINE_ARG_DEF)
771 struct turnstile *ts;
772 uintptr_t setv, queue;
774 if (SCHEDULER_STOPPED())
777 if (__rw_runlock_try(rw, td, &v))
781 * Ok, we know we have waiters and we think we are the
782 * last reader, so grab the turnstile lock.
784 turnstile_chain_lock(&rw->lock_object);
785 v = RW_READ_VALUE(rw);
787 if (__rw_runlock_try(rw, td, &v))
790 MPASS(v & RW_LOCK_WAITERS);
793 * Try to drop our lock leaving the lock in a unlocked
796 * If you wanted to do explicit lock handoff you'd have to
797 * do it here. You'd also want to use turnstile_signal()
798 * and you'd have to handle the race where a higher
799 * priority thread blocks on the write lock before the
800 * thread you wakeup actually runs and have the new thread
801 * "steal" the lock. For now it's a lot simpler to just
802 * wakeup all of the waiters.
804 * As above, if we fail, then another thread might have
805 * acquired a read lock, so drop the turnstile lock and
809 queue = TS_SHARED_QUEUE;
810 if (v & RW_LOCK_WRITE_WAITERS) {
811 queue = TS_EXCLUSIVE_QUEUE;
812 setv |= (v & RW_LOCK_READ_WAITERS);
814 setv |= (v & RW_LOCK_WRITE_SPINNER);
815 if (!atomic_fcmpset_rel_ptr(&rw->rw_lock, &v, setv))
817 if (LOCK_LOG_TEST(&rw->lock_object, 0))
818 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
822 * Ok. The lock is released and all that's left is to
823 * wake up the waiters. Note that the lock might not be
824 * free anymore, but in that case the writers will just
825 * block again if they run before the new lock holder(s)
828 ts = turnstile_lookup(&rw->lock_object);
830 turnstile_broadcast(ts, queue);
831 turnstile_unpend(ts);
835 turnstile_chain_unlock(&rw->lock_object);
837 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
841 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
846 KASSERT(rw->rw_lock != RW_DESTROYED,
847 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
848 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
849 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
850 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
853 v = RW_READ_VALUE(rw);
855 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__release) ||
856 !__rw_runlock_try(rw, td, &v)))
857 __rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
859 lock_profile_release_lock(&rw->lock_object);
861 TD_LOCKS_DEC(curthread);
865 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
870 _rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
873 #ifdef ADAPTIVE_RWLOCKS
875 rw_drop_critical(uintptr_t v, bool *in_critical, int *extra_work)
878 if (v & RW_LOCK_WRITE_SPINNER)
882 *in_critical = false;
887 #define rw_drop_critical(v, in_critical, extra_work) do { } while (0)
891 * This function is called when we are unable to obtain a write lock on the
892 * first try. This means that at least one other thread holds either a
893 * read or write lock.
896 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
900 struct turnstile *ts;
901 struct thread *owner;
902 #ifdef ADAPTIVE_RWLOCKS
905 enum { READERS, WRITER } sleep_reason = READERS;
906 bool in_critical = false;
909 #ifdef LOCK_PROFILING
910 uint64_t waittime = 0;
913 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
914 struct lock_delay_arg lda;
918 int64_t sleep_time = 0;
919 int64_t all_time = 0;
921 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
923 int doing_lockprof = 0;
927 tid = (uintptr_t)curthread;
931 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
932 while (v == RW_UNLOCKED) {
933 if (_rw_write_lock_fetch(rw, &v, tid))
938 all_time -= lockstat_nsecs(&rw->lock_object);
942 #ifdef LOCK_PROFILING
948 if (SCHEDULER_STOPPED())
951 if (__predict_false(v == RW_UNLOCKED))
952 v = RW_READ_VALUE(rw);
954 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
955 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
956 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
957 __func__, rw->lock_object.lo_name, file, line));
959 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
960 if (LOCK_LOG_TEST(&rw->lock_object, 0))
961 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
965 if (LOCK_LOG_TEST(&rw->lock_object, 0))
966 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
967 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
969 #if defined(ADAPTIVE_RWLOCKS)
970 lock_delay_arg_init(&lda, &rw_delay);
971 #elif defined(KDTRACE_HOOKS)
972 lock_delay_arg_init_noadapt(&lda);
976 PMC_SOFT_CALL( , , lock, failed);
978 lock_profile_obtain_lock_failed(&rw->lock_object,
979 &contested, &waittime);
982 if (v == RW_UNLOCKED) {
983 if (_rw_write_lock_fetch(rw, &v, tid))
991 #ifdef ADAPTIVE_RWLOCKS
992 if (v == (RW_LOCK_READ | RW_LOCK_WRITE_SPINNER)) {
993 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
999 * If the lock is write locked and the owner is
1000 * running on another CPU, spin until the owner stops
1001 * running or the state of the lock changes.
1003 if (!(v & RW_LOCK_READ)) {
1004 rw_drop_critical(v, &in_critical, &extra_work);
1005 sleep_reason = WRITER;
1006 owner = lv_rw_wowner(v);
1007 if (!TD_IS_RUNNING(owner))
1009 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1010 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
1011 __func__, rw, owner);
1012 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1013 "spinning", "lockname:\"%s\"",
1014 rw->lock_object.lo_name);
1017 v = RW_READ_VALUE(rw);
1018 owner = lv_rw_wowner(v);
1019 } while (owner != NULL && TD_IS_RUNNING(owner));
1020 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1023 } else if (RW_READERS(v) > 0) {
1024 sleep_reason = READERS;
1025 if (spintries == rowner_retries)
1027 if (!(v & RW_LOCK_WRITE_SPINNER)) {
1033 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1034 v | RW_LOCK_WRITE_SPINNER)) {
1036 in_critical = false;
1042 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1043 "spinning", "lockname:\"%s\"",
1044 rw->lock_object.lo_name);
1046 for (i = 0; i < rowner_loops; i += n) {
1048 v = RW_READ_VALUE(rw);
1049 if (!(v & RW_LOCK_WRITE_SPINNER))
1051 if (!(v & RW_LOCK_READ))
1057 #ifdef KDTRACE_HOOKS
1060 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1062 if (i < rowner_loops)
1067 ts = turnstile_trywait(&rw->lock_object);
1068 v = RW_READ_VALUE(rw);
1070 owner = lv_rw_wowner(v);
1072 #ifdef ADAPTIVE_RWLOCKS
1074 * The current lock owner might have started executing
1075 * on another CPU (or the lock could have changed
1076 * owners) while we were waiting on the turnstile
1077 * chain lock. If so, drop the turnstile lock and try
1080 if (owner != NULL) {
1081 if (TD_IS_RUNNING(owner)) {
1082 turnstile_cancel(ts);
1083 rw_drop_critical(v, &in_critical, &extra_work);
1086 } else if (RW_READERS(v) > 0 && sleep_reason == WRITER) {
1087 turnstile_cancel(ts);
1088 rw_drop_critical(v, &in_critical, &extra_work);
1093 * Check for the waiters flags about this rwlock.
1094 * If the lock was released, without maintain any pending
1095 * waiters queue, simply try to acquire it.
1096 * If a pending waiters queue is present, claim the lock
1097 * ownership and maintain the pending queue.
1099 setv = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1100 if ((v & ~setv) == RW_UNLOCKED) {
1101 setv &= ~RW_LOCK_WRITE_SPINNER;
1102 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid | setv)) {
1104 turnstile_claim(ts);
1106 turnstile_cancel(ts);
1112 #ifdef ADAPTIVE_RWLOCKS
1114 if ((v & RW_LOCK_WRITE_SPINNER) ||
1115 !((v & RW_LOCK_WRITE_WAITERS))) {
1116 setv = v & ~RW_LOCK_WRITE_SPINNER;
1117 setv |= RW_LOCK_WRITE_WAITERS;
1118 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v, setv))
1122 in_critical = false;
1127 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1128 * set it. If we fail to set it, then loop back and try
1131 if (!(v & RW_LOCK_WRITE_WAITERS)) {
1132 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1133 v | RW_LOCK_WRITE_WAITERS))
1135 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1136 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1139 #ifdef ADAPTIVE_RWLOCKS
1143 * We were unable to acquire the lock and the write waiters
1144 * flag is set, so we must block on the turnstile.
1146 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1147 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1149 #ifdef KDTRACE_HOOKS
1150 sleep_time -= lockstat_nsecs(&rw->lock_object);
1152 MPASS(owner == rw_owner(rw));
1153 turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
1154 #ifdef KDTRACE_HOOKS
1155 sleep_time += lockstat_nsecs(&rw->lock_object);
1158 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1159 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1161 #ifdef ADAPTIVE_RWLOCKS
1164 v = RW_READ_VALUE(rw);
1166 if (__predict_true(!extra_work))
1168 #ifdef ADAPTIVE_RWLOCKS
1172 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1173 if (__predict_true(!doing_lockprof))
1176 #ifdef KDTRACE_HOOKS
1177 all_time += lockstat_nsecs(&rw->lock_object);
1179 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1180 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1181 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1183 /* Record only the loops spinning and not sleeping. */
1184 if (lda.spin_cnt > sleep_cnt)
1185 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1186 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1187 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1190 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1191 waittime, file, line, LOCKSTAT_WRITER);
1195 * This function is called if lockstat is active or the first try at releasing
1196 * a write lock failed. The latter means that the lock is recursed or one of
1197 * the 2 waiter bits must be set indicating that at least one thread is waiting
1201 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1204 struct turnstile *ts;
1205 uintptr_t tid, setv;
1208 tid = (uintptr_t)curthread;
1209 if (SCHEDULER_STOPPED())
1213 if (__predict_false(v == tid))
1214 v = RW_READ_VALUE(rw);
1216 if (v & RW_LOCK_WRITER_RECURSED) {
1217 if (--(rw->rw_recurse) == 0)
1218 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1219 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1220 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1224 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1225 if (v == tid && _rw_write_unlock(rw, tid))
1228 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1229 ("%s: neither of the waiter flags are set", __func__));
1231 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1232 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1234 turnstile_chain_lock(&rw->lock_object);
1237 * Use the same algo as sx locks for now. Prefer waking up shared
1238 * waiters if we have any over writers. This is probably not ideal.
1240 * 'v' is the value we are going to write back to rw_lock. If we
1241 * have waiters on both queues, we need to preserve the state of
1242 * the waiter flag for the queue we don't wake up. For now this is
1243 * hardcoded for the algorithm mentioned above.
1245 * In the case of both readers and writers waiting we wakeup the
1246 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1247 * new writer comes in before a reader it will claim the lock up
1248 * above. There is probably a potential priority inversion in
1249 * there that could be worked around either by waking both queues
1250 * of waiters or doing some complicated lock handoff gymnastics.
1253 v = RW_READ_VALUE(rw);
1254 queue = TS_SHARED_QUEUE;
1255 if (v & RW_LOCK_WRITE_WAITERS) {
1256 queue = TS_EXCLUSIVE_QUEUE;
1257 setv |= (v & RW_LOCK_READ_WAITERS);
1259 atomic_store_rel_ptr(&rw->rw_lock, setv);
1261 /* Wake up all waiters for the specific queue. */
1262 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1263 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1264 queue == TS_SHARED_QUEUE ? "read" : "write");
1266 ts = turnstile_lookup(&rw->lock_object);
1268 turnstile_broadcast(ts, queue);
1269 turnstile_unpend(ts);
1270 turnstile_chain_unlock(&rw->lock_object);
1274 * Attempt to do a non-blocking upgrade from a read lock to a write
1275 * lock. This will only succeed if this thread holds a single read
1276 * lock. Returns true if the upgrade succeeded and false otherwise.
1279 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1281 uintptr_t v, setv, tid;
1282 struct turnstile *ts;
1285 if (SCHEDULER_STOPPED())
1288 KASSERT(rw->rw_lock != RW_DESTROYED,
1289 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1290 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1293 * Attempt to switch from one reader to a writer. If there
1294 * are any write waiters, then we will have to lock the
1295 * turnstile first to prevent races with another writer
1296 * calling turnstile_wait() before we have claimed this
1297 * turnstile. So, do the simple case of no waiters first.
1299 tid = (uintptr_t)curthread;
1301 v = RW_READ_VALUE(rw);
1303 if (RW_READERS(v) > 1)
1305 if (!(v & RW_LOCK_WAITERS)) {
1306 success = atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid);
1313 * Ok, we think we have waiters, so lock the turnstile.
1315 ts = turnstile_trywait(&rw->lock_object);
1316 v = RW_READ_VALUE(rw);
1318 if (RW_READERS(v) > 1) {
1319 turnstile_cancel(ts);
1323 * Try to switch from one reader to a writer again. This time
1324 * we honor the current state of the waiters flags.
1325 * If we obtain the lock with the flags set, then claim
1326 * ownership of the turnstile.
1328 setv = tid | (v & RW_LOCK_WAITERS);
1329 success = atomic_fcmpset_ptr(&rw->rw_lock, &v, setv);
1331 if (v & RW_LOCK_WAITERS)
1332 turnstile_claim(ts);
1334 turnstile_cancel(ts);
1339 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1341 curthread->td_rw_rlocks--;
1342 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1344 LOCKSTAT_RECORD0(rw__upgrade, rw);
1350 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1355 return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1359 * Downgrade a write lock into a single read lock.
1362 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1364 struct turnstile *ts;
1368 if (SCHEDULER_STOPPED())
1371 KASSERT(rw->rw_lock != RW_DESTROYED,
1372 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1373 __rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1375 if (rw_recursed(rw))
1376 panic("downgrade of a recursed lock");
1379 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1382 * Convert from a writer to a single reader. First we handle
1383 * the easy case with no waiters. If there are any waiters, we
1384 * lock the turnstile and "disown" the lock.
1386 tid = (uintptr_t)curthread;
1387 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1391 * Ok, we think we have waiters, so lock the turnstile so we can
1392 * read the waiter flags without any races.
1394 turnstile_chain_lock(&rw->lock_object);
1395 v = rw->rw_lock & RW_LOCK_WAITERS;
1396 rwait = v & RW_LOCK_READ_WAITERS;
1397 wwait = v & RW_LOCK_WRITE_WAITERS;
1398 MPASS(rwait | wwait);
1401 * Downgrade from a write lock while preserving waiters flag
1402 * and give up ownership of the turnstile.
1404 ts = turnstile_lookup(&rw->lock_object);
1407 v &= ~RW_LOCK_READ_WAITERS;
1408 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1410 * Wake other readers if there are no writers pending. Otherwise they
1411 * won't be able to acquire the lock anyway.
1413 if (rwait && !wwait) {
1414 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1415 turnstile_unpend(ts);
1417 turnstile_disown(ts);
1418 turnstile_chain_unlock(&rw->lock_object);
1420 curthread->td_rw_rlocks++;
1421 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1422 LOCKSTAT_RECORD0(rw__downgrade, rw);
1426 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1431 __rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1434 #ifdef INVARIANT_SUPPORT
1440 * In the non-WITNESS case, rw_assert() can only detect that at least
1441 * *some* thread owns an rlock, but it cannot guarantee that *this*
1442 * thread owns an rlock.
1445 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1447 const struct rwlock *rw;
1449 if (SCHEDULER_STOPPED())
1456 case RA_LOCKED | RA_RECURSED:
1457 case RA_LOCKED | RA_NOTRECURSED:
1459 case RA_RLOCKED | RA_RECURSED:
1460 case RA_RLOCKED | RA_NOTRECURSED:
1462 witness_assert(&rw->lock_object, what, file, line);
1465 * If some other thread has a write lock or we have one
1466 * and are asserting a read lock, fail. Also, if no one
1467 * has a lock at all, fail.
1469 if (rw->rw_lock == RW_UNLOCKED ||
1470 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1471 rw_wowner(rw) != curthread)))
1472 panic("Lock %s not %slocked @ %s:%d\n",
1473 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1474 "read " : "", file, line);
1476 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1477 if (rw_recursed(rw)) {
1478 if (what & RA_NOTRECURSED)
1479 panic("Lock %s recursed @ %s:%d\n",
1480 rw->lock_object.lo_name, file,
1482 } else if (what & RA_RECURSED)
1483 panic("Lock %s not recursed @ %s:%d\n",
1484 rw->lock_object.lo_name, file, line);
1489 case RA_WLOCKED | RA_RECURSED:
1490 case RA_WLOCKED | RA_NOTRECURSED:
1491 if (rw_wowner(rw) != curthread)
1492 panic("Lock %s not exclusively locked @ %s:%d\n",
1493 rw->lock_object.lo_name, file, line);
1494 if (rw_recursed(rw)) {
1495 if (what & RA_NOTRECURSED)
1496 panic("Lock %s recursed @ %s:%d\n",
1497 rw->lock_object.lo_name, file, line);
1498 } else if (what & RA_RECURSED)
1499 panic("Lock %s not recursed @ %s:%d\n",
1500 rw->lock_object.lo_name, file, line);
1504 witness_assert(&rw->lock_object, what, file, line);
1507 * If we hold a write lock fail. We can't reliably check
1508 * to see if we hold a read lock or not.
1510 if (rw_wowner(rw) == curthread)
1511 panic("Lock %s exclusively locked @ %s:%d\n",
1512 rw->lock_object.lo_name, file, line);
1516 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1520 #endif /* INVARIANT_SUPPORT */
1524 db_show_rwlock(const struct lock_object *lock)
1526 const struct rwlock *rw;
1529 rw = (const struct rwlock *)lock;
1531 db_printf(" state: ");
1532 if (rw->rw_lock == RW_UNLOCKED)
1533 db_printf("UNLOCKED\n");
1534 else if (rw->rw_lock == RW_DESTROYED) {
1535 db_printf("DESTROYED\n");
1537 } else if (rw->rw_lock & RW_LOCK_READ)
1538 db_printf("RLOCK: %ju locks\n",
1539 (uintmax_t)(RW_READERS(rw->rw_lock)));
1542 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1543 td->td_tid, td->td_proc->p_pid, td->td_name);
1544 if (rw_recursed(rw))
1545 db_printf(" recursed: %u\n", rw->rw_recurse);
1547 db_printf(" waiters: ");
1548 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1549 case RW_LOCK_READ_WAITERS:
1550 db_printf("readers\n");
1552 case RW_LOCK_WRITE_WAITERS:
1553 db_printf("writers\n");
1555 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1556 db_printf("readers and writers\n");
1559 db_printf("none\n");