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");
513 } else if (spintries < rowner_retries) {
515 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
516 "spinning", "lockname:\"%s\"",
517 rw->lock_object.lo_name);
518 for (i = 0; i < rowner_loops; i += n) {
521 v = RW_READ_VALUE(rw);
522 if ((v & RW_LOCK_READ) == 0 || __rw_can_read(td, v, false))
526 lda.spin_cnt += rowner_loops - i;
528 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
530 if (i < rowner_loops)
536 * Okay, now it's the hard case. Some other thread already
537 * has a write lock or there are write waiters present,
538 * acquire the turnstile lock so we can begin the process
541 ts = turnstile_trywait(&rw->lock_object);
544 * The lock might have been released while we spun, so
545 * recheck its state and restart the loop if needed.
547 v = RW_READ_VALUE(rw);
549 if (__rw_can_read(td, v, false)) {
550 turnstile_cancel(ts);
554 owner = lv_rw_wowner(v);
556 #ifdef ADAPTIVE_RWLOCKS
558 * The current lock owner might have started executing
559 * on another CPU (or the lock could have changed
560 * owners) while we were waiting on the turnstile
561 * chain lock. If so, drop the turnstile lock and try
565 if (TD_IS_RUNNING(owner)) {
566 turnstile_cancel(ts);
573 * The lock is held in write mode or it already has waiters.
575 MPASS(!__rw_can_read(td, v, false));
578 * If the RW_LOCK_READ_WAITERS flag is already set, then
579 * we can go ahead and block. If it is not set then try
580 * to set it. If we fail to set it drop the turnstile
581 * lock and restart the loop.
583 if (!(v & RW_LOCK_READ_WAITERS)) {
584 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
585 v | RW_LOCK_READ_WAITERS))
587 if (LOCK_LOG_TEST(&rw->lock_object, 0))
588 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
593 * We were unable to acquire the lock and the read waiters
594 * flag is set, so we must block on the turnstile.
596 if (LOCK_LOG_TEST(&rw->lock_object, 0))
597 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
600 sleep_time -= lockstat_nsecs(&rw->lock_object);
602 MPASS(owner == rw_owner(rw));
603 turnstile_wait(ts, owner, TS_SHARED_QUEUE);
605 sleep_time += lockstat_nsecs(&rw->lock_object);
608 if (LOCK_LOG_TEST(&rw->lock_object, 0))
609 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
611 v = RW_READ_VALUE(rw);
613 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
614 if (__predict_true(!doing_lockprof))
618 all_time += lockstat_nsecs(&rw->lock_object);
620 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
621 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
622 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
624 /* Record only the loops spinning and not sleeping. */
625 if (lda.spin_cnt > sleep_cnt)
626 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
627 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
628 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
632 * TODO: acquire "owner of record" here. Here be turnstile dragons
633 * however. turnstiles don't like owners changing between calls to
634 * turnstile_wait() currently.
636 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
637 waittime, file, line, LOCKSTAT_READER);
641 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
648 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
649 !TD_IS_IDLETHREAD(td),
650 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
651 td, rw->lock_object.lo_name, file, line));
652 KASSERT(rw->rw_lock != RW_DESTROYED,
653 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
654 KASSERT(rw_wowner(rw) != td,
655 ("rw_rlock: wlock already held for %s @ %s:%d",
656 rw->lock_object.lo_name, file, line));
657 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
659 v = RW_READ_VALUE(rw);
660 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__acquire) ||
661 !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
662 __rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
664 lock_profile_obtain_lock_success(&rw->lock_object, 0, 0,
667 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
668 WITNESS_LOCK(&rw->lock_object, 0, file, line);
669 TD_LOCKS_INC(curthread);
673 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
678 __rw_rlock_int(rw LOCK_FILE_LINE_ARG);
682 __rw_try_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
686 if (SCHEDULER_STOPPED())
689 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
690 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
691 curthread, rw->lock_object.lo_name, file, line));
695 KASSERT(rw->rw_lock != RW_DESTROYED,
696 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
697 if (!(x & RW_LOCK_READ))
699 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
700 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
702 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
703 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
704 rw, 0, 0, file, line, LOCKSTAT_READER);
705 TD_LOCKS_INC(curthread);
706 curthread->td_rw_rlocks++;
711 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
716 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
721 return (__rw_try_rlock_int(rw LOCK_FILE_LINE_ARG));
724 static bool __always_inline
725 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
730 * See if there is more than one read lock held. If so,
731 * just drop one and return.
733 if (RW_READERS(*vp) > 1) {
734 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
735 *vp - RW_ONE_READER)) {
736 if (LOCK_LOG_TEST(&rw->lock_object, 0))
738 "%s: %p succeeded %p -> %p",
739 __func__, rw, (void *)*vp,
740 (void *)(*vp - RW_ONE_READER));
747 * If there aren't any waiters for a write lock, then try
748 * to drop it quickly.
750 if (!(*vp & RW_LOCK_WAITERS)) {
751 MPASS((*vp & ~RW_LOCK_WRITE_SPINNER) ==
753 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
755 if (LOCK_LOG_TEST(&rw->lock_object, 0))
756 CTR2(KTR_LOCK, "%s: %p last succeeded",
768 static void __noinline
769 __rw_runlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
770 LOCK_FILE_LINE_ARG_DEF)
772 struct turnstile *ts;
773 uintptr_t setv, queue;
775 if (SCHEDULER_STOPPED())
778 if (__rw_runlock_try(rw, td, &v))
782 * Ok, we know we have waiters and we think we are the
783 * last reader, so grab the turnstile lock.
785 turnstile_chain_lock(&rw->lock_object);
786 v = RW_READ_VALUE(rw);
788 if (__rw_runlock_try(rw, td, &v))
791 v &= (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
792 MPASS(v & RW_LOCK_WAITERS);
795 * Try to drop our lock leaving the lock in a unlocked
798 * If you wanted to do explicit lock handoff you'd have to
799 * do it here. You'd also want to use turnstile_signal()
800 * and you'd have to handle the race where a higher
801 * priority thread blocks on the write lock before the
802 * thread you wakeup actually runs and have the new thread
803 * "steal" the lock. For now it's a lot simpler to just
804 * wakeup all of the waiters.
806 * As above, if we fail, then another thread might have
807 * acquired a read lock, so drop the turnstile lock and
811 queue = TS_SHARED_QUEUE;
812 if (v & RW_LOCK_WRITE_WAITERS) {
813 queue = TS_EXCLUSIVE_QUEUE;
814 setv |= (v & RW_LOCK_READ_WAITERS);
816 v |= RW_READERS_LOCK(1);
817 if (!atomic_fcmpset_rel_ptr(&rw->rw_lock, &v, setv))
819 if (LOCK_LOG_TEST(&rw->lock_object, 0))
820 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
824 * Ok. The lock is released and all that's left is to
825 * wake up the waiters. Note that the lock might not be
826 * free anymore, but in that case the writers will just
827 * block again if they run before the new lock holder(s)
830 ts = turnstile_lookup(&rw->lock_object);
832 turnstile_broadcast(ts, queue);
833 turnstile_unpend(ts, TS_SHARED_LOCK);
837 turnstile_chain_unlock(&rw->lock_object);
839 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
843 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
848 KASSERT(rw->rw_lock != RW_DESTROYED,
849 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
850 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
851 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
852 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
855 v = RW_READ_VALUE(rw);
857 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__release) ||
858 !__rw_runlock_try(rw, td, &v)))
859 __rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
861 lock_profile_release_lock(&rw->lock_object);
863 TD_LOCKS_DEC(curthread);
867 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
872 _rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
876 * This function is called when we are unable to obtain a write lock on the
877 * first try. This means that at least one other thread holds either a
878 * read or write lock.
881 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
885 struct turnstile *ts;
886 struct thread *owner;
887 #ifdef ADAPTIVE_RWLOCKS
890 enum { READERS, WRITER } sleep_reason;
893 #ifdef LOCK_PROFILING
894 uint64_t waittime = 0;
897 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
898 struct lock_delay_arg lda;
902 int64_t sleep_time = 0;
903 int64_t all_time = 0;
905 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
907 int doing_lockprof = 0;
910 tid = (uintptr_t)curthread;
914 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
915 while (v == RW_UNLOCKED) {
916 if (_rw_write_lock_fetch(rw, &v, tid))
920 all_time -= lockstat_nsecs(&rw->lock_object);
924 #ifdef LOCK_PROFILING
929 if (SCHEDULER_STOPPED())
932 #if defined(ADAPTIVE_RWLOCKS)
933 lock_delay_arg_init(&lda, &rw_delay);
934 #elif defined(KDTRACE_HOOKS)
935 lock_delay_arg_init(&lda, NULL);
937 if (__predict_false(v == RW_UNLOCKED))
938 v = RW_READ_VALUE(rw);
940 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
941 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
942 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
943 __func__, rw->lock_object.lo_name, file, line));
945 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
946 if (LOCK_LOG_TEST(&rw->lock_object, 0))
947 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
951 if (LOCK_LOG_TEST(&rw->lock_object, 0))
952 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
953 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
956 PMC_SOFT_CALL( , , lock, failed);
958 lock_profile_obtain_lock_failed(&rw->lock_object,
959 &contested, &waittime);
962 if (v == RW_UNLOCKED) {
963 if (_rw_write_lock_fetch(rw, &v, tid))
971 #ifdef ADAPTIVE_RWLOCKS
973 * If the lock is write locked and the owner is
974 * running on another CPU, spin until the owner stops
975 * running or the state of the lock changes.
977 if (!(v & RW_LOCK_READ)) {
978 sleep_reason = WRITER;
979 owner = lv_rw_wowner(v);
980 if (!TD_IS_RUNNING(owner))
982 if (LOCK_LOG_TEST(&rw->lock_object, 0))
983 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
984 __func__, rw, owner);
985 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
986 "spinning", "lockname:\"%s\"",
987 rw->lock_object.lo_name);
990 v = RW_READ_VALUE(rw);
991 owner = lv_rw_wowner(v);
992 } while (owner != NULL && TD_IS_RUNNING(owner));
993 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
996 } else if (RW_READERS(v) > 0) {
997 sleep_reason = READERS;
998 if (spintries == rowner_retries)
1000 if (!(v & RW_LOCK_WRITE_SPINNER)) {
1001 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1002 v | RW_LOCK_WRITE_SPINNER)) {
1007 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1008 "spinning", "lockname:\"%s\"",
1009 rw->lock_object.lo_name);
1010 for (i = 0; i < rowner_loops; i += n) {
1013 v = RW_READ_VALUE(rw);
1014 if ((v & RW_LOCK_WRITE_SPINNER) == 0)
1017 #ifdef KDTRACE_HOOKS
1020 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1022 if (i < rowner_loops)
1027 ts = turnstile_trywait(&rw->lock_object);
1028 v = RW_READ_VALUE(rw);
1030 owner = lv_rw_wowner(v);
1032 #ifdef ADAPTIVE_RWLOCKS
1034 * The current lock owner might have started executing
1035 * on another CPU (or the lock could have changed
1036 * owners) while we were waiting on the turnstile
1037 * chain lock. If so, drop the turnstile lock and try
1040 if (owner != NULL) {
1041 if (TD_IS_RUNNING(owner)) {
1042 turnstile_cancel(ts);
1045 } else if (RW_READERS(v) > 0 && sleep_reason == WRITER) {
1046 turnstile_cancel(ts);
1051 * Check for the waiters flags about this rwlock.
1052 * If the lock was released, without maintain any pending
1053 * waiters queue, simply try to acquire it.
1054 * If a pending waiters queue is present, claim the lock
1055 * ownership and maintain the pending queue.
1057 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1058 if ((v & ~x) == RW_UNLOCKED) {
1059 x &= ~RW_LOCK_WRITE_SPINNER;
1060 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid | x)) {
1062 turnstile_claim(ts);
1064 turnstile_cancel(ts);
1070 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1071 * set it. If we fail to set it, then loop back and try
1074 if (!(v & RW_LOCK_WRITE_WAITERS)) {
1075 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1076 v | RW_LOCK_WRITE_WAITERS))
1078 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1079 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1083 * We were unable to acquire the lock and the write waiters
1084 * flag is set, so we must block on the turnstile.
1086 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1087 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1089 #ifdef KDTRACE_HOOKS
1090 sleep_time -= lockstat_nsecs(&rw->lock_object);
1092 MPASS(owner == rw_owner(rw));
1093 turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
1094 #ifdef KDTRACE_HOOKS
1095 sleep_time += lockstat_nsecs(&rw->lock_object);
1098 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1099 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1101 #ifdef ADAPTIVE_RWLOCKS
1104 v = RW_READ_VALUE(rw);
1106 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1107 if (__predict_true(!doing_lockprof))
1110 #ifdef KDTRACE_HOOKS
1111 all_time += lockstat_nsecs(&rw->lock_object);
1113 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1114 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1115 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1117 /* Record only the loops spinning and not sleeping. */
1118 if (lda.spin_cnt > sleep_cnt)
1119 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1120 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1121 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1124 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1125 waittime, file, line, LOCKSTAT_WRITER);
1129 * This function is called if lockstat is active or the first try at releasing
1130 * a write lock failed. The latter means that the lock is recursed or one of
1131 * the 2 waiter bits must be set indicating that at least one thread is waiting
1135 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1138 struct turnstile *ts;
1139 uintptr_t tid, setv;
1142 tid = (uintptr_t)curthread;
1143 if (SCHEDULER_STOPPED())
1147 if (__predict_false(v == tid))
1148 v = RW_READ_VALUE(rw);
1150 if (v & RW_LOCK_WRITER_RECURSED) {
1151 if (--(rw->rw_recurse) == 0)
1152 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1153 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1154 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1158 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1159 if (v == tid && _rw_write_unlock(rw, tid))
1162 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1163 ("%s: neither of the waiter flags are set", __func__));
1165 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1166 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1168 turnstile_chain_lock(&rw->lock_object);
1171 * Use the same algo as sx locks for now. Prefer waking up shared
1172 * waiters if we have any over writers. This is probably not ideal.
1174 * 'v' is the value we are going to write back to rw_lock. If we
1175 * have waiters on both queues, we need to preserve the state of
1176 * the waiter flag for the queue we don't wake up. For now this is
1177 * hardcoded for the algorithm mentioned above.
1179 * In the case of both readers and writers waiting we wakeup the
1180 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1181 * new writer comes in before a reader it will claim the lock up
1182 * above. There is probably a potential priority inversion in
1183 * there that could be worked around either by waking both queues
1184 * of waiters or doing some complicated lock handoff gymnastics.
1187 v = RW_READ_VALUE(rw);
1188 queue = TS_SHARED_QUEUE;
1189 if (v & RW_LOCK_WRITE_WAITERS) {
1190 queue = TS_EXCLUSIVE_QUEUE;
1191 setv |= (v & RW_LOCK_READ_WAITERS);
1193 atomic_store_rel_ptr(&rw->rw_lock, setv);
1195 /* Wake up all waiters for the specific queue. */
1196 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1197 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1198 queue == TS_SHARED_QUEUE ? "read" : "write");
1200 ts = turnstile_lookup(&rw->lock_object);
1202 turnstile_broadcast(ts, queue);
1203 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1204 turnstile_chain_unlock(&rw->lock_object);
1208 * Attempt to do a non-blocking upgrade from a read lock to a write
1209 * lock. This will only succeed if this thread holds a single read
1210 * lock. Returns true if the upgrade succeeded and false otherwise.
1213 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1215 uintptr_t v, setv, tid;
1216 struct turnstile *ts;
1219 if (SCHEDULER_STOPPED())
1222 KASSERT(rw->rw_lock != RW_DESTROYED,
1223 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1224 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1227 * Attempt to switch from one reader to a writer. If there
1228 * are any write waiters, then we will have to lock the
1229 * turnstile first to prevent races with another writer
1230 * calling turnstile_wait() before we have claimed this
1231 * turnstile. So, do the simple case of no waiters first.
1233 tid = (uintptr_t)curthread;
1235 v = RW_READ_VALUE(rw);
1237 if (RW_READERS(v) > 1)
1239 if (!(v & RW_LOCK_WAITERS)) {
1240 success = atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid);
1247 * Ok, we think we have waiters, so lock the turnstile.
1249 ts = turnstile_trywait(&rw->lock_object);
1250 v = RW_READ_VALUE(rw);
1252 if (RW_READERS(v) > 1) {
1253 turnstile_cancel(ts);
1257 * Try to switch from one reader to a writer again. This time
1258 * we honor the current state of the waiters flags.
1259 * If we obtain the lock with the flags set, then claim
1260 * ownership of the turnstile.
1262 setv = tid | (v & RW_LOCK_WAITERS);
1263 success = atomic_fcmpset_ptr(&rw->rw_lock, &v, setv);
1265 if (v & RW_LOCK_WAITERS)
1266 turnstile_claim(ts);
1268 turnstile_cancel(ts);
1273 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1275 curthread->td_rw_rlocks--;
1276 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1278 LOCKSTAT_RECORD0(rw__upgrade, rw);
1284 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1289 return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1293 * Downgrade a write lock into a single read lock.
1296 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1298 struct turnstile *ts;
1302 if (SCHEDULER_STOPPED())
1305 KASSERT(rw->rw_lock != RW_DESTROYED,
1306 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1307 __rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1309 if (rw_recursed(rw))
1310 panic("downgrade of a recursed lock");
1313 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1316 * Convert from a writer to a single reader. First we handle
1317 * the easy case with no waiters. If there are any waiters, we
1318 * lock the turnstile and "disown" the lock.
1320 tid = (uintptr_t)curthread;
1321 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1325 * Ok, we think we have waiters, so lock the turnstile so we can
1326 * read the waiter flags without any races.
1328 turnstile_chain_lock(&rw->lock_object);
1329 v = rw->rw_lock & RW_LOCK_WAITERS;
1330 rwait = v & RW_LOCK_READ_WAITERS;
1331 wwait = v & RW_LOCK_WRITE_WAITERS;
1332 MPASS(rwait | wwait);
1335 * Downgrade from a write lock while preserving waiters flag
1336 * and give up ownership of the turnstile.
1338 ts = turnstile_lookup(&rw->lock_object);
1341 v &= ~RW_LOCK_READ_WAITERS;
1342 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1344 * Wake other readers if there are no writers pending. Otherwise they
1345 * won't be able to acquire the lock anyway.
1347 if (rwait && !wwait) {
1348 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1349 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1351 turnstile_disown(ts);
1352 turnstile_chain_unlock(&rw->lock_object);
1354 curthread->td_rw_rlocks++;
1355 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1356 LOCKSTAT_RECORD0(rw__downgrade, rw);
1360 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1365 __rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1368 #ifdef INVARIANT_SUPPORT
1374 * In the non-WITNESS case, rw_assert() can only detect that at least
1375 * *some* thread owns an rlock, but it cannot guarantee that *this*
1376 * thread owns an rlock.
1379 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1381 const struct rwlock *rw;
1383 if (panicstr != NULL)
1390 case RA_LOCKED | RA_RECURSED:
1391 case RA_LOCKED | RA_NOTRECURSED:
1393 case RA_RLOCKED | RA_RECURSED:
1394 case RA_RLOCKED | RA_NOTRECURSED:
1396 witness_assert(&rw->lock_object, what, file, line);
1399 * If some other thread has a write lock or we have one
1400 * and are asserting a read lock, fail. Also, if no one
1401 * has a lock at all, fail.
1403 if (rw->rw_lock == RW_UNLOCKED ||
1404 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1405 rw_wowner(rw) != curthread)))
1406 panic("Lock %s not %slocked @ %s:%d\n",
1407 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1408 "read " : "", file, line);
1410 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1411 if (rw_recursed(rw)) {
1412 if (what & RA_NOTRECURSED)
1413 panic("Lock %s recursed @ %s:%d\n",
1414 rw->lock_object.lo_name, file,
1416 } else if (what & RA_RECURSED)
1417 panic("Lock %s not recursed @ %s:%d\n",
1418 rw->lock_object.lo_name, file, line);
1423 case RA_WLOCKED | RA_RECURSED:
1424 case RA_WLOCKED | RA_NOTRECURSED:
1425 if (rw_wowner(rw) != curthread)
1426 panic("Lock %s not exclusively locked @ %s:%d\n",
1427 rw->lock_object.lo_name, file, line);
1428 if (rw_recursed(rw)) {
1429 if (what & RA_NOTRECURSED)
1430 panic("Lock %s recursed @ %s:%d\n",
1431 rw->lock_object.lo_name, file, line);
1432 } else if (what & RA_RECURSED)
1433 panic("Lock %s not recursed @ %s:%d\n",
1434 rw->lock_object.lo_name, file, line);
1438 witness_assert(&rw->lock_object, what, file, line);
1441 * If we hold a write lock fail. We can't reliably check
1442 * to see if we hold a read lock or not.
1444 if (rw_wowner(rw) == curthread)
1445 panic("Lock %s exclusively locked @ %s:%d\n",
1446 rw->lock_object.lo_name, file, line);
1450 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1454 #endif /* INVARIANT_SUPPORT */
1458 db_show_rwlock(const struct lock_object *lock)
1460 const struct rwlock *rw;
1463 rw = (const struct rwlock *)lock;
1465 db_printf(" state: ");
1466 if (rw->rw_lock == RW_UNLOCKED)
1467 db_printf("UNLOCKED\n");
1468 else if (rw->rw_lock == RW_DESTROYED) {
1469 db_printf("DESTROYED\n");
1471 } else if (rw->rw_lock & RW_LOCK_READ)
1472 db_printf("RLOCK: %ju locks\n",
1473 (uintmax_t)(RW_READERS(rw->rw_lock)));
1476 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1477 td->td_tid, td->td_proc->p_pid, td->td_name);
1478 if (rw_recursed(rw))
1479 db_printf(" recursed: %u\n", rw->rw_recurse);
1481 db_printf(" waiters: ");
1482 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1483 case RW_LOCK_READ_WAITERS:
1484 db_printf("readers\n");
1486 case RW_LOCK_WRITE_WAITERS:
1487 db_printf("writers\n");
1489 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1490 db_printf("readers and writers\n");
1493 db_printf("none\n");