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 = 10;
97 static int __read_frequently rowner_loops = 10000;
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,
110 LOCK_DELAY_SYSINIT_DEFAULT(rw_delay);
114 * Return a pointer to the owning thread if the lock is write-locked or
115 * NULL if the lock is unlocked or read-locked.
118 #define lv_rw_wowner(v) \
119 ((v) & RW_LOCK_READ ? NULL : \
120 (struct thread *)RW_OWNER((v)))
122 #define rw_wowner(rw) lv_rw_wowner(RW_READ_VALUE(rw))
125 * Returns if a write owner is recursed. Write ownership is not assured
126 * here and should be previously checked.
128 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
131 * Return true if curthread helds the lock.
133 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
136 * Return a pointer to the owning thread for this lock who should receive
137 * any priority lent by threads that block on this lock. Currently this
138 * is identical to rw_wowner().
140 #define rw_owner(rw) rw_wowner(rw)
143 #define __rw_assert(c, what, file, line)
147 assert_rw(const struct lock_object *lock, int what)
150 rw_assert((const struct rwlock *)lock, what);
154 lock_rw(struct lock_object *lock, uintptr_t how)
158 rw = (struct rwlock *)lock;
166 unlock_rw(struct lock_object *lock)
170 rw = (struct rwlock *)lock;
171 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
172 if (rw->rw_lock & RW_LOCK_READ) {
183 owner_rw(const struct lock_object *lock, struct thread **owner)
185 const struct rwlock *rw = (const struct rwlock *)lock;
186 uintptr_t x = rw->rw_lock;
188 *owner = rw_wowner(rw);
189 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
195 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
202 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
203 RW_RECURSE | RW_NEW)) == 0);
204 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
205 ("%s: rw_lock not aligned for %s: %p", __func__, name,
208 flags = LO_UPGRADABLE;
211 if (opts & RW_NOPROFILE)
212 flags |= LO_NOPROFILE;
213 if (!(opts & RW_NOWITNESS))
215 if (opts & RW_RECURSE)
216 flags |= LO_RECURSABLE;
222 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
223 rw->rw_lock = RW_UNLOCKED;
228 _rw_destroy(volatile uintptr_t *c)
234 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
235 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
236 rw->rw_lock = RW_DESTROYED;
237 lock_destroy(&rw->lock_object);
241 rw_sysinit(void *arg)
243 struct rw_args *args = arg;
245 rw_init((struct rwlock *)args->ra_rw, args->ra_desc);
249 rw_sysinit_flags(void *arg)
251 struct rw_args_flags *args = arg;
253 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
258 _rw_wowned(const volatile uintptr_t *c)
261 return (rw_wowner(rwlock2rw(c)) == curthread);
265 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
272 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
273 !TD_IS_IDLETHREAD(curthread),
274 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
275 curthread, rw->lock_object.lo_name, file, line));
276 KASSERT(rw->rw_lock != RW_DESTROYED,
277 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
278 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
280 tid = (uintptr_t)curthread;
282 if (!_rw_write_lock_fetch(rw, &v, tid))
283 _rw_wlock_hard(rw, v, tid, file, line);
285 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
286 0, 0, file, line, LOCKSTAT_WRITER);
288 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
289 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
290 TD_LOCKS_INC(curthread);
294 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
304 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_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
351 KASSERT(rw->rw_lock != RW_DESTROYED,
352 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
353 __rw_assert(c, RA_WLOCKED, file, line);
354 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
355 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
358 #ifdef LOCK_PROFILING
359 _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
361 __rw_wunlock(rw, curthread, file, line);
364 TD_LOCKS_DEC(curthread);
368 * Determines whether a new reader can acquire a lock. Succeeds if the
369 * reader already owns a read lock and the lock is locked for read to
370 * prevent deadlock from reader recursion. Also succeeds if the lock
371 * is unlocked and has no writer waiters or spinners. Failing otherwise
372 * prioritizes writers before readers.
374 #define RW_CAN_READ(td, _rw) \
375 (((_rw) & (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) ==\
376 RW_LOCK_READ || ((td)->td_rw_rlocks && (_rw) & RW_LOCK_READ))
378 static bool __always_inline
379 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp,
380 const char *file, int line)
384 * Handle the easy case. If no other thread has a write
385 * lock, then try to bump up the count of read locks. Note
386 * that we have to preserve the current state of the
387 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
388 * read lock, then rw_lock must have changed, so restart
389 * the loop. Note that this handles the case of a
390 * completely unlocked rwlock since such a lock is encoded
391 * as a read lock with no waiters.
393 while (RW_CAN_READ(td, *vp)) {
394 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
395 *vp + RW_ONE_READER)) {
396 if (LOCK_LOG_TEST(&rw->lock_object, 0))
398 "%s: %p succeed %p -> %p", __func__,
400 (void *)(*vp + RW_ONE_READER));
408 static void __noinline
409 __rw_rlock_hard(volatile uintptr_t *c, struct thread *td, uintptr_t v,
410 const char *file, int line)
413 struct turnstile *ts;
414 #ifdef ADAPTIVE_RWLOCKS
415 volatile struct thread *owner;
419 #ifdef LOCK_PROFILING
420 uint64_t waittime = 0;
423 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
424 struct lock_delay_arg lda;
429 int64_t sleep_time = 0;
430 int64_t all_time = 0;
433 if (SCHEDULER_STOPPED())
436 #if defined(ADAPTIVE_RWLOCKS)
437 lock_delay_arg_init(&lda, &rw_delay);
438 #elif defined(KDTRACE_HOOKS)
439 lock_delay_arg_init(&lda, NULL);
444 all_time -= lockstat_nsecs(&rw->lock_object);
450 if (__rw_rlock_try(rw, td, &v, file, line))
456 PMC_SOFT_CALL( , , lock, failed);
458 lock_profile_obtain_lock_failed(&rw->lock_object,
459 &contested, &waittime);
461 #ifdef ADAPTIVE_RWLOCKS
463 * If the owner is running on another CPU, spin until
464 * the owner stops running or the state of the lock
467 if ((v & RW_LOCK_READ) == 0) {
468 owner = (struct thread *)RW_OWNER(v);
469 if (TD_IS_RUNNING(owner)) {
470 if (LOCK_LOG_TEST(&rw->lock_object, 0))
472 "%s: spinning on %p held by %p",
473 __func__, rw, owner);
474 KTR_STATE1(KTR_SCHED, "thread",
475 sched_tdname(curthread), "spinning",
476 "lockname:\"%s\"", rw->lock_object.lo_name);
479 v = RW_READ_VALUE(rw);
480 owner = lv_rw_wowner(v);
481 } while (owner != NULL && TD_IS_RUNNING(owner));
482 KTR_STATE0(KTR_SCHED, "thread",
483 sched_tdname(curthread), "running");
486 } else if (spintries < rowner_retries) {
488 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
489 "spinning", "lockname:\"%s\"",
490 rw->lock_object.lo_name);
491 for (i = 0; i < rowner_loops; i += n) {
494 v = RW_READ_VALUE(rw);
495 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(td, v))
499 lda.spin_cnt += rowner_loops - i;
501 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
503 if (i != rowner_loops)
509 * Okay, now it's the hard case. Some other thread already
510 * has a write lock or there are write waiters present,
511 * acquire the turnstile lock so we can begin the process
514 ts = turnstile_trywait(&rw->lock_object);
517 * The lock might have been released while we spun, so
518 * recheck its state and restart the loop if needed.
520 v = RW_READ_VALUE(rw);
521 if (RW_CAN_READ(td, v)) {
522 turnstile_cancel(ts);
526 #ifdef ADAPTIVE_RWLOCKS
528 * The current lock owner might have started executing
529 * on another CPU (or the lock could have changed
530 * owners) while we were waiting on the turnstile
531 * chain lock. If so, drop the turnstile lock and try
534 if ((v & RW_LOCK_READ) == 0) {
535 owner = (struct thread *)RW_OWNER(v);
536 if (TD_IS_RUNNING(owner)) {
537 turnstile_cancel(ts);
544 * The lock is held in write mode or it already has waiters.
546 MPASS(!RW_CAN_READ(td, v));
549 * If the RW_LOCK_READ_WAITERS flag is already set, then
550 * we can go ahead and block. If it is not set then try
551 * to set it. If we fail to set it drop the turnstile
552 * lock and restart the loop.
554 if (!(v & RW_LOCK_READ_WAITERS)) {
555 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
556 v | RW_LOCK_READ_WAITERS)) {
557 turnstile_cancel(ts);
558 v = RW_READ_VALUE(rw);
561 if (LOCK_LOG_TEST(&rw->lock_object, 0))
562 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
567 * We were unable to acquire the lock and the read waiters
568 * flag is set, so we must block on the turnstile.
570 if (LOCK_LOG_TEST(&rw->lock_object, 0))
571 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
574 sleep_time -= lockstat_nsecs(&rw->lock_object);
576 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
578 sleep_time += lockstat_nsecs(&rw->lock_object);
581 if (LOCK_LOG_TEST(&rw->lock_object, 0))
582 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
584 v = RW_READ_VALUE(rw);
587 all_time += lockstat_nsecs(&rw->lock_object);
589 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
590 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
591 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
593 /* Record only the loops spinning and not sleeping. */
594 if (lda.spin_cnt > sleep_cnt)
595 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
596 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
597 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
600 * TODO: acquire "owner of record" here. Here be turnstile dragons
601 * however. turnstiles don't like owners changing between calls to
602 * turnstile_wait() currently.
604 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
605 waittime, file, line, LOCKSTAT_READER);
609 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
618 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
619 !TD_IS_IDLETHREAD(td),
620 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
621 td, rw->lock_object.lo_name, file, line));
622 KASSERT(rw->rw_lock != RW_DESTROYED,
623 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
624 KASSERT(rw_wowner(rw) != td,
625 ("rw_rlock: wlock already held for %s @ %s:%d",
626 rw->lock_object.lo_name, file, line));
627 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
629 v = RW_READ_VALUE(rw);
630 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__acquire) ||
631 !__rw_rlock_try(rw, td, &v, file, line)))
632 __rw_rlock_hard(c, td, v, file, line);
634 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
635 WITNESS_LOCK(&rw->lock_object, 0, file, line);
636 TD_LOCKS_INC(curthread);
640 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
645 if (SCHEDULER_STOPPED())
650 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
651 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
652 curthread, rw->lock_object.lo_name, file, line));
656 KASSERT(rw->rw_lock != RW_DESTROYED,
657 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
658 if (!(x & RW_LOCK_READ))
660 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
661 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
663 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
664 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
665 rw, 0, 0, file, line, LOCKSTAT_READER);
666 TD_LOCKS_INC(curthread);
667 curthread->td_rw_rlocks++;
672 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
676 static bool __always_inline
677 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
682 * See if there is more than one read lock held. If so,
683 * just drop one and return.
685 if (RW_READERS(*vp) > 1) {
686 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
687 *vp - RW_ONE_READER)) {
688 if (LOCK_LOG_TEST(&rw->lock_object, 0))
690 "%s: %p succeeded %p -> %p",
691 __func__, rw, (void *)*vp,
692 (void *)(*vp - RW_ONE_READER));
699 * If there aren't any waiters for a write lock, then try
700 * to drop it quickly.
702 if (!(*vp & RW_LOCK_WAITERS)) {
703 MPASS((*vp & ~RW_LOCK_WRITE_SPINNER) ==
705 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
707 if (LOCK_LOG_TEST(&rw->lock_object, 0))
708 CTR2(KTR_LOCK, "%s: %p last succeeded",
720 static void __noinline
721 __rw_runlock_hard(volatile uintptr_t *c, struct thread *td, uintptr_t v,
722 const char *file, int line)
725 struct turnstile *ts;
728 if (SCHEDULER_STOPPED())
734 if (__rw_runlock_try(rw, td, &v))
738 * Ok, we know we have waiters and we think we are the
739 * last reader, so grab the turnstile lock.
741 turnstile_chain_lock(&rw->lock_object);
742 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
743 MPASS(v & RW_LOCK_WAITERS);
746 * Try to drop our lock leaving the lock in a unlocked
749 * If you wanted to do explicit lock handoff you'd have to
750 * do it here. You'd also want to use turnstile_signal()
751 * and you'd have to handle the race where a higher
752 * priority thread blocks on the write lock before the
753 * thread you wakeup actually runs and have the new thread
754 * "steal" the lock. For now it's a lot simpler to just
755 * wakeup all of the waiters.
757 * As above, if we fail, then another thread might have
758 * acquired a read lock, so drop the turnstile lock and
762 if (v & RW_LOCK_WRITE_WAITERS) {
763 queue = TS_EXCLUSIVE_QUEUE;
764 x |= (v & RW_LOCK_READ_WAITERS);
766 queue = TS_SHARED_QUEUE;
767 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
769 turnstile_chain_unlock(&rw->lock_object);
770 v = RW_READ_VALUE(rw);
773 if (LOCK_LOG_TEST(&rw->lock_object, 0))
774 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
778 * Ok. The lock is released and all that's left is to
779 * wake up the waiters. Note that the lock might not be
780 * free anymore, but in that case the writers will just
781 * block again if they run before the new lock holder(s)
784 ts = turnstile_lookup(&rw->lock_object);
786 turnstile_broadcast(ts, queue);
787 turnstile_unpend(ts, TS_SHARED_LOCK);
788 turnstile_chain_unlock(&rw->lock_object);
792 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
796 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
804 KASSERT(rw->rw_lock != RW_DESTROYED,
805 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
806 __rw_assert(c, RA_RLOCKED, file, line);
807 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
808 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
811 v = RW_READ_VALUE(rw);
813 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__release) ||
814 !__rw_runlock_try(rw, td, &v)))
815 __rw_runlock_hard(c, td, v, file, line);
817 TD_LOCKS_DEC(curthread);
821 * This function is called when we are unable to obtain a write lock on the
822 * first try. This means that at least one other thread holds either a
823 * read or write lock.
826 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v, uintptr_t tid,
827 const char *file, int line)
830 struct turnstile *ts;
831 #ifdef ADAPTIVE_RWLOCKS
832 volatile struct thread *owner;
837 #ifdef LOCK_PROFILING
838 uint64_t waittime = 0;
841 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
842 struct lock_delay_arg lda;
846 int64_t sleep_time = 0;
847 int64_t all_time = 0;
849 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
854 if (SCHEDULER_STOPPED())
857 #if defined(ADAPTIVE_RWLOCKS)
858 lock_delay_arg_init(&lda, &rw_delay);
859 #elif defined(KDTRACE_HOOKS)
860 lock_delay_arg_init(&lda, NULL);
863 if (__predict_false(v == RW_UNLOCKED))
864 v = RW_READ_VALUE(rw);
866 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
867 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
868 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
869 __func__, rw->lock_object.lo_name, file, line));
871 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
872 if (LOCK_LOG_TEST(&rw->lock_object, 0))
873 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
877 if (LOCK_LOG_TEST(&rw->lock_object, 0))
878 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
879 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
881 #ifdef LOCK_PROFILING
884 #elif defined(KDTRACE_HOOKS)
885 doing_lockprof = lockstat_enabled;
886 if (__predict_false(doing_lockprof)) {
887 all_time -= lockstat_nsecs(&rw->lock_object);
893 if (v == RW_UNLOCKED) {
894 if (_rw_write_lock_fetch(rw, &v, tid))
902 PMC_SOFT_CALL( , , lock, failed);
904 lock_profile_obtain_lock_failed(&rw->lock_object,
905 &contested, &waittime);
906 #ifdef ADAPTIVE_RWLOCKS
908 * If the lock is write locked and the owner is
909 * running on another CPU, spin until the owner stops
910 * running or the state of the lock changes.
912 owner = lv_rw_wowner(v);
913 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
914 if (LOCK_LOG_TEST(&rw->lock_object, 0))
915 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
916 __func__, rw, owner);
917 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
918 "spinning", "lockname:\"%s\"",
919 rw->lock_object.lo_name);
922 v = RW_READ_VALUE(rw);
923 owner = lv_rw_wowner(v);
924 } while (owner != NULL && TD_IS_RUNNING(owner));
925 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
929 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
930 spintries < rowner_retries) {
931 if (!(v & RW_LOCK_WRITE_SPINNER)) {
932 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
933 v | RW_LOCK_WRITE_SPINNER)) {
938 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
939 "spinning", "lockname:\"%s\"",
940 rw->lock_object.lo_name);
941 for (i = 0; i < rowner_loops; i += n) {
944 v = RW_READ_VALUE(rw);
945 if ((v & RW_LOCK_WRITE_SPINNER) == 0)
948 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
951 lda.spin_cnt += rowner_loops - i;
953 if (i != rowner_loops)
957 ts = turnstile_trywait(&rw->lock_object);
958 v = RW_READ_VALUE(rw);
960 #ifdef ADAPTIVE_RWLOCKS
962 * The current lock owner might have started executing
963 * on another CPU (or the lock could have changed
964 * owners) while we were waiting on the turnstile
965 * chain lock. If so, drop the turnstile lock and try
968 if (!(v & RW_LOCK_READ)) {
969 owner = (struct thread *)RW_OWNER(v);
970 if (TD_IS_RUNNING(owner)) {
971 turnstile_cancel(ts);
977 * Check for the waiters flags about this rwlock.
978 * If the lock was released, without maintain any pending
979 * waiters queue, simply try to acquire it.
980 * If a pending waiters queue is present, claim the lock
981 * ownership and maintain the pending queue.
983 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
984 if ((v & ~x) == RW_UNLOCKED) {
985 x &= ~RW_LOCK_WRITE_SPINNER;
986 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
990 turnstile_cancel(ts);
993 turnstile_cancel(ts);
994 v = RW_READ_VALUE(rw);
998 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
999 * set it. If we fail to set it, then loop back and try
1002 if (!(v & RW_LOCK_WRITE_WAITERS)) {
1003 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
1004 v | RW_LOCK_WRITE_WAITERS)) {
1005 turnstile_cancel(ts);
1006 v = RW_READ_VALUE(rw);
1009 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1010 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1014 * We were unable to acquire the lock and the write waiters
1015 * flag is set, so we must block on the turnstile.
1017 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1018 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1020 #ifdef KDTRACE_HOOKS
1021 sleep_time -= lockstat_nsecs(&rw->lock_object);
1023 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
1024 #ifdef KDTRACE_HOOKS
1025 sleep_time += lockstat_nsecs(&rw->lock_object);
1028 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1029 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1031 #ifdef ADAPTIVE_RWLOCKS
1034 v = RW_READ_VALUE(rw);
1036 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1037 if (__predict_true(!doing_lockprof))
1040 #ifdef KDTRACE_HOOKS
1041 all_time += lockstat_nsecs(&rw->lock_object);
1043 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1044 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1045 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1047 /* Record only the loops spinning and not sleeping. */
1048 if (lda.spin_cnt > sleep_cnt)
1049 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1050 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1051 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1053 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1054 waittime, file, line, LOCKSTAT_WRITER);
1058 * This function is called if lockstat is active or the first try at releasing
1059 * a write lock failed. The latter means that the lock is recursed or one of
1060 * the 2 waiter bits must be set indicating that at least one thread is waiting
1064 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
1068 struct turnstile *ts;
1072 if (SCHEDULER_STOPPED())
1076 v = RW_READ_VALUE(rw);
1077 if (v & RW_LOCK_WRITER_RECURSED) {
1078 if (--(rw->rw_recurse) == 0)
1079 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1080 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1081 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1085 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1086 if (v == tid && _rw_write_unlock(rw, tid))
1089 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1090 ("%s: neither of the waiter flags are set", __func__));
1092 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1093 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1095 turnstile_chain_lock(&rw->lock_object);
1096 ts = turnstile_lookup(&rw->lock_object);
1100 * Use the same algo as sx locks for now. Prefer waking up shared
1101 * waiters if we have any over writers. This is probably not ideal.
1103 * 'v' is the value we are going to write back to rw_lock. If we
1104 * have waiters on both queues, we need to preserve the state of
1105 * the waiter flag for the queue we don't wake up. For now this is
1106 * hardcoded for the algorithm mentioned above.
1108 * In the case of both readers and writers waiting we wakeup the
1109 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1110 * new writer comes in before a reader it will claim the lock up
1111 * above. There is probably a potential priority inversion in
1112 * there that could be worked around either by waking both queues
1113 * of waiters or doing some complicated lock handoff gymnastics.
1116 if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
1117 queue = TS_EXCLUSIVE_QUEUE;
1118 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
1120 queue = TS_SHARED_QUEUE;
1122 /* Wake up all waiters for the specific queue. */
1123 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1124 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1125 queue == TS_SHARED_QUEUE ? "read" : "write");
1126 turnstile_broadcast(ts, queue);
1127 atomic_store_rel_ptr(&rw->rw_lock, v);
1128 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1129 turnstile_chain_unlock(&rw->lock_object);
1133 * Attempt to do a non-blocking upgrade from a read lock to a write
1134 * lock. This will only succeed if this thread holds a single read
1135 * lock. Returns true if the upgrade succeeded and false otherwise.
1138 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1141 uintptr_t v, x, tid;
1142 struct turnstile *ts;
1145 if (SCHEDULER_STOPPED())
1150 KASSERT(rw->rw_lock != RW_DESTROYED,
1151 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1152 __rw_assert(c, RA_RLOCKED, file, line);
1155 * Attempt to switch from one reader to a writer. If there
1156 * are any write waiters, then we will have to lock the
1157 * turnstile first to prevent races with another writer
1158 * calling turnstile_wait() before we have claimed this
1159 * turnstile. So, do the simple case of no waiters first.
1161 tid = (uintptr_t)curthread;
1165 if (RW_READERS(v) > 1)
1167 if (!(v & RW_LOCK_WAITERS)) {
1168 success = atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid);
1175 * Ok, we think we have waiters, so lock the turnstile.
1177 ts = turnstile_trywait(&rw->lock_object);
1179 if (RW_READERS(v) > 1) {
1180 turnstile_cancel(ts);
1184 * Try to switch from one reader to a writer again. This time
1185 * we honor the current state of the waiters flags.
1186 * If we obtain the lock with the flags set, then claim
1187 * ownership of the turnstile.
1189 x = rw->rw_lock & RW_LOCK_WAITERS;
1190 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1193 turnstile_claim(ts);
1195 turnstile_cancel(ts);
1198 turnstile_cancel(ts);
1200 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1202 curthread->td_rw_rlocks--;
1203 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1205 LOCKSTAT_RECORD0(rw__upgrade, rw);
1211 * Downgrade a write lock into a single read lock.
1214 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1217 struct turnstile *ts;
1221 if (SCHEDULER_STOPPED())
1226 KASSERT(rw->rw_lock != RW_DESTROYED,
1227 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1228 __rw_assert(c, RA_WLOCKED | RA_NOTRECURSED, file, line);
1230 if (rw_recursed(rw))
1231 panic("downgrade of a recursed lock");
1234 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1237 * Convert from a writer to a single reader. First we handle
1238 * the easy case with no waiters. If there are any waiters, we
1239 * lock the turnstile and "disown" the lock.
1241 tid = (uintptr_t)curthread;
1242 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1246 * Ok, we think we have waiters, so lock the turnstile so we can
1247 * read the waiter flags without any races.
1249 turnstile_chain_lock(&rw->lock_object);
1250 v = rw->rw_lock & RW_LOCK_WAITERS;
1251 rwait = v & RW_LOCK_READ_WAITERS;
1252 wwait = v & RW_LOCK_WRITE_WAITERS;
1253 MPASS(rwait | wwait);
1256 * Downgrade from a write lock while preserving waiters flag
1257 * and give up ownership of the turnstile.
1259 ts = turnstile_lookup(&rw->lock_object);
1262 v &= ~RW_LOCK_READ_WAITERS;
1263 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1265 * Wake other readers if there are no writers pending. Otherwise they
1266 * won't be able to acquire the lock anyway.
1268 if (rwait && !wwait) {
1269 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1270 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1272 turnstile_disown(ts);
1273 turnstile_chain_unlock(&rw->lock_object);
1275 curthread->td_rw_rlocks++;
1276 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1277 LOCKSTAT_RECORD0(rw__downgrade, rw);
1280 #ifdef INVARIANT_SUPPORT
1286 * In the non-WITNESS case, rw_assert() can only detect that at least
1287 * *some* thread owns an rlock, but it cannot guarantee that *this*
1288 * thread owns an rlock.
1291 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1293 const struct rwlock *rw;
1295 if (panicstr != NULL)
1302 case RA_LOCKED | RA_RECURSED:
1303 case RA_LOCKED | RA_NOTRECURSED:
1305 case RA_RLOCKED | RA_RECURSED:
1306 case RA_RLOCKED | RA_NOTRECURSED:
1308 witness_assert(&rw->lock_object, what, file, line);
1311 * If some other thread has a write lock or we have one
1312 * and are asserting a read lock, fail. Also, if no one
1313 * has a lock at all, fail.
1315 if (rw->rw_lock == RW_UNLOCKED ||
1316 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1317 rw_wowner(rw) != curthread)))
1318 panic("Lock %s not %slocked @ %s:%d\n",
1319 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1320 "read " : "", file, line);
1322 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1323 if (rw_recursed(rw)) {
1324 if (what & RA_NOTRECURSED)
1325 panic("Lock %s recursed @ %s:%d\n",
1326 rw->lock_object.lo_name, file,
1328 } else if (what & RA_RECURSED)
1329 panic("Lock %s not recursed @ %s:%d\n",
1330 rw->lock_object.lo_name, file, line);
1335 case RA_WLOCKED | RA_RECURSED:
1336 case RA_WLOCKED | RA_NOTRECURSED:
1337 if (rw_wowner(rw) != curthread)
1338 panic("Lock %s not exclusively locked @ %s:%d\n",
1339 rw->lock_object.lo_name, file, line);
1340 if (rw_recursed(rw)) {
1341 if (what & RA_NOTRECURSED)
1342 panic("Lock %s recursed @ %s:%d\n",
1343 rw->lock_object.lo_name, file, line);
1344 } else if (what & RA_RECURSED)
1345 panic("Lock %s not recursed @ %s:%d\n",
1346 rw->lock_object.lo_name, file, line);
1350 witness_assert(&rw->lock_object, what, file, line);
1353 * If we hold a write lock fail. We can't reliably check
1354 * to see if we hold a read lock or not.
1356 if (rw_wowner(rw) == curthread)
1357 panic("Lock %s exclusively locked @ %s:%d\n",
1358 rw->lock_object.lo_name, file, line);
1362 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1366 #endif /* INVARIANT_SUPPORT */
1370 db_show_rwlock(const struct lock_object *lock)
1372 const struct rwlock *rw;
1375 rw = (const struct rwlock *)lock;
1377 db_printf(" state: ");
1378 if (rw->rw_lock == RW_UNLOCKED)
1379 db_printf("UNLOCKED\n");
1380 else if (rw->rw_lock == RW_DESTROYED) {
1381 db_printf("DESTROYED\n");
1383 } else if (rw->rw_lock & RW_LOCK_READ)
1384 db_printf("RLOCK: %ju locks\n",
1385 (uintmax_t)(RW_READERS(rw->rw_lock)));
1388 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1389 td->td_tid, td->td_proc->p_pid, td->td_name);
1390 if (rw_recursed(rw))
1391 db_printf(" recursed: %u\n", rw->rw_recurse);
1393 db_printf(" waiters: ");
1394 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1395 case RW_LOCK_READ_WAITERS:
1396 db_printf("readers\n");
1398 case RW_LOCK_WRITE_WAITERS:
1399 db_printf("writers\n");
1401 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1402 db_printf("readers and writers\n");
1405 db_printf("none\n");