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;
246 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
251 _rw_wowned(const volatile uintptr_t *c)
254 return (rw_wowner(rwlock2rw(c)) == curthread);
258 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
265 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
266 !TD_IS_IDLETHREAD(curthread),
267 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
268 curthread, rw->lock_object.lo_name, file, line));
269 KASSERT(rw->rw_lock != RW_DESTROYED,
270 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
271 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
273 tid = (uintptr_t)curthread;
275 if (!_rw_write_lock_fetch(rw, &v, tid))
276 _rw_wlock_hard(rw, v, file, line);
278 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
279 0, 0, file, line, LOCKSTAT_WRITER);
281 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
282 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
283 TD_LOCKS_INC(curthread);
287 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
297 if (SCHEDULER_STOPPED_TD(td))
302 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
303 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
304 curthread, rw->lock_object.lo_name, file, line));
305 KASSERT(rw->rw_lock != RW_DESTROYED,
306 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
312 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
314 if (v == RW_UNLOCKED)
316 if (v == tid && (rw->lock_object.lo_flags & LO_RECURSABLE)) {
318 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
325 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
327 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
330 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
331 rw, 0, 0, file, line, LOCKSTAT_WRITER);
332 TD_LOCKS_INC(curthread);
338 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
344 KASSERT(rw->rw_lock != RW_DESTROYED,
345 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
346 __rw_assert(c, RA_WLOCKED, file, line);
347 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
348 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
351 #ifdef LOCK_PROFILING
352 _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
354 __rw_wunlock(rw, curthread, file, line);
357 TD_LOCKS_DEC(curthread);
361 * Determines whether a new reader can acquire a lock. Succeeds if the
362 * reader already owns a read lock and the lock is locked for read to
363 * prevent deadlock from reader recursion. Also succeeds if the lock
364 * is unlocked and has no writer waiters or spinners. Failing otherwise
365 * prioritizes writers before readers.
367 static bool __always_inline
368 __rw_can_read(struct thread *td, uintptr_t v, bool fp)
371 if ((v & (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER))
374 if (!fp && td->td_rw_rlocks && (v & RW_LOCK_READ))
379 static bool __always_inline
380 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp, bool fp
381 LOCK_FILE_LINE_ARG_DEF)
385 * Handle the easy case. If no other thread has a write
386 * lock, then try to bump up the count of read locks. Note
387 * that we have to preserve the current state of the
388 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
389 * read lock, then rw_lock must have changed, so restart
390 * the loop. Note that this handles the case of a
391 * completely unlocked rwlock since such a lock is encoded
392 * as a read lock with no waiters.
394 while (__rw_can_read(td, *vp, fp)) {
395 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
396 *vp + RW_ONE_READER)) {
397 if (LOCK_LOG_TEST(&rw->lock_object, 0))
399 "%s: %p succeed %p -> %p", __func__,
401 (void *)(*vp + RW_ONE_READER));
409 static void __noinline
410 __rw_rlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
411 LOCK_FILE_LINE_ARG_DEF)
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;
428 int64_t sleep_time = 0;
429 int64_t all_time = 0;
431 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
436 if (SCHEDULER_STOPPED())
439 #if defined(ADAPTIVE_RWLOCKS)
440 lock_delay_arg_init(&lda, &rw_delay);
441 #elif defined(KDTRACE_HOOKS)
442 lock_delay_arg_init(&lda, NULL);
446 PMC_SOFT_CALL( , , lock, failed);
448 lock_profile_obtain_lock_failed(&rw->lock_object,
449 &contested, &waittime);
451 #ifdef LOCK_PROFILING
454 #elif defined(KDTRACE_HOOKS)
455 doing_lockprof = lockstat_enabled;
456 if (__predict_false(doing_lockprof)) {
457 all_time -= lockstat_nsecs(&rw->lock_object);
463 if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
469 #ifdef ADAPTIVE_RWLOCKS
471 * If the owner is running on another CPU, spin until
472 * the owner stops running or the state of the lock
475 if ((v & RW_LOCK_READ) == 0) {
476 owner = (struct thread *)RW_OWNER(v);
477 if (TD_IS_RUNNING(owner)) {
478 if (LOCK_LOG_TEST(&rw->lock_object, 0))
480 "%s: spinning on %p held by %p",
481 __func__, rw, owner);
482 KTR_STATE1(KTR_SCHED, "thread",
483 sched_tdname(curthread), "spinning",
484 "lockname:\"%s\"", rw->lock_object.lo_name);
487 v = RW_READ_VALUE(rw);
488 owner = lv_rw_wowner(v);
489 } while (owner != NULL && TD_IS_RUNNING(owner));
490 KTR_STATE0(KTR_SCHED, "thread",
491 sched_tdname(curthread), "running");
494 } else if (spintries < rowner_retries) {
496 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
497 "spinning", "lockname:\"%s\"",
498 rw->lock_object.lo_name);
499 for (i = 0; i < rowner_loops; i += n) {
502 v = RW_READ_VALUE(rw);
503 if ((v & RW_LOCK_READ) == 0 || __rw_can_read(td, v, false))
507 lda.spin_cnt += rowner_loops - i;
509 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
511 if (i != rowner_loops)
517 * Okay, now it's the hard case. Some other thread already
518 * has a write lock or there are write waiters present,
519 * acquire the turnstile lock so we can begin the process
522 ts = turnstile_trywait(&rw->lock_object);
525 * The lock might have been released while we spun, so
526 * recheck its state and restart the loop if needed.
528 v = RW_READ_VALUE(rw);
529 if (__rw_can_read(td, v, false)) {
530 turnstile_cancel(ts);
534 #ifdef ADAPTIVE_RWLOCKS
536 * The current lock owner might have started executing
537 * on another CPU (or the lock could have changed
538 * owners) while we were waiting on the turnstile
539 * chain lock. If so, drop the turnstile lock and try
542 if ((v & RW_LOCK_READ) == 0) {
543 owner = (struct thread *)RW_OWNER(v);
544 if (TD_IS_RUNNING(owner)) {
545 turnstile_cancel(ts);
552 * The lock is held in write mode or it already has waiters.
554 MPASS(!__rw_can_read(td, v, false));
557 * If the RW_LOCK_READ_WAITERS flag is already set, then
558 * we can go ahead and block. If it is not set then try
559 * to set it. If we fail to set it drop the turnstile
560 * lock and restart the loop.
562 if (!(v & RW_LOCK_READ_WAITERS)) {
563 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
564 v | RW_LOCK_READ_WAITERS)) {
565 turnstile_cancel(ts);
566 v = RW_READ_VALUE(rw);
569 if (LOCK_LOG_TEST(&rw->lock_object, 0))
570 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
575 * We were unable to acquire the lock and the read waiters
576 * flag is set, so we must block on the turnstile.
578 if (LOCK_LOG_TEST(&rw->lock_object, 0))
579 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
582 sleep_time -= lockstat_nsecs(&rw->lock_object);
584 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
586 sleep_time += lockstat_nsecs(&rw->lock_object);
589 if (LOCK_LOG_TEST(&rw->lock_object, 0))
590 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
592 v = RW_READ_VALUE(rw);
594 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
595 if (__predict_true(!doing_lockprof))
599 all_time += lockstat_nsecs(&rw->lock_object);
601 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
602 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
603 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
605 /* Record only the loops spinning and not sleeping. */
606 if (lda.spin_cnt > sleep_cnt)
607 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
608 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
609 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
612 * TODO: acquire "owner of record" here. Here be turnstile dragons
613 * however. turnstiles don't like owners changing between calls to
614 * turnstile_wait() currently.
616 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
617 waittime, file, line, LOCKSTAT_READER);
621 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
628 KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
629 !TD_IS_IDLETHREAD(td),
630 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
631 td, rw->lock_object.lo_name, file, line));
632 KASSERT(rw->rw_lock != RW_DESTROYED,
633 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
634 KASSERT(rw_wowner(rw) != td,
635 ("rw_rlock: wlock already held for %s @ %s:%d",
636 rw->lock_object.lo_name, file, line));
637 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
639 v = RW_READ_VALUE(rw);
640 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__acquire) ||
641 !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
642 __rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
644 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
645 WITNESS_LOCK(&rw->lock_object, 0, file, line);
646 TD_LOCKS_INC(curthread);
650 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
655 __rw_rlock_int(rw LOCK_FILE_LINE_ARG);
659 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
664 if (SCHEDULER_STOPPED())
669 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
670 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
671 curthread, rw->lock_object.lo_name, file, line));
675 KASSERT(rw->rw_lock != RW_DESTROYED,
676 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
677 if (!(x & RW_LOCK_READ))
679 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
680 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
682 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
683 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
684 rw, 0, 0, file, line, LOCKSTAT_READER);
685 TD_LOCKS_INC(curthread);
686 curthread->td_rw_rlocks++;
691 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
695 static bool __always_inline
696 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
701 * See if there is more than one read lock held. If so,
702 * just drop one and return.
704 if (RW_READERS(*vp) > 1) {
705 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
706 *vp - RW_ONE_READER)) {
707 if (LOCK_LOG_TEST(&rw->lock_object, 0))
709 "%s: %p succeeded %p -> %p",
710 __func__, rw, (void *)*vp,
711 (void *)(*vp - RW_ONE_READER));
718 * If there aren't any waiters for a write lock, then try
719 * to drop it quickly.
721 if (!(*vp & RW_LOCK_WAITERS)) {
722 MPASS((*vp & ~RW_LOCK_WRITE_SPINNER) ==
724 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
726 if (LOCK_LOG_TEST(&rw->lock_object, 0))
727 CTR2(KTR_LOCK, "%s: %p last succeeded",
739 static void __noinline
740 __rw_runlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
741 LOCK_FILE_LINE_ARG_DEF)
743 struct turnstile *ts;
746 if (SCHEDULER_STOPPED())
750 if (__rw_runlock_try(rw, td, &v))
754 * Ok, we know we have waiters and we think we are the
755 * last reader, so grab the turnstile lock.
757 turnstile_chain_lock(&rw->lock_object);
758 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
759 MPASS(v & RW_LOCK_WAITERS);
762 * Try to drop our lock leaving the lock in a unlocked
765 * If you wanted to do explicit lock handoff you'd have to
766 * do it here. You'd also want to use turnstile_signal()
767 * and you'd have to handle the race where a higher
768 * priority thread blocks on the write lock before the
769 * thread you wakeup actually runs and have the new thread
770 * "steal" the lock. For now it's a lot simpler to just
771 * wakeup all of the waiters.
773 * As above, if we fail, then another thread might have
774 * acquired a read lock, so drop the turnstile lock and
778 if (v & RW_LOCK_WRITE_WAITERS) {
779 queue = TS_EXCLUSIVE_QUEUE;
780 x |= (v & RW_LOCK_READ_WAITERS);
782 queue = TS_SHARED_QUEUE;
783 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
785 turnstile_chain_unlock(&rw->lock_object);
786 v = RW_READ_VALUE(rw);
789 if (LOCK_LOG_TEST(&rw->lock_object, 0))
790 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
794 * Ok. The lock is released and all that's left is to
795 * wake up the waiters. Note that the lock might not be
796 * free anymore, but in that case the writers will just
797 * block again if they run before the new lock holder(s)
800 ts = turnstile_lookup(&rw->lock_object);
802 turnstile_broadcast(ts, queue);
803 turnstile_unpend(ts, TS_SHARED_LOCK);
804 turnstile_chain_unlock(&rw->lock_object);
808 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
812 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
817 KASSERT(rw->rw_lock != RW_DESTROYED,
818 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
819 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
820 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
821 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
824 v = RW_READ_VALUE(rw);
826 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__release) ||
827 !__rw_runlock_try(rw, td, &v)))
828 __rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
830 TD_LOCKS_DEC(curthread);
834 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
839 _rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
843 * This function is called when we are unable to obtain a write lock on the
844 * first try. This means that at least one other thread holds either a
845 * read or write lock.
848 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
852 struct turnstile *ts;
853 #ifdef ADAPTIVE_RWLOCKS
854 volatile struct thread *owner;
859 #ifdef LOCK_PROFILING
860 uint64_t waittime = 0;
863 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
864 struct lock_delay_arg lda;
868 int64_t sleep_time = 0;
869 int64_t all_time = 0;
871 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
876 tid = (uintptr_t)curthread;
877 if (SCHEDULER_STOPPED())
880 #if defined(ADAPTIVE_RWLOCKS)
881 lock_delay_arg_init(&lda, &rw_delay);
882 #elif defined(KDTRACE_HOOKS)
883 lock_delay_arg_init(&lda, NULL);
886 if (__predict_false(v == RW_UNLOCKED))
887 v = RW_READ_VALUE(rw);
889 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
890 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
891 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
892 __func__, rw->lock_object.lo_name, file, line));
894 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
895 if (LOCK_LOG_TEST(&rw->lock_object, 0))
896 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
900 if (LOCK_LOG_TEST(&rw->lock_object, 0))
901 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
902 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
905 PMC_SOFT_CALL( , , lock, failed);
907 lock_profile_obtain_lock_failed(&rw->lock_object,
908 &contested, &waittime);
910 #ifdef LOCK_PROFILING
913 #elif defined(KDTRACE_HOOKS)
914 doing_lockprof = lockstat_enabled;
915 if (__predict_false(doing_lockprof)) {
916 all_time -= lockstat_nsecs(&rw->lock_object);
922 if (v == RW_UNLOCKED) {
923 if (_rw_write_lock_fetch(rw, &v, tid))
931 #ifdef ADAPTIVE_RWLOCKS
933 * If the lock is write locked and the owner is
934 * running on another CPU, spin until the owner stops
935 * running or the state of the lock changes.
937 owner = lv_rw_wowner(v);
938 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
939 if (LOCK_LOG_TEST(&rw->lock_object, 0))
940 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
941 __func__, rw, owner);
942 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
943 "spinning", "lockname:\"%s\"",
944 rw->lock_object.lo_name);
947 v = RW_READ_VALUE(rw);
948 owner = lv_rw_wowner(v);
949 } while (owner != NULL && TD_IS_RUNNING(owner));
950 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
954 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
955 spintries < rowner_retries) {
956 if (!(v & RW_LOCK_WRITE_SPINNER)) {
957 if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
958 v | RW_LOCK_WRITE_SPINNER)) {
963 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
964 "spinning", "lockname:\"%s\"",
965 rw->lock_object.lo_name);
966 for (i = 0; i < rowner_loops; i += n) {
969 v = RW_READ_VALUE(rw);
970 if ((v & RW_LOCK_WRITE_SPINNER) == 0)
973 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
976 lda.spin_cnt += rowner_loops - i;
978 if (i != rowner_loops)
982 ts = turnstile_trywait(&rw->lock_object);
983 v = RW_READ_VALUE(rw);
985 #ifdef ADAPTIVE_RWLOCKS
987 * The current lock owner might have started executing
988 * on another CPU (or the lock could have changed
989 * owners) while we were waiting on the turnstile
990 * chain lock. If so, drop the turnstile lock and try
993 if (!(v & RW_LOCK_READ)) {
994 owner = (struct thread *)RW_OWNER(v);
995 if (TD_IS_RUNNING(owner)) {
996 turnstile_cancel(ts);
1002 * Check for the waiters flags about this rwlock.
1003 * If the lock was released, without maintain any pending
1004 * waiters queue, simply try to acquire it.
1005 * If a pending waiters queue is present, claim the lock
1006 * ownership and maintain the pending queue.
1008 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1009 if ((v & ~x) == RW_UNLOCKED) {
1010 x &= ~RW_LOCK_WRITE_SPINNER;
1011 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
1013 turnstile_claim(ts);
1015 turnstile_cancel(ts);
1018 turnstile_cancel(ts);
1019 v = RW_READ_VALUE(rw);
1023 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1024 * set it. If we fail to set it, then loop back and try
1027 if (!(v & RW_LOCK_WRITE_WAITERS)) {
1028 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
1029 v | RW_LOCK_WRITE_WAITERS)) {
1030 turnstile_cancel(ts);
1031 v = RW_READ_VALUE(rw);
1034 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1035 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1039 * We were unable to acquire the lock and the write waiters
1040 * flag is set, so we must block on the turnstile.
1042 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1043 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1045 #ifdef KDTRACE_HOOKS
1046 sleep_time -= lockstat_nsecs(&rw->lock_object);
1048 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
1049 #ifdef KDTRACE_HOOKS
1050 sleep_time += lockstat_nsecs(&rw->lock_object);
1053 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1054 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1056 #ifdef ADAPTIVE_RWLOCKS
1059 v = RW_READ_VALUE(rw);
1061 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1062 if (__predict_true(!doing_lockprof))
1065 #ifdef KDTRACE_HOOKS
1066 all_time += lockstat_nsecs(&rw->lock_object);
1068 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1069 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1070 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1072 /* Record only the loops spinning and not sleeping. */
1073 if (lda.spin_cnt > sleep_cnt)
1074 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1075 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1076 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1078 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1079 waittime, file, line, LOCKSTAT_WRITER);
1083 * This function is called if lockstat is active or the first try at releasing
1084 * a write lock failed. The latter means that the lock is recursed or one of
1085 * the 2 waiter bits must be set indicating that at least one thread is waiting
1089 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1092 struct turnstile *ts;
1093 uintptr_t tid, setv;
1096 tid = (uintptr_t)curthread;
1097 if (SCHEDULER_STOPPED())
1101 if (__predict_false(v == tid))
1102 v = RW_READ_VALUE(rw);
1104 if (v & RW_LOCK_WRITER_RECURSED) {
1105 if (--(rw->rw_recurse) == 0)
1106 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1107 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1108 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1112 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1113 if (v == tid && _rw_write_unlock(rw, tid))
1116 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1117 ("%s: neither of the waiter flags are set", __func__));
1119 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1120 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1122 turnstile_chain_lock(&rw->lock_object);
1125 * Use the same algo as sx locks for now. Prefer waking up shared
1126 * waiters if we have any over writers. This is probably not ideal.
1128 * 'v' is the value we are going to write back to rw_lock. If we
1129 * have waiters on both queues, we need to preserve the state of
1130 * the waiter flag for the queue we don't wake up. For now this is
1131 * hardcoded for the algorithm mentioned above.
1133 * In the case of both readers and writers waiting we wakeup the
1134 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1135 * new writer comes in before a reader it will claim the lock up
1136 * above. There is probably a potential priority inversion in
1137 * there that could be worked around either by waking both queues
1138 * of waiters or doing some complicated lock handoff gymnastics.
1141 v = RW_READ_VALUE(rw);
1142 queue = TS_SHARED_QUEUE;
1143 if (v & RW_LOCK_WRITE_WAITERS) {
1144 queue = TS_EXCLUSIVE_QUEUE;
1145 setv |= (v & RW_LOCK_READ_WAITERS);
1147 atomic_store_rel_ptr(&rw->rw_lock, setv);
1149 /* Wake up all waiters for the specific queue. */
1150 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1151 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1152 queue == TS_SHARED_QUEUE ? "read" : "write");
1154 ts = turnstile_lookup(&rw->lock_object);
1156 turnstile_broadcast(ts, queue);
1157 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1158 turnstile_chain_unlock(&rw->lock_object);
1162 * Attempt to do a non-blocking upgrade from a read lock to a write
1163 * lock. This will only succeed if this thread holds a single read
1164 * lock. Returns true if the upgrade succeeded and false otherwise.
1167 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1169 uintptr_t v, x, tid;
1170 struct turnstile *ts;
1173 if (SCHEDULER_STOPPED())
1176 KASSERT(rw->rw_lock != RW_DESTROYED,
1177 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1178 __rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1181 * Attempt to switch from one reader to a writer. If there
1182 * are any write waiters, then we will have to lock the
1183 * turnstile first to prevent races with another writer
1184 * calling turnstile_wait() before we have claimed this
1185 * turnstile. So, do the simple case of no waiters first.
1187 tid = (uintptr_t)curthread;
1191 if (RW_READERS(v) > 1)
1193 if (!(v & RW_LOCK_WAITERS)) {
1194 success = atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid);
1201 * Ok, we think we have waiters, so lock the turnstile.
1203 ts = turnstile_trywait(&rw->lock_object);
1205 if (RW_READERS(v) > 1) {
1206 turnstile_cancel(ts);
1210 * Try to switch from one reader to a writer again. This time
1211 * we honor the current state of the waiters flags.
1212 * If we obtain the lock with the flags set, then claim
1213 * ownership of the turnstile.
1215 x = rw->rw_lock & RW_LOCK_WAITERS;
1216 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1219 turnstile_claim(ts);
1221 turnstile_cancel(ts);
1224 turnstile_cancel(ts);
1226 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1228 curthread->td_rw_rlocks--;
1229 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1231 LOCKSTAT_RECORD0(rw__upgrade, rw);
1237 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1242 return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1246 * Downgrade a write lock into a single read lock.
1249 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1251 struct turnstile *ts;
1255 if (SCHEDULER_STOPPED())
1258 KASSERT(rw->rw_lock != RW_DESTROYED,
1259 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1260 __rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1262 if (rw_recursed(rw))
1263 panic("downgrade of a recursed lock");
1266 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1269 * Convert from a writer to a single reader. First we handle
1270 * the easy case with no waiters. If there are any waiters, we
1271 * lock the turnstile and "disown" the lock.
1273 tid = (uintptr_t)curthread;
1274 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1278 * Ok, we think we have waiters, so lock the turnstile so we can
1279 * read the waiter flags without any races.
1281 turnstile_chain_lock(&rw->lock_object);
1282 v = rw->rw_lock & RW_LOCK_WAITERS;
1283 rwait = v & RW_LOCK_READ_WAITERS;
1284 wwait = v & RW_LOCK_WRITE_WAITERS;
1285 MPASS(rwait | wwait);
1288 * Downgrade from a write lock while preserving waiters flag
1289 * and give up ownership of the turnstile.
1291 ts = turnstile_lookup(&rw->lock_object);
1294 v &= ~RW_LOCK_READ_WAITERS;
1295 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1297 * Wake other readers if there are no writers pending. Otherwise they
1298 * won't be able to acquire the lock anyway.
1300 if (rwait && !wwait) {
1301 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1302 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1304 turnstile_disown(ts);
1305 turnstile_chain_unlock(&rw->lock_object);
1307 curthread->td_rw_rlocks++;
1308 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1309 LOCKSTAT_RECORD0(rw__downgrade, rw);
1313 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1318 __rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1321 #ifdef INVARIANT_SUPPORT
1327 * In the non-WITNESS case, rw_assert() can only detect that at least
1328 * *some* thread owns an rlock, but it cannot guarantee that *this*
1329 * thread owns an rlock.
1332 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1334 const struct rwlock *rw;
1336 if (panicstr != NULL)
1343 case RA_LOCKED | RA_RECURSED:
1344 case RA_LOCKED | RA_NOTRECURSED:
1346 case RA_RLOCKED | RA_RECURSED:
1347 case RA_RLOCKED | RA_NOTRECURSED:
1349 witness_assert(&rw->lock_object, what, file, line);
1352 * If some other thread has a write lock or we have one
1353 * and are asserting a read lock, fail. Also, if no one
1354 * has a lock at all, fail.
1356 if (rw->rw_lock == RW_UNLOCKED ||
1357 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1358 rw_wowner(rw) != curthread)))
1359 panic("Lock %s not %slocked @ %s:%d\n",
1360 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1361 "read " : "", file, line);
1363 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1364 if (rw_recursed(rw)) {
1365 if (what & RA_NOTRECURSED)
1366 panic("Lock %s recursed @ %s:%d\n",
1367 rw->lock_object.lo_name, file,
1369 } else if (what & RA_RECURSED)
1370 panic("Lock %s not recursed @ %s:%d\n",
1371 rw->lock_object.lo_name, file, line);
1376 case RA_WLOCKED | RA_RECURSED:
1377 case RA_WLOCKED | RA_NOTRECURSED:
1378 if (rw_wowner(rw) != curthread)
1379 panic("Lock %s not exclusively locked @ %s:%d\n",
1380 rw->lock_object.lo_name, file, line);
1381 if (rw_recursed(rw)) {
1382 if (what & RA_NOTRECURSED)
1383 panic("Lock %s recursed @ %s:%d\n",
1384 rw->lock_object.lo_name, file, line);
1385 } else if (what & RA_RECURSED)
1386 panic("Lock %s not recursed @ %s:%d\n",
1387 rw->lock_object.lo_name, file, line);
1391 witness_assert(&rw->lock_object, what, file, line);
1394 * If we hold a write lock fail. We can't reliably check
1395 * to see if we hold a read lock or not.
1397 if (rw_wowner(rw) == curthread)
1398 panic("Lock %s exclusively locked @ %s:%d\n",
1399 rw->lock_object.lo_name, file, line);
1403 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1407 #endif /* INVARIANT_SUPPORT */
1411 db_show_rwlock(const struct lock_object *lock)
1413 const struct rwlock *rw;
1416 rw = (const struct rwlock *)lock;
1418 db_printf(" state: ");
1419 if (rw->rw_lock == RW_UNLOCKED)
1420 db_printf("UNLOCKED\n");
1421 else if (rw->rw_lock == RW_DESTROYED) {
1422 db_printf("DESTROYED\n");
1424 } else if (rw->rw_lock & RW_LOCK_READ)
1425 db_printf("RLOCK: %ju locks\n",
1426 (uintmax_t)(RW_READERS(rw->rw_lock)));
1429 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1430 td->td_tid, td->td_proc->p_pid, td->td_name);
1431 if (rw_recursed(rw))
1432 db_printf(" recursed: %u\n", rw->rw_recurse);
1434 db_printf(" waiters: ");
1435 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1436 case RW_LOCK_READ_WAITERS:
1437 db_printf("readers\n");
1439 case RW_LOCK_WRITE_WAITERS:
1440 db_printf("writers\n");
1442 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1443 db_printf("readers and writers\n");
1446 db_printf("none\n");