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 rowner_retries = 10;
97 static int 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_mostly 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 || !TD_IS_IDLETHREAD(curthread),
273 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
274 curthread, rw->lock_object.lo_name, file, line));
275 KASSERT(rw->rw_lock != RW_DESTROYED,
276 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
277 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
279 tid = (uintptr_t)curthread;
281 if (!_rw_write_lock_fetch(rw, &v, tid))
282 _rw_wlock_hard(rw, v, tid, file, line);
284 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
285 0, 0, file, line, LOCKSTAT_WRITER);
287 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
288 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
289 TD_LOCKS_INC(curthread);
293 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
298 if (SCHEDULER_STOPPED())
303 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
304 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
305 curthread, rw->lock_object.lo_name, file, line));
306 KASSERT(rw->rw_lock != RW_DESTROYED,
307 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
309 if (rw_wlocked(rw) &&
310 (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
312 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
315 rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
316 (uintptr_t)curthread);
318 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
320 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
322 if (!rw_recursed(rw))
323 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
324 rw, 0, 0, file, line, LOCKSTAT_WRITER);
325 TD_LOCKS_INC(curthread);
331 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
337 KASSERT(rw->rw_lock != RW_DESTROYED,
338 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
339 __rw_assert(c, RA_WLOCKED, file, line);
340 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
341 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
344 #ifdef LOCK_PROFILING
345 _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
347 __rw_wunlock(rw, curthread, file, line);
350 TD_LOCKS_DEC(curthread);
354 * Determines whether a new reader can acquire a lock. Succeeds if the
355 * reader already owns a read lock and the lock is locked for read to
356 * prevent deadlock from reader recursion. Also succeeds if the lock
357 * is unlocked and has no writer waiters or spinners. Failing otherwise
358 * prioritizes writers before readers.
360 #define RW_CAN_READ(td, _rw) \
361 (((td)->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) & \
362 (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) == \
365 static bool __always_inline
366 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp,
367 const char *file, int line)
371 * Handle the easy case. If no other thread has a write
372 * lock, then try to bump up the count of read locks. Note
373 * that we have to preserve the current state of the
374 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
375 * read lock, then rw_lock must have changed, so restart
376 * the loop. Note that this handles the case of a
377 * completely unlocked rwlock since such a lock is encoded
378 * as a read lock with no waiters.
380 while (RW_CAN_READ(td, *vp)) {
381 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
382 *vp + RW_ONE_READER)) {
383 if (LOCK_LOG_TEST(&rw->lock_object, 0))
385 "%s: %p succeed %p -> %p", __func__,
387 (void *)(*vp + RW_ONE_READER));
395 static void __noinline
396 __rw_rlock_hard(volatile uintptr_t *c, struct thread *td, uintptr_t v,
397 const char *file, int line)
400 struct turnstile *ts;
401 #ifdef ADAPTIVE_RWLOCKS
402 volatile struct thread *owner;
406 #ifdef LOCK_PROFILING
407 uint64_t waittime = 0;
410 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
411 struct lock_delay_arg lda;
416 int64_t sleep_time = 0;
417 int64_t all_time = 0;
420 if (SCHEDULER_STOPPED())
423 #if defined(ADAPTIVE_RWLOCKS)
424 lock_delay_arg_init(&lda, &rw_delay);
425 #elif defined(KDTRACE_HOOKS)
426 lock_delay_arg_init(&lda, NULL);
431 all_time -= lockstat_nsecs(&rw->lock_object);
437 if (__rw_rlock_try(rw, td, &v, file, line))
443 PMC_SOFT_CALL( , , lock, failed);
445 lock_profile_obtain_lock_failed(&rw->lock_object,
446 &contested, &waittime);
448 #ifdef ADAPTIVE_RWLOCKS
450 * If the owner is running on another CPU, spin until
451 * the owner stops running or the state of the lock
454 if ((v & RW_LOCK_READ) == 0) {
455 owner = (struct thread *)RW_OWNER(v);
456 if (TD_IS_RUNNING(owner)) {
457 if (LOCK_LOG_TEST(&rw->lock_object, 0))
459 "%s: spinning on %p held by %p",
460 __func__, rw, owner);
461 KTR_STATE1(KTR_SCHED, "thread",
462 sched_tdname(curthread), "spinning",
463 "lockname:\"%s\"", rw->lock_object.lo_name);
466 v = RW_READ_VALUE(rw);
467 owner = lv_rw_wowner(v);
468 } while (owner != NULL && TD_IS_RUNNING(owner));
469 KTR_STATE0(KTR_SCHED, "thread",
470 sched_tdname(curthread), "running");
473 } else if (spintries < rowner_retries) {
475 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
476 "spinning", "lockname:\"%s\"",
477 rw->lock_object.lo_name);
478 for (i = 0; i < rowner_loops; i++) {
479 v = RW_READ_VALUE(rw);
480 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(td, v))
484 v = RW_READ_VALUE(rw);
486 lda.spin_cnt += rowner_loops - i;
488 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
490 if (i != rowner_loops)
496 * Okay, now it's the hard case. Some other thread already
497 * has a write lock or there are write waiters present,
498 * acquire the turnstile lock so we can begin the process
501 ts = turnstile_trywait(&rw->lock_object);
504 * The lock might have been released while we spun, so
505 * recheck its state and restart the loop if needed.
507 v = RW_READ_VALUE(rw);
508 if (RW_CAN_READ(td, v)) {
509 turnstile_cancel(ts);
513 #ifdef ADAPTIVE_RWLOCKS
515 * The current lock owner might have started executing
516 * on another CPU (or the lock could have changed
517 * owners) while we were waiting on the turnstile
518 * chain lock. If so, drop the turnstile lock and try
521 if ((v & RW_LOCK_READ) == 0) {
522 owner = (struct thread *)RW_OWNER(v);
523 if (TD_IS_RUNNING(owner)) {
524 turnstile_cancel(ts);
531 * The lock is held in write mode or it already has waiters.
533 MPASS(!RW_CAN_READ(td, v));
536 * If the RW_LOCK_READ_WAITERS flag is already set, then
537 * we can go ahead and block. If it is not set then try
538 * to set it. If we fail to set it drop the turnstile
539 * lock and restart the loop.
541 if (!(v & RW_LOCK_READ_WAITERS)) {
542 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
543 v | RW_LOCK_READ_WAITERS)) {
544 turnstile_cancel(ts);
545 v = RW_READ_VALUE(rw);
548 if (LOCK_LOG_TEST(&rw->lock_object, 0))
549 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
554 * We were unable to acquire the lock and the read waiters
555 * flag is set, so we must block on the turnstile.
557 if (LOCK_LOG_TEST(&rw->lock_object, 0))
558 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
561 sleep_time -= lockstat_nsecs(&rw->lock_object);
563 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
565 sleep_time += lockstat_nsecs(&rw->lock_object);
568 if (LOCK_LOG_TEST(&rw->lock_object, 0))
569 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
571 v = RW_READ_VALUE(rw);
574 all_time += lockstat_nsecs(&rw->lock_object);
576 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
577 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
578 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
580 /* Record only the loops spinning and not sleeping. */
581 if (lda.spin_cnt > sleep_cnt)
582 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
583 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
584 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
587 * TODO: acquire "owner of record" here. Here be turnstile dragons
588 * however. turnstiles don't like owners changing between calls to
589 * turnstile_wait() currently.
591 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
592 waittime, file, line, LOCKSTAT_READER);
596 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
605 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
606 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
607 td, rw->lock_object.lo_name, file, line));
608 KASSERT(rw->rw_lock != RW_DESTROYED,
609 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
610 KASSERT(rw_wowner(rw) != td,
611 ("rw_rlock: wlock already held for %s @ %s:%d",
612 rw->lock_object.lo_name, file, line));
613 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
615 v = RW_READ_VALUE(rw);
616 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__acquire) ||
617 !__rw_rlock_try(rw, td, &v, file, line)))
618 __rw_rlock_hard(c, td, v, file, line);
620 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
621 WITNESS_LOCK(&rw->lock_object, 0, file, line);
622 TD_LOCKS_INC(curthread);
626 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
631 if (SCHEDULER_STOPPED())
636 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
637 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
638 curthread, rw->lock_object.lo_name, file, line));
642 KASSERT(rw->rw_lock != RW_DESTROYED,
643 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
644 if (!(x & RW_LOCK_READ))
646 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
647 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
649 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
650 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
651 rw, 0, 0, file, line, LOCKSTAT_READER);
652 TD_LOCKS_INC(curthread);
653 curthread->td_rw_rlocks++;
658 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
662 static bool __always_inline
663 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
668 * See if there is more than one read lock held. If so,
669 * just drop one and return.
671 if (RW_READERS(*vp) > 1) {
672 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
673 *vp - RW_ONE_READER)) {
674 if (LOCK_LOG_TEST(&rw->lock_object, 0))
676 "%s: %p succeeded %p -> %p",
677 __func__, rw, (void *)*vp,
678 (void *)(*vp - RW_ONE_READER));
685 * If there aren't any waiters for a write lock, then try
686 * to drop it quickly.
688 if (!(*vp & RW_LOCK_WAITERS)) {
689 MPASS((*vp & ~RW_LOCK_WRITE_SPINNER) ==
691 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
693 if (LOCK_LOG_TEST(&rw->lock_object, 0))
694 CTR2(KTR_LOCK, "%s: %p last succeeded",
706 static void __noinline
707 __rw_runlock_hard(volatile uintptr_t *c, struct thread *td, uintptr_t v,
708 const char *file, int line)
711 struct turnstile *ts;
714 if (SCHEDULER_STOPPED())
720 if (__rw_runlock_try(rw, td, &v))
724 * Ok, we know we have waiters and we think we are the
725 * last reader, so grab the turnstile lock.
727 turnstile_chain_lock(&rw->lock_object);
728 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
729 MPASS(v & RW_LOCK_WAITERS);
732 * Try to drop our lock leaving the lock in a unlocked
735 * If you wanted to do explicit lock handoff you'd have to
736 * do it here. You'd also want to use turnstile_signal()
737 * and you'd have to handle the race where a higher
738 * priority thread blocks on the write lock before the
739 * thread you wakeup actually runs and have the new thread
740 * "steal" the lock. For now it's a lot simpler to just
741 * wakeup all of the waiters.
743 * As above, if we fail, then another thread might have
744 * acquired a read lock, so drop the turnstile lock and
748 if (v & RW_LOCK_WRITE_WAITERS) {
749 queue = TS_EXCLUSIVE_QUEUE;
750 x |= (v & RW_LOCK_READ_WAITERS);
752 queue = TS_SHARED_QUEUE;
753 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
755 turnstile_chain_unlock(&rw->lock_object);
756 v = RW_READ_VALUE(rw);
759 if (LOCK_LOG_TEST(&rw->lock_object, 0))
760 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
764 * Ok. The lock is released and all that's left is to
765 * wake up the waiters. Note that the lock might not be
766 * free anymore, but in that case the writers will just
767 * block again if they run before the new lock holder(s)
770 ts = turnstile_lookup(&rw->lock_object);
772 turnstile_broadcast(ts, queue);
773 turnstile_unpend(ts, TS_SHARED_LOCK);
774 turnstile_chain_unlock(&rw->lock_object);
778 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
782 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
790 KASSERT(rw->rw_lock != RW_DESTROYED,
791 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
792 __rw_assert(c, RA_RLOCKED, file, line);
793 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
794 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
797 v = RW_READ_VALUE(rw);
799 if (__predict_false(LOCKSTAT_OOL_PROFILE_ENABLED(rw__release) ||
800 !__rw_runlock_try(rw, td, &v)))
801 __rw_runlock_hard(c, td, v, file, line);
803 TD_LOCKS_DEC(curthread);
808 * This function is called when we are unable to obtain a write lock on the
809 * first try. This means that at least one other thread holds either a
810 * read or write lock.
813 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v, uintptr_t tid,
814 const char *file, int line)
817 struct turnstile *ts;
818 #ifdef ADAPTIVE_RWLOCKS
819 volatile struct thread *owner;
824 #ifdef LOCK_PROFILING
825 uint64_t waittime = 0;
828 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
829 struct lock_delay_arg lda;
834 int64_t sleep_time = 0;
835 int64_t all_time = 0;
838 if (SCHEDULER_STOPPED())
841 #if defined(ADAPTIVE_RWLOCKS)
842 lock_delay_arg_init(&lda, &rw_delay);
843 #elif defined(KDTRACE_HOOKS)
844 lock_delay_arg_init(&lda, NULL);
847 if (__predict_false(v == RW_UNLOCKED))
848 v = RW_READ_VALUE(rw);
850 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
851 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
852 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
853 __func__, rw->lock_object.lo_name, file, line));
855 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
856 if (LOCK_LOG_TEST(&rw->lock_object, 0))
857 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
861 if (LOCK_LOG_TEST(&rw->lock_object, 0))
862 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
863 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
866 all_time -= lockstat_nsecs(&rw->lock_object);
870 if (v == RW_UNLOCKED) {
871 if (_rw_write_lock_fetch(rw, &v, tid))
879 PMC_SOFT_CALL( , , lock, failed);
881 lock_profile_obtain_lock_failed(&rw->lock_object,
882 &contested, &waittime);
883 #ifdef ADAPTIVE_RWLOCKS
885 * If the lock is write locked and the owner is
886 * running on another CPU, spin until the owner stops
887 * running or the state of the lock changes.
889 owner = lv_rw_wowner(v);
890 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
891 if (LOCK_LOG_TEST(&rw->lock_object, 0))
892 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
893 __func__, rw, owner);
894 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
895 "spinning", "lockname:\"%s\"",
896 rw->lock_object.lo_name);
899 v = RW_READ_VALUE(rw);
900 owner = lv_rw_wowner(v);
901 } while (owner != NULL && TD_IS_RUNNING(owner));
902 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
906 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
907 spintries < rowner_retries) {
908 if (!(v & RW_LOCK_WRITE_SPINNER)) {
909 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
910 v | RW_LOCK_WRITE_SPINNER)) {
911 v = RW_READ_VALUE(rw);
916 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
917 "spinning", "lockname:\"%s\"",
918 rw->lock_object.lo_name);
919 for (i = 0; i < rowner_loops; i++) {
920 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
924 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
926 v = RW_READ_VALUE(rw);
928 lda.spin_cnt += rowner_loops - i;
930 if (i != rowner_loops)
934 ts = turnstile_trywait(&rw->lock_object);
935 v = RW_READ_VALUE(rw);
937 #ifdef ADAPTIVE_RWLOCKS
939 * The current lock owner might have started executing
940 * on another CPU (or the lock could have changed
941 * owners) while we were waiting on the turnstile
942 * chain lock. If so, drop the turnstile lock and try
945 if (!(v & RW_LOCK_READ)) {
946 owner = (struct thread *)RW_OWNER(v);
947 if (TD_IS_RUNNING(owner)) {
948 turnstile_cancel(ts);
954 * Check for the waiters flags about this rwlock.
955 * If the lock was released, without maintain any pending
956 * waiters queue, simply try to acquire it.
957 * If a pending waiters queue is present, claim the lock
958 * ownership and maintain the pending queue.
960 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
961 if ((v & ~x) == RW_UNLOCKED) {
962 x &= ~RW_LOCK_WRITE_SPINNER;
963 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
967 turnstile_cancel(ts);
970 turnstile_cancel(ts);
971 v = RW_READ_VALUE(rw);
975 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
976 * set it. If we fail to set it, then loop back and try
979 if (!(v & RW_LOCK_WRITE_WAITERS)) {
980 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
981 v | RW_LOCK_WRITE_WAITERS)) {
982 turnstile_cancel(ts);
983 v = RW_READ_VALUE(rw);
986 if (LOCK_LOG_TEST(&rw->lock_object, 0))
987 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
991 * We were unable to acquire the lock and the write waiters
992 * flag is set, so we must block on the turnstile.
994 if (LOCK_LOG_TEST(&rw->lock_object, 0))
995 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
998 sleep_time -= lockstat_nsecs(&rw->lock_object);
1000 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
1001 #ifdef KDTRACE_HOOKS
1002 sleep_time += lockstat_nsecs(&rw->lock_object);
1005 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1006 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1008 #ifdef ADAPTIVE_RWLOCKS
1011 v = RW_READ_VALUE(rw);
1013 #ifdef KDTRACE_HOOKS
1014 all_time += lockstat_nsecs(&rw->lock_object);
1016 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1017 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1018 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1020 /* Record only the loops spinning and not sleeping. */
1021 if (lda.spin_cnt > sleep_cnt)
1022 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1023 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1024 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1026 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1027 waittime, file, line, LOCKSTAT_WRITER);
1031 * This function is called if lockstat is active or the first try at releasing
1032 * a write lock failed. The latter means that the lock is recursed or one of
1033 * the 2 waiter bits must be set indicating that at least one thread is waiting
1037 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
1041 struct turnstile *ts;
1045 if (SCHEDULER_STOPPED())
1049 v = RW_READ_VALUE(rw);
1050 if (v & RW_LOCK_WRITER_RECURSED) {
1051 if (--(rw->rw_recurse) == 0)
1052 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1053 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1054 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1058 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1059 if (v == tid && _rw_write_unlock(rw, tid))
1062 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1063 ("%s: neither of the waiter flags are set", __func__));
1065 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1066 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1068 turnstile_chain_lock(&rw->lock_object);
1069 ts = turnstile_lookup(&rw->lock_object);
1073 * Use the same algo as sx locks for now. Prefer waking up shared
1074 * waiters if we have any over writers. This is probably not ideal.
1076 * 'v' is the value we are going to write back to rw_lock. If we
1077 * have waiters on both queues, we need to preserve the state of
1078 * the waiter flag for the queue we don't wake up. For now this is
1079 * hardcoded for the algorithm mentioned above.
1081 * In the case of both readers and writers waiting we wakeup the
1082 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1083 * new writer comes in before a reader it will claim the lock up
1084 * above. There is probably a potential priority inversion in
1085 * there that could be worked around either by waking both queues
1086 * of waiters or doing some complicated lock handoff gymnastics.
1089 if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
1090 queue = TS_EXCLUSIVE_QUEUE;
1091 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
1093 queue = TS_SHARED_QUEUE;
1095 /* Wake up all waiters for the specific queue. */
1096 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1097 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1098 queue == TS_SHARED_QUEUE ? "read" : "write");
1099 turnstile_broadcast(ts, queue);
1100 atomic_store_rel_ptr(&rw->rw_lock, v);
1101 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1102 turnstile_chain_unlock(&rw->lock_object);
1106 * Attempt to do a non-blocking upgrade from a read lock to a write
1107 * lock. This will only succeed if this thread holds a single read
1108 * lock. Returns true if the upgrade succeeded and false otherwise.
1111 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1114 uintptr_t v, x, tid;
1115 struct turnstile *ts;
1118 if (SCHEDULER_STOPPED())
1123 KASSERT(rw->rw_lock != RW_DESTROYED,
1124 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1125 __rw_assert(c, RA_RLOCKED, file, line);
1128 * Attempt to switch from one reader to a writer. If there
1129 * are any write waiters, then we will have to lock the
1130 * turnstile first to prevent races with another writer
1131 * calling turnstile_wait() before we have claimed this
1132 * turnstile. So, do the simple case of no waiters first.
1134 tid = (uintptr_t)curthread;
1138 if (RW_READERS(v) > 1)
1140 if (!(v & RW_LOCK_WAITERS)) {
1141 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
1148 * Ok, we think we have waiters, so lock the turnstile.
1150 ts = turnstile_trywait(&rw->lock_object);
1152 if (RW_READERS(v) > 1) {
1153 turnstile_cancel(ts);
1157 * Try to switch from one reader to a writer again. This time
1158 * we honor the current state of the waiters flags.
1159 * If we obtain the lock with the flags set, then claim
1160 * ownership of the turnstile.
1162 x = rw->rw_lock & RW_LOCK_WAITERS;
1163 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1166 turnstile_claim(ts);
1168 turnstile_cancel(ts);
1171 turnstile_cancel(ts);
1173 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1175 curthread->td_rw_rlocks--;
1176 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1178 LOCKSTAT_RECORD0(rw__upgrade, rw);
1184 * Downgrade a write lock into a single read lock.
1187 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1190 struct turnstile *ts;
1194 if (SCHEDULER_STOPPED())
1199 KASSERT(rw->rw_lock != RW_DESTROYED,
1200 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1201 __rw_assert(c, RA_WLOCKED | RA_NOTRECURSED, file, line);
1203 if (rw_recursed(rw))
1204 panic("downgrade of a recursed lock");
1207 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1210 * Convert from a writer to a single reader. First we handle
1211 * the easy case with no waiters. If there are any waiters, we
1212 * lock the turnstile and "disown" the lock.
1214 tid = (uintptr_t)curthread;
1215 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1219 * Ok, we think we have waiters, so lock the turnstile so we can
1220 * read the waiter flags without any races.
1222 turnstile_chain_lock(&rw->lock_object);
1223 v = rw->rw_lock & RW_LOCK_WAITERS;
1224 rwait = v & RW_LOCK_READ_WAITERS;
1225 wwait = v & RW_LOCK_WRITE_WAITERS;
1226 MPASS(rwait | wwait);
1229 * Downgrade from a write lock while preserving waiters flag
1230 * and give up ownership of the turnstile.
1232 ts = turnstile_lookup(&rw->lock_object);
1235 v &= ~RW_LOCK_READ_WAITERS;
1236 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1238 * Wake other readers if there are no writers pending. Otherwise they
1239 * won't be able to acquire the lock anyway.
1241 if (rwait && !wwait) {
1242 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1243 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1245 turnstile_disown(ts);
1246 turnstile_chain_unlock(&rw->lock_object);
1248 curthread->td_rw_rlocks++;
1249 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1250 LOCKSTAT_RECORD0(rw__downgrade, rw);
1253 #ifdef INVARIANT_SUPPORT
1259 * In the non-WITNESS case, rw_assert() can only detect that at least
1260 * *some* thread owns an rlock, but it cannot guarantee that *this*
1261 * thread owns an rlock.
1264 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1266 const struct rwlock *rw;
1268 if (panicstr != NULL)
1275 case RA_LOCKED | RA_RECURSED:
1276 case RA_LOCKED | RA_NOTRECURSED:
1278 case RA_RLOCKED | RA_RECURSED:
1279 case RA_RLOCKED | RA_NOTRECURSED:
1281 witness_assert(&rw->lock_object, what, file, line);
1284 * If some other thread has a write lock or we have one
1285 * and are asserting a read lock, fail. Also, if no one
1286 * has a lock at all, fail.
1288 if (rw->rw_lock == RW_UNLOCKED ||
1289 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1290 rw_wowner(rw) != curthread)))
1291 panic("Lock %s not %slocked @ %s:%d\n",
1292 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1293 "read " : "", file, line);
1295 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1296 if (rw_recursed(rw)) {
1297 if (what & RA_NOTRECURSED)
1298 panic("Lock %s recursed @ %s:%d\n",
1299 rw->lock_object.lo_name, file,
1301 } else if (what & RA_RECURSED)
1302 panic("Lock %s not recursed @ %s:%d\n",
1303 rw->lock_object.lo_name, file, line);
1308 case RA_WLOCKED | RA_RECURSED:
1309 case RA_WLOCKED | RA_NOTRECURSED:
1310 if (rw_wowner(rw) != curthread)
1311 panic("Lock %s not exclusively locked @ %s:%d\n",
1312 rw->lock_object.lo_name, file, line);
1313 if (rw_recursed(rw)) {
1314 if (what & RA_NOTRECURSED)
1315 panic("Lock %s recursed @ %s:%d\n",
1316 rw->lock_object.lo_name, file, line);
1317 } else if (what & RA_RECURSED)
1318 panic("Lock %s not recursed @ %s:%d\n",
1319 rw->lock_object.lo_name, file, line);
1323 witness_assert(&rw->lock_object, what, file, line);
1326 * If we hold a write lock fail. We can't reliably check
1327 * to see if we hold a read lock or not.
1329 if (rw_wowner(rw) == curthread)
1330 panic("Lock %s exclusively locked @ %s:%d\n",
1331 rw->lock_object.lo_name, file, line);
1335 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1339 #endif /* INVARIANT_SUPPORT */
1343 db_show_rwlock(const struct lock_object *lock)
1345 const struct rwlock *rw;
1348 rw = (const struct rwlock *)lock;
1350 db_printf(" state: ");
1351 if (rw->rw_lock == RW_UNLOCKED)
1352 db_printf("UNLOCKED\n");
1353 else if (rw->rw_lock == RW_DESTROYED) {
1354 db_printf("DESTROYED\n");
1356 } else if (rw->rw_lock & RW_LOCK_READ)
1357 db_printf("RLOCK: %ju locks\n",
1358 (uintmax_t)(RW_READERS(rw->rw_lock)));
1361 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1362 td->td_tid, td->td_proc->p_pid, td->td_name);
1363 if (rw_recursed(rw))
1364 db_printf(" recursed: %u\n", rw->rw_recurse);
1366 db_printf(" waiters: ");
1367 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1368 case RW_LOCK_READ_WAITERS:
1369 db_printf("readers\n");
1371 case RW_LOCK_WRITE_WAITERS:
1372 db_printf("writers\n");
1374 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1375 db_printf("readers and writers\n");
1378 db_printf("none\n");