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, CTLFLAG_RD, NULL,
102 SYSCTL_U16(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
103 SYSCTL_U16(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
105 static struct lock_delay_config __read_frequently rw_delay;
107 SYSCTL_U16(_debug_rwlock, OID_AUTO, delay_base, CTLFLAG_RW, &rw_delay.base,
109 SYSCTL_U16(_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);
122 #define rw_delay locks_delay
123 #define rowner_retries locks_delay_retries
124 #define rowner_loops locks_delay_loops
129 * Return a pointer to the owning thread if the lock is write-locked or
130 * NULL if the lock is unlocked or read-locked.
133 #define lv_rw_wowner(v) \
134 ((v) & RW_LOCK_READ ? NULL : \
135 (struct thread *)RW_OWNER((v)))
137 #define rw_wowner(rw) lv_rw_wowner(RW_READ_VALUE(rw))
140 * Returns if a write owner is recursed. Write ownership is not assured
141 * here and should be previously checked.
143 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
146 * Return true if curthread helds the lock.
148 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
151 * Return a pointer to the owning thread for this lock who should receive
152 * any priority lent by threads that block on this lock. Currently this
153 * is identical to rw_wowner().
155 #define rw_owner(rw) rw_wowner(rw)
158 #define __rw_assert(c, what, file, line)
162 assert_rw(const struct lock_object *lock, int what)
165 rw_assert((const struct rwlock *)lock, what);
169 lock_rw(struct lock_object *lock, uintptr_t how)
173 rw = (struct rwlock *)lock;
181 unlock_rw(struct lock_object *lock)
185 rw = (struct rwlock *)lock;
186 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
187 if (rw->rw_lock & RW_LOCK_READ) {
198 owner_rw(const struct lock_object *lock, struct thread **owner)
200 const struct rwlock *rw = (const struct rwlock *)lock;
201 uintptr_t x = rw->rw_lock;
203 *owner = rw_wowner(rw);
204 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
210 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
217 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
218 RW_RECURSE | RW_NEW)) == 0);
219 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
220 ("%s: rw_lock not aligned for %s: %p", __func__, name,
223 flags = LO_UPGRADABLE;
226 if (opts & RW_NOPROFILE)
227 flags |= LO_NOPROFILE;
228 if (!(opts & RW_NOWITNESS))
230 if (opts & RW_RECURSE)
231 flags |= LO_RECURSABLE;
237 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
238 rw->rw_lock = RW_UNLOCKED;
243 _rw_destroy(volatile uintptr_t *c)
249 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
250 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
251 rw->rw_lock = RW_DESTROYED;
252 lock_destroy(&rw->lock_object);
256 rw_sysinit(void *arg)
258 struct rw_args *args;
261 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
266 _rw_wowned(const volatile uintptr_t *c)
269 return (rw_wowner(rwlock2rw(c)) == curthread);
273 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
280 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
281 !TD_IS_IDLETHREAD(curthread),
282 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
283 curthread, rw->lock_object.lo_name, file, line));
284 KASSERT(rw->rw_lock != RW_DESTROYED,
285 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
286 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
288 tid = (uintptr_t)curthread;
290 if (!_rw_write_lock_fetch(rw, &v, tid))
291 _rw_wlock_hard(rw, v, file, line);
293 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
294 0, 0, file, line, LOCKSTAT_WRITER);
296 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
297 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
298 TD_LOCKS_INC(curthread);
302 __rw_try_wlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
311 if (SCHEDULER_STOPPED_TD(td))
314 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
315 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
316 curthread, rw->lock_object.lo_name, file, line));
317 KASSERT(rw->rw_lock != RW_DESTROYED,
318 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
324 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
326 if (v == RW_UNLOCKED)
328 if (v == tid && (rw->lock_object.lo_flags & LO_RECURSABLE)) {
330 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
337 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
339 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
342 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
343 rw, 0, 0, file, line, LOCKSTAT_WRITER);
344 TD_LOCKS_INC(curthread);
350 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
355 return (__rw_try_wlock_int(rw LOCK_FILE_LINE_ARG));
359 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
365 KASSERT(rw->rw_lock != RW_DESTROYED,
366 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
367 __rw_assert(c, RA_WLOCKED, file, line);
368 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
369 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
372 #ifdef LOCK_PROFILING
373 _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
375 __rw_wunlock(rw, curthread, file, line);
378 TD_LOCKS_DEC(curthread);
382 * Determines whether a new reader can acquire a lock. Succeeds if the
383 * reader already owns a read lock and the lock is locked for read to
384 * prevent deadlock from reader recursion. Also succeeds if the lock
385 * is unlocked and has no writer waiters or spinners. Failing otherwise
386 * prioritizes writers before readers.
388 static bool __always_inline
389 __rw_can_read(struct thread *td, uintptr_t v, bool fp)
392 if ((v & (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER))
395 if (!fp && td->td_rw_rlocks && (v & RW_LOCK_READ))
400 static bool __always_inline
401 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp, bool fp
402 LOCK_FILE_LINE_ARG_DEF)
406 * Handle the easy case. If no other thread has a write
407 * lock, then try to bump up the count of read locks. Note
408 * that we have to preserve the current state of the
409 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
410 * read lock, then rw_lock must have changed, so restart
411 * the loop. Note that this handles the case of a
412 * completely unlocked rwlock since such a lock is encoded
413 * as a read lock with no waiters.
415 while (__rw_can_read(td, *vp, fp)) {
416 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
417 *vp + RW_ONE_READER)) {
418 if (LOCK_LOG_TEST(&rw->lock_object, 0))
420 "%s: %p succeed %p -> %p", __func__,
422 (void *)(*vp + RW_ONE_READER));
430 static void __noinline
431 __rw_rlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
432 LOCK_FILE_LINE_ARG_DEF)
434 struct turnstile *ts;
435 struct thread *owner;
436 #ifdef ADAPTIVE_RWLOCKS
440 #ifdef LOCK_PROFILING
441 uint64_t waittime = 0;
444 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
445 struct lock_delay_arg lda;
449 int64_t sleep_time = 0;
450 int64_t all_time = 0;
452 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
454 int doing_lockprof = 0;
458 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
459 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
462 all_time -= lockstat_nsecs(&rw->lock_object);
466 #ifdef LOCK_PROFILING
471 if (SCHEDULER_STOPPED())
474 #if defined(ADAPTIVE_RWLOCKS)
475 lock_delay_arg_init(&lda, &rw_delay);
476 #elif defined(KDTRACE_HOOKS)
477 lock_delay_arg_init(&lda, NULL);
481 PMC_SOFT_CALL( , , lock, failed);
483 lock_profile_obtain_lock_failed(&rw->lock_object,
484 &contested, &waittime);
487 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
493 #ifdef ADAPTIVE_RWLOCKS
495 * If the owner is running on another CPU, spin until
496 * the owner stops running or the state of the lock
499 if ((v & RW_LOCK_READ) == 0) {
500 owner = (struct thread *)RW_OWNER(v);
501 if (TD_IS_RUNNING(owner)) {
502 if (LOCK_LOG_TEST(&rw->lock_object, 0))
504 "%s: spinning on %p held by %p",
505 __func__, rw, owner);
506 KTR_STATE1(KTR_SCHED, "thread",
507 sched_tdname(curthread), "spinning",
508 "lockname:\"%s\"", rw->lock_object.lo_name);
511 v = RW_READ_VALUE(rw);
512 owner = lv_rw_wowner(v);
513 } while (owner != NULL && TD_IS_RUNNING(owner));
514 KTR_STATE0(KTR_SCHED, "thread",
515 sched_tdname(curthread), "running");
519 if ((v & RW_LOCK_WRITE_SPINNER) && RW_READERS(v) == 0) {
520 MPASS(!__rw_can_read(td, v, false));
522 v = RW_READ_VALUE(rw);
525 if (spintries < rowner_retries) {
527 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
528 "spinning", "lockname:\"%s\"",
529 rw->lock_object.lo_name);
531 for (i = 0; i < rowner_loops; i += n) {
533 v = RW_READ_VALUE(rw);
534 if (!(v & RW_LOCK_READ))
539 if (__rw_can_read(td, v, false))
543 lda.spin_cnt += rowner_loops - i;
545 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
547 if (i < rowner_loops)
554 * Okay, now it's the hard case. Some other thread already
555 * has a write lock or there are write waiters present,
556 * acquire the turnstile lock so we can begin the process
559 ts = turnstile_trywait(&rw->lock_object);
562 * The lock might have been released while we spun, so
563 * recheck its state and restart the loop if needed.
565 v = RW_READ_VALUE(rw);
567 if (((v & RW_LOCK_WRITE_SPINNER) && RW_READERS(v) == 0) ||
568 __rw_can_read(td, v, false)) {
569 turnstile_cancel(ts);
573 owner = lv_rw_wowner(v);
575 #ifdef ADAPTIVE_RWLOCKS
577 * The current lock owner might have started executing
578 * on another CPU (or the lock could have changed
579 * owners) while we were waiting on the turnstile
580 * chain lock. If so, drop the turnstile lock and try
584 if (TD_IS_RUNNING(owner)) {
585 turnstile_cancel(ts);
592 * The lock is held in write mode or it already has waiters.
594 MPASS(!__rw_can_read(td, v, false));
597 * If the RW_LOCK_READ_WAITERS flag is already set, then
598 * we can go ahead and block. If it is not set then try
599 * to set it. If we fail to set it drop the turnstile
600 * lock and restart the loop.
602 if (!(v & RW_LOCK_READ_WAITERS)) {
603 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
604 v | RW_LOCK_READ_WAITERS))
606 if (LOCK_LOG_TEST(&rw->lock_object, 0))
607 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
612 * We were unable to acquire the lock and the read waiters
613 * flag is set, so we must block on the turnstile.
615 if (LOCK_LOG_TEST(&rw->lock_object, 0))
616 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
619 sleep_time -= lockstat_nsecs(&rw->lock_object);
621 MPASS(owner == rw_owner(rw));
622 turnstile_wait(ts, owner, TS_SHARED_QUEUE);
624 sleep_time += lockstat_nsecs(&rw->lock_object);
627 if (LOCK_LOG_TEST(&rw->lock_object, 0))
628 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
630 v = RW_READ_VALUE(rw);
632 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
633 if (__predict_true(!doing_lockprof))
637 all_time += lockstat_nsecs(&rw->lock_object);
639 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
640 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
641 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
643 /* Record only the loops spinning and not sleeping. */
644 if (lda.spin_cnt > sleep_cnt)
645 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
646 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
647 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
651 * TODO: acquire "owner of record" here. Here be turnstile dragons
652 * however. turnstiles don't like owners changing between calls to
653 * turnstile_wait() currently.
655 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
656 waittime, file, line, LOCKSTAT_READER);
660 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
667 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
668 !TD_IS_IDLETHREAD(td),
669 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
670 td, rw->lock_object.lo_name, file, line));
671 KASSERT(rw->rw_lock != RW_DESTROYED,
672 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
673 KASSERT(rw_wowner(rw) != td,
674 ("rw_rlock: wlock already held for %s @ %s:%d",
675 rw->lock_object.lo_name, file, line));
676 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
678 v = RW_READ_VALUE(rw);
679 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__acquire) ||
680 !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
681 __rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
683 lock_profile_obtain_lock_success(&rw->lock_object, 0, 0,
686 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
687 WITNESS_LOCK(&rw->lock_object, 0, file, line);
688 TD_LOCKS_INC(curthread);
692 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
697 __rw_rlock_int(rw LOCK_FILE_LINE_ARG);
701 __rw_try_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
705 if (SCHEDULER_STOPPED())
708 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
709 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
710 curthread, rw->lock_object.lo_name, file, line));
714 KASSERT(rw->rw_lock != RW_DESTROYED,
715 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
716 if (!(x & RW_LOCK_READ))
718 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
719 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
721 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
722 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
723 rw, 0, 0, file, line, LOCKSTAT_READER);
724 TD_LOCKS_INC(curthread);
725 curthread->td_rw_rlocks++;
730 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
735 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
740 return (__rw_try_rlock_int(rw LOCK_FILE_LINE_ARG));
743 static bool __always_inline
744 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
748 if (RW_READERS(*vp) > 1 || !(*vp & RW_LOCK_WAITERS)) {
749 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
750 *vp - RW_ONE_READER)) {
751 if (LOCK_LOG_TEST(&rw->lock_object, 0))
753 "%s: %p succeeded %p -> %p",
754 __func__, rw, (void *)*vp,
755 (void *)(*vp - RW_ONE_READER));
766 static void __noinline
767 __rw_runlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
768 LOCK_FILE_LINE_ARG_DEF)
770 struct turnstile *ts;
771 uintptr_t setv, queue;
773 if (SCHEDULER_STOPPED())
776 if (__rw_runlock_try(rw, td, &v))
780 * Ok, we know we have waiters and we think we are the
781 * last reader, so grab the turnstile lock.
783 turnstile_chain_lock(&rw->lock_object);
784 v = RW_READ_VALUE(rw);
786 if (__rw_runlock_try(rw, td, &v))
789 MPASS(v & RW_LOCK_WAITERS);
792 * Try to drop our lock leaving the lock in a unlocked
795 * If you wanted to do explicit lock handoff you'd have to
796 * do it here. You'd also want to use turnstile_signal()
797 * and you'd have to handle the race where a higher
798 * priority thread blocks on the write lock before the
799 * thread you wakeup actually runs and have the new thread
800 * "steal" the lock. For now it's a lot simpler to just
801 * wakeup all of the waiters.
803 * As above, if we fail, then another thread might have
804 * acquired a read lock, so drop the turnstile lock and
808 queue = TS_SHARED_QUEUE;
809 if (v & RW_LOCK_WRITE_WAITERS) {
810 queue = TS_EXCLUSIVE_QUEUE;
811 setv |= (v & RW_LOCK_READ_WAITERS);
813 setv |= (v & RW_LOCK_WRITE_SPINNER);
814 if (!atomic_fcmpset_rel_ptr(&rw->rw_lock, &v, setv))
816 if (LOCK_LOG_TEST(&rw->lock_object, 0))
817 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
821 * Ok. The lock is released and all that's left is to
822 * wake up the waiters. Note that the lock might not be
823 * free anymore, but in that case the writers will just
824 * block again if they run before the new lock holder(s)
827 ts = turnstile_lookup(&rw->lock_object);
829 turnstile_broadcast(ts, queue);
830 turnstile_unpend(ts);
834 turnstile_chain_unlock(&rw->lock_object);
836 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
840 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
845 KASSERT(rw->rw_lock != RW_DESTROYED,
846 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
847 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
848 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
849 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
852 v = RW_READ_VALUE(rw);
854 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__release) ||
855 !__rw_runlock_try(rw, td, &v)))
856 __rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
858 lock_profile_release_lock(&rw->lock_object);
860 TD_LOCKS_DEC(curthread);
864 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
869 _rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
872 #ifdef ADAPTIVE_RWLOCKS
874 rw_drop_critical(uintptr_t v, bool *in_critical, int *extra_work)
877 if (v & RW_LOCK_WRITE_SPINNER)
881 *in_critical = false;
886 #define rw_drop_critical(v, in_critical, extra_work) do { } while (0)
890 * This function is called when we are unable to obtain a write lock on the
891 * first try. This means that at least one other thread holds either a
892 * read or write lock.
895 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
899 struct turnstile *ts;
900 struct thread *owner;
901 #ifdef ADAPTIVE_RWLOCKS
904 enum { READERS, WRITER } sleep_reason = READERS;
905 bool in_critical = false;
908 #ifdef LOCK_PROFILING
909 uint64_t waittime = 0;
912 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
913 struct lock_delay_arg lda;
917 int64_t sleep_time = 0;
918 int64_t all_time = 0;
920 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
922 int doing_lockprof = 0;
926 tid = (uintptr_t)curthread;
930 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
931 while (v == RW_UNLOCKED) {
932 if (_rw_write_lock_fetch(rw, &v, tid))
937 all_time -= lockstat_nsecs(&rw->lock_object);
941 #ifdef LOCK_PROFILING
947 if (SCHEDULER_STOPPED())
950 #if defined(ADAPTIVE_RWLOCKS)
951 lock_delay_arg_init(&lda, &rw_delay);
952 #elif defined(KDTRACE_HOOKS)
953 lock_delay_arg_init(&lda, NULL);
955 if (__predict_false(v == RW_UNLOCKED))
956 v = RW_READ_VALUE(rw);
958 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
959 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
960 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
961 __func__, rw->lock_object.lo_name, file, line));
963 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
964 if (LOCK_LOG_TEST(&rw->lock_object, 0))
965 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
969 if (LOCK_LOG_TEST(&rw->lock_object, 0))
970 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
971 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
974 PMC_SOFT_CALL( , , lock, failed);
976 lock_profile_obtain_lock_failed(&rw->lock_object,
977 &contested, &waittime);
980 if (v == RW_UNLOCKED) {
981 if (_rw_write_lock_fetch(rw, &v, tid))
989 #ifdef ADAPTIVE_RWLOCKS
990 if (v == (RW_LOCK_READ | RW_LOCK_WRITE_SPINNER)) {
991 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
997 * If the lock is write locked and the owner is
998 * running on another CPU, spin until the owner stops
999 * running or the state of the lock changes.
1001 if (!(v & RW_LOCK_READ)) {
1002 rw_drop_critical(v, &in_critical, &extra_work);
1003 sleep_reason = WRITER;
1004 owner = lv_rw_wowner(v);
1005 if (!TD_IS_RUNNING(owner))
1007 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1008 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
1009 __func__, rw, owner);
1010 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1011 "spinning", "lockname:\"%s\"",
1012 rw->lock_object.lo_name);
1015 v = RW_READ_VALUE(rw);
1016 owner = lv_rw_wowner(v);
1017 } while (owner != NULL && TD_IS_RUNNING(owner));
1018 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1021 } else if (RW_READERS(v) > 0) {
1022 sleep_reason = READERS;
1023 if (spintries == rowner_retries)
1025 if (!(v & RW_LOCK_WRITE_SPINNER)) {
1031 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1032 v | RW_LOCK_WRITE_SPINNER)) {
1034 in_critical = false;
1040 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1041 "spinning", "lockname:\"%s\"",
1042 rw->lock_object.lo_name);
1044 for (i = 0; i < rowner_loops; i += n) {
1046 v = RW_READ_VALUE(rw);
1047 if (!(v & RW_LOCK_WRITE_SPINNER))
1049 if (!(v & RW_LOCK_READ))
1055 #ifdef KDTRACE_HOOKS
1058 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1060 if (i < rowner_loops)
1065 ts = turnstile_trywait(&rw->lock_object);
1066 v = RW_READ_VALUE(rw);
1068 owner = lv_rw_wowner(v);
1070 #ifdef ADAPTIVE_RWLOCKS
1072 * The current lock owner might have started executing
1073 * on another CPU (or the lock could have changed
1074 * owners) while we were waiting on the turnstile
1075 * chain lock. If so, drop the turnstile lock and try
1078 if (owner != NULL) {
1079 if (TD_IS_RUNNING(owner)) {
1080 turnstile_cancel(ts);
1081 rw_drop_critical(v, &in_critical, &extra_work);
1084 } else if (RW_READERS(v) > 0 && sleep_reason == WRITER) {
1085 turnstile_cancel(ts);
1086 rw_drop_critical(v, &in_critical, &extra_work);
1091 * Check for the waiters flags about this rwlock.
1092 * If the lock was released, without maintain any pending
1093 * waiters queue, simply try to acquire it.
1094 * If a pending waiters queue is present, claim the lock
1095 * ownership and maintain the pending queue.
1097 setv = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1098 if ((v & ~setv) == RW_UNLOCKED) {
1099 setv &= ~RW_LOCK_WRITE_SPINNER;
1100 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid | setv)) {
1102 turnstile_claim(ts);
1104 turnstile_cancel(ts);
1110 #ifdef ADAPTIVE_RWLOCKS
1112 if ((v & RW_LOCK_WRITE_SPINNER) ||
1113 !((v & RW_LOCK_WRITE_WAITERS))) {
1114 setv = v & ~RW_LOCK_WRITE_SPINNER;
1115 setv |= RW_LOCK_WRITE_WAITERS;
1116 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v, setv))
1120 in_critical = false;
1125 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1126 * set it. If we fail to set it, then loop back and try
1129 if (!(v & RW_LOCK_WRITE_WAITERS)) {
1130 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1131 v | RW_LOCK_WRITE_WAITERS))
1133 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1134 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1137 #ifdef ADAPTIVE_RWLOCKS
1141 * We were unable to acquire the lock and the write waiters
1142 * flag is set, so we must block on the turnstile.
1144 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1145 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1147 #ifdef KDTRACE_HOOKS
1148 sleep_time -= lockstat_nsecs(&rw->lock_object);
1150 MPASS(owner == rw_owner(rw));
1151 turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
1152 #ifdef KDTRACE_HOOKS
1153 sleep_time += lockstat_nsecs(&rw->lock_object);
1156 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1157 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1159 #ifdef ADAPTIVE_RWLOCKS
1162 v = RW_READ_VALUE(rw);
1164 if (__predict_true(!extra_work))
1166 #ifdef ADAPTIVE_RWLOCKS
1170 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1171 if (__predict_true(!doing_lockprof))
1174 #ifdef KDTRACE_HOOKS
1175 all_time += lockstat_nsecs(&rw->lock_object);
1177 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1178 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1179 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1181 /* Record only the loops spinning and not sleeping. */
1182 if (lda.spin_cnt > sleep_cnt)
1183 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1184 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1185 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1188 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1189 waittime, file, line, LOCKSTAT_WRITER);
1193 * This function is called if lockstat is active or the first try at releasing
1194 * a write lock failed. The latter means that the lock is recursed or one of
1195 * the 2 waiter bits must be set indicating that at least one thread is waiting
1199 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1202 struct turnstile *ts;
1203 uintptr_t tid, setv;
1206 tid = (uintptr_t)curthread;
1207 if (SCHEDULER_STOPPED())
1211 if (__predict_false(v == tid))
1212 v = RW_READ_VALUE(rw);
1214 if (v & RW_LOCK_WRITER_RECURSED) {
1215 if (--(rw->rw_recurse) == 0)
1216 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1217 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1218 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1222 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1223 if (v == tid && _rw_write_unlock(rw, tid))
1226 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1227 ("%s: neither of the waiter flags are set", __func__));
1229 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1230 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1232 turnstile_chain_lock(&rw->lock_object);
1235 * Use the same algo as sx locks for now. Prefer waking up shared
1236 * waiters if we have any over writers. This is probably not ideal.
1238 * 'v' is the value we are going to write back to rw_lock. If we
1239 * have waiters on both queues, we need to preserve the state of
1240 * the waiter flag for the queue we don't wake up. For now this is
1241 * hardcoded for the algorithm mentioned above.
1243 * In the case of both readers and writers waiting we wakeup the
1244 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1245 * new writer comes in before a reader it will claim the lock up
1246 * above. There is probably a potential priority inversion in
1247 * there that could be worked around either by waking both queues
1248 * of waiters or doing some complicated lock handoff gymnastics.
1251 v = RW_READ_VALUE(rw);
1252 queue = TS_SHARED_QUEUE;
1253 if (v & RW_LOCK_WRITE_WAITERS) {
1254 queue = TS_EXCLUSIVE_QUEUE;
1255 setv |= (v & RW_LOCK_READ_WAITERS);
1257 atomic_store_rel_ptr(&rw->rw_lock, setv);
1259 /* Wake up all waiters for the specific queue. */
1260 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1261 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1262 queue == TS_SHARED_QUEUE ? "read" : "write");
1264 ts = turnstile_lookup(&rw->lock_object);
1266 turnstile_broadcast(ts, queue);
1267 turnstile_unpend(ts);
1268 turnstile_chain_unlock(&rw->lock_object);
1272 * Attempt to do a non-blocking upgrade from a read lock to a write
1273 * lock. This will only succeed if this thread holds a single read
1274 * lock. Returns true if the upgrade succeeded and false otherwise.
1277 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1279 uintptr_t v, setv, tid;
1280 struct turnstile *ts;
1283 if (SCHEDULER_STOPPED())
1286 KASSERT(rw->rw_lock != RW_DESTROYED,
1287 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1288 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1291 * Attempt to switch from one reader to a writer. If there
1292 * are any write waiters, then we will have to lock the
1293 * turnstile first to prevent races with another writer
1294 * calling turnstile_wait() before we have claimed this
1295 * turnstile. So, do the simple case of no waiters first.
1297 tid = (uintptr_t)curthread;
1299 v = RW_READ_VALUE(rw);
1301 if (RW_READERS(v) > 1)
1303 if (!(v & RW_LOCK_WAITERS)) {
1304 success = atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid);
1311 * Ok, we think we have waiters, so lock the turnstile.
1313 ts = turnstile_trywait(&rw->lock_object);
1314 v = RW_READ_VALUE(rw);
1316 if (RW_READERS(v) > 1) {
1317 turnstile_cancel(ts);
1321 * Try to switch from one reader to a writer again. This time
1322 * we honor the current state of the waiters flags.
1323 * If we obtain the lock with the flags set, then claim
1324 * ownership of the turnstile.
1326 setv = tid | (v & RW_LOCK_WAITERS);
1327 success = atomic_fcmpset_ptr(&rw->rw_lock, &v, setv);
1329 if (v & RW_LOCK_WAITERS)
1330 turnstile_claim(ts);
1332 turnstile_cancel(ts);
1337 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1339 curthread->td_rw_rlocks--;
1340 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1342 LOCKSTAT_RECORD0(rw__upgrade, rw);
1348 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1353 return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1357 * Downgrade a write lock into a single read lock.
1360 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1362 struct turnstile *ts;
1366 if (SCHEDULER_STOPPED())
1369 KASSERT(rw->rw_lock != RW_DESTROYED,
1370 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1371 __rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1373 if (rw_recursed(rw))
1374 panic("downgrade of a recursed lock");
1377 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1380 * Convert from a writer to a single reader. First we handle
1381 * the easy case with no waiters. If there are any waiters, we
1382 * lock the turnstile and "disown" the lock.
1384 tid = (uintptr_t)curthread;
1385 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1389 * Ok, we think we have waiters, so lock the turnstile so we can
1390 * read the waiter flags without any races.
1392 turnstile_chain_lock(&rw->lock_object);
1393 v = rw->rw_lock & RW_LOCK_WAITERS;
1394 rwait = v & RW_LOCK_READ_WAITERS;
1395 wwait = v & RW_LOCK_WRITE_WAITERS;
1396 MPASS(rwait | wwait);
1399 * Downgrade from a write lock while preserving waiters flag
1400 * and give up ownership of the turnstile.
1402 ts = turnstile_lookup(&rw->lock_object);
1405 v &= ~RW_LOCK_READ_WAITERS;
1406 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1408 * Wake other readers if there are no writers pending. Otherwise they
1409 * won't be able to acquire the lock anyway.
1411 if (rwait && !wwait) {
1412 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1413 turnstile_unpend(ts);
1415 turnstile_disown(ts);
1416 turnstile_chain_unlock(&rw->lock_object);
1418 curthread->td_rw_rlocks++;
1419 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1420 LOCKSTAT_RECORD0(rw__downgrade, rw);
1424 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1429 __rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1432 #ifdef INVARIANT_SUPPORT
1438 * In the non-WITNESS case, rw_assert() can only detect that at least
1439 * *some* thread owns an rlock, but it cannot guarantee that *this*
1440 * thread owns an rlock.
1443 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1445 const struct rwlock *rw;
1447 if (SCHEDULER_STOPPED())
1454 case RA_LOCKED | RA_RECURSED:
1455 case RA_LOCKED | RA_NOTRECURSED:
1457 case RA_RLOCKED | RA_RECURSED:
1458 case RA_RLOCKED | RA_NOTRECURSED:
1460 witness_assert(&rw->lock_object, what, file, line);
1463 * If some other thread has a write lock or we have one
1464 * and are asserting a read lock, fail. Also, if no one
1465 * has a lock at all, fail.
1467 if (rw->rw_lock == RW_UNLOCKED ||
1468 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1469 rw_wowner(rw) != curthread)))
1470 panic("Lock %s not %slocked @ %s:%d\n",
1471 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1472 "read " : "", file, line);
1474 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1475 if (rw_recursed(rw)) {
1476 if (what & RA_NOTRECURSED)
1477 panic("Lock %s recursed @ %s:%d\n",
1478 rw->lock_object.lo_name, file,
1480 } else if (what & RA_RECURSED)
1481 panic("Lock %s not recursed @ %s:%d\n",
1482 rw->lock_object.lo_name, file, line);
1487 case RA_WLOCKED | RA_RECURSED:
1488 case RA_WLOCKED | RA_NOTRECURSED:
1489 if (rw_wowner(rw) != curthread)
1490 panic("Lock %s not exclusively locked @ %s:%d\n",
1491 rw->lock_object.lo_name, file, line);
1492 if (rw_recursed(rw)) {
1493 if (what & RA_NOTRECURSED)
1494 panic("Lock %s recursed @ %s:%d\n",
1495 rw->lock_object.lo_name, file, line);
1496 } else if (what & RA_RECURSED)
1497 panic("Lock %s not recursed @ %s:%d\n",
1498 rw->lock_object.lo_name, file, line);
1502 witness_assert(&rw->lock_object, what, file, line);
1505 * If we hold a write lock fail. We can't reliably check
1506 * to see if we hold a read lock or not.
1508 if (rw_wowner(rw) == curthread)
1509 panic("Lock %s exclusively locked @ %s:%d\n",
1510 rw->lock_object.lo_name, file, line);
1514 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1518 #endif /* INVARIANT_SUPPORT */
1522 db_show_rwlock(const struct lock_object *lock)
1524 const struct rwlock *rw;
1527 rw = (const struct rwlock *)lock;
1529 db_printf(" state: ");
1530 if (rw->rw_lock == RW_UNLOCKED)
1531 db_printf("UNLOCKED\n");
1532 else if (rw->rw_lock == RW_DESTROYED) {
1533 db_printf("DESTROYED\n");
1535 } else if (rw->rw_lock & RW_LOCK_READ)
1536 db_printf("RLOCK: %ju locks\n",
1537 (uintmax_t)(RW_READERS(rw->rw_lock)));
1540 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1541 td->td_tid, td->td_proc->p_pid, td->td_name);
1542 if (rw_recursed(rw))
1543 db_printf(" recursed: %u\n", rw->rw_recurse);
1545 db_printf(" waiters: ");
1546 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1547 case RW_LOCK_READ_WAITERS:
1548 db_printf("readers\n");
1550 case RW_LOCK_WRITE_WAITERS:
1551 db_printf("writers\n");
1553 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1554 db_printf("readers and writers\n");
1557 db_printf("none\n");