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/sysctl.h>
48 #include <sys/systm.h>
49 #include <sys/turnstile.h>
51 #include <machine/cpu.h>
53 #if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
54 #define ADAPTIVE_RWLOCKS
58 #include <sys/pmckern.h>
59 PMC_SOFT_DECLARE( , , lock, failed);
63 * Return the rwlock address when the lock cookie address is provided.
64 * This functionality assumes that struct rwlock* have a member named rw_lock.
66 #define rwlock2rw(c) (__containerof(c, struct rwlock, rw_lock))
68 #ifdef ADAPTIVE_RWLOCKS
69 static int rowner_retries = 10;
70 static int rowner_loops = 10000;
71 static SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL,
73 SYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
74 SYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
80 static void db_show_rwlock(const struct lock_object *lock);
82 static void assert_rw(const struct lock_object *lock, int what);
83 static void lock_rw(struct lock_object *lock, uintptr_t how);
85 static int owner_rw(const struct lock_object *lock, struct thread **owner);
87 static uintptr_t unlock_rw(struct lock_object *lock);
89 struct lock_class lock_class_rw = {
91 .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
92 .lc_assert = assert_rw,
94 .lc_ddb_show = db_show_rwlock,
97 .lc_unlock = unlock_rw,
104 * Return a pointer to the owning thread if the lock is write-locked or
105 * NULL if the lock is unlocked or read-locked.
107 #define rw_wowner(rw) \
108 ((rw)->rw_lock & RW_LOCK_READ ? NULL : \
109 (struct thread *)RW_OWNER((rw)->rw_lock))
112 * Returns if a write owner is recursed. Write ownership is not assured
113 * here and should be previously checked.
115 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
118 * Return true if curthread helds the lock.
120 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
123 * Return a pointer to the owning thread for this lock who should receive
124 * any priority lent by threads that block on this lock. Currently this
125 * is identical to rw_wowner().
127 #define rw_owner(rw) rw_wowner(rw)
130 #define __rw_assert(c, what, file, line)
134 assert_rw(const struct lock_object *lock, int what)
137 rw_assert((const struct rwlock *)lock, what);
141 lock_rw(struct lock_object *lock, uintptr_t how)
145 rw = (struct rwlock *)lock;
153 unlock_rw(struct lock_object *lock)
157 rw = (struct rwlock *)lock;
158 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
159 if (rw->rw_lock & RW_LOCK_READ) {
170 owner_rw(const struct lock_object *lock, struct thread **owner)
172 const struct rwlock *rw = (const struct rwlock *)lock;
173 uintptr_t x = rw->rw_lock;
175 *owner = rw_wowner(rw);
176 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
182 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
189 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
191 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
192 ("%s: rw_lock not aligned for %s: %p", __func__, name,
195 flags = LO_UPGRADABLE;
198 if (opts & RW_NOPROFILE)
199 flags |= LO_NOPROFILE;
200 if (!(opts & RW_NOWITNESS))
202 if (opts & RW_RECURSE)
203 flags |= LO_RECURSABLE;
207 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
208 rw->rw_lock = RW_UNLOCKED;
213 _rw_destroy(volatile uintptr_t *c)
219 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
220 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
221 rw->rw_lock = RW_DESTROYED;
222 lock_destroy(&rw->lock_object);
226 rw_sysinit(void *arg)
228 struct rw_args *args = arg;
230 rw_init((struct rwlock *)args->ra_rw, args->ra_desc);
234 rw_sysinit_flags(void *arg)
236 struct rw_args_flags *args = arg;
238 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
243 _rw_wowned(const volatile uintptr_t *c)
246 return (rw_wowner(rwlock2rw(c)) == curthread);
250 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
254 if (SCHEDULER_STOPPED())
259 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
260 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
261 curthread, rw->lock_object.lo_name, file, line));
262 KASSERT(rw->rw_lock != RW_DESTROYED,
263 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
264 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
266 __rw_wlock(rw, curthread, file, line);
267 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
268 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
269 curthread->td_locks++;
273 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
278 if (SCHEDULER_STOPPED())
283 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
284 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
285 curthread, rw->lock_object.lo_name, file, line));
286 KASSERT(rw->rw_lock != RW_DESTROYED,
287 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
289 if (rw_wlocked(rw) &&
290 (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
294 rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
295 (uintptr_t)curthread);
297 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
299 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
301 curthread->td_locks++;
307 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
311 if (SCHEDULER_STOPPED())
316 KASSERT(rw->rw_lock != RW_DESTROYED,
317 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
318 __rw_assert(c, RA_WLOCKED, file, line);
319 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
320 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
322 if (!rw_recursed(rw))
323 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_WUNLOCK_RELEASE, rw);
324 __rw_wunlock(rw, curthread, file, line);
325 curthread->td_locks--;
328 * Determines whether a new reader can acquire a lock. Succeeds if the
329 * reader already owns a read lock and the lock is locked for read to
330 * prevent deadlock from reader recursion. Also succeeds if the lock
331 * is unlocked and has no writer waiters or spinners. Failing otherwise
332 * prioritizes writers before readers.
334 #define RW_CAN_READ(_rw) \
335 ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) & \
336 (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) == \
340 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
343 struct turnstile *ts;
344 #ifdef ADAPTIVE_RWLOCKS
345 volatile struct thread *owner;
349 #ifdef LOCK_PROFILING
350 uint64_t waittime = 0;
355 uint64_t spin_cnt = 0;
356 uint64_t sleep_cnt = 0;
357 int64_t sleep_time = 0;
360 if (SCHEDULER_STOPPED())
365 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
366 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
367 curthread, rw->lock_object.lo_name, file, line));
368 KASSERT(rw->rw_lock != RW_DESTROYED,
369 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
370 KASSERT(rw_wowner(rw) != curthread,
371 ("rw_rlock: wlock already held for %s @ %s:%d",
372 rw->lock_object.lo_name, file, line));
373 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
380 * Handle the easy case. If no other thread has a write
381 * lock, then try to bump up the count of read locks. Note
382 * that we have to preserve the current state of the
383 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
384 * read lock, then rw_lock must have changed, so restart
385 * the loop. Note that this handles the case of a
386 * completely unlocked rwlock since such a lock is encoded
387 * as a read lock with no waiters.
390 if (RW_CAN_READ(v)) {
392 * The RW_LOCK_READ_WAITERS flag should only be set
393 * if the lock has been unlocked and write waiters
396 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
397 v + RW_ONE_READER)) {
398 if (LOCK_LOG_TEST(&rw->lock_object, 0))
400 "%s: %p succeed %p -> %p", __func__,
402 (void *)(v + RW_ONE_READER));
408 PMC_SOFT_CALL( , , lock, failed);
410 lock_profile_obtain_lock_failed(&rw->lock_object,
411 &contested, &waittime);
413 #ifdef ADAPTIVE_RWLOCKS
415 * If the owner is running on another CPU, spin until
416 * the owner stops running or the state of the lock
419 if ((v & RW_LOCK_READ) == 0) {
420 owner = (struct thread *)RW_OWNER(v);
421 if (TD_IS_RUNNING(owner)) {
422 if (LOCK_LOG_TEST(&rw->lock_object, 0))
424 "%s: spinning on %p held by %p",
425 __func__, rw, owner);
426 while ((struct thread*)RW_OWNER(rw->rw_lock) ==
427 owner && TD_IS_RUNNING(owner)) {
435 } else if (spintries < rowner_retries) {
437 for (i = 0; i < rowner_loops; i++) {
439 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
443 if (i != rowner_loops)
449 * Okay, now it's the hard case. Some other thread already
450 * has a write lock or there are write waiters present,
451 * acquire the turnstile lock so we can begin the process
454 ts = turnstile_trywait(&rw->lock_object);
457 * The lock might have been released while we spun, so
458 * recheck its state and restart the loop if needed.
461 if (RW_CAN_READ(v)) {
462 turnstile_cancel(ts);
466 #ifdef ADAPTIVE_RWLOCKS
468 * The current lock owner might have started executing
469 * on another CPU (or the lock could have changed
470 * owners) while we were waiting on the turnstile
471 * chain lock. If so, drop the turnstile lock and try
474 if ((v & RW_LOCK_READ) == 0) {
475 owner = (struct thread *)RW_OWNER(v);
476 if (TD_IS_RUNNING(owner)) {
477 turnstile_cancel(ts);
484 * The lock is held in write mode or it already has waiters.
486 MPASS(!RW_CAN_READ(v));
489 * If the RW_LOCK_READ_WAITERS flag is already set, then
490 * we can go ahead and block. If it is not set then try
491 * to set it. If we fail to set it drop the turnstile
492 * lock and restart the loop.
494 if (!(v & RW_LOCK_READ_WAITERS)) {
495 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
496 v | RW_LOCK_READ_WAITERS)) {
497 turnstile_cancel(ts);
500 if (LOCK_LOG_TEST(&rw->lock_object, 0))
501 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
506 * We were unable to acquire the lock and the read waiters
507 * flag is set, so we must block on the turnstile.
509 if (LOCK_LOG_TEST(&rw->lock_object, 0))
510 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
513 sleep_time -= lockstat_nsecs();
515 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
517 sleep_time += lockstat_nsecs();
520 if (LOCK_LOG_TEST(&rw->lock_object, 0))
521 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
526 * TODO: acquire "owner of record" here. Here be turnstile dragons
527 * however. turnstiles don't like owners changing between calls to
528 * turnstile_wait() currently.
530 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
531 waittime, file, line);
532 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
533 WITNESS_LOCK(&rw->lock_object, 0, file, line);
534 curthread->td_locks++;
535 curthread->td_rw_rlocks++;
538 LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
541 * Record only the loops spinning and not sleeping.
543 if (spin_cnt > sleep_cnt)
544 LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
549 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
554 if (SCHEDULER_STOPPED())
559 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
560 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
561 curthread, rw->lock_object.lo_name, file, line));
565 KASSERT(rw->rw_lock != RW_DESTROYED,
566 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
567 if (!(x & RW_LOCK_READ))
569 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
570 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
572 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
573 curthread->td_locks++;
574 curthread->td_rw_rlocks++;
579 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
584 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
587 struct turnstile *ts;
588 uintptr_t x, v, queue;
590 if (SCHEDULER_STOPPED())
595 KASSERT(rw->rw_lock != RW_DESTROYED,
596 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
597 __rw_assert(c, RA_RLOCKED, file, line);
598 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
599 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
601 /* TODO: drop "owner of record" here. */
605 * See if there is more than one read lock held. If so,
606 * just drop one and return.
609 if (RW_READERS(x) > 1) {
610 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
611 x - RW_ONE_READER)) {
612 if (LOCK_LOG_TEST(&rw->lock_object, 0))
614 "%s: %p succeeded %p -> %p",
615 __func__, rw, (void *)x,
616 (void *)(x - RW_ONE_READER));
622 * If there aren't any waiters for a write lock, then try
623 * to drop it quickly.
625 if (!(x & RW_LOCK_WAITERS)) {
626 MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
628 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
630 if (LOCK_LOG_TEST(&rw->lock_object, 0))
631 CTR2(KTR_LOCK, "%s: %p last succeeded",
638 * Ok, we know we have waiters and we think we are the
639 * last reader, so grab the turnstile lock.
641 turnstile_chain_lock(&rw->lock_object);
642 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
643 MPASS(v & RW_LOCK_WAITERS);
646 * Try to drop our lock leaving the lock in a unlocked
649 * If you wanted to do explicit lock handoff you'd have to
650 * do it here. You'd also want to use turnstile_signal()
651 * and you'd have to handle the race where a higher
652 * priority thread blocks on the write lock before the
653 * thread you wakeup actually runs and have the new thread
654 * "steal" the lock. For now it's a lot simpler to just
655 * wakeup all of the waiters.
657 * As above, if we fail, then another thread might have
658 * acquired a read lock, so drop the turnstile lock and
662 if (v & RW_LOCK_WRITE_WAITERS) {
663 queue = TS_EXCLUSIVE_QUEUE;
664 x |= (v & RW_LOCK_READ_WAITERS);
666 queue = TS_SHARED_QUEUE;
667 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
669 turnstile_chain_unlock(&rw->lock_object);
672 if (LOCK_LOG_TEST(&rw->lock_object, 0))
673 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
677 * Ok. The lock is released and all that's left is to
678 * wake up the waiters. Note that the lock might not be
679 * free anymore, but in that case the writers will just
680 * block again if they run before the new lock holder(s)
683 ts = turnstile_lookup(&rw->lock_object);
685 turnstile_broadcast(ts, queue);
686 turnstile_unpend(ts, TS_SHARED_LOCK);
687 turnstile_chain_unlock(&rw->lock_object);
690 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
691 curthread->td_locks--;
692 curthread->td_rw_rlocks--;
696 * This function is called when we are unable to obtain a write lock on the
697 * first try. This means that at least one other thread holds either a
698 * read or write lock.
701 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
705 struct turnstile *ts;
706 #ifdef ADAPTIVE_RWLOCKS
707 volatile struct thread *owner;
712 #ifdef LOCK_PROFILING
713 uint64_t waittime = 0;
717 uint64_t spin_cnt = 0;
718 uint64_t sleep_cnt = 0;
719 int64_t sleep_time = 0;
722 if (SCHEDULER_STOPPED())
727 if (rw_wlocked(rw)) {
728 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
729 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
730 __func__, rw->lock_object.lo_name, file, line));
732 if (LOCK_LOG_TEST(&rw->lock_object, 0))
733 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
737 if (LOCK_LOG_TEST(&rw->lock_object, 0))
738 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
739 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
741 while (!_rw_write_lock(rw, tid)) {
746 PMC_SOFT_CALL( , , lock, failed);
748 lock_profile_obtain_lock_failed(&rw->lock_object,
749 &contested, &waittime);
750 #ifdef ADAPTIVE_RWLOCKS
752 * If the lock is write locked and the owner is
753 * running on another CPU, spin until the owner stops
754 * running or the state of the lock changes.
757 owner = (struct thread *)RW_OWNER(v);
758 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
759 if (LOCK_LOG_TEST(&rw->lock_object, 0))
760 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
761 __func__, rw, owner);
762 while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
763 TD_IS_RUNNING(owner)) {
771 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
772 spintries < rowner_retries) {
773 if (!(v & RW_LOCK_WRITE_SPINNER)) {
774 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
775 v | RW_LOCK_WRITE_SPINNER)) {
780 for (i = 0; i < rowner_loops; i++) {
781 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
786 spin_cnt += rowner_loops - i;
788 if (i != rowner_loops)
792 ts = turnstile_trywait(&rw->lock_object);
795 #ifdef ADAPTIVE_RWLOCKS
797 * The current lock owner might have started executing
798 * on another CPU (or the lock could have changed
799 * owners) while we were waiting on the turnstile
800 * chain lock. If so, drop the turnstile lock and try
803 if (!(v & RW_LOCK_READ)) {
804 owner = (struct thread *)RW_OWNER(v);
805 if (TD_IS_RUNNING(owner)) {
806 turnstile_cancel(ts);
812 * Check for the waiters flags about this rwlock.
813 * If the lock was released, without maintain any pending
814 * waiters queue, simply try to acquire it.
815 * If a pending waiters queue is present, claim the lock
816 * ownership and maintain the pending queue.
818 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
819 if ((v & ~x) == RW_UNLOCKED) {
820 x &= ~RW_LOCK_WRITE_SPINNER;
821 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
825 turnstile_cancel(ts);
828 turnstile_cancel(ts);
832 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
833 * set it. If we fail to set it, then loop back and try
836 if (!(v & RW_LOCK_WRITE_WAITERS)) {
837 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
838 v | RW_LOCK_WRITE_WAITERS)) {
839 turnstile_cancel(ts);
842 if (LOCK_LOG_TEST(&rw->lock_object, 0))
843 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
847 * We were unable to acquire the lock and the write waiters
848 * flag is set, so we must block on the turnstile.
850 if (LOCK_LOG_TEST(&rw->lock_object, 0))
851 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
854 sleep_time -= lockstat_nsecs();
856 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
858 sleep_time += lockstat_nsecs();
861 if (LOCK_LOG_TEST(&rw->lock_object, 0))
862 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
864 #ifdef ADAPTIVE_RWLOCKS
868 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
869 waittime, file, line);
872 LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
875 * Record only the loops spinning and not sleeping.
877 if (spin_cnt > sleep_cnt)
878 LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
883 * This function is called if the first try at releasing a write lock failed.
884 * This means that one of the 2 waiter bits must be set indicating that at
885 * least one thread is waiting on this lock.
888 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
892 struct turnstile *ts;
896 if (SCHEDULER_STOPPED())
901 if (rw_wlocked(rw) && rw_recursed(rw)) {
903 if (LOCK_LOG_TEST(&rw->lock_object, 0))
904 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
908 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
909 ("%s: neither of the waiter flags are set", __func__));
911 if (LOCK_LOG_TEST(&rw->lock_object, 0))
912 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
914 turnstile_chain_lock(&rw->lock_object);
915 ts = turnstile_lookup(&rw->lock_object);
919 * Use the same algo as sx locks for now. Prefer waking up shared
920 * waiters if we have any over writers. This is probably not ideal.
922 * 'v' is the value we are going to write back to rw_lock. If we
923 * have waiters on both queues, we need to preserve the state of
924 * the waiter flag for the queue we don't wake up. For now this is
925 * hardcoded for the algorithm mentioned above.
927 * In the case of both readers and writers waiting we wakeup the
928 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
929 * new writer comes in before a reader it will claim the lock up
930 * above. There is probably a potential priority inversion in
931 * there that could be worked around either by waking both queues
932 * of waiters or doing some complicated lock handoff gymnastics.
935 if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
936 queue = TS_EXCLUSIVE_QUEUE;
937 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
939 queue = TS_SHARED_QUEUE;
941 /* Wake up all waiters for the specific queue. */
942 if (LOCK_LOG_TEST(&rw->lock_object, 0))
943 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
944 queue == TS_SHARED_QUEUE ? "read" : "write");
945 turnstile_broadcast(ts, queue);
946 atomic_store_rel_ptr(&rw->rw_lock, v);
947 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
948 turnstile_chain_unlock(&rw->lock_object);
952 * Attempt to do a non-blocking upgrade from a read lock to a write
953 * lock. This will only succeed if this thread holds a single read
954 * lock. Returns true if the upgrade succeeded and false otherwise.
957 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
961 struct turnstile *ts;
964 if (SCHEDULER_STOPPED())
969 KASSERT(rw->rw_lock != RW_DESTROYED,
970 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
971 __rw_assert(c, RA_RLOCKED, file, line);
974 * Attempt to switch from one reader to a writer. If there
975 * are any write waiters, then we will have to lock the
976 * turnstile first to prevent races with another writer
977 * calling turnstile_wait() before we have claimed this
978 * turnstile. So, do the simple case of no waiters first.
980 tid = (uintptr_t)curthread;
984 if (RW_READERS(v) > 1)
986 if (!(v & RW_LOCK_WAITERS)) {
987 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
994 * Ok, we think we have waiters, so lock the turnstile.
996 ts = turnstile_trywait(&rw->lock_object);
998 if (RW_READERS(v) > 1) {
999 turnstile_cancel(ts);
1003 * Try to switch from one reader to a writer again. This time
1004 * we honor the current state of the waiters flags.
1005 * If we obtain the lock with the flags set, then claim
1006 * ownership of the turnstile.
1008 x = rw->rw_lock & RW_LOCK_WAITERS;
1009 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1012 turnstile_claim(ts);
1014 turnstile_cancel(ts);
1017 turnstile_cancel(ts);
1019 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1021 curthread->td_rw_rlocks--;
1022 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1024 LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
1030 * Downgrade a write lock into a single read lock.
1033 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1036 struct turnstile *ts;
1040 if (SCHEDULER_STOPPED())
1045 KASSERT(rw->rw_lock != RW_DESTROYED,
1046 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1047 __rw_assert(c, RA_WLOCKED | RA_NOTRECURSED, file, line);
1049 if (rw_recursed(rw))
1050 panic("downgrade of a recursed lock");
1053 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1056 * Convert from a writer to a single reader. First we handle
1057 * the easy case with no waiters. If there are any waiters, we
1058 * lock the turnstile and "disown" the lock.
1060 tid = (uintptr_t)curthread;
1061 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1065 * Ok, we think we have waiters, so lock the turnstile so we can
1066 * read the waiter flags without any races.
1068 turnstile_chain_lock(&rw->lock_object);
1069 v = rw->rw_lock & RW_LOCK_WAITERS;
1070 rwait = v & RW_LOCK_READ_WAITERS;
1071 wwait = v & RW_LOCK_WRITE_WAITERS;
1072 MPASS(rwait | wwait);
1075 * Downgrade from a write lock while preserving waiters flag
1076 * and give up ownership of the turnstile.
1078 ts = turnstile_lookup(&rw->lock_object);
1081 v &= ~RW_LOCK_READ_WAITERS;
1082 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1084 * Wake other readers if there are no writers pending. Otherwise they
1085 * won't be able to acquire the lock anyway.
1087 if (rwait && !wwait) {
1088 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1089 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1091 turnstile_disown(ts);
1092 turnstile_chain_unlock(&rw->lock_object);
1094 curthread->td_rw_rlocks++;
1095 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1096 LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1099 #ifdef INVARIANT_SUPPORT
1105 * In the non-WITNESS case, rw_assert() can only detect that at least
1106 * *some* thread owns an rlock, but it cannot guarantee that *this*
1107 * thread owns an rlock.
1110 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1112 const struct rwlock *rw;
1114 if (panicstr != NULL)
1121 case RA_LOCKED | RA_RECURSED:
1122 case RA_LOCKED | RA_NOTRECURSED:
1124 case RA_RLOCKED | RA_RECURSED:
1125 case RA_RLOCKED | RA_NOTRECURSED:
1127 witness_assert(&rw->lock_object, what, file, line);
1130 * If some other thread has a write lock or we have one
1131 * and are asserting a read lock, fail. Also, if no one
1132 * has a lock at all, fail.
1134 if (rw->rw_lock == RW_UNLOCKED ||
1135 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1136 rw_wowner(rw) != curthread)))
1137 panic("Lock %s not %slocked @ %s:%d\n",
1138 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1139 "read " : "", file, line);
1141 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1142 if (rw_recursed(rw)) {
1143 if (what & RA_NOTRECURSED)
1144 panic("Lock %s recursed @ %s:%d\n",
1145 rw->lock_object.lo_name, file,
1147 } else if (what & RA_RECURSED)
1148 panic("Lock %s not recursed @ %s:%d\n",
1149 rw->lock_object.lo_name, file, line);
1154 case RA_WLOCKED | RA_RECURSED:
1155 case RA_WLOCKED | RA_NOTRECURSED:
1156 if (rw_wowner(rw) != curthread)
1157 panic("Lock %s not exclusively locked @ %s:%d\n",
1158 rw->lock_object.lo_name, file, line);
1159 if (rw_recursed(rw)) {
1160 if (what & RA_NOTRECURSED)
1161 panic("Lock %s recursed @ %s:%d\n",
1162 rw->lock_object.lo_name, file, line);
1163 } else if (what & RA_RECURSED)
1164 panic("Lock %s not recursed @ %s:%d\n",
1165 rw->lock_object.lo_name, file, line);
1169 witness_assert(&rw->lock_object, what, file, line);
1172 * If we hold a write lock fail. We can't reliably check
1173 * to see if we hold a read lock or not.
1175 if (rw_wowner(rw) == curthread)
1176 panic("Lock %s exclusively locked @ %s:%d\n",
1177 rw->lock_object.lo_name, file, line);
1181 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1185 #endif /* INVARIANT_SUPPORT */
1189 db_show_rwlock(const struct lock_object *lock)
1191 const struct rwlock *rw;
1194 rw = (const struct rwlock *)lock;
1196 db_printf(" state: ");
1197 if (rw->rw_lock == RW_UNLOCKED)
1198 db_printf("UNLOCKED\n");
1199 else if (rw->rw_lock == RW_DESTROYED) {
1200 db_printf("DESTROYED\n");
1202 } else if (rw->rw_lock & RW_LOCK_READ)
1203 db_printf("RLOCK: %ju locks\n",
1204 (uintmax_t)(RW_READERS(rw->rw_lock)));
1207 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1208 td->td_tid, td->td_proc->p_pid, td->td_name);
1209 if (rw_recursed(rw))
1210 db_printf(" recursed: %u\n", rw->rw_recurse);
1212 db_printf(" waiters: ");
1213 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1214 case RW_LOCK_READ_WAITERS:
1215 db_printf("readers\n");
1217 case RW_LOCK_WRITE_WAITERS:
1218 db_printf("writers\n");
1220 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1221 db_printf("readers and writers\n");
1224 db_printf("none\n");