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 = 10;
99 static int __read_frequently rowner_loops = 10000;
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,
112 LOCK_DELAY_SYSINIT_DEFAULT(rw_delay);
116 * Return a pointer to the owning thread if the lock is write-locked or
117 * NULL if the lock is unlocked or read-locked.
120 #define lv_rw_wowner(v) \
121 ((v) & RW_LOCK_READ ? NULL : \
122 (struct thread *)RW_OWNER((v)))
124 #define rw_wowner(rw) lv_rw_wowner(RW_READ_VALUE(rw))
127 * Returns if a write owner is recursed. Write ownership is not assured
128 * here and should be previously checked.
130 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
133 * Return true if curthread helds the lock.
135 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
138 * Return a pointer to the owning thread for this lock who should receive
139 * any priority lent by threads that block on this lock. Currently this
140 * is identical to rw_wowner().
142 #define rw_owner(rw) rw_wowner(rw)
145 #define __rw_assert(c, what, file, line)
149 assert_rw(const struct lock_object *lock, int what)
152 rw_assert((const struct rwlock *)lock, what);
156 lock_rw(struct lock_object *lock, uintptr_t how)
160 rw = (struct rwlock *)lock;
168 unlock_rw(struct lock_object *lock)
172 rw = (struct rwlock *)lock;
173 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
174 if (rw->rw_lock & RW_LOCK_READ) {
185 owner_rw(const struct lock_object *lock, struct thread **owner)
187 const struct rwlock *rw = (const struct rwlock *)lock;
188 uintptr_t x = rw->rw_lock;
190 *owner = rw_wowner(rw);
191 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
197 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
204 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
205 RW_RECURSE | RW_NEW)) == 0);
206 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
207 ("%s: rw_lock not aligned for %s: %p", __func__, name,
210 flags = LO_UPGRADABLE;
213 if (opts & RW_NOPROFILE)
214 flags |= LO_NOPROFILE;
215 if (!(opts & RW_NOWITNESS))
217 if (opts & RW_RECURSE)
218 flags |= LO_RECURSABLE;
224 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
225 rw->rw_lock = RW_UNLOCKED;
230 _rw_destroy(volatile uintptr_t *c)
236 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
237 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
238 rw->rw_lock = RW_DESTROYED;
239 lock_destroy(&rw->lock_object);
243 rw_sysinit(void *arg)
245 struct rw_args *args;
248 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
253 _rw_wowned(const volatile uintptr_t *c)
256 return (rw_wowner(rwlock2rw(c)) == curthread);
260 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
267 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
268 !TD_IS_IDLETHREAD(curthread),
269 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
270 curthread, rw->lock_object.lo_name, file, line));
271 KASSERT(rw->rw_lock != RW_DESTROYED,
272 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
273 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
275 tid = (uintptr_t)curthread;
277 if (!_rw_write_lock_fetch(rw, &v, tid))
278 _rw_wlock_hard(rw, v, file, line);
280 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
281 0, 0, file, line, LOCKSTAT_WRITER);
283 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
284 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
285 TD_LOCKS_INC(curthread);
289 __rw_try_wlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
298 if (SCHEDULER_STOPPED_TD(td))
301 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
302 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
303 curthread, rw->lock_object.lo_name, file, line));
304 KASSERT(rw->rw_lock != RW_DESTROYED,
305 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
311 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
313 if (v == RW_UNLOCKED)
315 if (v == tid && (rw->lock_object.lo_flags & LO_RECURSABLE)) {
317 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
324 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
326 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
329 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
330 rw, 0, 0, file, line, LOCKSTAT_WRITER);
331 TD_LOCKS_INC(curthread);
337 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
342 return (__rw_try_wlock_int(rw LOCK_FILE_LINE_ARG));
346 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
352 KASSERT(rw->rw_lock != RW_DESTROYED,
353 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
354 __rw_assert(c, RA_WLOCKED, file, line);
355 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
356 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
359 #ifdef LOCK_PROFILING
360 _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
362 __rw_wunlock(rw, curthread, file, line);
365 TD_LOCKS_DEC(curthread);
369 * Determines whether a new reader can acquire a lock. Succeeds if the
370 * reader already owns a read lock and the lock is locked for read to
371 * prevent deadlock from reader recursion. Also succeeds if the lock
372 * is unlocked and has no writer waiters or spinners. Failing otherwise
373 * prioritizes writers before readers.
375 static bool __always_inline
376 __rw_can_read(struct thread *td, uintptr_t v, bool fp)
379 if ((v & (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER))
382 if (!fp && td->td_rw_rlocks && (v & RW_LOCK_READ))
387 static bool __always_inline
388 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp, bool fp
389 LOCK_FILE_LINE_ARG_DEF)
393 * Handle the easy case. If no other thread has a write
394 * lock, then try to bump up the count of read locks. Note
395 * that we have to preserve the current state of the
396 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
397 * read lock, then rw_lock must have changed, so restart
398 * the loop. Note that this handles the case of a
399 * completely unlocked rwlock since such a lock is encoded
400 * as a read lock with no waiters.
402 while (__rw_can_read(td, *vp, fp)) {
403 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
404 *vp + RW_ONE_READER)) {
405 if (LOCK_LOG_TEST(&rw->lock_object, 0))
407 "%s: %p succeed %p -> %p", __func__,
409 (void *)(*vp + RW_ONE_READER));
417 static void __noinline
418 __rw_rlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
419 LOCK_FILE_LINE_ARG_DEF)
421 struct turnstile *ts;
422 struct thread *owner;
423 #ifdef ADAPTIVE_RWLOCKS
427 #ifdef LOCK_PROFILING
428 uint64_t waittime = 0;
431 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
432 struct lock_delay_arg lda;
436 int64_t sleep_time = 0;
437 int64_t all_time = 0;
439 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
444 if (SCHEDULER_STOPPED())
447 #if defined(ADAPTIVE_RWLOCKS)
448 lock_delay_arg_init(&lda, &rw_delay);
449 #elif defined(KDTRACE_HOOKS)
450 lock_delay_arg_init(&lda, NULL);
454 PMC_SOFT_CALL( , , lock, failed);
456 lock_profile_obtain_lock_failed(&rw->lock_object,
457 &contested, &waittime);
459 #ifdef LOCK_PROFILING
462 #elif defined(KDTRACE_HOOKS)
463 doing_lockprof = lockstat_enabled;
464 if (__predict_false(doing_lockprof)) {
465 all_time -= lockstat_nsecs(&rw->lock_object);
471 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
477 #ifdef ADAPTIVE_RWLOCKS
479 * If the owner is running on another CPU, spin until
480 * the owner stops running or the state of the lock
483 if ((v & RW_LOCK_READ) == 0) {
484 owner = (struct thread *)RW_OWNER(v);
485 if (TD_IS_RUNNING(owner)) {
486 if (LOCK_LOG_TEST(&rw->lock_object, 0))
488 "%s: spinning on %p held by %p",
489 __func__, rw, owner);
490 KTR_STATE1(KTR_SCHED, "thread",
491 sched_tdname(curthread), "spinning",
492 "lockname:\"%s\"", rw->lock_object.lo_name);
495 v = RW_READ_VALUE(rw);
496 owner = lv_rw_wowner(v);
497 } while (owner != NULL && TD_IS_RUNNING(owner));
498 KTR_STATE0(KTR_SCHED, "thread",
499 sched_tdname(curthread), "running");
502 } else if (spintries < rowner_retries) {
504 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
505 "spinning", "lockname:\"%s\"",
506 rw->lock_object.lo_name);
507 for (i = 0; i < rowner_loops; i += n) {
510 v = RW_READ_VALUE(rw);
511 if ((v & RW_LOCK_READ) == 0 || __rw_can_read(td, v, false))
515 lda.spin_cnt += rowner_loops - i;
517 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
519 if (i != rowner_loops)
525 * Okay, now it's the hard case. Some other thread already
526 * has a write lock or there are write waiters present,
527 * acquire the turnstile lock so we can begin the process
530 ts = turnstile_trywait(&rw->lock_object);
533 * The lock might have been released while we spun, so
534 * recheck its state and restart the loop if needed.
536 v = RW_READ_VALUE(rw);
538 if (__rw_can_read(td, v, false)) {
539 turnstile_cancel(ts);
543 owner = lv_rw_wowner(v);
545 #ifdef ADAPTIVE_RWLOCKS
547 * The current lock owner might have started executing
548 * on another CPU (or the lock could have changed
549 * owners) while we were waiting on the turnstile
550 * chain lock. If so, drop the turnstile lock and try
554 if (TD_IS_RUNNING(owner)) {
555 turnstile_cancel(ts);
562 * The lock is held in write mode or it already has waiters.
564 MPASS(!__rw_can_read(td, v, false));
567 * If the RW_LOCK_READ_WAITERS flag is already set, then
568 * we can go ahead and block. If it is not set then try
569 * to set it. If we fail to set it drop the turnstile
570 * lock and restart the loop.
572 if (!(v & RW_LOCK_READ_WAITERS)) {
573 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
574 v | RW_LOCK_READ_WAITERS))
576 if (LOCK_LOG_TEST(&rw->lock_object, 0))
577 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
582 * We were unable to acquire the lock and the read waiters
583 * flag is set, so we must block on the turnstile.
585 if (LOCK_LOG_TEST(&rw->lock_object, 0))
586 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
589 sleep_time -= lockstat_nsecs(&rw->lock_object);
591 MPASS(owner == rw_owner(rw));
592 turnstile_wait(ts, owner, TS_SHARED_QUEUE);
594 sleep_time += lockstat_nsecs(&rw->lock_object);
597 if (LOCK_LOG_TEST(&rw->lock_object, 0))
598 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
600 v = RW_READ_VALUE(rw);
602 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
603 if (__predict_true(!doing_lockprof))
607 all_time += lockstat_nsecs(&rw->lock_object);
609 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
610 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
611 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
613 /* Record only the loops spinning and not sleeping. */
614 if (lda.spin_cnt > sleep_cnt)
615 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
616 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
617 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
620 * TODO: acquire "owner of record" here. Here be turnstile dragons
621 * however. turnstiles don't like owners changing between calls to
622 * turnstile_wait() currently.
624 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
625 waittime, file, line, LOCKSTAT_READER);
629 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
636 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
637 !TD_IS_IDLETHREAD(td),
638 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
639 td, rw->lock_object.lo_name, file, line));
640 KASSERT(rw->rw_lock != RW_DESTROYED,
641 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
642 KASSERT(rw_wowner(rw) != td,
643 ("rw_rlock: wlock already held for %s @ %s:%d",
644 rw->lock_object.lo_name, file, line));
645 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
647 v = RW_READ_VALUE(rw);
648 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__acquire) ||
649 !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
650 __rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
652 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
653 WITNESS_LOCK(&rw->lock_object, 0, file, line);
654 TD_LOCKS_INC(curthread);
658 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
663 __rw_rlock_int(rw LOCK_FILE_LINE_ARG);
667 __rw_try_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
671 if (SCHEDULER_STOPPED())
674 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
675 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
676 curthread, rw->lock_object.lo_name, file, line));
680 KASSERT(rw->rw_lock != RW_DESTROYED,
681 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
682 if (!(x & RW_LOCK_READ))
684 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
685 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
687 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
688 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
689 rw, 0, 0, file, line, LOCKSTAT_READER);
690 TD_LOCKS_INC(curthread);
691 curthread->td_rw_rlocks++;
696 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
701 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
706 return (__rw_try_rlock_int(rw LOCK_FILE_LINE_ARG));
709 static bool __always_inline
710 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
715 * See if there is more than one read lock held. If so,
716 * just drop one and return.
718 if (RW_READERS(*vp) > 1) {
719 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
720 *vp - RW_ONE_READER)) {
721 if (LOCK_LOG_TEST(&rw->lock_object, 0))
723 "%s: %p succeeded %p -> %p",
724 __func__, rw, (void *)*vp,
725 (void *)(*vp - RW_ONE_READER));
732 * If there aren't any waiters for a write lock, then try
733 * to drop it quickly.
735 if (!(*vp & RW_LOCK_WAITERS)) {
736 MPASS((*vp & ~RW_LOCK_WRITE_SPINNER) ==
738 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
740 if (LOCK_LOG_TEST(&rw->lock_object, 0))
741 CTR2(KTR_LOCK, "%s: %p last succeeded",
753 static void __noinline
754 __rw_runlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
755 LOCK_FILE_LINE_ARG_DEF)
757 struct turnstile *ts;
760 if (SCHEDULER_STOPPED())
764 if (__rw_runlock_try(rw, td, &v))
768 * Ok, we know we have waiters and we think we are the
769 * last reader, so grab the turnstile lock.
771 turnstile_chain_lock(&rw->lock_object);
772 v = RW_READ_VALUE(rw);
774 if (__predict_false(RW_READERS(v) > 1)) {
775 turnstile_chain_unlock(&rw->lock_object);
779 v &= (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
780 MPASS(v & RW_LOCK_WAITERS);
783 * Try to drop our lock leaving the lock in a unlocked
786 * If you wanted to do explicit lock handoff you'd have to
787 * do it here. You'd also want to use turnstile_signal()
788 * and you'd have to handle the race where a higher
789 * priority thread blocks on the write lock before the
790 * thread you wakeup actually runs and have the new thread
791 * "steal" the lock. For now it's a lot simpler to just
792 * wakeup all of the waiters.
794 * As above, if we fail, then another thread might have
795 * acquired a read lock, so drop the turnstile lock and
799 if (v & RW_LOCK_WRITE_WAITERS) {
800 queue = TS_EXCLUSIVE_QUEUE;
801 x |= (v & RW_LOCK_READ_WAITERS);
803 queue = TS_SHARED_QUEUE;
804 v |= RW_READERS_LOCK(1);
805 if (!atomic_fcmpset_rel_ptr(&rw->rw_lock, &v, x))
807 if (LOCK_LOG_TEST(&rw->lock_object, 0))
808 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
812 * Ok. The lock is released and all that's left is to
813 * wake up the waiters. Note that the lock might not be
814 * free anymore, but in that case the writers will just
815 * block again if they run before the new lock holder(s)
818 ts = turnstile_lookup(&rw->lock_object);
820 turnstile_broadcast(ts, queue);
821 turnstile_unpend(ts, TS_SHARED_LOCK);
822 turnstile_chain_unlock(&rw->lock_object);
826 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
830 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
835 KASSERT(rw->rw_lock != RW_DESTROYED,
836 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
837 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
838 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
839 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
842 v = RW_READ_VALUE(rw);
844 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__release) ||
845 !__rw_runlock_try(rw, td, &v)))
846 __rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
848 TD_LOCKS_DEC(curthread);
852 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
857 _rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
861 * This function is called when we are unable to obtain a write lock on the
862 * first try. This means that at least one other thread holds either a
863 * read or write lock.
866 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
870 struct turnstile *ts;
871 struct thread *owner;
872 #ifdef ADAPTIVE_RWLOCKS
877 #ifdef LOCK_PROFILING
878 uint64_t waittime = 0;
881 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
882 struct lock_delay_arg lda;
886 int64_t sleep_time = 0;
887 int64_t all_time = 0;
889 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
894 tid = (uintptr_t)curthread;
895 if (SCHEDULER_STOPPED())
898 #if defined(ADAPTIVE_RWLOCKS)
899 lock_delay_arg_init(&lda, &rw_delay);
900 #elif defined(KDTRACE_HOOKS)
901 lock_delay_arg_init(&lda, NULL);
904 if (__predict_false(v == RW_UNLOCKED))
905 v = RW_READ_VALUE(rw);
907 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
908 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
909 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
910 __func__, rw->lock_object.lo_name, file, line));
912 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
913 if (LOCK_LOG_TEST(&rw->lock_object, 0))
914 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
918 if (LOCK_LOG_TEST(&rw->lock_object, 0))
919 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
920 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
923 PMC_SOFT_CALL( , , lock, failed);
925 lock_profile_obtain_lock_failed(&rw->lock_object,
926 &contested, &waittime);
928 #ifdef LOCK_PROFILING
931 #elif defined(KDTRACE_HOOKS)
932 doing_lockprof = lockstat_enabled;
933 if (__predict_false(doing_lockprof)) {
934 all_time -= lockstat_nsecs(&rw->lock_object);
940 if (v == RW_UNLOCKED) {
941 if (_rw_write_lock_fetch(rw, &v, tid))
949 #ifdef ADAPTIVE_RWLOCKS
951 * If the lock is write locked and the owner is
952 * running on another CPU, spin until the owner stops
953 * running or the state of the lock changes.
955 owner = lv_rw_wowner(v);
956 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
957 if (LOCK_LOG_TEST(&rw->lock_object, 0))
958 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
959 __func__, rw, owner);
960 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
961 "spinning", "lockname:\"%s\"",
962 rw->lock_object.lo_name);
965 v = RW_READ_VALUE(rw);
966 owner = lv_rw_wowner(v);
967 } while (owner != NULL && TD_IS_RUNNING(owner));
968 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
972 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
973 spintries < rowner_retries) {
974 if (!(v & RW_LOCK_WRITE_SPINNER)) {
975 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
976 v | RW_LOCK_WRITE_SPINNER)) {
981 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
982 "spinning", "lockname:\"%s\"",
983 rw->lock_object.lo_name);
984 for (i = 0; i < rowner_loops; i += n) {
987 v = RW_READ_VALUE(rw);
988 if ((v & RW_LOCK_WRITE_SPINNER) == 0)
991 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
994 lda.spin_cnt += rowner_loops - i;
996 if (i != rowner_loops)
1000 ts = turnstile_trywait(&rw->lock_object);
1001 v = RW_READ_VALUE(rw);
1003 owner = lv_rw_wowner(v);
1005 #ifdef ADAPTIVE_RWLOCKS
1007 * The current lock owner might have started executing
1008 * on another CPU (or the lock could have changed
1009 * owners) while we were waiting on the turnstile
1010 * chain lock. If so, drop the turnstile lock and try
1013 if (owner != NULL) {
1014 if (TD_IS_RUNNING(owner)) {
1015 turnstile_cancel(ts);
1021 * Check for the waiters flags about this rwlock.
1022 * If the lock was released, without maintain any pending
1023 * waiters queue, simply try to acquire it.
1024 * If a pending waiters queue is present, claim the lock
1025 * ownership and maintain the pending queue.
1027 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1028 if ((v & ~x) == RW_UNLOCKED) {
1029 x &= ~RW_LOCK_WRITE_SPINNER;
1030 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid | x)) {
1032 turnstile_claim(ts);
1034 turnstile_cancel(ts);
1040 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1041 * set it. If we fail to set it, then loop back and try
1044 if (!(v & RW_LOCK_WRITE_WAITERS)) {
1045 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1046 v | RW_LOCK_WRITE_WAITERS))
1048 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1049 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1053 * We were unable to acquire the lock and the write waiters
1054 * flag is set, so we must block on the turnstile.
1056 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1057 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1059 #ifdef KDTRACE_HOOKS
1060 sleep_time -= lockstat_nsecs(&rw->lock_object);
1062 MPASS(owner == rw_owner(rw));
1063 turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
1064 #ifdef KDTRACE_HOOKS
1065 sleep_time += lockstat_nsecs(&rw->lock_object);
1068 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1069 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1071 #ifdef ADAPTIVE_RWLOCKS
1074 v = RW_READ_VALUE(rw);
1076 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1077 if (__predict_true(!doing_lockprof))
1080 #ifdef KDTRACE_HOOKS
1081 all_time += lockstat_nsecs(&rw->lock_object);
1083 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1084 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1085 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1087 /* Record only the loops spinning and not sleeping. */
1088 if (lda.spin_cnt > sleep_cnt)
1089 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1090 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1091 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1093 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1094 waittime, file, line, LOCKSTAT_WRITER);
1098 * This function is called if lockstat is active or the first try at releasing
1099 * a write lock failed. The latter means that the lock is recursed or one of
1100 * the 2 waiter bits must be set indicating that at least one thread is waiting
1104 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1107 struct turnstile *ts;
1108 uintptr_t tid, setv;
1111 tid = (uintptr_t)curthread;
1112 if (SCHEDULER_STOPPED())
1116 if (__predict_false(v == tid))
1117 v = RW_READ_VALUE(rw);
1119 if (v & RW_LOCK_WRITER_RECURSED) {
1120 if (--(rw->rw_recurse) == 0)
1121 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1122 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1123 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1127 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1128 if (v == tid && _rw_write_unlock(rw, tid))
1131 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1132 ("%s: neither of the waiter flags are set", __func__));
1134 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1135 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1137 turnstile_chain_lock(&rw->lock_object);
1140 * Use the same algo as sx locks for now. Prefer waking up shared
1141 * waiters if we have any over writers. This is probably not ideal.
1143 * 'v' is the value we are going to write back to rw_lock. If we
1144 * have waiters on both queues, we need to preserve the state of
1145 * the waiter flag for the queue we don't wake up. For now this is
1146 * hardcoded for the algorithm mentioned above.
1148 * In the case of both readers and writers waiting we wakeup the
1149 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1150 * new writer comes in before a reader it will claim the lock up
1151 * above. There is probably a potential priority inversion in
1152 * there that could be worked around either by waking both queues
1153 * of waiters or doing some complicated lock handoff gymnastics.
1156 v = RW_READ_VALUE(rw);
1157 queue = TS_SHARED_QUEUE;
1158 if (v & RW_LOCK_WRITE_WAITERS) {
1159 queue = TS_EXCLUSIVE_QUEUE;
1160 setv |= (v & RW_LOCK_READ_WAITERS);
1162 atomic_store_rel_ptr(&rw->rw_lock, setv);
1164 /* Wake up all waiters for the specific queue. */
1165 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1166 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1167 queue == TS_SHARED_QUEUE ? "read" : "write");
1169 ts = turnstile_lookup(&rw->lock_object);
1171 turnstile_broadcast(ts, queue);
1172 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1173 turnstile_chain_unlock(&rw->lock_object);
1177 * Attempt to do a non-blocking upgrade from a read lock to a write
1178 * lock. This will only succeed if this thread holds a single read
1179 * lock. Returns true if the upgrade succeeded and false otherwise.
1182 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1184 uintptr_t v, x, tid;
1185 struct turnstile *ts;
1188 if (SCHEDULER_STOPPED())
1191 KASSERT(rw->rw_lock != RW_DESTROYED,
1192 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1193 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1196 * Attempt to switch from one reader to a writer. If there
1197 * are any write waiters, then we will have to lock the
1198 * turnstile first to prevent races with another writer
1199 * calling turnstile_wait() before we have claimed this
1200 * turnstile. So, do the simple case of no waiters first.
1202 tid = (uintptr_t)curthread;
1206 if (RW_READERS(v) > 1)
1208 if (!(v & RW_LOCK_WAITERS)) {
1209 success = atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid);
1216 * Ok, we think we have waiters, so lock the turnstile.
1218 ts = turnstile_trywait(&rw->lock_object);
1220 if (RW_READERS(v) > 1) {
1221 turnstile_cancel(ts);
1225 * Try to switch from one reader to a writer again. This time
1226 * we honor the current state of the waiters flags.
1227 * If we obtain the lock with the flags set, then claim
1228 * ownership of the turnstile.
1230 x = rw->rw_lock & RW_LOCK_WAITERS;
1231 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1234 turnstile_claim(ts);
1236 turnstile_cancel(ts);
1239 turnstile_cancel(ts);
1241 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1243 curthread->td_rw_rlocks--;
1244 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1246 LOCKSTAT_RECORD0(rw__upgrade, rw);
1252 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1257 return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1261 * Downgrade a write lock into a single read lock.
1264 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1266 struct turnstile *ts;
1270 if (SCHEDULER_STOPPED())
1273 KASSERT(rw->rw_lock != RW_DESTROYED,
1274 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1275 __rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1277 if (rw_recursed(rw))
1278 panic("downgrade of a recursed lock");
1281 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1284 * Convert from a writer to a single reader. First we handle
1285 * the easy case with no waiters. If there are any waiters, we
1286 * lock the turnstile and "disown" the lock.
1288 tid = (uintptr_t)curthread;
1289 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1293 * Ok, we think we have waiters, so lock the turnstile so we can
1294 * read the waiter flags without any races.
1296 turnstile_chain_lock(&rw->lock_object);
1297 v = rw->rw_lock & RW_LOCK_WAITERS;
1298 rwait = v & RW_LOCK_READ_WAITERS;
1299 wwait = v & RW_LOCK_WRITE_WAITERS;
1300 MPASS(rwait | wwait);
1303 * Downgrade from a write lock while preserving waiters flag
1304 * and give up ownership of the turnstile.
1306 ts = turnstile_lookup(&rw->lock_object);
1309 v &= ~RW_LOCK_READ_WAITERS;
1310 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1312 * Wake other readers if there are no writers pending. Otherwise they
1313 * won't be able to acquire the lock anyway.
1315 if (rwait && !wwait) {
1316 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1317 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1319 turnstile_disown(ts);
1320 turnstile_chain_unlock(&rw->lock_object);
1322 curthread->td_rw_rlocks++;
1323 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1324 LOCKSTAT_RECORD0(rw__downgrade, rw);
1328 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1333 __rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1336 #ifdef INVARIANT_SUPPORT
1342 * In the non-WITNESS case, rw_assert() can only detect that at least
1343 * *some* thread owns an rlock, but it cannot guarantee that *this*
1344 * thread owns an rlock.
1347 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1349 const struct rwlock *rw;
1351 if (panicstr != NULL)
1358 case RA_LOCKED | RA_RECURSED:
1359 case RA_LOCKED | RA_NOTRECURSED:
1361 case RA_RLOCKED | RA_RECURSED:
1362 case RA_RLOCKED | RA_NOTRECURSED:
1364 witness_assert(&rw->lock_object, what, file, line);
1367 * If some other thread has a write lock or we have one
1368 * and are asserting a read lock, fail. Also, if no one
1369 * has a lock at all, fail.
1371 if (rw->rw_lock == RW_UNLOCKED ||
1372 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1373 rw_wowner(rw) != curthread)))
1374 panic("Lock %s not %slocked @ %s:%d\n",
1375 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1376 "read " : "", file, line);
1378 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1379 if (rw_recursed(rw)) {
1380 if (what & RA_NOTRECURSED)
1381 panic("Lock %s recursed @ %s:%d\n",
1382 rw->lock_object.lo_name, file,
1384 } else if (what & RA_RECURSED)
1385 panic("Lock %s not recursed @ %s:%d\n",
1386 rw->lock_object.lo_name, file, line);
1391 case RA_WLOCKED | RA_RECURSED:
1392 case RA_WLOCKED | RA_NOTRECURSED:
1393 if (rw_wowner(rw) != curthread)
1394 panic("Lock %s not exclusively locked @ %s:%d\n",
1395 rw->lock_object.lo_name, file, line);
1396 if (rw_recursed(rw)) {
1397 if (what & RA_NOTRECURSED)
1398 panic("Lock %s recursed @ %s:%d\n",
1399 rw->lock_object.lo_name, file, line);
1400 } else if (what & RA_RECURSED)
1401 panic("Lock %s not recursed @ %s:%d\n",
1402 rw->lock_object.lo_name, file, line);
1406 witness_assert(&rw->lock_object, what, file, line);
1409 * If we hold a write lock fail. We can't reliably check
1410 * to see if we hold a read lock or not.
1412 if (rw_wowner(rw) == curthread)
1413 panic("Lock %s exclusively locked @ %s:%d\n",
1414 rw->lock_object.lo_name, file, line);
1418 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1422 #endif /* INVARIANT_SUPPORT */
1426 db_show_rwlock(const struct lock_object *lock)
1428 const struct rwlock *rw;
1431 rw = (const struct rwlock *)lock;
1433 db_printf(" state: ");
1434 if (rw->rw_lock == RW_UNLOCKED)
1435 db_printf("UNLOCKED\n");
1436 else if (rw->rw_lock == RW_DESTROYED) {
1437 db_printf("DESTROYED\n");
1439 } else if (rw->rw_lock & RW_LOCK_READ)
1440 db_printf("RLOCK: %ju locks\n",
1441 (uintmax_t)(RW_READERS(rw->rw_lock)));
1444 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1445 td->td_tid, td->td_proc->p_pid, td->td_name);
1446 if (rw_recursed(rw))
1447 db_printf(" recursed: %u\n", rw->rw_recurse);
1449 db_printf(" waiters: ");
1450 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1451 case RW_LOCK_READ_WAITERS:
1452 db_printf("readers\n");
1454 case RW_LOCK_WRITE_WAITERS:
1455 db_printf("writers\n");
1457 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1458 db_printf("readers and writers\n");
1461 db_printf("none\n");