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>
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 |
190 RW_RECURSE | RW_NEW)) == 0);
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;
209 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
210 rw->rw_lock = RW_UNLOCKED;
215 _rw_destroy(volatile uintptr_t *c)
221 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
222 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
223 rw->rw_lock = RW_DESTROYED;
224 lock_destroy(&rw->lock_object);
228 rw_sysinit(void *arg)
230 struct rw_args *args = arg;
232 rw_init((struct rwlock *)args->ra_rw, args->ra_desc);
236 rw_sysinit_flags(void *arg)
238 struct rw_args_flags *args = arg;
240 rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
245 _rw_wowned(const volatile uintptr_t *c)
248 return (rw_wowner(rwlock2rw(c)) == curthread);
252 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
256 if (SCHEDULER_STOPPED())
261 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
262 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
263 curthread, rw->lock_object.lo_name, file, line));
264 KASSERT(rw->rw_lock != RW_DESTROYED,
265 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
266 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
268 __rw_wlock(rw, curthread, file, line);
269 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
270 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
271 curthread->td_locks++;
275 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
280 if (SCHEDULER_STOPPED())
285 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
286 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
287 curthread, rw->lock_object.lo_name, file, line));
288 KASSERT(rw->rw_lock != RW_DESTROYED,
289 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
291 if (rw_wlocked(rw) &&
292 (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
296 rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
297 (uintptr_t)curthread);
299 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
301 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
303 if (!rw_recursed(rw))
304 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE,
305 rw, 0, 0, file, line);
306 curthread->td_locks++;
312 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
316 if (SCHEDULER_STOPPED())
321 KASSERT(rw->rw_lock != RW_DESTROYED,
322 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
323 __rw_assert(c, RA_WLOCKED, file, line);
324 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
325 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
327 __rw_wunlock(rw, curthread, file, line);
328 curthread->td_locks--;
331 * Determines whether a new reader can acquire a lock. Succeeds if the
332 * reader already owns a read lock and the lock is locked for read to
333 * prevent deadlock from reader recursion. Also succeeds if the lock
334 * is unlocked and has no writer waiters or spinners. Failing otherwise
335 * prioritizes writers before readers.
337 #define RW_CAN_READ(_rw) \
338 ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) & \
339 (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) == \
343 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
346 struct turnstile *ts;
347 #ifdef ADAPTIVE_RWLOCKS
348 volatile struct thread *owner;
352 #ifdef LOCK_PROFILING
353 uint64_t waittime = 0;
359 uint64_t spin_cnt = 0;
360 uint64_t sleep_cnt = 0;
361 int64_t sleep_time = 0;
362 int64_t all_time = 0;
365 if (SCHEDULER_STOPPED())
370 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
371 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
372 curthread, rw->lock_object.lo_name, file, line));
373 KASSERT(rw->rw_lock != RW_DESTROYED,
374 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
375 KASSERT(rw_wowner(rw) != curthread,
376 ("rw_rlock: wlock already held for %s @ %s:%d",
377 rw->lock_object.lo_name, file, line));
378 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
381 all_time -= lockstat_nsecs();
389 * Handle the easy case. If no other thread has a write
390 * lock, then try to bump up the count of read locks. Note
391 * that we have to preserve the current state of the
392 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
393 * read lock, then rw_lock must have changed, so restart
394 * the loop. Note that this handles the case of a
395 * completely unlocked rwlock since such a lock is encoded
396 * as a read lock with no waiters.
399 if (RW_CAN_READ(v)) {
401 * The RW_LOCK_READ_WAITERS flag should only be set
402 * if the lock has been unlocked and write waiters
405 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
406 v + RW_ONE_READER)) {
407 if (LOCK_LOG_TEST(&rw->lock_object, 0))
409 "%s: %p succeed %p -> %p", __func__,
411 (void *)(v + RW_ONE_READER));
417 PMC_SOFT_CALL( , , lock, failed);
419 lock_profile_obtain_lock_failed(&rw->lock_object,
420 &contested, &waittime);
422 #ifdef ADAPTIVE_RWLOCKS
424 * If the owner is running on another CPU, spin until
425 * the owner stops running or the state of the lock
428 if ((v & RW_LOCK_READ) == 0) {
429 owner = (struct thread *)RW_OWNER(v);
430 if (TD_IS_RUNNING(owner)) {
431 if (LOCK_LOG_TEST(&rw->lock_object, 0))
433 "%s: spinning on %p held by %p",
434 __func__, rw, owner);
435 KTR_STATE1(KTR_SCHED, "thread",
436 sched_tdname(curthread), "spinning",
437 "lockname:\"%s\"", rw->lock_object.lo_name);
438 while ((struct thread*)RW_OWNER(rw->rw_lock) ==
439 owner && TD_IS_RUNNING(owner)) {
445 KTR_STATE0(KTR_SCHED, "thread",
446 sched_tdname(curthread), "running");
449 } else if (spintries < rowner_retries) {
451 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
452 "spinning", "lockname:\"%s\"",
453 rw->lock_object.lo_name);
454 for (i = 0; i < rowner_loops; i++) {
456 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
461 spin_cnt += rowner_loops - i;
463 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
465 if (i != rowner_loops)
471 * Okay, now it's the hard case. Some other thread already
472 * has a write lock or there are write waiters present,
473 * acquire the turnstile lock so we can begin the process
476 ts = turnstile_trywait(&rw->lock_object);
479 * The lock might have been released while we spun, so
480 * recheck its state and restart the loop if needed.
483 if (RW_CAN_READ(v)) {
484 turnstile_cancel(ts);
488 #ifdef ADAPTIVE_RWLOCKS
490 * The current lock owner might have started executing
491 * on another CPU (or the lock could have changed
492 * owners) while we were waiting on the turnstile
493 * chain lock. If so, drop the turnstile lock and try
496 if ((v & RW_LOCK_READ) == 0) {
497 owner = (struct thread *)RW_OWNER(v);
498 if (TD_IS_RUNNING(owner)) {
499 turnstile_cancel(ts);
506 * The lock is held in write mode or it already has waiters.
508 MPASS(!RW_CAN_READ(v));
511 * If the RW_LOCK_READ_WAITERS flag is already set, then
512 * we can go ahead and block. If it is not set then try
513 * to set it. If we fail to set it drop the turnstile
514 * lock and restart the loop.
516 if (!(v & RW_LOCK_READ_WAITERS)) {
517 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
518 v | RW_LOCK_READ_WAITERS)) {
519 turnstile_cancel(ts);
522 if (LOCK_LOG_TEST(&rw->lock_object, 0))
523 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
528 * We were unable to acquire the lock and the read waiters
529 * flag is set, so we must block on the turnstile.
531 if (LOCK_LOG_TEST(&rw->lock_object, 0))
532 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
535 sleep_time -= lockstat_nsecs();
537 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
539 sleep_time += lockstat_nsecs();
542 if (LOCK_LOG_TEST(&rw->lock_object, 0))
543 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
547 all_time += lockstat_nsecs();
549 LOCKSTAT_RECORD4(LS_RW_RLOCK_BLOCK, rw, sleep_time,
550 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
551 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
553 /* Record only the loops spinning and not sleeping. */
554 if (spin_cnt > sleep_cnt)
555 LOCKSTAT_RECORD4(LS_RW_RLOCK_SPIN, rw, all_time - sleep_time,
556 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
557 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
560 * TODO: acquire "owner of record" here. Here be turnstile dragons
561 * however. turnstiles don't like owners changing between calls to
562 * turnstile_wait() currently.
564 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
565 waittime, file, line);
566 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
567 WITNESS_LOCK(&rw->lock_object, 0, file, line);
568 curthread->td_locks++;
569 curthread->td_rw_rlocks++;
573 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
578 if (SCHEDULER_STOPPED())
583 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
584 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
585 curthread, rw->lock_object.lo_name, file, line));
589 KASSERT(rw->rw_lock != RW_DESTROYED,
590 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
591 if (!(x & RW_LOCK_READ))
593 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
594 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
596 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
597 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE,
598 rw, 0, 0, file, line);
599 curthread->td_locks++;
600 curthread->td_rw_rlocks++;
605 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
610 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
613 struct turnstile *ts;
614 uintptr_t x, v, queue;
616 if (SCHEDULER_STOPPED())
621 KASSERT(rw->rw_lock != RW_DESTROYED,
622 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
623 __rw_assert(c, RA_RLOCKED, file, line);
624 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
625 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
627 /* TODO: drop "owner of record" here. */
631 * See if there is more than one read lock held. If so,
632 * just drop one and return.
635 if (RW_READERS(x) > 1) {
636 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
637 x - RW_ONE_READER)) {
638 if (LOCK_LOG_TEST(&rw->lock_object, 0))
640 "%s: %p succeeded %p -> %p",
641 __func__, rw, (void *)x,
642 (void *)(x - RW_ONE_READER));
648 * If there aren't any waiters for a write lock, then try
649 * to drop it quickly.
651 if (!(x & RW_LOCK_WAITERS)) {
652 MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
654 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
656 if (LOCK_LOG_TEST(&rw->lock_object, 0))
657 CTR2(KTR_LOCK, "%s: %p last succeeded",
664 * Ok, we know we have waiters and we think we are the
665 * last reader, so grab the turnstile lock.
667 turnstile_chain_lock(&rw->lock_object);
668 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
669 MPASS(v & RW_LOCK_WAITERS);
672 * Try to drop our lock leaving the lock in a unlocked
675 * If you wanted to do explicit lock handoff you'd have to
676 * do it here. You'd also want to use turnstile_signal()
677 * and you'd have to handle the race where a higher
678 * priority thread blocks on the write lock before the
679 * thread you wakeup actually runs and have the new thread
680 * "steal" the lock. For now it's a lot simpler to just
681 * wakeup all of the waiters.
683 * As above, if we fail, then another thread might have
684 * acquired a read lock, so drop the turnstile lock and
688 if (v & RW_LOCK_WRITE_WAITERS) {
689 queue = TS_EXCLUSIVE_QUEUE;
690 x |= (v & RW_LOCK_READ_WAITERS);
692 queue = TS_SHARED_QUEUE;
693 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
695 turnstile_chain_unlock(&rw->lock_object);
698 if (LOCK_LOG_TEST(&rw->lock_object, 0))
699 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
703 * Ok. The lock is released and all that's left is to
704 * wake up the waiters. Note that the lock might not be
705 * free anymore, but in that case the writers will just
706 * block again if they run before the new lock holder(s)
709 ts = turnstile_lookup(&rw->lock_object);
711 turnstile_broadcast(ts, queue);
712 turnstile_unpend(ts, TS_SHARED_LOCK);
713 turnstile_chain_unlock(&rw->lock_object);
716 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
717 curthread->td_locks--;
718 curthread->td_rw_rlocks--;
722 * This function is called when we are unable to obtain a write lock on the
723 * first try. This means that at least one other thread holds either a
724 * read or write lock.
727 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
731 struct turnstile *ts;
732 #ifdef ADAPTIVE_RWLOCKS
733 volatile struct thread *owner;
738 #ifdef LOCK_PROFILING
739 uint64_t waittime = 0;
744 uint64_t spin_cnt = 0;
745 uint64_t sleep_cnt = 0;
746 int64_t sleep_time = 0;
747 int64_t all_time = 0;
750 if (SCHEDULER_STOPPED())
755 if (rw_wlocked(rw)) {
756 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
757 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
758 __func__, rw->lock_object.lo_name, file, line));
760 if (LOCK_LOG_TEST(&rw->lock_object, 0))
761 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
765 if (LOCK_LOG_TEST(&rw->lock_object, 0))
766 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
767 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
770 all_time -= lockstat_nsecs();
773 while (!_rw_write_lock(rw, tid)) {
778 PMC_SOFT_CALL( , , lock, failed);
780 lock_profile_obtain_lock_failed(&rw->lock_object,
781 &contested, &waittime);
782 #ifdef ADAPTIVE_RWLOCKS
784 * If the lock is write locked and the owner is
785 * running on another CPU, spin until the owner stops
786 * running or the state of the lock changes.
789 owner = (struct thread *)RW_OWNER(v);
790 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
791 if (LOCK_LOG_TEST(&rw->lock_object, 0))
792 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
793 __func__, rw, owner);
794 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
795 "spinning", "lockname:\"%s\"",
796 rw->lock_object.lo_name);
797 while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
798 TD_IS_RUNNING(owner)) {
804 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
808 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
809 spintries < rowner_retries) {
810 if (!(v & RW_LOCK_WRITE_SPINNER)) {
811 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
812 v | RW_LOCK_WRITE_SPINNER)) {
817 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
818 "spinning", "lockname:\"%s\"",
819 rw->lock_object.lo_name);
820 for (i = 0; i < rowner_loops; i++) {
821 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
825 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
828 spin_cnt += rowner_loops - i;
830 if (i != rowner_loops)
834 ts = turnstile_trywait(&rw->lock_object);
837 #ifdef ADAPTIVE_RWLOCKS
839 * The current lock owner might have started executing
840 * on another CPU (or the lock could have changed
841 * owners) while we were waiting on the turnstile
842 * chain lock. If so, drop the turnstile lock and try
845 if (!(v & RW_LOCK_READ)) {
846 owner = (struct thread *)RW_OWNER(v);
847 if (TD_IS_RUNNING(owner)) {
848 turnstile_cancel(ts);
854 * Check for the waiters flags about this rwlock.
855 * If the lock was released, without maintain any pending
856 * waiters queue, simply try to acquire it.
857 * If a pending waiters queue is present, claim the lock
858 * ownership and maintain the pending queue.
860 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
861 if ((v & ~x) == RW_UNLOCKED) {
862 x &= ~RW_LOCK_WRITE_SPINNER;
863 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
867 turnstile_cancel(ts);
870 turnstile_cancel(ts);
874 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
875 * set it. If we fail to set it, then loop back and try
878 if (!(v & RW_LOCK_WRITE_WAITERS)) {
879 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
880 v | RW_LOCK_WRITE_WAITERS)) {
881 turnstile_cancel(ts);
884 if (LOCK_LOG_TEST(&rw->lock_object, 0))
885 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
889 * We were unable to acquire the lock and the write waiters
890 * flag is set, so we must block on the turnstile.
892 if (LOCK_LOG_TEST(&rw->lock_object, 0))
893 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
896 sleep_time -= lockstat_nsecs();
898 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
900 sleep_time += lockstat_nsecs();
903 if (LOCK_LOG_TEST(&rw->lock_object, 0))
904 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
906 #ifdef ADAPTIVE_RWLOCKS
911 all_time += lockstat_nsecs();
913 LOCKSTAT_RECORD4(LS_RW_WLOCK_BLOCK, rw, sleep_time,
914 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
915 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
917 /* Record only the loops spinning and not sleeping. */
918 if (spin_cnt > sleep_cnt)
919 LOCKSTAT_RECORD4(LS_RW_WLOCK_SPIN, rw, all_time - sleep_time,
920 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
921 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
923 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
924 waittime, file, line);
928 * This function is called if the first try at releasing a write lock failed.
929 * This means that one of the 2 waiter bits must be set indicating that at
930 * least one thread is waiting on this lock.
933 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
937 struct turnstile *ts;
941 if (SCHEDULER_STOPPED())
946 if (rw_wlocked(rw) && rw_recursed(rw)) {
948 if (LOCK_LOG_TEST(&rw->lock_object, 0))
949 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
953 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
954 ("%s: neither of the waiter flags are set", __func__));
956 if (LOCK_LOG_TEST(&rw->lock_object, 0))
957 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
959 turnstile_chain_lock(&rw->lock_object);
960 ts = turnstile_lookup(&rw->lock_object);
964 * Use the same algo as sx locks for now. Prefer waking up shared
965 * waiters if we have any over writers. This is probably not ideal.
967 * 'v' is the value we are going to write back to rw_lock. If we
968 * have waiters on both queues, we need to preserve the state of
969 * the waiter flag for the queue we don't wake up. For now this is
970 * hardcoded for the algorithm mentioned above.
972 * In the case of both readers and writers waiting we wakeup the
973 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
974 * new writer comes in before a reader it will claim the lock up
975 * above. There is probably a potential priority inversion in
976 * there that could be worked around either by waking both queues
977 * of waiters or doing some complicated lock handoff gymnastics.
980 if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
981 queue = TS_EXCLUSIVE_QUEUE;
982 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
984 queue = TS_SHARED_QUEUE;
986 /* Wake up all waiters for the specific queue. */
987 if (LOCK_LOG_TEST(&rw->lock_object, 0))
988 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
989 queue == TS_SHARED_QUEUE ? "read" : "write");
990 turnstile_broadcast(ts, queue);
991 atomic_store_rel_ptr(&rw->rw_lock, v);
992 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
993 turnstile_chain_unlock(&rw->lock_object);
997 * Attempt to do a non-blocking upgrade from a read lock to a write
998 * lock. This will only succeed if this thread holds a single read
999 * lock. Returns true if the upgrade succeeded and false otherwise.
1002 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1005 uintptr_t v, x, tid;
1006 struct turnstile *ts;
1009 if (SCHEDULER_STOPPED())
1014 KASSERT(rw->rw_lock != RW_DESTROYED,
1015 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1016 __rw_assert(c, RA_RLOCKED, file, line);
1019 * Attempt to switch from one reader to a writer. If there
1020 * are any write waiters, then we will have to lock the
1021 * turnstile first to prevent races with another writer
1022 * calling turnstile_wait() before we have claimed this
1023 * turnstile. So, do the simple case of no waiters first.
1025 tid = (uintptr_t)curthread;
1029 if (RW_READERS(v) > 1)
1031 if (!(v & RW_LOCK_WAITERS)) {
1032 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
1039 * Ok, we think we have waiters, so lock the turnstile.
1041 ts = turnstile_trywait(&rw->lock_object);
1043 if (RW_READERS(v) > 1) {
1044 turnstile_cancel(ts);
1048 * Try to switch from one reader to a writer again. This time
1049 * we honor the current state of the waiters flags.
1050 * If we obtain the lock with the flags set, then claim
1051 * ownership of the turnstile.
1053 x = rw->rw_lock & RW_LOCK_WAITERS;
1054 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1057 turnstile_claim(ts);
1059 turnstile_cancel(ts);
1062 turnstile_cancel(ts);
1064 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1066 curthread->td_rw_rlocks--;
1067 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1069 LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
1075 * Downgrade a write lock into a single read lock.
1078 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1081 struct turnstile *ts;
1085 if (SCHEDULER_STOPPED())
1090 KASSERT(rw->rw_lock != RW_DESTROYED,
1091 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1092 __rw_assert(c, RA_WLOCKED | RA_NOTRECURSED, file, line);
1094 if (rw_recursed(rw))
1095 panic("downgrade of a recursed lock");
1098 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1101 * Convert from a writer to a single reader. First we handle
1102 * the easy case with no waiters. If there are any waiters, we
1103 * lock the turnstile and "disown" the lock.
1105 tid = (uintptr_t)curthread;
1106 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1110 * Ok, we think we have waiters, so lock the turnstile so we can
1111 * read the waiter flags without any races.
1113 turnstile_chain_lock(&rw->lock_object);
1114 v = rw->rw_lock & RW_LOCK_WAITERS;
1115 rwait = v & RW_LOCK_READ_WAITERS;
1116 wwait = v & RW_LOCK_WRITE_WAITERS;
1117 MPASS(rwait | wwait);
1120 * Downgrade from a write lock while preserving waiters flag
1121 * and give up ownership of the turnstile.
1123 ts = turnstile_lookup(&rw->lock_object);
1126 v &= ~RW_LOCK_READ_WAITERS;
1127 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1129 * Wake other readers if there are no writers pending. Otherwise they
1130 * won't be able to acquire the lock anyway.
1132 if (rwait && !wwait) {
1133 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1134 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1136 turnstile_disown(ts);
1137 turnstile_chain_unlock(&rw->lock_object);
1139 curthread->td_rw_rlocks++;
1140 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1141 LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1144 #ifdef INVARIANT_SUPPORT
1150 * In the non-WITNESS case, rw_assert() can only detect that at least
1151 * *some* thread owns an rlock, but it cannot guarantee that *this*
1152 * thread owns an rlock.
1155 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1157 const struct rwlock *rw;
1159 if (panicstr != NULL)
1166 case RA_LOCKED | RA_RECURSED:
1167 case RA_LOCKED | RA_NOTRECURSED:
1169 case RA_RLOCKED | RA_RECURSED:
1170 case RA_RLOCKED | RA_NOTRECURSED:
1172 witness_assert(&rw->lock_object, what, file, line);
1175 * If some other thread has a write lock or we have one
1176 * and are asserting a read lock, fail. Also, if no one
1177 * has a lock at all, fail.
1179 if (rw->rw_lock == RW_UNLOCKED ||
1180 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1181 rw_wowner(rw) != curthread)))
1182 panic("Lock %s not %slocked @ %s:%d\n",
1183 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1184 "read " : "", file, line);
1186 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1187 if (rw_recursed(rw)) {
1188 if (what & RA_NOTRECURSED)
1189 panic("Lock %s recursed @ %s:%d\n",
1190 rw->lock_object.lo_name, file,
1192 } else if (what & RA_RECURSED)
1193 panic("Lock %s not recursed @ %s:%d\n",
1194 rw->lock_object.lo_name, file, line);
1199 case RA_WLOCKED | RA_RECURSED:
1200 case RA_WLOCKED | RA_NOTRECURSED:
1201 if (rw_wowner(rw) != curthread)
1202 panic("Lock %s not exclusively locked @ %s:%d\n",
1203 rw->lock_object.lo_name, file, line);
1204 if (rw_recursed(rw)) {
1205 if (what & RA_NOTRECURSED)
1206 panic("Lock %s recursed @ %s:%d\n",
1207 rw->lock_object.lo_name, file, line);
1208 } else if (what & RA_RECURSED)
1209 panic("Lock %s not recursed @ %s:%d\n",
1210 rw->lock_object.lo_name, file, line);
1214 witness_assert(&rw->lock_object, what, file, line);
1217 * If we hold a write lock fail. We can't reliably check
1218 * to see if we hold a read lock or not.
1220 if (rw_wowner(rw) == curthread)
1221 panic("Lock %s exclusively locked @ %s:%d\n",
1222 rw->lock_object.lo_name, file, line);
1226 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1230 #endif /* INVARIANT_SUPPORT */
1234 db_show_rwlock(const struct lock_object *lock)
1236 const struct rwlock *rw;
1239 rw = (const struct rwlock *)lock;
1241 db_printf(" state: ");
1242 if (rw->rw_lock == RW_UNLOCKED)
1243 db_printf("UNLOCKED\n");
1244 else if (rw->rw_lock == RW_DESTROYED) {
1245 db_printf("DESTROYED\n");
1247 } else if (rw->rw_lock & RW_LOCK_READ)
1248 db_printf("RLOCK: %ju locks\n",
1249 (uintmax_t)(RW_READERS(rw->rw_lock)));
1252 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1253 td->td_tid, td->td_proc->p_pid, td->td_name);
1254 if (rw_recursed(rw))
1255 db_printf(" recursed: %u\n", rw->rw_recurse);
1257 db_printf(" waiters: ");
1258 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1259 case RW_LOCK_READ_WAITERS:
1260 db_printf("readers\n");
1262 case RW_LOCK_WRITE_WAITERS:
1263 db_printf("writers\n");
1265 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1266 db_printf("readers and writers\n");
1269 db_printf("none\n");