2 * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * Machine independent bits of reader/writer lock implementation.
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
35 #include "opt_hwpmc_hooks.h"
36 #include "opt_no_adaptive_rwlocks.h"
38 #include <sys/param.h>
41 #include <sys/kernel.h>
43 #include <sys/mutex.h>
45 #include <sys/rwlock.h>
46 #include <sys/sched.h>
48 #include <sys/sysctl.h>
49 #include <sys/systm.h>
50 #include <sys/turnstile.h>
52 #include <machine/cpu.h>
54 #if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
55 #define ADAPTIVE_RWLOCKS
59 #include <sys/pmckern.h>
60 PMC_SOFT_DECLARE( , , lock, failed);
64 * Return the rwlock address when the lock cookie address is provided.
65 * This functionality assumes that struct rwlock* have a member named rw_lock.
67 #define rwlock2rw(c) (__containerof(c, struct rwlock, rw_lock))
72 static void db_show_rwlock(const struct lock_object *lock);
74 static void assert_rw(const struct lock_object *lock, int what);
75 static void lock_rw(struct lock_object *lock, uintptr_t how);
77 static int owner_rw(const struct lock_object *lock, struct thread **owner);
79 static uintptr_t unlock_rw(struct lock_object *lock);
81 struct lock_class lock_class_rw = {
83 .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
84 .lc_assert = assert_rw,
86 .lc_ddb_show = db_show_rwlock,
89 .lc_unlock = unlock_rw,
95 #ifdef ADAPTIVE_RWLOCKS
96 static int __read_frequently rowner_retries;
97 static int __read_frequently rowner_loops;
98 static SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL,
100 SYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
101 SYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
103 static struct lock_delay_config __read_frequently rw_delay;
105 SYSCTL_INT(_debug_rwlock, OID_AUTO, delay_base, CTLFLAG_RW, &rw_delay.base,
107 SYSCTL_INT(_debug_rwlock, OID_AUTO, delay_max, CTLFLAG_RW, &rw_delay.max,
111 rw_lock_delay_init(void *arg __unused)
114 lock_delay_default_init(&rw_delay);
116 rowner_loops = max(10000, rw_delay.max);
118 LOCK_DELAY_SYSINIT(rw_lock_delay_init);
122 * Return a pointer to the owning thread if the lock is write-locked or
123 * NULL if the lock is unlocked or read-locked.
126 #define lv_rw_wowner(v) \
127 ((v) & RW_LOCK_READ ? NULL : \
128 (struct thread *)RW_OWNER((v)))
130 #define rw_wowner(rw) lv_rw_wowner(RW_READ_VALUE(rw))
133 * Returns if a write owner is recursed. Write ownership is not assured
134 * here and should be previously checked.
136 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
139 * Return true if curthread helds the lock.
141 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
144 * Return a pointer to the owning thread for this lock who should receive
145 * any priority lent by threads that block on this lock. Currently this
146 * is identical to rw_wowner().
148 #define rw_owner(rw) rw_wowner(rw)
151 #define __rw_assert(c, what, file, line)
155 assert_rw(const struct lock_object *lock, int what)
158 rw_assert((const struct rwlock *)lock, what);
162 lock_rw(struct lock_object *lock, uintptr_t how)
166 rw = (struct rwlock *)lock;
174 unlock_rw(struct lock_object *lock)
178 rw = (struct rwlock *)lock;
179 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
180 if (rw->rw_lock & RW_LOCK_READ) {
191 owner_rw(const struct lock_object *lock, struct thread **owner)
193 const struct rwlock *rw = (const struct rwlock *)lock;
194 uintptr_t x = rw->rw_lock;
196 *owner = rw_wowner(rw);
197 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
203 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
210 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
211 RW_RECURSE | RW_NEW)) == 0);
212 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
213 ("%s: rw_lock not aligned for %s: %p", __func__, name,
216 flags = LO_UPGRADABLE;
219 if (opts & RW_NOPROFILE)
220 flags |= LO_NOPROFILE;
221 if (!(opts & RW_NOWITNESS))
223 if (opts & RW_RECURSE)
224 flags |= LO_RECURSABLE;
230 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
231 rw->rw_lock = RW_UNLOCKED;
236 _rw_destroy(volatile uintptr_t *c)
242 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
243 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
244 rw->rw_lock = RW_DESTROYED;
245 lock_destroy(&rw->lock_object);
249 rw_sysinit(void *arg)
251 struct rw_args *args;
254 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
259 _rw_wowned(const volatile uintptr_t *c)
262 return (rw_wowner(rwlock2rw(c)) == curthread);
266 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
273 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
274 !TD_IS_IDLETHREAD(curthread),
275 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
276 curthread, rw->lock_object.lo_name, file, line));
277 KASSERT(rw->rw_lock != RW_DESTROYED,
278 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
279 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
281 tid = (uintptr_t)curthread;
283 if (!_rw_write_lock_fetch(rw, &v, tid))
284 _rw_wlock_hard(rw, v, file, line);
286 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
287 0, 0, file, line, LOCKSTAT_WRITER);
289 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
290 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
291 TD_LOCKS_INC(curthread);
295 __rw_try_wlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
304 if (SCHEDULER_STOPPED_TD(td))
307 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
308 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
309 curthread, rw->lock_object.lo_name, file, line));
310 KASSERT(rw->rw_lock != RW_DESTROYED,
311 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
317 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
319 if (v == RW_UNLOCKED)
321 if (v == tid && (rw->lock_object.lo_flags & LO_RECURSABLE)) {
323 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
330 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
332 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
335 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
336 rw, 0, 0, file, line, LOCKSTAT_WRITER);
337 TD_LOCKS_INC(curthread);
343 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
348 return (__rw_try_wlock_int(rw LOCK_FILE_LINE_ARG));
352 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
358 KASSERT(rw->rw_lock != RW_DESTROYED,
359 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
360 __rw_assert(c, RA_WLOCKED, file, line);
361 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
362 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
365 #ifdef LOCK_PROFILING
366 _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
368 __rw_wunlock(rw, curthread, file, line);
371 TD_LOCKS_DEC(curthread);
375 * Determines whether a new reader can acquire a lock. Succeeds if the
376 * reader already owns a read lock and the lock is locked for read to
377 * prevent deadlock from reader recursion. Also succeeds if the lock
378 * is unlocked and has no writer waiters or spinners. Failing otherwise
379 * prioritizes writers before readers.
381 static bool __always_inline
382 __rw_can_read(struct thread *td, uintptr_t v, bool fp)
385 if ((v & (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER))
388 if (!fp && td->td_rw_rlocks && (v & RW_LOCK_READ))
393 static bool __always_inline
394 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp, bool fp
395 LOCK_FILE_LINE_ARG_DEF)
399 * Handle the easy case. If no other thread has a write
400 * lock, then try to bump up the count of read locks. Note
401 * that we have to preserve the current state of the
402 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
403 * read lock, then rw_lock must have changed, so restart
404 * the loop. Note that this handles the case of a
405 * completely unlocked rwlock since such a lock is encoded
406 * as a read lock with no waiters.
408 while (__rw_can_read(td, *vp, fp)) {
409 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
410 *vp + RW_ONE_READER)) {
411 if (LOCK_LOG_TEST(&rw->lock_object, 0))
413 "%s: %p succeed %p -> %p", __func__,
415 (void *)(*vp + RW_ONE_READER));
423 static void __noinline
424 __rw_rlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
425 LOCK_FILE_LINE_ARG_DEF)
427 struct turnstile *ts;
428 struct thread *owner;
429 #ifdef ADAPTIVE_RWLOCKS
433 #ifdef LOCK_PROFILING
434 uint64_t waittime = 0;
437 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
438 struct lock_delay_arg lda;
442 int64_t sleep_time = 0;
443 int64_t all_time = 0;
445 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
447 int doing_lockprof = 0;
451 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
452 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
455 all_time -= lockstat_nsecs(&rw->lock_object);
459 #ifdef LOCK_PROFILING
464 if (SCHEDULER_STOPPED())
467 #if defined(ADAPTIVE_RWLOCKS)
468 lock_delay_arg_init(&lda, &rw_delay);
469 #elif defined(KDTRACE_HOOKS)
470 lock_delay_arg_init(&lda, NULL);
474 PMC_SOFT_CALL( , , lock, failed);
476 lock_profile_obtain_lock_failed(&rw->lock_object,
477 &contested, &waittime);
480 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
486 #ifdef ADAPTIVE_RWLOCKS
488 * If the owner is running on another CPU, spin until
489 * the owner stops running or the state of the lock
492 if ((v & RW_LOCK_READ) == 0) {
493 owner = (struct thread *)RW_OWNER(v);
494 if (TD_IS_RUNNING(owner)) {
495 if (LOCK_LOG_TEST(&rw->lock_object, 0))
497 "%s: spinning on %p held by %p",
498 __func__, rw, owner);
499 KTR_STATE1(KTR_SCHED, "thread",
500 sched_tdname(curthread), "spinning",
501 "lockname:\"%s\"", rw->lock_object.lo_name);
504 v = RW_READ_VALUE(rw);
505 owner = lv_rw_wowner(v);
506 } while (owner != NULL && TD_IS_RUNNING(owner));
507 KTR_STATE0(KTR_SCHED, "thread",
508 sched_tdname(curthread), "running");
511 } else if (spintries < rowner_retries) {
513 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
514 "spinning", "lockname:\"%s\"",
515 rw->lock_object.lo_name);
516 for (i = 0; i < rowner_loops; i += n) {
519 v = RW_READ_VALUE(rw);
520 if ((v & RW_LOCK_READ) == 0 || __rw_can_read(td, v, false))
524 lda.spin_cnt += rowner_loops - i;
526 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
528 if (i < rowner_loops)
534 * Okay, now it's the hard case. Some other thread already
535 * has a write lock or there are write waiters present,
536 * acquire the turnstile lock so we can begin the process
539 ts = turnstile_trywait(&rw->lock_object);
542 * The lock might have been released while we spun, so
543 * recheck its state and restart the loop if needed.
545 v = RW_READ_VALUE(rw);
547 if (__rw_can_read(td, v, false)) {
548 turnstile_cancel(ts);
552 owner = lv_rw_wowner(v);
554 #ifdef ADAPTIVE_RWLOCKS
556 * The current lock owner might have started executing
557 * on another CPU (or the lock could have changed
558 * owners) while we were waiting on the turnstile
559 * chain lock. If so, drop the turnstile lock and try
563 if (TD_IS_RUNNING(owner)) {
564 turnstile_cancel(ts);
571 * The lock is held in write mode or it already has waiters.
573 MPASS(!__rw_can_read(td, v, false));
576 * If the RW_LOCK_READ_WAITERS flag is already set, then
577 * we can go ahead and block. If it is not set then try
578 * to set it. If we fail to set it drop the turnstile
579 * lock and restart the loop.
581 if (!(v & RW_LOCK_READ_WAITERS)) {
582 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
583 v | RW_LOCK_READ_WAITERS))
585 if (LOCK_LOG_TEST(&rw->lock_object, 0))
586 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
591 * We were unable to acquire the lock and the read waiters
592 * flag is set, so we must block on the turnstile.
594 if (LOCK_LOG_TEST(&rw->lock_object, 0))
595 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
598 sleep_time -= lockstat_nsecs(&rw->lock_object);
600 MPASS(owner == rw_owner(rw));
601 turnstile_wait(ts, owner, TS_SHARED_QUEUE);
603 sleep_time += lockstat_nsecs(&rw->lock_object);
606 if (LOCK_LOG_TEST(&rw->lock_object, 0))
607 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
609 v = RW_READ_VALUE(rw);
611 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
612 if (__predict_true(!doing_lockprof))
616 all_time += lockstat_nsecs(&rw->lock_object);
618 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
619 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
620 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
622 /* Record only the loops spinning and not sleeping. */
623 if (lda.spin_cnt > sleep_cnt)
624 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
625 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
626 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
630 * TODO: acquire "owner of record" here. Here be turnstile dragons
631 * however. turnstiles don't like owners changing between calls to
632 * turnstile_wait() currently.
634 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
635 waittime, file, line, LOCKSTAT_READER);
639 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
646 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
647 !TD_IS_IDLETHREAD(td),
648 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
649 td, rw->lock_object.lo_name, file, line));
650 KASSERT(rw->rw_lock != RW_DESTROYED,
651 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
652 KASSERT(rw_wowner(rw) != td,
653 ("rw_rlock: wlock already held for %s @ %s:%d",
654 rw->lock_object.lo_name, file, line));
655 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
657 v = RW_READ_VALUE(rw);
658 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__acquire) ||
659 !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
660 __rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
662 lock_profile_obtain_lock_success(&rw->lock_object, 0, 0,
665 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
666 WITNESS_LOCK(&rw->lock_object, 0, file, line);
667 TD_LOCKS_INC(curthread);
671 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
676 __rw_rlock_int(rw LOCK_FILE_LINE_ARG);
680 __rw_try_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
684 if (SCHEDULER_STOPPED())
687 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
688 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
689 curthread, rw->lock_object.lo_name, file, line));
693 KASSERT(rw->rw_lock != RW_DESTROYED,
694 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
695 if (!(x & RW_LOCK_READ))
697 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
698 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
700 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
701 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
702 rw, 0, 0, file, line, LOCKSTAT_READER);
703 TD_LOCKS_INC(curthread);
704 curthread->td_rw_rlocks++;
709 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
714 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
719 return (__rw_try_rlock_int(rw LOCK_FILE_LINE_ARG));
722 static bool __always_inline
723 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
728 * See if there is more than one read lock held. If so,
729 * just drop one and return.
731 if (RW_READERS(*vp) > 1) {
732 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
733 *vp - RW_ONE_READER)) {
734 if (LOCK_LOG_TEST(&rw->lock_object, 0))
736 "%s: %p succeeded %p -> %p",
737 __func__, rw, (void *)*vp,
738 (void *)(*vp - RW_ONE_READER));
745 * If there aren't any waiters for a write lock, then try
746 * to drop it quickly.
748 if (!(*vp & RW_LOCK_WAITERS)) {
749 MPASS((*vp & ~RW_LOCK_WRITE_SPINNER) ==
751 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
753 if (LOCK_LOG_TEST(&rw->lock_object, 0))
754 CTR2(KTR_LOCK, "%s: %p last succeeded",
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 v &= (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
790 MPASS(v & RW_LOCK_WAITERS);
793 * Try to drop our lock leaving the lock in a unlocked
796 * If you wanted to do explicit lock handoff you'd have to
797 * do it here. You'd also want to use turnstile_signal()
798 * and you'd have to handle the race where a higher
799 * priority thread blocks on the write lock before the
800 * thread you wakeup actually runs and have the new thread
801 * "steal" the lock. For now it's a lot simpler to just
802 * wakeup all of the waiters.
804 * As above, if we fail, then another thread might have
805 * acquired a read lock, so drop the turnstile lock and
809 queue = TS_SHARED_QUEUE;
810 if (v & RW_LOCK_WRITE_WAITERS) {
811 queue = TS_EXCLUSIVE_QUEUE;
812 setv |= (v & RW_LOCK_READ_WAITERS);
814 v |= RW_READERS_LOCK(1);
815 if (!atomic_fcmpset_rel_ptr(&rw->rw_lock, &v, setv))
817 if (LOCK_LOG_TEST(&rw->lock_object, 0))
818 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
822 * Ok. The lock is released and all that's left is to
823 * wake up the waiters. Note that the lock might not be
824 * free anymore, but in that case the writers will just
825 * block again if they run before the new lock holder(s)
828 ts = turnstile_lookup(&rw->lock_object);
830 turnstile_broadcast(ts, queue);
831 turnstile_unpend(ts, TS_SHARED_LOCK);
835 turnstile_chain_unlock(&rw->lock_object);
837 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
841 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
846 KASSERT(rw->rw_lock != RW_DESTROYED,
847 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
848 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
849 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
850 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
853 v = RW_READ_VALUE(rw);
855 if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__release) ||
856 !__rw_runlock_try(rw, td, &v)))
857 __rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
859 lock_profile_release_lock(&rw->lock_object);
861 TD_LOCKS_DEC(curthread);
865 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
870 _rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
874 * This function is called when we are unable to obtain a write lock on the
875 * first try. This means that at least one other thread holds either a
876 * read or write lock.
879 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
883 struct turnstile *ts;
884 struct thread *owner;
885 #ifdef ADAPTIVE_RWLOCKS
888 enum { READERS, WRITER } sleep_reason = READERS;
891 #ifdef LOCK_PROFILING
892 uint64_t waittime = 0;
895 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
896 struct lock_delay_arg lda;
900 int64_t sleep_time = 0;
901 int64_t all_time = 0;
903 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
905 int doing_lockprof = 0;
908 tid = (uintptr_t)curthread;
912 if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
913 while (v == RW_UNLOCKED) {
914 if (_rw_write_lock_fetch(rw, &v, tid))
918 all_time -= lockstat_nsecs(&rw->lock_object);
922 #ifdef LOCK_PROFILING
927 if (SCHEDULER_STOPPED())
930 #if defined(ADAPTIVE_RWLOCKS)
931 lock_delay_arg_init(&lda, &rw_delay);
932 #elif defined(KDTRACE_HOOKS)
933 lock_delay_arg_init(&lda, NULL);
935 if (__predict_false(v == RW_UNLOCKED))
936 v = RW_READ_VALUE(rw);
938 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
939 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
940 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
941 __func__, rw->lock_object.lo_name, file, line));
943 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
944 if (LOCK_LOG_TEST(&rw->lock_object, 0))
945 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
949 if (LOCK_LOG_TEST(&rw->lock_object, 0))
950 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
951 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
954 PMC_SOFT_CALL( , , lock, failed);
956 lock_profile_obtain_lock_failed(&rw->lock_object,
957 &contested, &waittime);
960 if (v == RW_UNLOCKED) {
961 if (_rw_write_lock_fetch(rw, &v, tid))
969 #ifdef ADAPTIVE_RWLOCKS
971 * If the lock is write locked and the owner is
972 * running on another CPU, spin until the owner stops
973 * running or the state of the lock changes.
975 if (!(v & RW_LOCK_READ)) {
976 sleep_reason = WRITER;
977 owner = lv_rw_wowner(v);
978 if (!TD_IS_RUNNING(owner))
980 if (LOCK_LOG_TEST(&rw->lock_object, 0))
981 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
982 __func__, rw, owner);
983 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
984 "spinning", "lockname:\"%s\"",
985 rw->lock_object.lo_name);
988 v = RW_READ_VALUE(rw);
989 owner = lv_rw_wowner(v);
990 } while (owner != NULL && TD_IS_RUNNING(owner));
991 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
994 } else if (RW_READERS(v) > 0) {
995 sleep_reason = READERS;
996 if (spintries == rowner_retries)
998 if (!(v & RW_LOCK_WRITE_SPINNER)) {
999 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1000 v | RW_LOCK_WRITE_SPINNER)) {
1005 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1006 "spinning", "lockname:\"%s\"",
1007 rw->lock_object.lo_name);
1008 for (i = 0; i < rowner_loops; i += n) {
1011 v = RW_READ_VALUE(rw);
1012 if ((v & RW_LOCK_WRITE_SPINNER) == 0)
1015 #ifdef KDTRACE_HOOKS
1018 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1020 if (i < rowner_loops)
1025 ts = turnstile_trywait(&rw->lock_object);
1026 v = RW_READ_VALUE(rw);
1028 owner = lv_rw_wowner(v);
1030 #ifdef ADAPTIVE_RWLOCKS
1032 * The current lock owner might have started executing
1033 * on another CPU (or the lock could have changed
1034 * owners) while we were waiting on the turnstile
1035 * chain lock. If so, drop the turnstile lock and try
1038 if (owner != NULL) {
1039 if (TD_IS_RUNNING(owner)) {
1040 turnstile_cancel(ts);
1043 } else if (RW_READERS(v) > 0 && sleep_reason == WRITER) {
1044 turnstile_cancel(ts);
1049 * Check for the waiters flags about this rwlock.
1050 * If the lock was released, without maintain any pending
1051 * waiters queue, simply try to acquire it.
1052 * If a pending waiters queue is present, claim the lock
1053 * ownership and maintain the pending queue.
1055 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1056 if ((v & ~x) == RW_UNLOCKED) {
1057 x &= ~RW_LOCK_WRITE_SPINNER;
1058 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid | x)) {
1060 turnstile_claim(ts);
1062 turnstile_cancel(ts);
1068 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1069 * set it. If we fail to set it, then loop back and try
1072 if (!(v & RW_LOCK_WRITE_WAITERS)) {
1073 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1074 v | RW_LOCK_WRITE_WAITERS))
1076 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1077 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1081 * We were unable to acquire the lock and the write waiters
1082 * flag is set, so we must block on the turnstile.
1084 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1085 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1087 #ifdef KDTRACE_HOOKS
1088 sleep_time -= lockstat_nsecs(&rw->lock_object);
1090 MPASS(owner == rw_owner(rw));
1091 turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
1092 #ifdef KDTRACE_HOOKS
1093 sleep_time += lockstat_nsecs(&rw->lock_object);
1096 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1097 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1099 #ifdef ADAPTIVE_RWLOCKS
1102 v = RW_READ_VALUE(rw);
1104 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1105 if (__predict_true(!doing_lockprof))
1108 #ifdef KDTRACE_HOOKS
1109 all_time += lockstat_nsecs(&rw->lock_object);
1111 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1112 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1113 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1115 /* Record only the loops spinning and not sleeping. */
1116 if (lda.spin_cnt > sleep_cnt)
1117 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1118 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1119 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1122 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1123 waittime, file, line, LOCKSTAT_WRITER);
1127 * This function is called if lockstat is active or the first try at releasing
1128 * a write lock failed. The latter means that the lock is recursed or one of
1129 * the 2 waiter bits must be set indicating that at least one thread is waiting
1133 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1136 struct turnstile *ts;
1137 uintptr_t tid, setv;
1140 tid = (uintptr_t)curthread;
1141 if (SCHEDULER_STOPPED())
1145 if (__predict_false(v == tid))
1146 v = RW_READ_VALUE(rw);
1148 if (v & RW_LOCK_WRITER_RECURSED) {
1149 if (--(rw->rw_recurse) == 0)
1150 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1151 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1152 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1156 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1157 if (v == tid && _rw_write_unlock(rw, tid))
1160 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1161 ("%s: neither of the waiter flags are set", __func__));
1163 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1164 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1166 turnstile_chain_lock(&rw->lock_object);
1169 * Use the same algo as sx locks for now. Prefer waking up shared
1170 * waiters if we have any over writers. This is probably not ideal.
1172 * 'v' is the value we are going to write back to rw_lock. If we
1173 * have waiters on both queues, we need to preserve the state of
1174 * the waiter flag for the queue we don't wake up. For now this is
1175 * hardcoded for the algorithm mentioned above.
1177 * In the case of both readers and writers waiting we wakeup the
1178 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1179 * new writer comes in before a reader it will claim the lock up
1180 * above. There is probably a potential priority inversion in
1181 * there that could be worked around either by waking both queues
1182 * of waiters or doing some complicated lock handoff gymnastics.
1185 v = RW_READ_VALUE(rw);
1186 queue = TS_SHARED_QUEUE;
1187 if (v & RW_LOCK_WRITE_WAITERS) {
1188 queue = TS_EXCLUSIVE_QUEUE;
1189 setv |= (v & RW_LOCK_READ_WAITERS);
1191 atomic_store_rel_ptr(&rw->rw_lock, setv);
1193 /* Wake up all waiters for the specific queue. */
1194 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1195 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1196 queue == TS_SHARED_QUEUE ? "read" : "write");
1198 ts = turnstile_lookup(&rw->lock_object);
1200 turnstile_broadcast(ts, queue);
1201 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1202 turnstile_chain_unlock(&rw->lock_object);
1206 * Attempt to do a non-blocking upgrade from a read lock to a write
1207 * lock. This will only succeed if this thread holds a single read
1208 * lock. Returns true if the upgrade succeeded and false otherwise.
1211 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1213 uintptr_t v, setv, tid;
1214 struct turnstile *ts;
1217 if (SCHEDULER_STOPPED())
1220 KASSERT(rw->rw_lock != RW_DESTROYED,
1221 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1222 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1225 * Attempt to switch from one reader to a writer. If there
1226 * are any write waiters, then we will have to lock the
1227 * turnstile first to prevent races with another writer
1228 * calling turnstile_wait() before we have claimed this
1229 * turnstile. So, do the simple case of no waiters first.
1231 tid = (uintptr_t)curthread;
1233 v = RW_READ_VALUE(rw);
1235 if (RW_READERS(v) > 1)
1237 if (!(v & RW_LOCK_WAITERS)) {
1238 success = atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid);
1245 * Ok, we think we have waiters, so lock the turnstile.
1247 ts = turnstile_trywait(&rw->lock_object);
1248 v = RW_READ_VALUE(rw);
1250 if (RW_READERS(v) > 1) {
1251 turnstile_cancel(ts);
1255 * Try to switch from one reader to a writer again. This time
1256 * we honor the current state of the waiters flags.
1257 * If we obtain the lock with the flags set, then claim
1258 * ownership of the turnstile.
1260 setv = tid | (v & RW_LOCK_WAITERS);
1261 success = atomic_fcmpset_ptr(&rw->rw_lock, &v, setv);
1263 if (v & RW_LOCK_WAITERS)
1264 turnstile_claim(ts);
1266 turnstile_cancel(ts);
1271 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1273 curthread->td_rw_rlocks--;
1274 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1276 LOCKSTAT_RECORD0(rw__upgrade, rw);
1282 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1287 return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1291 * Downgrade a write lock into a single read lock.
1294 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1296 struct turnstile *ts;
1300 if (SCHEDULER_STOPPED())
1303 KASSERT(rw->rw_lock != RW_DESTROYED,
1304 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1305 __rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1307 if (rw_recursed(rw))
1308 panic("downgrade of a recursed lock");
1311 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1314 * Convert from a writer to a single reader. First we handle
1315 * the easy case with no waiters. If there are any waiters, we
1316 * lock the turnstile and "disown" the lock.
1318 tid = (uintptr_t)curthread;
1319 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1323 * Ok, we think we have waiters, so lock the turnstile so we can
1324 * read the waiter flags without any races.
1326 turnstile_chain_lock(&rw->lock_object);
1327 v = rw->rw_lock & RW_LOCK_WAITERS;
1328 rwait = v & RW_LOCK_READ_WAITERS;
1329 wwait = v & RW_LOCK_WRITE_WAITERS;
1330 MPASS(rwait | wwait);
1333 * Downgrade from a write lock while preserving waiters flag
1334 * and give up ownership of the turnstile.
1336 ts = turnstile_lookup(&rw->lock_object);
1339 v &= ~RW_LOCK_READ_WAITERS;
1340 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1342 * Wake other readers if there are no writers pending. Otherwise they
1343 * won't be able to acquire the lock anyway.
1345 if (rwait && !wwait) {
1346 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1347 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1349 turnstile_disown(ts);
1350 turnstile_chain_unlock(&rw->lock_object);
1352 curthread->td_rw_rlocks++;
1353 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1354 LOCKSTAT_RECORD0(rw__downgrade, rw);
1358 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1363 __rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1366 #ifdef INVARIANT_SUPPORT
1372 * In the non-WITNESS case, rw_assert() can only detect that at least
1373 * *some* thread owns an rlock, but it cannot guarantee that *this*
1374 * thread owns an rlock.
1377 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1379 const struct rwlock *rw;
1381 if (SCHEDULER_STOPPED())
1388 case RA_LOCKED | RA_RECURSED:
1389 case RA_LOCKED | RA_NOTRECURSED:
1391 case RA_RLOCKED | RA_RECURSED:
1392 case RA_RLOCKED | RA_NOTRECURSED:
1394 witness_assert(&rw->lock_object, what, file, line);
1397 * If some other thread has a write lock or we have one
1398 * and are asserting a read lock, fail. Also, if no one
1399 * has a lock at all, fail.
1401 if (rw->rw_lock == RW_UNLOCKED ||
1402 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1403 rw_wowner(rw) != curthread)))
1404 panic("Lock %s not %slocked @ %s:%d\n",
1405 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1406 "read " : "", file, line);
1408 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1409 if (rw_recursed(rw)) {
1410 if (what & RA_NOTRECURSED)
1411 panic("Lock %s recursed @ %s:%d\n",
1412 rw->lock_object.lo_name, file,
1414 } else if (what & RA_RECURSED)
1415 panic("Lock %s not recursed @ %s:%d\n",
1416 rw->lock_object.lo_name, file, line);
1421 case RA_WLOCKED | RA_RECURSED:
1422 case RA_WLOCKED | RA_NOTRECURSED:
1423 if (rw_wowner(rw) != curthread)
1424 panic("Lock %s not exclusively locked @ %s:%d\n",
1425 rw->lock_object.lo_name, file, line);
1426 if (rw_recursed(rw)) {
1427 if (what & RA_NOTRECURSED)
1428 panic("Lock %s recursed @ %s:%d\n",
1429 rw->lock_object.lo_name, file, line);
1430 } else if (what & RA_RECURSED)
1431 panic("Lock %s not recursed @ %s:%d\n",
1432 rw->lock_object.lo_name, file, line);
1436 witness_assert(&rw->lock_object, what, file, line);
1439 * If we hold a write lock fail. We can't reliably check
1440 * to see if we hold a read lock or not.
1442 if (rw_wowner(rw) == curthread)
1443 panic("Lock %s exclusively locked @ %s:%d\n",
1444 rw->lock_object.lo_name, file, line);
1448 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1452 #endif /* INVARIANT_SUPPORT */
1456 db_show_rwlock(const struct lock_object *lock)
1458 const struct rwlock *rw;
1461 rw = (const struct rwlock *)lock;
1463 db_printf(" state: ");
1464 if (rw->rw_lock == RW_UNLOCKED)
1465 db_printf("UNLOCKED\n");
1466 else if (rw->rw_lock == RW_DESTROYED) {
1467 db_printf("DESTROYED\n");
1469 } else if (rw->rw_lock & RW_LOCK_READ)
1470 db_printf("RLOCK: %ju locks\n",
1471 (uintmax_t)(RW_READERS(rw->rw_lock)));
1474 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1475 td->td_tid, td->td_proc->p_pid, td->td_name);
1476 if (rw_recursed(rw))
1477 db_printf(" recursed: %u\n", rw->rw_recurse);
1479 db_printf(" waiters: ");
1480 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1481 case RW_LOCK_READ_WAITERS:
1482 db_printf("readers\n");
1484 case RW_LOCK_WRITE_WAITERS:
1485 db_printf("writers\n");
1487 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1488 db_printf("readers and writers\n");
1491 db_printf("none\n");