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_kdtrace.h"
37 #include "opt_no_adaptive_rwlocks.h"
39 #include <sys/param.h>
42 #include <sys/kernel.h>
44 #include <sys/mutex.h>
46 #include <sys/rwlock.h>
47 #include <sys/sched.h>
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))
69 #ifdef ADAPTIVE_RWLOCKS
70 static int rowner_retries = 10;
71 static int rowner_loops = 10000;
72 static SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL,
74 SYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
75 SYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
81 static void db_show_rwlock(const struct lock_object *lock);
83 static void assert_rw(const struct lock_object *lock, int what);
84 static void lock_rw(struct lock_object *lock, uintptr_t how);
86 static int owner_rw(const struct lock_object *lock, struct thread **owner);
88 static uintptr_t unlock_rw(struct lock_object *lock);
90 struct lock_class lock_class_rw = {
92 .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
93 .lc_assert = assert_rw,
95 .lc_ddb_show = db_show_rwlock,
98 .lc_unlock = unlock_rw,
100 .lc_owner = owner_rw,
105 * Return a pointer to the owning thread if the lock is write-locked or
106 * NULL if the lock is unlocked or read-locked.
108 #define rw_wowner(rw) \
109 ((rw)->rw_lock & RW_LOCK_READ ? NULL : \
110 (struct thread *)RW_OWNER((rw)->rw_lock))
113 * Returns if a write owner is recursed. Write ownership is not assured
114 * here and should be previously checked.
116 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
119 * Return true if curthread helds the lock.
121 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
124 * Return a pointer to the owning thread for this lock who should receive
125 * any priority lent by threads that block on this lock. Currently this
126 * is identical to rw_wowner().
128 #define rw_owner(rw) rw_wowner(rw)
131 #define __rw_assert(c, what, file, line)
135 assert_rw(const struct lock_object *lock, int what)
138 rw_assert((const struct rwlock *)lock, what);
142 lock_rw(struct lock_object *lock, uintptr_t how)
146 rw = (struct rwlock *)lock;
154 unlock_rw(struct lock_object *lock)
158 rw = (struct rwlock *)lock;
159 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
160 if (rw->rw_lock & RW_LOCK_READ) {
171 owner_rw(const struct lock_object *lock, struct thread **owner)
173 const struct rwlock *rw = (const struct rwlock *)lock;
174 uintptr_t x = rw->rw_lock;
176 *owner = rw_wowner(rw);
177 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
183 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
190 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
192 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
193 ("%s: rw_lock not aligned for %s: %p", __func__, name,
196 flags = LO_UPGRADABLE;
199 if (opts & RW_NOPROFILE)
200 flags |= LO_NOPROFILE;
201 if (!(opts & RW_NOWITNESS))
203 if (opts & RW_RECURSE)
204 flags |= LO_RECURSABLE;
208 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
209 rw->rw_lock = RW_UNLOCKED;
214 _rw_destroy(volatile uintptr_t *c)
220 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
221 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
222 rw->rw_lock = RW_DESTROYED;
223 lock_destroy(&rw->lock_object);
227 rw_sysinit(void *arg)
229 struct rw_args *args = arg;
231 rw_init((struct rwlock *)args->ra_rw, args->ra_desc);
235 rw_sysinit_flags(void *arg)
237 struct rw_args_flags *args = arg;
239 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
244 _rw_wowned(const volatile uintptr_t *c)
247 return (rw_wowner(rwlock2rw(c)) == curthread);
251 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
255 if (SCHEDULER_STOPPED())
260 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
261 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
262 curthread, rw->lock_object.lo_name, file, line));
263 KASSERT(rw->rw_lock != RW_DESTROYED,
264 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
265 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
267 __rw_wlock(rw, curthread, file, line);
268 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
269 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
270 curthread->td_locks++;
274 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
279 if (SCHEDULER_STOPPED())
284 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
285 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
286 curthread, rw->lock_object.lo_name, file, line));
287 KASSERT(rw->rw_lock != RW_DESTROYED,
288 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
290 if (rw_wlocked(rw) &&
291 (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
295 rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
296 (uintptr_t)curthread);
298 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
300 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
302 curthread->td_locks++;
308 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
312 if (SCHEDULER_STOPPED())
317 KASSERT(rw->rw_lock != RW_DESTROYED,
318 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
319 __rw_assert(c, RA_WLOCKED, file, line);
320 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
321 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
323 if (!rw_recursed(rw))
324 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_WUNLOCK_RELEASE, rw);
325 __rw_wunlock(rw, curthread, file, line);
326 curthread->td_locks--;
329 * Determines whether a new reader can acquire a lock. Succeeds if the
330 * reader already owns a read lock and the lock is locked for read to
331 * prevent deadlock from reader recursion. Also succeeds if the lock
332 * is unlocked and has no writer waiters or spinners. Failing otherwise
333 * prioritizes writers before readers.
335 #define RW_CAN_READ(_rw) \
336 ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) & \
337 (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) == \
341 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
344 struct turnstile *ts;
345 #ifdef ADAPTIVE_RWLOCKS
346 volatile struct thread *owner;
350 #ifdef LOCK_PROFILING
351 uint64_t waittime = 0;
356 uint64_t spin_cnt = 0;
357 uint64_t sleep_cnt = 0;
358 int64_t sleep_time = 0;
361 if (SCHEDULER_STOPPED())
366 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
367 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
368 curthread, rw->lock_object.lo_name, file, line));
369 KASSERT(rw->rw_lock != RW_DESTROYED,
370 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
371 KASSERT(rw_wowner(rw) != curthread,
372 ("rw_rlock: wlock already held for %s @ %s:%d",
373 rw->lock_object.lo_name, file, line));
374 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
381 * Handle the easy case. If no other thread has a write
382 * lock, then try to bump up the count of read locks. Note
383 * that we have to preserve the current state of the
384 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
385 * read lock, then rw_lock must have changed, so restart
386 * the loop. Note that this handles the case of a
387 * completely unlocked rwlock since such a lock is encoded
388 * as a read lock with no waiters.
391 if (RW_CAN_READ(v)) {
393 * The RW_LOCK_READ_WAITERS flag should only be set
394 * if the lock has been unlocked and write waiters
397 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
398 v + RW_ONE_READER)) {
399 if (LOCK_LOG_TEST(&rw->lock_object, 0))
401 "%s: %p succeed %p -> %p", __func__,
403 (void *)(v + RW_ONE_READER));
409 PMC_SOFT_CALL( , , lock, failed);
411 lock_profile_obtain_lock_failed(&rw->lock_object,
412 &contested, &waittime);
414 #ifdef ADAPTIVE_RWLOCKS
416 * If the owner is running on another CPU, spin until
417 * the owner stops running or the state of the lock
420 if ((v & RW_LOCK_READ) == 0) {
421 owner = (struct thread *)RW_OWNER(v);
422 if (TD_IS_RUNNING(owner)) {
423 if (LOCK_LOG_TEST(&rw->lock_object, 0))
425 "%s: spinning on %p held by %p",
426 __func__, rw, owner);
427 KTR_STATE1(KTR_SCHED, "thread",
428 sched_tdname(curthread), "spinning",
429 "lockname:\"%s\"", rw->lock_object.lo_name);
430 while ((struct thread*)RW_OWNER(rw->rw_lock) ==
431 owner && TD_IS_RUNNING(owner)) {
437 KTR_STATE0(KTR_SCHED, "thread",
438 sched_tdname(curthread), "running");
441 } else if (spintries < rowner_retries) {
443 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
444 "spinning", "lockname:\"%s\"",
445 rw->lock_object.lo_name);
446 for (i = 0; i < rowner_loops; i++) {
448 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
452 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
454 if (i != rowner_loops)
460 * Okay, now it's the hard case. Some other thread already
461 * has a write lock or there are write waiters present,
462 * acquire the turnstile lock so we can begin the process
465 ts = turnstile_trywait(&rw->lock_object);
468 * The lock might have been released while we spun, so
469 * recheck its state and restart the loop if needed.
472 if (RW_CAN_READ(v)) {
473 turnstile_cancel(ts);
477 #ifdef ADAPTIVE_RWLOCKS
479 * The current lock owner might have started executing
480 * on another CPU (or the lock could have changed
481 * owners) while we were waiting on the turnstile
482 * chain lock. If so, drop the turnstile lock and try
485 if ((v & RW_LOCK_READ) == 0) {
486 owner = (struct thread *)RW_OWNER(v);
487 if (TD_IS_RUNNING(owner)) {
488 turnstile_cancel(ts);
495 * The lock is held in write mode or it already has waiters.
497 MPASS(!RW_CAN_READ(v));
500 * If the RW_LOCK_READ_WAITERS flag is already set, then
501 * we can go ahead and block. If it is not set then try
502 * to set it. If we fail to set it drop the turnstile
503 * lock and restart the loop.
505 if (!(v & RW_LOCK_READ_WAITERS)) {
506 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
507 v | RW_LOCK_READ_WAITERS)) {
508 turnstile_cancel(ts);
511 if (LOCK_LOG_TEST(&rw->lock_object, 0))
512 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
517 * We were unable to acquire the lock and the read waiters
518 * flag is set, so we must block on the turnstile.
520 if (LOCK_LOG_TEST(&rw->lock_object, 0))
521 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
524 sleep_time -= lockstat_nsecs();
526 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
528 sleep_time += lockstat_nsecs();
531 if (LOCK_LOG_TEST(&rw->lock_object, 0))
532 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
537 * TODO: acquire "owner of record" here. Here be turnstile dragons
538 * however. turnstiles don't like owners changing between calls to
539 * turnstile_wait() currently.
541 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
542 waittime, file, line);
543 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
544 WITNESS_LOCK(&rw->lock_object, 0, file, line);
545 curthread->td_locks++;
546 curthread->td_rw_rlocks++;
549 LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
552 * Record only the loops spinning and not sleeping.
554 if (spin_cnt > sleep_cnt)
555 LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
560 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
565 if (SCHEDULER_STOPPED())
570 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
571 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
572 curthread, rw->lock_object.lo_name, file, line));
576 KASSERT(rw->rw_lock != RW_DESTROYED,
577 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
578 if (!(x & RW_LOCK_READ))
580 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
581 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
583 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
584 curthread->td_locks++;
585 curthread->td_rw_rlocks++;
590 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
595 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
598 struct turnstile *ts;
599 uintptr_t x, v, queue;
601 if (SCHEDULER_STOPPED())
606 KASSERT(rw->rw_lock != RW_DESTROYED,
607 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
608 __rw_assert(c, RA_RLOCKED, file, line);
609 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
610 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
612 /* TODO: drop "owner of record" here. */
616 * See if there is more than one read lock held. If so,
617 * just drop one and return.
620 if (RW_READERS(x) > 1) {
621 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
622 x - RW_ONE_READER)) {
623 if (LOCK_LOG_TEST(&rw->lock_object, 0))
625 "%s: %p succeeded %p -> %p",
626 __func__, rw, (void *)x,
627 (void *)(x - RW_ONE_READER));
633 * If there aren't any waiters for a write lock, then try
634 * to drop it quickly.
636 if (!(x & RW_LOCK_WAITERS)) {
637 MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
639 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
641 if (LOCK_LOG_TEST(&rw->lock_object, 0))
642 CTR2(KTR_LOCK, "%s: %p last succeeded",
649 * Ok, we know we have waiters and we think we are the
650 * last reader, so grab the turnstile lock.
652 turnstile_chain_lock(&rw->lock_object);
653 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
654 MPASS(v & RW_LOCK_WAITERS);
657 * Try to drop our lock leaving the lock in a unlocked
660 * If you wanted to do explicit lock handoff you'd have to
661 * do it here. You'd also want to use turnstile_signal()
662 * and you'd have to handle the race where a higher
663 * priority thread blocks on the write lock before the
664 * thread you wakeup actually runs and have the new thread
665 * "steal" the lock. For now it's a lot simpler to just
666 * wakeup all of the waiters.
668 * As above, if we fail, then another thread might have
669 * acquired a read lock, so drop the turnstile lock and
673 if (v & RW_LOCK_WRITE_WAITERS) {
674 queue = TS_EXCLUSIVE_QUEUE;
675 x |= (v & RW_LOCK_READ_WAITERS);
677 queue = TS_SHARED_QUEUE;
678 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
680 turnstile_chain_unlock(&rw->lock_object);
683 if (LOCK_LOG_TEST(&rw->lock_object, 0))
684 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
688 * Ok. The lock is released and all that's left is to
689 * wake up the waiters. Note that the lock might not be
690 * free anymore, but in that case the writers will just
691 * block again if they run before the new lock holder(s)
694 ts = turnstile_lookup(&rw->lock_object);
696 turnstile_broadcast(ts, queue);
697 turnstile_unpend(ts, TS_SHARED_LOCK);
698 turnstile_chain_unlock(&rw->lock_object);
701 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
702 curthread->td_locks--;
703 curthread->td_rw_rlocks--;
707 * This function is called when we are unable to obtain a write lock on the
708 * first try. This means that at least one other thread holds either a
709 * read or write lock.
712 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
716 struct turnstile *ts;
717 #ifdef ADAPTIVE_RWLOCKS
718 volatile struct thread *owner;
723 #ifdef LOCK_PROFILING
724 uint64_t waittime = 0;
728 uint64_t spin_cnt = 0;
729 uint64_t sleep_cnt = 0;
730 int64_t sleep_time = 0;
733 if (SCHEDULER_STOPPED())
738 if (rw_wlocked(rw)) {
739 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
740 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
741 __func__, rw->lock_object.lo_name, file, line));
743 if (LOCK_LOG_TEST(&rw->lock_object, 0))
744 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
748 if (LOCK_LOG_TEST(&rw->lock_object, 0))
749 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
750 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
752 while (!_rw_write_lock(rw, tid)) {
757 PMC_SOFT_CALL( , , lock, failed);
759 lock_profile_obtain_lock_failed(&rw->lock_object,
760 &contested, &waittime);
761 #ifdef ADAPTIVE_RWLOCKS
763 * If the lock is write locked and the owner is
764 * running on another CPU, spin until the owner stops
765 * running or the state of the lock changes.
768 owner = (struct thread *)RW_OWNER(v);
769 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
770 if (LOCK_LOG_TEST(&rw->lock_object, 0))
771 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
772 __func__, rw, owner);
773 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
774 "spinning", "lockname:\"%s\"",
775 rw->lock_object.lo_name);
776 while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
777 TD_IS_RUNNING(owner)) {
783 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
787 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
788 spintries < rowner_retries) {
789 if (!(v & RW_LOCK_WRITE_SPINNER)) {
790 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
791 v | RW_LOCK_WRITE_SPINNER)) {
796 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
797 "spinning", "lockname:\"%s\"",
798 rw->lock_object.lo_name);
799 for (i = 0; i < rowner_loops; i++) {
800 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
804 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
807 spin_cnt += rowner_loops - i;
809 if (i != rowner_loops)
813 ts = turnstile_trywait(&rw->lock_object);
816 #ifdef ADAPTIVE_RWLOCKS
818 * The current lock owner might have started executing
819 * on another CPU (or the lock could have changed
820 * owners) while we were waiting on the turnstile
821 * chain lock. If so, drop the turnstile lock and try
824 if (!(v & RW_LOCK_READ)) {
825 owner = (struct thread *)RW_OWNER(v);
826 if (TD_IS_RUNNING(owner)) {
827 turnstile_cancel(ts);
833 * Check for the waiters flags about this rwlock.
834 * If the lock was released, without maintain any pending
835 * waiters queue, simply try to acquire it.
836 * If a pending waiters queue is present, claim the lock
837 * ownership and maintain the pending queue.
839 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
840 if ((v & ~x) == RW_UNLOCKED) {
841 x &= ~RW_LOCK_WRITE_SPINNER;
842 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
846 turnstile_cancel(ts);
849 turnstile_cancel(ts);
853 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
854 * set it. If we fail to set it, then loop back and try
857 if (!(v & RW_LOCK_WRITE_WAITERS)) {
858 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
859 v | RW_LOCK_WRITE_WAITERS)) {
860 turnstile_cancel(ts);
863 if (LOCK_LOG_TEST(&rw->lock_object, 0))
864 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
868 * We were unable to acquire the lock and the write waiters
869 * flag is set, so we must block on the turnstile.
871 if (LOCK_LOG_TEST(&rw->lock_object, 0))
872 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
875 sleep_time -= lockstat_nsecs();
877 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
879 sleep_time += lockstat_nsecs();
882 if (LOCK_LOG_TEST(&rw->lock_object, 0))
883 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
885 #ifdef ADAPTIVE_RWLOCKS
889 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
890 waittime, file, line);
893 LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
896 * Record only the loops spinning and not sleeping.
898 if (spin_cnt > sleep_cnt)
899 LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
904 * This function is called if the first try at releasing a write lock failed.
905 * This means that one of the 2 waiter bits must be set indicating that at
906 * least one thread is waiting on this lock.
909 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
913 struct turnstile *ts;
917 if (SCHEDULER_STOPPED())
922 if (rw_wlocked(rw) && rw_recursed(rw)) {
924 if (LOCK_LOG_TEST(&rw->lock_object, 0))
925 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
929 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
930 ("%s: neither of the waiter flags are set", __func__));
932 if (LOCK_LOG_TEST(&rw->lock_object, 0))
933 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
935 turnstile_chain_lock(&rw->lock_object);
936 ts = turnstile_lookup(&rw->lock_object);
940 * Use the same algo as sx locks for now. Prefer waking up shared
941 * waiters if we have any over writers. This is probably not ideal.
943 * 'v' is the value we are going to write back to rw_lock. If we
944 * have waiters on both queues, we need to preserve the state of
945 * the waiter flag for the queue we don't wake up. For now this is
946 * hardcoded for the algorithm mentioned above.
948 * In the case of both readers and writers waiting we wakeup the
949 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
950 * new writer comes in before a reader it will claim the lock up
951 * above. There is probably a potential priority inversion in
952 * there that could be worked around either by waking both queues
953 * of waiters or doing some complicated lock handoff gymnastics.
956 if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
957 queue = TS_EXCLUSIVE_QUEUE;
958 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
960 queue = TS_SHARED_QUEUE;
962 /* Wake up all waiters for the specific queue. */
963 if (LOCK_LOG_TEST(&rw->lock_object, 0))
964 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
965 queue == TS_SHARED_QUEUE ? "read" : "write");
966 turnstile_broadcast(ts, queue);
967 atomic_store_rel_ptr(&rw->rw_lock, v);
968 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
969 turnstile_chain_unlock(&rw->lock_object);
973 * Attempt to do a non-blocking upgrade from a read lock to a write
974 * lock. This will only succeed if this thread holds a single read
975 * lock. Returns true if the upgrade succeeded and false otherwise.
978 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
982 struct turnstile *ts;
985 if (SCHEDULER_STOPPED())
990 KASSERT(rw->rw_lock != RW_DESTROYED,
991 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
992 __rw_assert(c, RA_RLOCKED, file, line);
995 * Attempt to switch from one reader to a writer. If there
996 * are any write waiters, then we will have to lock the
997 * turnstile first to prevent races with another writer
998 * calling turnstile_wait() before we have claimed this
999 * turnstile. So, do the simple case of no waiters first.
1001 tid = (uintptr_t)curthread;
1005 if (RW_READERS(v) > 1)
1007 if (!(v & RW_LOCK_WAITERS)) {
1008 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
1015 * Ok, we think we have waiters, so lock the turnstile.
1017 ts = turnstile_trywait(&rw->lock_object);
1019 if (RW_READERS(v) > 1) {
1020 turnstile_cancel(ts);
1024 * Try to switch from one reader to a writer again. This time
1025 * we honor the current state of the waiters flags.
1026 * If we obtain the lock with the flags set, then claim
1027 * ownership of the turnstile.
1029 x = rw->rw_lock & RW_LOCK_WAITERS;
1030 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1033 turnstile_claim(ts);
1035 turnstile_cancel(ts);
1038 turnstile_cancel(ts);
1040 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1042 curthread->td_rw_rlocks--;
1043 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1045 LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
1051 * Downgrade a write lock into a single read lock.
1054 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1057 struct turnstile *ts;
1061 if (SCHEDULER_STOPPED())
1066 KASSERT(rw->rw_lock != RW_DESTROYED,
1067 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1068 __rw_assert(c, RA_WLOCKED | RA_NOTRECURSED, file, line);
1070 if (rw_recursed(rw))
1071 panic("downgrade of a recursed lock");
1074 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1077 * Convert from a writer to a single reader. First we handle
1078 * the easy case with no waiters. If there are any waiters, we
1079 * lock the turnstile and "disown" the lock.
1081 tid = (uintptr_t)curthread;
1082 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1086 * Ok, we think we have waiters, so lock the turnstile so we can
1087 * read the waiter flags without any races.
1089 turnstile_chain_lock(&rw->lock_object);
1090 v = rw->rw_lock & RW_LOCK_WAITERS;
1091 rwait = v & RW_LOCK_READ_WAITERS;
1092 wwait = v & RW_LOCK_WRITE_WAITERS;
1093 MPASS(rwait | wwait);
1096 * Downgrade from a write lock while preserving waiters flag
1097 * and give up ownership of the turnstile.
1099 ts = turnstile_lookup(&rw->lock_object);
1102 v &= ~RW_LOCK_READ_WAITERS;
1103 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1105 * Wake other readers if there are no writers pending. Otherwise they
1106 * won't be able to acquire the lock anyway.
1108 if (rwait && !wwait) {
1109 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1110 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1112 turnstile_disown(ts);
1113 turnstile_chain_unlock(&rw->lock_object);
1115 curthread->td_rw_rlocks++;
1116 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1117 LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1120 #ifdef INVARIANT_SUPPORT
1126 * In the non-WITNESS case, rw_assert() can only detect that at least
1127 * *some* thread owns an rlock, but it cannot guarantee that *this*
1128 * thread owns an rlock.
1131 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1133 const struct rwlock *rw;
1135 if (panicstr != NULL)
1142 case RA_LOCKED | RA_RECURSED:
1143 case RA_LOCKED | RA_NOTRECURSED:
1145 case RA_RLOCKED | RA_RECURSED:
1146 case RA_RLOCKED | RA_NOTRECURSED:
1148 witness_assert(&rw->lock_object, what, file, line);
1151 * If some other thread has a write lock or we have one
1152 * and are asserting a read lock, fail. Also, if no one
1153 * has a lock at all, fail.
1155 if (rw->rw_lock == RW_UNLOCKED ||
1156 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1157 rw_wowner(rw) != curthread)))
1158 panic("Lock %s not %slocked @ %s:%d\n",
1159 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1160 "read " : "", file, line);
1162 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1163 if (rw_recursed(rw)) {
1164 if (what & RA_NOTRECURSED)
1165 panic("Lock %s recursed @ %s:%d\n",
1166 rw->lock_object.lo_name, file,
1168 } else if (what & RA_RECURSED)
1169 panic("Lock %s not recursed @ %s:%d\n",
1170 rw->lock_object.lo_name, file, line);
1175 case RA_WLOCKED | RA_RECURSED:
1176 case RA_WLOCKED | RA_NOTRECURSED:
1177 if (rw_wowner(rw) != curthread)
1178 panic("Lock %s not exclusively locked @ %s:%d\n",
1179 rw->lock_object.lo_name, file, line);
1180 if (rw_recursed(rw)) {
1181 if (what & RA_NOTRECURSED)
1182 panic("Lock %s recursed @ %s:%d\n",
1183 rw->lock_object.lo_name, file, line);
1184 } else if (what & RA_RECURSED)
1185 panic("Lock %s not recursed @ %s:%d\n",
1186 rw->lock_object.lo_name, file, line);
1190 witness_assert(&rw->lock_object, what, file, line);
1193 * If we hold a write lock fail. We can't reliably check
1194 * to see if we hold a read lock or not.
1196 if (rw_wowner(rw) == curthread)
1197 panic("Lock %s exclusively locked @ %s:%d\n",
1198 rw->lock_object.lo_name, file, line);
1202 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1206 #endif /* INVARIANT_SUPPORT */
1210 db_show_rwlock(const struct lock_object *lock)
1212 const struct rwlock *rw;
1215 rw = (const struct rwlock *)lock;
1217 db_printf(" state: ");
1218 if (rw->rw_lock == RW_UNLOCKED)
1219 db_printf("UNLOCKED\n");
1220 else if (rw->rw_lock == RW_DESTROYED) {
1221 db_printf("DESTROYED\n");
1223 } else if (rw->rw_lock & RW_LOCK_READ)
1224 db_printf("RLOCK: %ju locks\n",
1225 (uintmax_t)(RW_READERS(rw->rw_lock)));
1228 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1229 td->td_tid, td->td_proc->p_pid, td->td_name);
1230 if (rw_recursed(rw))
1231 db_printf(" recursed: %u\n", rw->rw_recurse);
1233 db_printf(" waiters: ");
1234 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1235 case RW_LOCK_READ_WAITERS:
1236 db_printf("readers\n");
1238 case RW_LOCK_WRITE_WAITERS:
1239 db_printf("writers\n");
1241 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1242 db_printf("readers and writers\n");
1245 db_printf("none\n");