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 static int __read_frequently rowner_retries;
98 static int __read_frequently rowner_loops;
99 static SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL,
101 SYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
102 SYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
104 static struct lock_delay_config __read_frequently rw_delay;
106 SYSCTL_INT(_debug_rwlock, OID_AUTO, delay_base, CTLFLAG_RW, &rw_delay.base,
108 SYSCTL_INT(_debug_rwlock, OID_AUTO, delay_max, CTLFLAG_RW, &rw_delay.max,
112 rw_lock_delay_init(void *arg __unused)
115 lock_delay_default_init(&rw_delay);
117 rowner_loops = max(10000, rw_delay.max);
119 LOCK_DELAY_SYSINIT(rw_lock_delay_init);
123 * Return a pointer to the owning thread if the lock is write-locked or
124 * NULL if the lock is unlocked or read-locked.
127 #define lv_rw_wowner(v) \
128 ((v) & RW_LOCK_READ ? NULL : \
129 (struct thread *)RW_OWNER((v)))
131 #define rw_wowner(rw) lv_rw_wowner(RW_READ_VALUE(rw))
134 * Returns if a write owner is recursed. Write ownership is not assured
135 * here and should be previously checked.
137 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
140 * Return true if curthread helds the lock.
142 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
145 * Return a pointer to the owning thread for this lock who should receive
146 * any priority lent by threads that block on this lock. Currently this
147 * is identical to rw_wowner().
149 #define rw_owner(rw) rw_wowner(rw)
152 #define __rw_assert(c, what, file, line)
156 assert_rw(const struct lock_object *lock, int what)
159 rw_assert((const struct rwlock *)lock, what);
163 lock_rw(struct lock_object *lock, uintptr_t how)
167 rw = (struct rwlock *)lock;
175 unlock_rw(struct lock_object *lock)
179 rw = (struct rwlock *)lock;
180 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
181 if (rw->rw_lock & RW_LOCK_READ) {
192 owner_rw(const struct lock_object *lock, struct thread **owner)
194 const struct rwlock *rw = (const struct rwlock *)lock;
195 uintptr_t x = rw->rw_lock;
197 *owner = rw_wowner(rw);
198 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
204 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
211 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
212 RW_RECURSE | RW_NEW)) == 0);
213 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
214 ("%s: rw_lock not aligned for %s: %p", __func__, name,
217 flags = LO_UPGRADABLE;
220 if (opts & RW_NOPROFILE)
221 flags |= LO_NOPROFILE;
222 if (!(opts & RW_NOWITNESS))
224 if (opts & RW_RECURSE)
225 flags |= LO_RECURSABLE;
231 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
232 rw->rw_lock = RW_UNLOCKED;
237 _rw_destroy(volatile uintptr_t *c)
243 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
244 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
245 rw->rw_lock = RW_DESTROYED;
246 lock_destroy(&rw->lock_object);
250 rw_sysinit(void *arg)
252 struct rw_args *args;
255 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
260 _rw_wowned(const volatile uintptr_t *c)
263 return (rw_wowner(rwlock2rw(c)) == curthread);
267 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
274 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
275 !TD_IS_IDLETHREAD(curthread),
276 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
277 curthread, rw->lock_object.lo_name, file, line));
278 KASSERT(rw->rw_lock != RW_DESTROYED,
279 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
280 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
282 tid = (uintptr_t)curthread;
284 if (!_rw_write_lock_fetch(rw, &v, tid))
285 _rw_wlock_hard(rw, v, file, line);
287 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
288 0, 0, file, line, LOCKSTAT_WRITER);
290 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
291 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
292 TD_LOCKS_INC(curthread);
296 __rw_try_wlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
305 if (SCHEDULER_STOPPED_TD(td))
308 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
309 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
310 curthread, rw->lock_object.lo_name, file, line));
311 KASSERT(rw->rw_lock != RW_DESTROYED,
312 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
318 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
320 if (v == RW_UNLOCKED)
322 if (v == tid && (rw->lock_object.lo_flags & LO_RECURSABLE)) {
324 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
331 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
333 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
336 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
337 rw, 0, 0, file, line, LOCKSTAT_WRITER);
338 TD_LOCKS_INC(curthread);
344 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
349 return (__rw_try_wlock_int(rw LOCK_FILE_LINE_ARG));
353 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
359 KASSERT(rw->rw_lock != RW_DESTROYED,
360 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
361 __rw_assert(c, RA_WLOCKED, file, line);
362 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
363 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
366 #ifdef LOCK_PROFILING
367 _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
369 __rw_wunlock(rw, curthread, file, line);
372 TD_LOCKS_DEC(curthread);
376 * Determines whether a new reader can acquire a lock. Succeeds if the
377 * reader already owns a read lock and the lock is locked for read to
378 * prevent deadlock from reader recursion. Also succeeds if the lock
379 * is unlocked and has no writer waiters or spinners. Failing otherwise
380 * prioritizes writers before readers.
382 static bool __always_inline
383 __rw_can_read(struct thread *td, uintptr_t v, bool fp)
386 if ((v & (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER))
389 if (!fp && td->td_rw_rlocks && (v & RW_LOCK_READ))
394 static bool __always_inline
395 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp, bool fp
396 LOCK_FILE_LINE_ARG_DEF)
400 * Handle the easy case. If no other thread has a write
401 * lock, then try to bump up the count of read locks. Note
402 * that we have to preserve the current state of the
403 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
404 * read lock, then rw_lock must have changed, so restart
405 * the loop. Note that this handles the case of a
406 * completely unlocked rwlock since such a lock is encoded
407 * as a read lock with no waiters.
409 while (__rw_can_read(td, *vp, fp)) {
410 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
411 *vp + RW_ONE_READER)) {
412 if (LOCK_LOG_TEST(&rw->lock_object, 0))
414 "%s: %p succeed %p -> %p", __func__,
416 (void *)(*vp + RW_ONE_READER));
424 static void __noinline
425 __rw_rlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
426 LOCK_FILE_LINE_ARG_DEF)
428 struct turnstile *ts;
429 struct thread *owner;
430 #ifdef ADAPTIVE_RWLOCKS
434 #ifdef LOCK_PROFILING
435 uint64_t waittime = 0;
438 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
439 struct lock_delay_arg lda;
443 int64_t sleep_time = 0;
444 int64_t all_time = 0;
446 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
448 int doing_lockprof = 0;
452 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
453 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
456 all_time -= lockstat_nsecs(&rw->lock_object);
460 #ifdef LOCK_PROFILING
465 if (SCHEDULER_STOPPED())
468 #if defined(ADAPTIVE_RWLOCKS)
469 lock_delay_arg_init(&lda, &rw_delay);
470 #elif defined(KDTRACE_HOOKS)
471 lock_delay_arg_init(&lda, NULL);
475 PMC_SOFT_CALL( , , lock, failed);
477 lock_profile_obtain_lock_failed(&rw->lock_object,
478 &contested, &waittime);
481 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
487 #ifdef ADAPTIVE_RWLOCKS
489 * If the owner is running on another CPU, spin until
490 * the owner stops running or the state of the lock
493 if ((v & RW_LOCK_READ) == 0) {
494 owner = (struct thread *)RW_OWNER(v);
495 if (TD_IS_RUNNING(owner)) {
496 if (LOCK_LOG_TEST(&rw->lock_object, 0))
498 "%s: spinning on %p held by %p",
499 __func__, rw, owner);
500 KTR_STATE1(KTR_SCHED, "thread",
501 sched_tdname(curthread), "spinning",
502 "lockname:\"%s\"", rw->lock_object.lo_name);
505 v = RW_READ_VALUE(rw);
506 owner = lv_rw_wowner(v);
507 } while (owner != NULL && TD_IS_RUNNING(owner));
508 KTR_STATE0(KTR_SCHED, "thread",
509 sched_tdname(curthread), "running");
513 if ((v & RW_LOCK_WRITE_SPINNER) && RW_READERS(v) == 0) {
514 MPASS(!__rw_can_read(td, v, false));
516 v = RW_READ_VALUE(rw);
519 if (spintries < rowner_retries) {
521 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
522 "spinning", "lockname:\"%s\"",
523 rw->lock_object.lo_name);
525 for (i = 0; i < rowner_loops; i += n) {
527 v = RW_READ_VALUE(rw);
528 if (!(v & RW_LOCK_READ))
533 if (__rw_can_read(td, v, false))
537 lda.spin_cnt += rowner_loops - i;
539 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
541 if (i < rowner_loops)
548 * Okay, now it's the hard case. Some other thread already
549 * has a write lock or there are write waiters present,
550 * acquire the turnstile lock so we can begin the process
553 ts = turnstile_trywait(&rw->lock_object);
556 * The lock might have been released while we spun, so
557 * recheck its state and restart the loop if needed.
559 v = RW_READ_VALUE(rw);
561 if (((v & RW_LOCK_WRITE_SPINNER) && RW_READERS(v) == 0) ||
562 __rw_can_read(td, v, false)) {
563 turnstile_cancel(ts);
567 owner = lv_rw_wowner(v);
569 #ifdef ADAPTIVE_RWLOCKS
571 * The current lock owner might have started executing
572 * on another CPU (or the lock could have changed
573 * owners) while we were waiting on the turnstile
574 * chain lock. If so, drop the turnstile lock and try
578 if (TD_IS_RUNNING(owner)) {
579 turnstile_cancel(ts);
586 * The lock is held in write mode or it already has waiters.
588 MPASS(!__rw_can_read(td, v, false));
591 * If the RW_LOCK_READ_WAITERS flag is already set, then
592 * we can go ahead and block. If it is not set then try
593 * to set it. If we fail to set it drop the turnstile
594 * lock and restart the loop.
596 if (!(v & RW_LOCK_READ_WAITERS)) {
597 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
598 v | RW_LOCK_READ_WAITERS))
600 if (LOCK_LOG_TEST(&rw->lock_object, 0))
601 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
606 * We were unable to acquire the lock and the read waiters
607 * flag is set, so we must block on the turnstile.
609 if (LOCK_LOG_TEST(&rw->lock_object, 0))
610 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
613 sleep_time -= lockstat_nsecs(&rw->lock_object);
615 MPASS(owner == rw_owner(rw));
616 turnstile_wait(ts, owner, TS_SHARED_QUEUE);
618 sleep_time += lockstat_nsecs(&rw->lock_object);
621 if (LOCK_LOG_TEST(&rw->lock_object, 0))
622 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
624 v = RW_READ_VALUE(rw);
626 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
627 if (__predict_true(!doing_lockprof))
631 all_time += lockstat_nsecs(&rw->lock_object);
633 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
634 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
635 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
637 /* Record only the loops spinning and not sleeping. */
638 if (lda.spin_cnt > sleep_cnt)
639 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
640 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
641 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
645 * TODO: acquire "owner of record" here. Here be turnstile dragons
646 * however. turnstiles don't like owners changing between calls to
647 * turnstile_wait() currently.
649 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
650 waittime, file, line, LOCKSTAT_READER);
654 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
661 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
662 !TD_IS_IDLETHREAD(td),
663 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
664 td, rw->lock_object.lo_name, file, line));
665 KASSERT(rw->rw_lock != RW_DESTROYED,
666 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
667 KASSERT(rw_wowner(rw) != td,
668 ("rw_rlock: wlock already held for %s @ %s:%d",
669 rw->lock_object.lo_name, file, line));
670 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
672 v = RW_READ_VALUE(rw);
673 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__acquire) ||
674 !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
675 __rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
677 lock_profile_obtain_lock_success(&rw->lock_object, 0, 0,
680 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
681 WITNESS_LOCK(&rw->lock_object, 0, file, line);
682 TD_LOCKS_INC(curthread);
686 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
691 __rw_rlock_int(rw LOCK_FILE_LINE_ARG);
695 __rw_try_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
699 if (SCHEDULER_STOPPED())
702 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
703 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
704 curthread, rw->lock_object.lo_name, file, line));
708 KASSERT(rw->rw_lock != RW_DESTROYED,
709 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
710 if (!(x & RW_LOCK_READ))
712 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
713 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
715 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
716 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
717 rw, 0, 0, file, line, LOCKSTAT_READER);
718 TD_LOCKS_INC(curthread);
719 curthread->td_rw_rlocks++;
724 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
729 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
734 return (__rw_try_rlock_int(rw LOCK_FILE_LINE_ARG));
737 static bool __always_inline
738 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
742 if (RW_READERS(*vp) > 1 || !(*vp & RW_LOCK_WAITERS)) {
743 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
744 *vp - RW_ONE_READER)) {
745 if (LOCK_LOG_TEST(&rw->lock_object, 0))
747 "%s: %p succeeded %p -> %p",
748 __func__, rw, (void *)*vp,
749 (void *)(*vp - RW_ONE_READER));
760 static void __noinline
761 __rw_runlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
762 LOCK_FILE_LINE_ARG_DEF)
764 struct turnstile *ts;
765 uintptr_t setv, queue;
767 if (SCHEDULER_STOPPED())
770 if (__rw_runlock_try(rw, td, &v))
774 * Ok, we know we have waiters and we think we are the
775 * last reader, so grab the turnstile lock.
777 turnstile_chain_lock(&rw->lock_object);
778 v = RW_READ_VALUE(rw);
780 if (__rw_runlock_try(rw, td, &v))
783 MPASS(v & RW_LOCK_WAITERS);
786 * Try to drop our lock leaving the lock in a unlocked
789 * If you wanted to do explicit lock handoff you'd have to
790 * do it here. You'd also want to use turnstile_signal()
791 * and you'd have to handle the race where a higher
792 * priority thread blocks on the write lock before the
793 * thread you wakeup actually runs and have the new thread
794 * "steal" the lock. For now it's a lot simpler to just
795 * wakeup all of the waiters.
797 * As above, if we fail, then another thread might have
798 * acquired a read lock, so drop the turnstile lock and
802 queue = TS_SHARED_QUEUE;
803 if (v & RW_LOCK_WRITE_WAITERS) {
804 queue = TS_EXCLUSIVE_QUEUE;
805 setv |= (v & RW_LOCK_READ_WAITERS);
807 setv |= (v & RW_LOCK_WRITE_SPINNER);
808 if (!atomic_fcmpset_rel_ptr(&rw->rw_lock, &v, setv))
810 if (LOCK_LOG_TEST(&rw->lock_object, 0))
811 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
815 * Ok. The lock is released and all that's left is to
816 * wake up the waiters. Note that the lock might not be
817 * free anymore, but in that case the writers will just
818 * block again if they run before the new lock holder(s)
821 ts = turnstile_lookup(&rw->lock_object);
823 turnstile_broadcast(ts, queue);
824 turnstile_unpend(ts);
828 turnstile_chain_unlock(&rw->lock_object);
830 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
834 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
839 KASSERT(rw->rw_lock != RW_DESTROYED,
840 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
841 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
842 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
843 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
846 v = RW_READ_VALUE(rw);
848 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__release) ||
849 !__rw_runlock_try(rw, td, &v)))
850 __rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
852 lock_profile_release_lock(&rw->lock_object);
854 TD_LOCKS_DEC(curthread);
858 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
863 _rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
866 #ifdef ADAPTIVE_RWLOCKS
868 rw_drop_critical(uintptr_t v, bool *in_critical, int *extra_work)
871 if (v & RW_LOCK_WRITE_SPINNER)
875 *in_critical = false;
880 #define rw_drop_critical(v, in_critical, extra_work) do { } while (0)
884 * This function is called when we are unable to obtain a write lock on the
885 * first try. This means that at least one other thread holds either a
886 * read or write lock.
889 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
893 struct turnstile *ts;
894 struct thread *owner;
895 #ifdef ADAPTIVE_RWLOCKS
898 enum { READERS, WRITER } sleep_reason = READERS;
899 bool in_critical = false;
902 #ifdef LOCK_PROFILING
903 uint64_t waittime = 0;
906 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
907 struct lock_delay_arg lda;
911 int64_t sleep_time = 0;
912 int64_t all_time = 0;
914 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
916 int doing_lockprof = 0;
920 tid = (uintptr_t)curthread;
924 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
925 while (v == RW_UNLOCKED) {
926 if (_rw_write_lock_fetch(rw, &v, tid))
931 all_time -= lockstat_nsecs(&rw->lock_object);
935 #ifdef LOCK_PROFILING
941 if (SCHEDULER_STOPPED())
944 #if defined(ADAPTIVE_RWLOCKS)
945 lock_delay_arg_init(&lda, &rw_delay);
946 #elif defined(KDTRACE_HOOKS)
947 lock_delay_arg_init(&lda, NULL);
949 if (__predict_false(v == RW_UNLOCKED))
950 v = RW_READ_VALUE(rw);
952 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
953 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
954 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
955 __func__, rw->lock_object.lo_name, file, line));
957 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
958 if (LOCK_LOG_TEST(&rw->lock_object, 0))
959 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
963 if (LOCK_LOG_TEST(&rw->lock_object, 0))
964 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
965 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
968 PMC_SOFT_CALL( , , lock, failed);
970 lock_profile_obtain_lock_failed(&rw->lock_object,
971 &contested, &waittime);
974 if (v == RW_UNLOCKED) {
975 if (_rw_write_lock_fetch(rw, &v, tid))
983 #ifdef ADAPTIVE_RWLOCKS
984 if (v == (RW_LOCK_READ | RW_LOCK_WRITE_SPINNER)) {
985 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
991 * If the lock is write locked and the owner is
992 * running on another CPU, spin until the owner stops
993 * running or the state of the lock changes.
995 if (!(v & RW_LOCK_READ)) {
996 rw_drop_critical(v, &in_critical, &extra_work);
997 sleep_reason = WRITER;
998 owner = lv_rw_wowner(v);
999 if (!TD_IS_RUNNING(owner))
1001 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1002 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
1003 __func__, rw, owner);
1004 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1005 "spinning", "lockname:\"%s\"",
1006 rw->lock_object.lo_name);
1009 v = RW_READ_VALUE(rw);
1010 owner = lv_rw_wowner(v);
1011 } while (owner != NULL && TD_IS_RUNNING(owner));
1012 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1015 } else if (RW_READERS(v) > 0) {
1016 sleep_reason = READERS;
1017 if (spintries == rowner_retries)
1019 if (!(v & RW_LOCK_WRITE_SPINNER)) {
1025 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1026 v | RW_LOCK_WRITE_SPINNER)) {
1028 in_critical = false;
1034 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1035 "spinning", "lockname:\"%s\"",
1036 rw->lock_object.lo_name);
1038 for (i = 0; i < rowner_loops; i += n) {
1040 v = RW_READ_VALUE(rw);
1041 if (!(v & RW_LOCK_WRITE_SPINNER))
1043 if (!(v & RW_LOCK_READ))
1049 #ifdef KDTRACE_HOOKS
1052 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1054 if (i < rowner_loops)
1059 ts = turnstile_trywait(&rw->lock_object);
1060 v = RW_READ_VALUE(rw);
1062 owner = lv_rw_wowner(v);
1064 #ifdef ADAPTIVE_RWLOCKS
1066 * The current lock owner might have started executing
1067 * on another CPU (or the lock could have changed
1068 * owners) while we were waiting on the turnstile
1069 * chain lock. If so, drop the turnstile lock and try
1072 if (owner != NULL) {
1073 if (TD_IS_RUNNING(owner)) {
1074 turnstile_cancel(ts);
1075 rw_drop_critical(v, &in_critical, &extra_work);
1078 } else if (RW_READERS(v) > 0 && sleep_reason == WRITER) {
1079 turnstile_cancel(ts);
1080 rw_drop_critical(v, &in_critical, &extra_work);
1085 * Check for the waiters flags about this rwlock.
1086 * If the lock was released, without maintain any pending
1087 * waiters queue, simply try to acquire it.
1088 * If a pending waiters queue is present, claim the lock
1089 * ownership and maintain the pending queue.
1091 setv = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1092 if ((v & ~setv) == RW_UNLOCKED) {
1093 setv &= ~RW_LOCK_WRITE_SPINNER;
1094 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid | setv)) {
1096 turnstile_claim(ts);
1098 turnstile_cancel(ts);
1104 #ifdef ADAPTIVE_RWLOCKS
1106 if ((v & RW_LOCK_WRITE_SPINNER) ||
1107 !((v & RW_LOCK_WRITE_WAITERS))) {
1108 setv = v & ~RW_LOCK_WRITE_SPINNER;
1109 setv |= RW_LOCK_WRITE_WAITERS;
1110 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v, setv))
1114 in_critical = false;
1119 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1120 * set it. If we fail to set it, then loop back and try
1123 if (!(v & RW_LOCK_WRITE_WAITERS)) {
1124 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1125 v | RW_LOCK_WRITE_WAITERS))
1127 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1128 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1131 #ifdef ADAPTIVE_RWLOCKS
1135 * We were unable to acquire the lock and the write waiters
1136 * flag is set, so we must block on the turnstile.
1138 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1139 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1141 #ifdef KDTRACE_HOOKS
1142 sleep_time -= lockstat_nsecs(&rw->lock_object);
1144 MPASS(owner == rw_owner(rw));
1145 turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
1146 #ifdef KDTRACE_HOOKS
1147 sleep_time += lockstat_nsecs(&rw->lock_object);
1150 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1151 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1153 #ifdef ADAPTIVE_RWLOCKS
1156 v = RW_READ_VALUE(rw);
1158 if (__predict_true(!extra_work))
1160 #ifdef ADAPTIVE_RWLOCKS
1164 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1165 if (__predict_true(!doing_lockprof))
1168 #ifdef KDTRACE_HOOKS
1169 all_time += lockstat_nsecs(&rw->lock_object);
1171 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1172 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1173 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1175 /* Record only the loops spinning and not sleeping. */
1176 if (lda.spin_cnt > sleep_cnt)
1177 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1178 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1179 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1182 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1183 waittime, file, line, LOCKSTAT_WRITER);
1187 * This function is called if lockstat is active or the first try at releasing
1188 * a write lock failed. The latter means that the lock is recursed or one of
1189 * the 2 waiter bits must be set indicating that at least one thread is waiting
1193 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1196 struct turnstile *ts;
1197 uintptr_t tid, setv;
1200 tid = (uintptr_t)curthread;
1201 if (SCHEDULER_STOPPED())
1205 if (__predict_false(v == tid))
1206 v = RW_READ_VALUE(rw);
1208 if (v & RW_LOCK_WRITER_RECURSED) {
1209 if (--(rw->rw_recurse) == 0)
1210 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1211 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1212 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1216 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1217 if (v == tid && _rw_write_unlock(rw, tid))
1220 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1221 ("%s: neither of the waiter flags are set", __func__));
1223 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1224 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1226 turnstile_chain_lock(&rw->lock_object);
1229 * Use the same algo as sx locks for now. Prefer waking up shared
1230 * waiters if we have any over writers. This is probably not ideal.
1232 * 'v' is the value we are going to write back to rw_lock. If we
1233 * have waiters on both queues, we need to preserve the state of
1234 * the waiter flag for the queue we don't wake up. For now this is
1235 * hardcoded for the algorithm mentioned above.
1237 * In the case of both readers and writers waiting we wakeup the
1238 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1239 * new writer comes in before a reader it will claim the lock up
1240 * above. There is probably a potential priority inversion in
1241 * there that could be worked around either by waking both queues
1242 * of waiters or doing some complicated lock handoff gymnastics.
1245 v = RW_READ_VALUE(rw);
1246 queue = TS_SHARED_QUEUE;
1247 if (v & RW_LOCK_WRITE_WAITERS) {
1248 queue = TS_EXCLUSIVE_QUEUE;
1249 setv |= (v & RW_LOCK_READ_WAITERS);
1251 atomic_store_rel_ptr(&rw->rw_lock, setv);
1253 /* Wake up all waiters for the specific queue. */
1254 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1255 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1256 queue == TS_SHARED_QUEUE ? "read" : "write");
1258 ts = turnstile_lookup(&rw->lock_object);
1260 turnstile_broadcast(ts, queue);
1261 turnstile_unpend(ts);
1262 turnstile_chain_unlock(&rw->lock_object);
1266 * Attempt to do a non-blocking upgrade from a read lock to a write
1267 * lock. This will only succeed if this thread holds a single read
1268 * lock. Returns true if the upgrade succeeded and false otherwise.
1271 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1273 uintptr_t v, setv, tid;
1274 struct turnstile *ts;
1277 if (SCHEDULER_STOPPED())
1280 KASSERT(rw->rw_lock != RW_DESTROYED,
1281 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1282 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1285 * Attempt to switch from one reader to a writer. If there
1286 * are any write waiters, then we will have to lock the
1287 * turnstile first to prevent races with another writer
1288 * calling turnstile_wait() before we have claimed this
1289 * turnstile. So, do the simple case of no waiters first.
1291 tid = (uintptr_t)curthread;
1293 v = RW_READ_VALUE(rw);
1295 if (RW_READERS(v) > 1)
1297 if (!(v & RW_LOCK_WAITERS)) {
1298 success = atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid);
1305 * Ok, we think we have waiters, so lock the turnstile.
1307 ts = turnstile_trywait(&rw->lock_object);
1308 v = RW_READ_VALUE(rw);
1310 if (RW_READERS(v) > 1) {
1311 turnstile_cancel(ts);
1315 * Try to switch from one reader to a writer again. This time
1316 * we honor the current state of the waiters flags.
1317 * If we obtain the lock with the flags set, then claim
1318 * ownership of the turnstile.
1320 setv = tid | (v & RW_LOCK_WAITERS);
1321 success = atomic_fcmpset_ptr(&rw->rw_lock, &v, setv);
1323 if (v & RW_LOCK_WAITERS)
1324 turnstile_claim(ts);
1326 turnstile_cancel(ts);
1331 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1333 curthread->td_rw_rlocks--;
1334 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1336 LOCKSTAT_RECORD0(rw__upgrade, rw);
1342 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1347 return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1351 * Downgrade a write lock into a single read lock.
1354 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1356 struct turnstile *ts;
1360 if (SCHEDULER_STOPPED())
1363 KASSERT(rw->rw_lock != RW_DESTROYED,
1364 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1365 __rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1367 if (rw_recursed(rw))
1368 panic("downgrade of a recursed lock");
1371 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1374 * Convert from a writer to a single reader. First we handle
1375 * the easy case with no waiters. If there are any waiters, we
1376 * lock the turnstile and "disown" the lock.
1378 tid = (uintptr_t)curthread;
1379 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1383 * Ok, we think we have waiters, so lock the turnstile so we can
1384 * read the waiter flags without any races.
1386 turnstile_chain_lock(&rw->lock_object);
1387 v = rw->rw_lock & RW_LOCK_WAITERS;
1388 rwait = v & RW_LOCK_READ_WAITERS;
1389 wwait = v & RW_LOCK_WRITE_WAITERS;
1390 MPASS(rwait | wwait);
1393 * Downgrade from a write lock while preserving waiters flag
1394 * and give up ownership of the turnstile.
1396 ts = turnstile_lookup(&rw->lock_object);
1399 v &= ~RW_LOCK_READ_WAITERS;
1400 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1402 * Wake other readers if there are no writers pending. Otherwise they
1403 * won't be able to acquire the lock anyway.
1405 if (rwait && !wwait) {
1406 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1407 turnstile_unpend(ts);
1409 turnstile_disown(ts);
1410 turnstile_chain_unlock(&rw->lock_object);
1412 curthread->td_rw_rlocks++;
1413 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1414 LOCKSTAT_RECORD0(rw__downgrade, rw);
1418 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1423 __rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1426 #ifdef INVARIANT_SUPPORT
1432 * In the non-WITNESS case, rw_assert() can only detect that at least
1433 * *some* thread owns an rlock, but it cannot guarantee that *this*
1434 * thread owns an rlock.
1437 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1439 const struct rwlock *rw;
1441 if (SCHEDULER_STOPPED())
1448 case RA_LOCKED | RA_RECURSED:
1449 case RA_LOCKED | RA_NOTRECURSED:
1451 case RA_RLOCKED | RA_RECURSED:
1452 case RA_RLOCKED | RA_NOTRECURSED:
1454 witness_assert(&rw->lock_object, what, file, line);
1457 * If some other thread has a write lock or we have one
1458 * and are asserting a read lock, fail. Also, if no one
1459 * has a lock at all, fail.
1461 if (rw->rw_lock == RW_UNLOCKED ||
1462 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1463 rw_wowner(rw) != curthread)))
1464 panic("Lock %s not %slocked @ %s:%d\n",
1465 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1466 "read " : "", file, line);
1468 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1469 if (rw_recursed(rw)) {
1470 if (what & RA_NOTRECURSED)
1471 panic("Lock %s recursed @ %s:%d\n",
1472 rw->lock_object.lo_name, file,
1474 } else if (what & RA_RECURSED)
1475 panic("Lock %s not recursed @ %s:%d\n",
1476 rw->lock_object.lo_name, file, line);
1481 case RA_WLOCKED | RA_RECURSED:
1482 case RA_WLOCKED | RA_NOTRECURSED:
1483 if (rw_wowner(rw) != curthread)
1484 panic("Lock %s not exclusively locked @ %s:%d\n",
1485 rw->lock_object.lo_name, file, line);
1486 if (rw_recursed(rw)) {
1487 if (what & RA_NOTRECURSED)
1488 panic("Lock %s recursed @ %s:%d\n",
1489 rw->lock_object.lo_name, file, line);
1490 } else if (what & RA_RECURSED)
1491 panic("Lock %s not recursed @ %s:%d\n",
1492 rw->lock_object.lo_name, file, line);
1496 witness_assert(&rw->lock_object, what, file, line);
1499 * If we hold a write lock fail. We can't reliably check
1500 * to see if we hold a read lock or not.
1502 if (rw_wowner(rw) == curthread)
1503 panic("Lock %s exclusively locked @ %s:%d\n",
1504 rw->lock_object.lo_name, file, line);
1508 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1512 #endif /* INVARIANT_SUPPORT */
1516 db_show_rwlock(const struct lock_object *lock)
1518 const struct rwlock *rw;
1521 rw = (const struct rwlock *)lock;
1523 db_printf(" state: ");
1524 if (rw->rw_lock == RW_UNLOCKED)
1525 db_printf("UNLOCKED\n");
1526 else if (rw->rw_lock == RW_DESTROYED) {
1527 db_printf("DESTROYED\n");
1529 } else if (rw->rw_lock & RW_LOCK_READ)
1530 db_printf("RLOCK: %ju locks\n",
1531 (uintmax_t)(RW_READERS(rw->rw_lock)));
1534 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1535 td->td_tid, td->td_proc->p_pid, td->td_name);
1536 if (rw_recursed(rw))
1537 db_printf(" recursed: %u\n", rw->rw_recurse);
1539 db_printf(" waiters: ");
1540 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1541 case RW_LOCK_READ_WAITERS:
1542 db_printf("readers\n");
1544 case RW_LOCK_WRITE_WAITERS:
1545 db_printf("writers\n");
1547 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1548 db_printf("readers and writers\n");
1551 db_printf("none\n");