2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * Machine independent bits of reader/writer lock implementation.
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
37 #include "opt_hwpmc_hooks.h"
38 #include "opt_no_adaptive_rwlocks.h"
40 #include <sys/param.h>
43 #include <sys/kernel.h>
45 #include <sys/mutex.h>
47 #include <sys/rwlock.h>
48 #include <sys/sched.h>
50 #include <sys/sysctl.h>
51 #include <sys/systm.h>
52 #include <sys/turnstile.h>
54 #include <machine/cpu.h>
56 #if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
57 #define ADAPTIVE_RWLOCKS
61 #include <sys/pmckern.h>
62 PMC_SOFT_DECLARE( , , lock, failed);
66 * Return the rwlock address when the lock cookie address is provided.
67 * This functionality assumes that struct rwlock* have a member named rw_lock.
69 #define rwlock2rw(c) (__containerof(c, struct rwlock, rw_lock))
74 static void db_show_rwlock(const struct lock_object *lock);
76 static void assert_rw(const struct lock_object *lock, int what);
77 static void lock_rw(struct lock_object *lock, uintptr_t how);
79 static int owner_rw(const struct lock_object *lock, struct thread **owner);
81 static uintptr_t unlock_rw(struct lock_object *lock);
83 struct lock_class lock_class_rw = {
85 .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
86 .lc_assert = assert_rw,
88 .lc_ddb_show = db_show_rwlock,
91 .lc_unlock = unlock_rw,
97 #ifdef ADAPTIVE_RWLOCKS
98 static int __read_frequently rowner_retries;
99 static int __read_frequently rowner_loops;
100 static SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL,
102 SYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
103 SYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
105 static struct lock_delay_config __read_frequently rw_delay;
107 SYSCTL_INT(_debug_rwlock, OID_AUTO, delay_base, CTLFLAG_RW, &rw_delay.base,
109 SYSCTL_INT(_debug_rwlock, OID_AUTO, delay_max, CTLFLAG_RW, &rw_delay.max,
113 rw_lock_delay_init(void *arg __unused)
116 lock_delay_default_init(&rw_delay);
118 rowner_loops = max(10000, rw_delay.max);
120 LOCK_DELAY_SYSINIT(rw_lock_delay_init);
124 * Return a pointer to the owning thread if the lock is write-locked or
125 * NULL if the lock is unlocked or read-locked.
128 #define lv_rw_wowner(v) \
129 ((v) & RW_LOCK_READ ? NULL : \
130 (struct thread *)RW_OWNER((v)))
132 #define rw_wowner(rw) lv_rw_wowner(RW_READ_VALUE(rw))
135 * Returns if a write owner is recursed. Write ownership is not assured
136 * here and should be previously checked.
138 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
141 * Return true if curthread helds the lock.
143 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
146 * Return a pointer to the owning thread for this lock who should receive
147 * any priority lent by threads that block on this lock. Currently this
148 * is identical to rw_wowner().
150 #define rw_owner(rw) rw_wowner(rw)
153 #define __rw_assert(c, what, file, line)
157 assert_rw(const struct lock_object *lock, int what)
160 rw_assert((const struct rwlock *)lock, what);
164 lock_rw(struct lock_object *lock, uintptr_t how)
168 rw = (struct rwlock *)lock;
176 unlock_rw(struct lock_object *lock)
180 rw = (struct rwlock *)lock;
181 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
182 if (rw->rw_lock & RW_LOCK_READ) {
193 owner_rw(const struct lock_object *lock, struct thread **owner)
195 const struct rwlock *rw = (const struct rwlock *)lock;
196 uintptr_t x = rw->rw_lock;
198 *owner = rw_wowner(rw);
199 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
205 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
212 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
213 RW_RECURSE | RW_NEW)) == 0);
214 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
215 ("%s: rw_lock not aligned for %s: %p", __func__, name,
218 flags = LO_UPGRADABLE;
221 if (opts & RW_NOPROFILE)
222 flags |= LO_NOPROFILE;
223 if (!(opts & RW_NOWITNESS))
225 if (opts & RW_RECURSE)
226 flags |= LO_RECURSABLE;
232 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
233 rw->rw_lock = RW_UNLOCKED;
238 _rw_destroy(volatile uintptr_t *c)
244 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
245 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
246 rw->rw_lock = RW_DESTROYED;
247 lock_destroy(&rw->lock_object);
251 rw_sysinit(void *arg)
253 struct rw_args *args;
256 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
261 _rw_wowned(const volatile uintptr_t *c)
264 return (rw_wowner(rwlock2rw(c)) == curthread);
268 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
275 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
276 !TD_IS_IDLETHREAD(curthread),
277 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
278 curthread, rw->lock_object.lo_name, file, line));
279 KASSERT(rw->rw_lock != RW_DESTROYED,
280 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
281 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
283 tid = (uintptr_t)curthread;
285 if (!_rw_write_lock_fetch(rw, &v, tid))
286 _rw_wlock_hard(rw, v, file, line);
288 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
289 0, 0, file, line, LOCKSTAT_WRITER);
291 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
292 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
293 TD_LOCKS_INC(curthread);
297 __rw_try_wlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
306 if (SCHEDULER_STOPPED_TD(td))
309 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
310 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
311 curthread, rw->lock_object.lo_name, file, line));
312 KASSERT(rw->rw_lock != RW_DESTROYED,
313 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
319 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
321 if (v == RW_UNLOCKED)
323 if (v == tid && (rw->lock_object.lo_flags & LO_RECURSABLE)) {
325 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
332 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
334 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
337 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
338 rw, 0, 0, file, line, LOCKSTAT_WRITER);
339 TD_LOCKS_INC(curthread);
345 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
350 return (__rw_try_wlock_int(rw LOCK_FILE_LINE_ARG));
354 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
360 KASSERT(rw->rw_lock != RW_DESTROYED,
361 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
362 __rw_assert(c, RA_WLOCKED, file, line);
363 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
364 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
367 #ifdef LOCK_PROFILING
368 _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
370 __rw_wunlock(rw, curthread, file, line);
373 TD_LOCKS_DEC(curthread);
377 * Determines whether a new reader can acquire a lock. Succeeds if the
378 * reader already owns a read lock and the lock is locked for read to
379 * prevent deadlock from reader recursion. Also succeeds if the lock
380 * is unlocked and has no writer waiters or spinners. Failing otherwise
381 * prioritizes writers before readers.
383 static bool __always_inline
384 __rw_can_read(struct thread *td, uintptr_t v, bool fp)
387 if ((v & (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER))
390 if (!fp && td->td_rw_rlocks && (v & RW_LOCK_READ))
395 static bool __always_inline
396 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp, bool fp
397 LOCK_FILE_LINE_ARG_DEF)
401 * Handle the easy case. If no other thread has a write
402 * lock, then try to bump up the count of read locks. Note
403 * that we have to preserve the current state of the
404 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
405 * read lock, then rw_lock must have changed, so restart
406 * the loop. Note that this handles the case of a
407 * completely unlocked rwlock since such a lock is encoded
408 * as a read lock with no waiters.
410 while (__rw_can_read(td, *vp, fp)) {
411 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
412 *vp + RW_ONE_READER)) {
413 if (LOCK_LOG_TEST(&rw->lock_object, 0))
415 "%s: %p succeed %p -> %p", __func__,
417 (void *)(*vp + RW_ONE_READER));
425 static void __noinline
426 __rw_rlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
427 LOCK_FILE_LINE_ARG_DEF)
429 struct turnstile *ts;
430 struct thread *owner;
431 #ifdef ADAPTIVE_RWLOCKS
435 #ifdef LOCK_PROFILING
436 uint64_t waittime = 0;
439 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
440 struct lock_delay_arg lda;
444 int64_t sleep_time = 0;
445 int64_t all_time = 0;
447 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
449 int doing_lockprof = 0;
453 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
454 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
457 all_time -= lockstat_nsecs(&rw->lock_object);
461 #ifdef LOCK_PROFILING
466 if (SCHEDULER_STOPPED())
469 #if defined(ADAPTIVE_RWLOCKS)
470 lock_delay_arg_init(&lda, &rw_delay);
471 #elif defined(KDTRACE_HOOKS)
472 lock_delay_arg_init(&lda, NULL);
476 PMC_SOFT_CALL( , , lock, failed);
478 lock_profile_obtain_lock_failed(&rw->lock_object,
479 &contested, &waittime);
482 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
488 #ifdef ADAPTIVE_RWLOCKS
490 * If the owner is running on another CPU, spin until
491 * the owner stops running or the state of the lock
494 if ((v & RW_LOCK_READ) == 0) {
495 owner = (struct thread *)RW_OWNER(v);
496 if (TD_IS_RUNNING(owner)) {
497 if (LOCK_LOG_TEST(&rw->lock_object, 0))
499 "%s: spinning on %p held by %p",
500 __func__, rw, owner);
501 KTR_STATE1(KTR_SCHED, "thread",
502 sched_tdname(curthread), "spinning",
503 "lockname:\"%s\"", rw->lock_object.lo_name);
506 v = RW_READ_VALUE(rw);
507 owner = lv_rw_wowner(v);
508 } while (owner != NULL && TD_IS_RUNNING(owner));
509 KTR_STATE0(KTR_SCHED, "thread",
510 sched_tdname(curthread), "running");
514 if ((v & RW_LOCK_WRITE_SPINNER) && RW_READERS(v) == 0) {
515 MPASS(!__rw_can_read(td, v, false));
517 v = RW_READ_VALUE(rw);
520 if (spintries < rowner_retries) {
522 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
523 "spinning", "lockname:\"%s\"",
524 rw->lock_object.lo_name);
526 for (i = 0; i < rowner_loops; i += n) {
528 v = RW_READ_VALUE(rw);
529 if (!(v & RW_LOCK_READ))
534 if (__rw_can_read(td, v, false))
538 lda.spin_cnt += rowner_loops - i;
540 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
542 if (i < rowner_loops)
549 * Okay, now it's the hard case. Some other thread already
550 * has a write lock or there are write waiters present,
551 * acquire the turnstile lock so we can begin the process
554 ts = turnstile_trywait(&rw->lock_object);
557 * The lock might have been released while we spun, so
558 * recheck its state and restart the loop if needed.
560 v = RW_READ_VALUE(rw);
562 if (((v & RW_LOCK_WRITE_SPINNER) && RW_READERS(v) == 0) ||
563 __rw_can_read(td, v, false)) {
564 turnstile_cancel(ts);
568 owner = lv_rw_wowner(v);
570 #ifdef ADAPTIVE_RWLOCKS
572 * The current lock owner might have started executing
573 * on another CPU (or the lock could have changed
574 * owners) while we were waiting on the turnstile
575 * chain lock. If so, drop the turnstile lock and try
579 if (TD_IS_RUNNING(owner)) {
580 turnstile_cancel(ts);
587 * The lock is held in write mode or it already has waiters.
589 MPASS(!__rw_can_read(td, v, false));
592 * If the RW_LOCK_READ_WAITERS flag is already set, then
593 * we can go ahead and block. If it is not set then try
594 * to set it. If we fail to set it drop the turnstile
595 * lock and restart the loop.
597 if (!(v & RW_LOCK_READ_WAITERS)) {
598 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
599 v | RW_LOCK_READ_WAITERS))
601 if (LOCK_LOG_TEST(&rw->lock_object, 0))
602 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
607 * We were unable to acquire the lock and the read waiters
608 * flag is set, so we must block on the turnstile.
610 if (LOCK_LOG_TEST(&rw->lock_object, 0))
611 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
614 sleep_time -= lockstat_nsecs(&rw->lock_object);
616 MPASS(owner == rw_owner(rw));
617 turnstile_wait(ts, owner, TS_SHARED_QUEUE);
619 sleep_time += lockstat_nsecs(&rw->lock_object);
622 if (LOCK_LOG_TEST(&rw->lock_object, 0))
623 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
625 v = RW_READ_VALUE(rw);
627 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
628 if (__predict_true(!doing_lockprof))
632 all_time += lockstat_nsecs(&rw->lock_object);
634 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
635 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
636 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
638 /* Record only the loops spinning and not sleeping. */
639 if (lda.spin_cnt > sleep_cnt)
640 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
641 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
642 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
646 * TODO: acquire "owner of record" here. Here be turnstile dragons
647 * however. turnstiles don't like owners changing between calls to
648 * turnstile_wait() currently.
650 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
651 waittime, file, line, LOCKSTAT_READER);
655 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
662 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
663 !TD_IS_IDLETHREAD(td),
664 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
665 td, rw->lock_object.lo_name, file, line));
666 KASSERT(rw->rw_lock != RW_DESTROYED,
667 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
668 KASSERT(rw_wowner(rw) != td,
669 ("rw_rlock: wlock already held for %s @ %s:%d",
670 rw->lock_object.lo_name, file, line));
671 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
673 v = RW_READ_VALUE(rw);
674 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__acquire) ||
675 !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
676 __rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
678 lock_profile_obtain_lock_success(&rw->lock_object, 0, 0,
681 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
682 WITNESS_LOCK(&rw->lock_object, 0, file, line);
683 TD_LOCKS_INC(curthread);
687 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
692 __rw_rlock_int(rw LOCK_FILE_LINE_ARG);
696 __rw_try_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
700 if (SCHEDULER_STOPPED())
703 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
704 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
705 curthread, rw->lock_object.lo_name, file, line));
709 KASSERT(rw->rw_lock != RW_DESTROYED,
710 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
711 if (!(x & RW_LOCK_READ))
713 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
714 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
716 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
717 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
718 rw, 0, 0, file, line, LOCKSTAT_READER);
719 TD_LOCKS_INC(curthread);
720 curthread->td_rw_rlocks++;
725 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
730 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
735 return (__rw_try_rlock_int(rw LOCK_FILE_LINE_ARG));
738 static bool __always_inline
739 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
743 if (RW_READERS(*vp) > 1 || !(*vp & RW_LOCK_WAITERS)) {
744 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
745 *vp - RW_ONE_READER)) {
746 if (LOCK_LOG_TEST(&rw->lock_object, 0))
748 "%s: %p succeeded %p -> %p",
749 __func__, rw, (void *)*vp,
750 (void *)(*vp - RW_ONE_READER));
761 static void __noinline
762 __rw_runlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
763 LOCK_FILE_LINE_ARG_DEF)
765 struct turnstile *ts;
766 uintptr_t setv, queue;
768 if (SCHEDULER_STOPPED())
771 if (__rw_runlock_try(rw, td, &v))
775 * Ok, we know we have waiters and we think we are the
776 * last reader, so grab the turnstile lock.
778 turnstile_chain_lock(&rw->lock_object);
779 v = RW_READ_VALUE(rw);
781 if (__rw_runlock_try(rw, td, &v))
784 MPASS(v & RW_LOCK_WAITERS);
787 * Try to drop our lock leaving the lock in a unlocked
790 * If you wanted to do explicit lock handoff you'd have to
791 * do it here. You'd also want to use turnstile_signal()
792 * and you'd have to handle the race where a higher
793 * priority thread blocks on the write lock before the
794 * thread you wakeup actually runs and have the new thread
795 * "steal" the lock. For now it's a lot simpler to just
796 * wakeup all of the waiters.
798 * As above, if we fail, then another thread might have
799 * acquired a read lock, so drop the turnstile lock and
803 queue = TS_SHARED_QUEUE;
804 if (v & RW_LOCK_WRITE_WAITERS) {
805 queue = TS_EXCLUSIVE_QUEUE;
806 setv |= (v & RW_LOCK_READ_WAITERS);
808 setv |= (v & RW_LOCK_WRITE_SPINNER);
809 if (!atomic_fcmpset_rel_ptr(&rw->rw_lock, &v, setv))
811 if (LOCK_LOG_TEST(&rw->lock_object, 0))
812 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
816 * Ok. The lock is released and all that's left is to
817 * wake up the waiters. Note that the lock might not be
818 * free anymore, but in that case the writers will just
819 * block again if they run before the new lock holder(s)
822 ts = turnstile_lookup(&rw->lock_object);
824 turnstile_broadcast(ts, queue);
825 turnstile_unpend(ts);
829 turnstile_chain_unlock(&rw->lock_object);
831 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
835 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
840 KASSERT(rw->rw_lock != RW_DESTROYED,
841 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
842 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
843 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
844 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
847 v = RW_READ_VALUE(rw);
849 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__release) ||
850 !__rw_runlock_try(rw, td, &v)))
851 __rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
853 lock_profile_release_lock(&rw->lock_object);
855 TD_LOCKS_DEC(curthread);
859 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
864 _rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
867 #ifdef ADAPTIVE_RWLOCKS
869 rw_drop_critical(uintptr_t v, bool *in_critical, int *extra_work)
872 if (v & RW_LOCK_WRITE_SPINNER)
876 *in_critical = false;
881 #define rw_drop_critical(v, in_critical, extra_work) do { } while (0)
885 * This function is called when we are unable to obtain a write lock on the
886 * first try. This means that at least one other thread holds either a
887 * read or write lock.
890 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
894 struct turnstile *ts;
895 struct thread *owner;
896 #ifdef ADAPTIVE_RWLOCKS
899 enum { READERS, WRITER } sleep_reason = READERS;
900 bool in_critical = false;
903 #ifdef LOCK_PROFILING
904 uint64_t waittime = 0;
907 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
908 struct lock_delay_arg lda;
912 int64_t sleep_time = 0;
913 int64_t all_time = 0;
915 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
917 int doing_lockprof = 0;
921 tid = (uintptr_t)curthread;
925 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
926 while (v == RW_UNLOCKED) {
927 if (_rw_write_lock_fetch(rw, &v, tid))
932 all_time -= lockstat_nsecs(&rw->lock_object);
936 #ifdef LOCK_PROFILING
942 if (SCHEDULER_STOPPED())
945 #if defined(ADAPTIVE_RWLOCKS)
946 lock_delay_arg_init(&lda, &rw_delay);
947 #elif defined(KDTRACE_HOOKS)
948 lock_delay_arg_init(&lda, NULL);
950 if (__predict_false(v == RW_UNLOCKED))
951 v = RW_READ_VALUE(rw);
953 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
954 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
955 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
956 __func__, rw->lock_object.lo_name, file, line));
958 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
959 if (LOCK_LOG_TEST(&rw->lock_object, 0))
960 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
964 if (LOCK_LOG_TEST(&rw->lock_object, 0))
965 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
966 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
969 PMC_SOFT_CALL( , , lock, failed);
971 lock_profile_obtain_lock_failed(&rw->lock_object,
972 &contested, &waittime);
975 if (v == RW_UNLOCKED) {
976 if (_rw_write_lock_fetch(rw, &v, tid))
984 #ifdef ADAPTIVE_RWLOCKS
985 if (v == (RW_LOCK_READ | RW_LOCK_WRITE_SPINNER)) {
986 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
992 * If the lock is write locked and the owner is
993 * running on another CPU, spin until the owner stops
994 * running or the state of the lock changes.
996 if (!(v & RW_LOCK_READ)) {
997 rw_drop_critical(v, &in_critical, &extra_work);
998 sleep_reason = WRITER;
999 owner = lv_rw_wowner(v);
1000 if (!TD_IS_RUNNING(owner))
1002 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1003 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
1004 __func__, rw, owner);
1005 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1006 "spinning", "lockname:\"%s\"",
1007 rw->lock_object.lo_name);
1010 v = RW_READ_VALUE(rw);
1011 owner = lv_rw_wowner(v);
1012 } while (owner != NULL && TD_IS_RUNNING(owner));
1013 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1016 } else if (RW_READERS(v) > 0) {
1017 sleep_reason = READERS;
1018 if (spintries == rowner_retries)
1020 if (!(v & RW_LOCK_WRITE_SPINNER)) {
1026 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1027 v | RW_LOCK_WRITE_SPINNER)) {
1029 in_critical = false;
1035 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1036 "spinning", "lockname:\"%s\"",
1037 rw->lock_object.lo_name);
1039 for (i = 0; i < rowner_loops; i += n) {
1041 v = RW_READ_VALUE(rw);
1042 if (!(v & RW_LOCK_WRITE_SPINNER))
1044 if (!(v & RW_LOCK_READ))
1050 #ifdef KDTRACE_HOOKS
1053 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1055 if (i < rowner_loops)
1060 ts = turnstile_trywait(&rw->lock_object);
1061 v = RW_READ_VALUE(rw);
1063 owner = lv_rw_wowner(v);
1065 #ifdef ADAPTIVE_RWLOCKS
1067 * The current lock owner might have started executing
1068 * on another CPU (or the lock could have changed
1069 * owners) while we were waiting on the turnstile
1070 * chain lock. If so, drop the turnstile lock and try
1073 if (owner != NULL) {
1074 if (TD_IS_RUNNING(owner)) {
1075 turnstile_cancel(ts);
1076 rw_drop_critical(v, &in_critical, &extra_work);
1079 } else if (RW_READERS(v) > 0 && sleep_reason == WRITER) {
1080 turnstile_cancel(ts);
1081 rw_drop_critical(v, &in_critical, &extra_work);
1086 * Check for the waiters flags about this rwlock.
1087 * If the lock was released, without maintain any pending
1088 * waiters queue, simply try to acquire it.
1089 * If a pending waiters queue is present, claim the lock
1090 * ownership and maintain the pending queue.
1092 setv = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1093 if ((v & ~setv) == RW_UNLOCKED) {
1094 setv &= ~RW_LOCK_WRITE_SPINNER;
1095 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid | setv)) {
1097 turnstile_claim(ts);
1099 turnstile_cancel(ts);
1105 #ifdef ADAPTIVE_RWLOCKS
1107 if ((v & RW_LOCK_WRITE_SPINNER) ||
1108 !((v & RW_LOCK_WRITE_WAITERS))) {
1109 setv = v & ~RW_LOCK_WRITE_SPINNER;
1110 setv |= RW_LOCK_WRITE_WAITERS;
1111 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v, setv))
1115 in_critical = false;
1120 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1121 * set it. If we fail to set it, then loop back and try
1124 if (!(v & RW_LOCK_WRITE_WAITERS)) {
1125 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1126 v | RW_LOCK_WRITE_WAITERS))
1128 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1129 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1132 #ifdef ADAPTIVE_RWLOCKS
1136 * We were unable to acquire the lock and the write waiters
1137 * flag is set, so we must block on the turnstile.
1139 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1140 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1142 #ifdef KDTRACE_HOOKS
1143 sleep_time -= lockstat_nsecs(&rw->lock_object);
1145 MPASS(owner == rw_owner(rw));
1146 turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
1147 #ifdef KDTRACE_HOOKS
1148 sleep_time += lockstat_nsecs(&rw->lock_object);
1151 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1152 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1154 #ifdef ADAPTIVE_RWLOCKS
1157 v = RW_READ_VALUE(rw);
1159 if (__predict_true(!extra_work))
1161 #ifdef ADAPTIVE_RWLOCKS
1165 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1166 if (__predict_true(!doing_lockprof))
1169 #ifdef KDTRACE_HOOKS
1170 all_time += lockstat_nsecs(&rw->lock_object);
1172 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1173 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1174 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1176 /* Record only the loops spinning and not sleeping. */
1177 if (lda.spin_cnt > sleep_cnt)
1178 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1179 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1180 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1183 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1184 waittime, file, line, LOCKSTAT_WRITER);
1188 * This function is called if lockstat is active or the first try at releasing
1189 * a write lock failed. The latter means that the lock is recursed or one of
1190 * the 2 waiter bits must be set indicating that at least one thread is waiting
1194 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1197 struct turnstile *ts;
1198 uintptr_t tid, setv;
1201 tid = (uintptr_t)curthread;
1202 if (SCHEDULER_STOPPED())
1206 if (__predict_false(v == tid))
1207 v = RW_READ_VALUE(rw);
1209 if (v & RW_LOCK_WRITER_RECURSED) {
1210 if (--(rw->rw_recurse) == 0)
1211 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1212 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1213 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1217 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1218 if (v == tid && _rw_write_unlock(rw, tid))
1221 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1222 ("%s: neither of the waiter flags are set", __func__));
1224 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1225 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1227 turnstile_chain_lock(&rw->lock_object);
1230 * Use the same algo as sx locks for now. Prefer waking up shared
1231 * waiters if we have any over writers. This is probably not ideal.
1233 * 'v' is the value we are going to write back to rw_lock. If we
1234 * have waiters on both queues, we need to preserve the state of
1235 * the waiter flag for the queue we don't wake up. For now this is
1236 * hardcoded for the algorithm mentioned above.
1238 * In the case of both readers and writers waiting we wakeup the
1239 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1240 * new writer comes in before a reader it will claim the lock up
1241 * above. There is probably a potential priority inversion in
1242 * there that could be worked around either by waking both queues
1243 * of waiters or doing some complicated lock handoff gymnastics.
1246 v = RW_READ_VALUE(rw);
1247 queue = TS_SHARED_QUEUE;
1248 if (v & RW_LOCK_WRITE_WAITERS) {
1249 queue = TS_EXCLUSIVE_QUEUE;
1250 setv |= (v & RW_LOCK_READ_WAITERS);
1252 atomic_store_rel_ptr(&rw->rw_lock, setv);
1254 /* Wake up all waiters for the specific queue. */
1255 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1256 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1257 queue == TS_SHARED_QUEUE ? "read" : "write");
1259 ts = turnstile_lookup(&rw->lock_object);
1261 turnstile_broadcast(ts, queue);
1262 turnstile_unpend(ts);
1263 turnstile_chain_unlock(&rw->lock_object);
1267 * Attempt to do a non-blocking upgrade from a read lock to a write
1268 * lock. This will only succeed if this thread holds a single read
1269 * lock. Returns true if the upgrade succeeded and false otherwise.
1272 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1274 uintptr_t v, setv, tid;
1275 struct turnstile *ts;
1278 if (SCHEDULER_STOPPED())
1281 KASSERT(rw->rw_lock != RW_DESTROYED,
1282 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1283 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1286 * Attempt to switch from one reader to a writer. If there
1287 * are any write waiters, then we will have to lock the
1288 * turnstile first to prevent races with another writer
1289 * calling turnstile_wait() before we have claimed this
1290 * turnstile. So, do the simple case of no waiters first.
1292 tid = (uintptr_t)curthread;
1294 v = RW_READ_VALUE(rw);
1296 if (RW_READERS(v) > 1)
1298 if (!(v & RW_LOCK_WAITERS)) {
1299 success = atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid);
1306 * Ok, we think we have waiters, so lock the turnstile.
1308 ts = turnstile_trywait(&rw->lock_object);
1309 v = RW_READ_VALUE(rw);
1311 if (RW_READERS(v) > 1) {
1312 turnstile_cancel(ts);
1316 * Try to switch from one reader to a writer again. This time
1317 * we honor the current state of the waiters flags.
1318 * If we obtain the lock with the flags set, then claim
1319 * ownership of the turnstile.
1321 setv = tid | (v & RW_LOCK_WAITERS);
1322 success = atomic_fcmpset_ptr(&rw->rw_lock, &v, setv);
1324 if (v & RW_LOCK_WAITERS)
1325 turnstile_claim(ts);
1327 turnstile_cancel(ts);
1332 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1334 curthread->td_rw_rlocks--;
1335 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1337 LOCKSTAT_RECORD0(rw__upgrade, rw);
1343 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1348 return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1352 * Downgrade a write lock into a single read lock.
1355 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1357 struct turnstile *ts;
1361 if (SCHEDULER_STOPPED())
1364 KASSERT(rw->rw_lock != RW_DESTROYED,
1365 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1366 __rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1368 if (rw_recursed(rw))
1369 panic("downgrade of a recursed lock");
1372 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1375 * Convert from a writer to a single reader. First we handle
1376 * the easy case with no waiters. If there are any waiters, we
1377 * lock the turnstile and "disown" the lock.
1379 tid = (uintptr_t)curthread;
1380 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1384 * Ok, we think we have waiters, so lock the turnstile so we can
1385 * read the waiter flags without any races.
1387 turnstile_chain_lock(&rw->lock_object);
1388 v = rw->rw_lock & RW_LOCK_WAITERS;
1389 rwait = v & RW_LOCK_READ_WAITERS;
1390 wwait = v & RW_LOCK_WRITE_WAITERS;
1391 MPASS(rwait | wwait);
1394 * Downgrade from a write lock while preserving waiters flag
1395 * and give up ownership of the turnstile.
1397 ts = turnstile_lookup(&rw->lock_object);
1400 v &= ~RW_LOCK_READ_WAITERS;
1401 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1403 * Wake other readers if there are no writers pending. Otherwise they
1404 * won't be able to acquire the lock anyway.
1406 if (rwait && !wwait) {
1407 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1408 turnstile_unpend(ts);
1410 turnstile_disown(ts);
1411 turnstile_chain_unlock(&rw->lock_object);
1413 curthread->td_rw_rlocks++;
1414 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1415 LOCKSTAT_RECORD0(rw__downgrade, rw);
1419 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1424 __rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1427 #ifdef INVARIANT_SUPPORT
1433 * In the non-WITNESS case, rw_assert() can only detect that at least
1434 * *some* thread owns an rlock, but it cannot guarantee that *this*
1435 * thread owns an rlock.
1438 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1440 const struct rwlock *rw;
1442 if (SCHEDULER_STOPPED())
1449 case RA_LOCKED | RA_RECURSED:
1450 case RA_LOCKED | RA_NOTRECURSED:
1452 case RA_RLOCKED | RA_RECURSED:
1453 case RA_RLOCKED | RA_NOTRECURSED:
1455 witness_assert(&rw->lock_object, what, file, line);
1458 * If some other thread has a write lock or we have one
1459 * and are asserting a read lock, fail. Also, if no one
1460 * has a lock at all, fail.
1462 if (rw->rw_lock == RW_UNLOCKED ||
1463 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1464 rw_wowner(rw) != curthread)))
1465 panic("Lock %s not %slocked @ %s:%d\n",
1466 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1467 "read " : "", file, line);
1469 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1470 if (rw_recursed(rw)) {
1471 if (what & RA_NOTRECURSED)
1472 panic("Lock %s recursed @ %s:%d\n",
1473 rw->lock_object.lo_name, file,
1475 } else if (what & RA_RECURSED)
1476 panic("Lock %s not recursed @ %s:%d\n",
1477 rw->lock_object.lo_name, file, line);
1482 case RA_WLOCKED | RA_RECURSED:
1483 case RA_WLOCKED | RA_NOTRECURSED:
1484 if (rw_wowner(rw) != curthread)
1485 panic("Lock %s not exclusively locked @ %s:%d\n",
1486 rw->lock_object.lo_name, file, line);
1487 if (rw_recursed(rw)) {
1488 if (what & RA_NOTRECURSED)
1489 panic("Lock %s recursed @ %s:%d\n",
1490 rw->lock_object.lo_name, file, line);
1491 } else if (what & RA_RECURSED)
1492 panic("Lock %s not recursed @ %s:%d\n",
1493 rw->lock_object.lo_name, file, line);
1497 witness_assert(&rw->lock_object, what, file, line);
1500 * If we hold a write lock fail. We can't reliably check
1501 * to see if we hold a read lock or not.
1503 if (rw_wowner(rw) == curthread)
1504 panic("Lock %s exclusively locked @ %s:%d\n",
1505 rw->lock_object.lo_name, file, line);
1509 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1513 #endif /* INVARIANT_SUPPORT */
1517 db_show_rwlock(const struct lock_object *lock)
1519 const struct rwlock *rw;
1522 rw = (const struct rwlock *)lock;
1524 db_printf(" state: ");
1525 if (rw->rw_lock == RW_UNLOCKED)
1526 db_printf("UNLOCKED\n");
1527 else if (rw->rw_lock == RW_DESTROYED) {
1528 db_printf("DESTROYED\n");
1530 } else if (rw->rw_lock & RW_LOCK_READ)
1531 db_printf("RLOCK: %ju locks\n",
1532 (uintmax_t)(RW_READERS(rw->rw_lock)));
1535 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1536 td->td_tid, td->td_proc->p_pid, td->td_name);
1537 if (rw_recursed(rw))
1538 db_printf(" recursed: %u\n", rw->rw_recurse);
1540 db_printf(" waiters: ");
1541 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1542 case RW_LOCK_READ_WAITERS:
1543 db_printf("readers\n");
1545 case RW_LOCK_WRITE_WAITERS:
1546 db_printf("writers\n");
1548 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1549 db_printf("readers and writers\n");
1552 db_printf("none\n");