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)
270 if (SCHEDULER_STOPPED())
275 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
276 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
277 curthread, rw->lock_object.lo_name, file, line));
278 KASSERT(rw->rw_lock != RW_DESTROYED,
279 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
280 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
282 tid = (uintptr_t)curthread;
284 if (!_rw_write_lock_fetch(rw, &v, tid))
285 _rw_wlock_hard(rw, v, tid, file, line);
287 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
288 0, 0, file, line, LOCKSTAT_WRITER);
290 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
291 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
292 TD_LOCKS_INC(curthread);
296 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
301 if (SCHEDULER_STOPPED())
306 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
307 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
308 curthread, rw->lock_object.lo_name, file, line));
309 KASSERT(rw->rw_lock != RW_DESTROYED,
310 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
312 if (rw_wlocked(rw) &&
313 (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
315 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
318 rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
319 (uintptr_t)curthread);
321 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
323 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
325 if (!rw_recursed(rw))
326 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
327 rw, 0, 0, file, line, LOCKSTAT_WRITER);
328 TD_LOCKS_INC(curthread);
334 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
338 if (SCHEDULER_STOPPED())
343 KASSERT(rw->rw_lock != RW_DESTROYED,
344 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
345 __rw_assert(c, RA_WLOCKED, file, line);
346 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
347 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
350 _rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
352 TD_LOCKS_DEC(curthread);
356 * Determines whether a new reader can acquire a lock. Succeeds if the
357 * reader already owns a read lock and the lock is locked for read to
358 * prevent deadlock from reader recursion. Also succeeds if the lock
359 * is unlocked and has no writer waiters or spinners. Failing otherwise
360 * prioritizes writers before readers.
362 #define RW_CAN_READ(_rw) \
363 ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) & \
364 (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) == \
368 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
371 struct turnstile *ts;
372 #ifdef ADAPTIVE_RWLOCKS
373 volatile struct thread *owner;
377 #ifdef LOCK_PROFILING
378 uint64_t waittime = 0;
382 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
383 struct lock_delay_arg lda;
388 int64_t sleep_time = 0;
389 int64_t all_time = 0;
392 if (SCHEDULER_STOPPED())
395 #if defined(ADAPTIVE_RWLOCKS)
396 lock_delay_arg_init(&lda, &rw_delay);
397 #elif defined(KDTRACE_HOOKS)
398 lock_delay_arg_init(&lda, NULL);
402 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
403 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
404 curthread, rw->lock_object.lo_name, file, line));
405 KASSERT(rw->rw_lock != RW_DESTROYED,
406 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
407 KASSERT(rw_wowner(rw) != curthread,
408 ("rw_rlock: wlock already held for %s @ %s:%d",
409 rw->lock_object.lo_name, file, line));
410 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
413 all_time -= lockstat_nsecs(&rw->lock_object);
415 v = RW_READ_VALUE(rw);
421 * Handle the easy case. If no other thread has a write
422 * lock, then try to bump up the count of read locks. Note
423 * that we have to preserve the current state of the
424 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
425 * read lock, then rw_lock must have changed, so restart
426 * the loop. Note that this handles the case of a
427 * completely unlocked rwlock since such a lock is encoded
428 * as a read lock with no waiters.
430 if (RW_CAN_READ(v)) {
432 * The RW_LOCK_READ_WAITERS flag should only be set
433 * if the lock has been unlocked and write waiters
436 if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v,
437 v + RW_ONE_READER)) {
438 if (LOCK_LOG_TEST(&rw->lock_object, 0))
440 "%s: %p succeed %p -> %p", __func__,
442 (void *)(v + RW_ONE_READER));
451 PMC_SOFT_CALL( , , lock, failed);
453 lock_profile_obtain_lock_failed(&rw->lock_object,
454 &contested, &waittime);
456 #ifdef ADAPTIVE_RWLOCKS
458 * If the owner is running on another CPU, spin until
459 * the owner stops running or the state of the lock
462 if ((v & RW_LOCK_READ) == 0) {
463 owner = (struct thread *)RW_OWNER(v);
464 if (TD_IS_RUNNING(owner)) {
465 if (LOCK_LOG_TEST(&rw->lock_object, 0))
467 "%s: spinning on %p held by %p",
468 __func__, rw, owner);
469 KTR_STATE1(KTR_SCHED, "thread",
470 sched_tdname(curthread), "spinning",
471 "lockname:\"%s\"", rw->lock_object.lo_name);
474 v = RW_READ_VALUE(rw);
475 owner = lv_rw_wowner(v);
476 } while (owner != NULL && TD_IS_RUNNING(owner));
477 KTR_STATE0(KTR_SCHED, "thread",
478 sched_tdname(curthread), "running");
481 } else if (spintries < rowner_retries) {
483 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
484 "spinning", "lockname:\"%s\"",
485 rw->lock_object.lo_name);
486 for (i = 0; i < rowner_loops; i++) {
487 v = RW_READ_VALUE(rw);
488 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
492 v = RW_READ_VALUE(rw);
494 lda.spin_cnt += rowner_loops - i;
496 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
498 if (i != rowner_loops)
504 * Okay, now it's the hard case. Some other thread already
505 * has a write lock or there are write waiters present,
506 * acquire the turnstile lock so we can begin the process
509 ts = turnstile_trywait(&rw->lock_object);
512 * The lock might have been released while we spun, so
513 * recheck its state and restart the loop if needed.
515 v = RW_READ_VALUE(rw);
516 if (RW_CAN_READ(v)) {
517 turnstile_cancel(ts);
521 #ifdef ADAPTIVE_RWLOCKS
523 * The current lock owner might have started executing
524 * on another CPU (or the lock could have changed
525 * owners) while we were waiting on the turnstile
526 * chain lock. If so, drop the turnstile lock and try
529 if ((v & RW_LOCK_READ) == 0) {
530 owner = (struct thread *)RW_OWNER(v);
531 if (TD_IS_RUNNING(owner)) {
532 turnstile_cancel(ts);
539 * The lock is held in write mode or it already has waiters.
541 MPASS(!RW_CAN_READ(v));
544 * If the RW_LOCK_READ_WAITERS flag is already set, then
545 * we can go ahead and block. If it is not set then try
546 * to set it. If we fail to set it drop the turnstile
547 * lock and restart the loop.
549 if (!(v & RW_LOCK_READ_WAITERS)) {
550 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
551 v | RW_LOCK_READ_WAITERS)) {
552 turnstile_cancel(ts);
553 v = RW_READ_VALUE(rw);
556 if (LOCK_LOG_TEST(&rw->lock_object, 0))
557 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
562 * We were unable to acquire the lock and the read waiters
563 * flag is set, so we must block on the turnstile.
565 if (LOCK_LOG_TEST(&rw->lock_object, 0))
566 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
569 sleep_time -= lockstat_nsecs(&rw->lock_object);
571 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
573 sleep_time += lockstat_nsecs(&rw->lock_object);
576 if (LOCK_LOG_TEST(&rw->lock_object, 0))
577 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
579 v = RW_READ_VALUE(rw);
582 all_time += lockstat_nsecs(&rw->lock_object);
584 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
585 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
586 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
588 /* Record only the loops spinning and not sleeping. */
589 if (lda.spin_cnt > sleep_cnt)
590 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
591 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
592 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
595 * TODO: acquire "owner of record" here. Here be turnstile dragons
596 * however. turnstiles don't like owners changing between calls to
597 * turnstile_wait() currently.
599 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
600 waittime, file, line, LOCKSTAT_READER);
601 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
602 WITNESS_LOCK(&rw->lock_object, 0, file, line);
603 TD_LOCKS_INC(curthread);
604 curthread->td_rw_rlocks++;
608 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
613 if (SCHEDULER_STOPPED())
618 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
619 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
620 curthread, rw->lock_object.lo_name, file, line));
624 KASSERT(rw->rw_lock != RW_DESTROYED,
625 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
626 if (!(x & RW_LOCK_READ))
628 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
629 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
631 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
632 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
633 rw, 0, 0, file, line, LOCKSTAT_READER);
634 TD_LOCKS_INC(curthread);
635 curthread->td_rw_rlocks++;
640 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
645 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
648 struct turnstile *ts;
649 uintptr_t x, v, queue;
651 if (SCHEDULER_STOPPED())
656 KASSERT(rw->rw_lock != RW_DESTROYED,
657 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
658 __rw_assert(c, RA_RLOCKED, file, line);
659 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
660 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
662 /* TODO: drop "owner of record" here. */
663 x = RW_READ_VALUE(rw);
666 * See if there is more than one read lock held. If so,
667 * just drop one and return.
669 if (RW_READERS(x) > 1) {
670 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, &x,
671 x - RW_ONE_READER)) {
672 if (LOCK_LOG_TEST(&rw->lock_object, 0))
674 "%s: %p succeeded %p -> %p",
675 __func__, rw, (void *)x,
676 (void *)(x - RW_ONE_READER));
682 * If there aren't any waiters for a write lock, then try
683 * to drop it quickly.
685 if (!(x & RW_LOCK_WAITERS)) {
686 MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
688 if (atomic_fcmpset_rel_ptr(&rw->rw_lock, &x,
690 if (LOCK_LOG_TEST(&rw->lock_object, 0))
691 CTR2(KTR_LOCK, "%s: %p last succeeded",
698 * Ok, we know we have waiters and we think we are the
699 * last reader, so grab the turnstile lock.
701 turnstile_chain_lock(&rw->lock_object);
702 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
703 MPASS(v & RW_LOCK_WAITERS);
706 * Try to drop our lock leaving the lock in a unlocked
709 * If you wanted to do explicit lock handoff you'd have to
710 * do it here. You'd also want to use turnstile_signal()
711 * and you'd have to handle the race where a higher
712 * priority thread blocks on the write lock before the
713 * thread you wakeup actually runs and have the new thread
714 * "steal" the lock. For now it's a lot simpler to just
715 * wakeup all of the waiters.
717 * As above, if we fail, then another thread might have
718 * acquired a read lock, so drop the turnstile lock and
722 if (v & RW_LOCK_WRITE_WAITERS) {
723 queue = TS_EXCLUSIVE_QUEUE;
724 x |= (v & RW_LOCK_READ_WAITERS);
726 queue = TS_SHARED_QUEUE;
727 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
729 turnstile_chain_unlock(&rw->lock_object);
730 x = RW_READ_VALUE(rw);
733 if (LOCK_LOG_TEST(&rw->lock_object, 0))
734 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
738 * Ok. The lock is released and all that's left is to
739 * wake up the waiters. Note that the lock might not be
740 * free anymore, but in that case the writers will just
741 * block again if they run before the new lock holder(s)
744 ts = turnstile_lookup(&rw->lock_object);
746 turnstile_broadcast(ts, queue);
747 turnstile_unpend(ts, TS_SHARED_LOCK);
748 turnstile_chain_unlock(&rw->lock_object);
751 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
752 TD_LOCKS_DEC(curthread);
753 curthread->td_rw_rlocks--;
757 * This function is called when we are unable to obtain a write lock on the
758 * first try. This means that at least one other thread holds either a
759 * read or write lock.
762 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v, uintptr_t tid,
763 const char *file, int line)
766 struct turnstile *ts;
767 #ifdef ADAPTIVE_RWLOCKS
768 volatile struct thread *owner;
773 #ifdef LOCK_PROFILING
774 uint64_t waittime = 0;
777 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
778 struct lock_delay_arg lda;
783 int64_t sleep_time = 0;
784 int64_t all_time = 0;
787 if (SCHEDULER_STOPPED())
790 #if defined(ADAPTIVE_RWLOCKS)
791 lock_delay_arg_init(&lda, &rw_delay);
792 #elif defined(KDTRACE_HOOKS)
793 lock_delay_arg_init(&lda, NULL);
796 if (__predict_false(v == RW_UNLOCKED))
797 v = RW_READ_VALUE(rw);
799 if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
800 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
801 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
802 __func__, rw->lock_object.lo_name, file, line));
804 atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
805 if (LOCK_LOG_TEST(&rw->lock_object, 0))
806 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
810 if (LOCK_LOG_TEST(&rw->lock_object, 0))
811 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
812 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
815 all_time -= lockstat_nsecs(&rw->lock_object);
819 if (v == RW_UNLOCKED) {
820 if (_rw_write_lock_fetch(rw, &v, tid))
828 PMC_SOFT_CALL( , , lock, failed);
830 lock_profile_obtain_lock_failed(&rw->lock_object,
831 &contested, &waittime);
832 #ifdef ADAPTIVE_RWLOCKS
834 * If the lock is write locked and the owner is
835 * running on another CPU, spin until the owner stops
836 * running or the state of the lock changes.
838 owner = lv_rw_wowner(v);
839 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
840 if (LOCK_LOG_TEST(&rw->lock_object, 0))
841 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
842 __func__, rw, owner);
843 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
844 "spinning", "lockname:\"%s\"",
845 rw->lock_object.lo_name);
848 v = RW_READ_VALUE(rw);
849 owner = lv_rw_wowner(v);
850 } while (owner != NULL && TD_IS_RUNNING(owner));
851 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
855 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
856 spintries < rowner_retries) {
857 if (!(v & RW_LOCK_WRITE_SPINNER)) {
858 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
859 v | RW_LOCK_WRITE_SPINNER)) {
860 v = RW_READ_VALUE(rw);
865 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
866 "spinning", "lockname:\"%s\"",
867 rw->lock_object.lo_name);
868 for (i = 0; i < rowner_loops; i++) {
869 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
873 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
875 v = RW_READ_VALUE(rw);
877 lda.spin_cnt += rowner_loops - i;
879 if (i != rowner_loops)
883 ts = turnstile_trywait(&rw->lock_object);
884 v = RW_READ_VALUE(rw);
886 #ifdef ADAPTIVE_RWLOCKS
888 * The current lock owner might have started executing
889 * on another CPU (or the lock could have changed
890 * owners) while we were waiting on the turnstile
891 * chain lock. If so, drop the turnstile lock and try
894 if (!(v & RW_LOCK_READ)) {
895 owner = (struct thread *)RW_OWNER(v);
896 if (TD_IS_RUNNING(owner)) {
897 turnstile_cancel(ts);
903 * Check for the waiters flags about this rwlock.
904 * If the lock was released, without maintain any pending
905 * waiters queue, simply try to acquire it.
906 * If a pending waiters queue is present, claim the lock
907 * ownership and maintain the pending queue.
909 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
910 if ((v & ~x) == RW_UNLOCKED) {
911 x &= ~RW_LOCK_WRITE_SPINNER;
912 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
916 turnstile_cancel(ts);
919 turnstile_cancel(ts);
920 v = RW_READ_VALUE(rw);
924 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
925 * set it. If we fail to set it, then loop back and try
928 if (!(v & RW_LOCK_WRITE_WAITERS)) {
929 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
930 v | RW_LOCK_WRITE_WAITERS)) {
931 turnstile_cancel(ts);
932 v = RW_READ_VALUE(rw);
935 if (LOCK_LOG_TEST(&rw->lock_object, 0))
936 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
940 * We were unable to acquire the lock and the write waiters
941 * flag is set, so we must block on the turnstile.
943 if (LOCK_LOG_TEST(&rw->lock_object, 0))
944 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
947 sleep_time -= lockstat_nsecs(&rw->lock_object);
949 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
951 sleep_time += lockstat_nsecs(&rw->lock_object);
954 if (LOCK_LOG_TEST(&rw->lock_object, 0))
955 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
957 #ifdef ADAPTIVE_RWLOCKS
960 v = RW_READ_VALUE(rw);
963 all_time += lockstat_nsecs(&rw->lock_object);
965 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
966 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
967 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
969 /* Record only the loops spinning and not sleeping. */
970 if (lda.spin_cnt > sleep_cnt)
971 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
972 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
973 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
975 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
976 waittime, file, line, LOCKSTAT_WRITER);
980 * This function is called if the first try at releasing a write lock failed.
981 * This means that one of the 2 waiter bits must be set indicating that at
982 * least one thread is waiting on this lock.
985 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
989 struct turnstile *ts;
993 if (SCHEDULER_STOPPED())
998 if (!rw_recursed(rw)) {
999 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw,
1001 if (_rw_write_unlock(rw, tid))
1004 if (--(rw->rw_recurse) == 0)
1005 atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1009 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1010 ("%s: neither of the waiter flags are set", __func__));
1012 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1013 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1015 turnstile_chain_lock(&rw->lock_object);
1016 ts = turnstile_lookup(&rw->lock_object);
1020 * Use the same algo as sx locks for now. Prefer waking up shared
1021 * waiters if we have any over writers. This is probably not ideal.
1023 * 'v' is the value we are going to write back to rw_lock. If we
1024 * have waiters on both queues, we need to preserve the state of
1025 * the waiter flag for the queue we don't wake up. For now this is
1026 * hardcoded for the algorithm mentioned above.
1028 * In the case of both readers and writers waiting we wakeup the
1029 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
1030 * new writer comes in before a reader it will claim the lock up
1031 * above. There is probably a potential priority inversion in
1032 * there that could be worked around either by waking both queues
1033 * of waiters or doing some complicated lock handoff gymnastics.
1036 if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
1037 queue = TS_EXCLUSIVE_QUEUE;
1038 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
1040 queue = TS_SHARED_QUEUE;
1042 /* Wake up all waiters for the specific queue. */
1043 if (LOCK_LOG_TEST(&rw->lock_object, 0))
1044 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1045 queue == TS_SHARED_QUEUE ? "read" : "write");
1046 turnstile_broadcast(ts, queue);
1047 atomic_store_rel_ptr(&rw->rw_lock, v);
1048 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1049 turnstile_chain_unlock(&rw->lock_object);
1053 * Attempt to do a non-blocking upgrade from a read lock to a write
1054 * lock. This will only succeed if this thread holds a single read
1055 * lock. Returns true if the upgrade succeeded and false otherwise.
1058 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1061 uintptr_t v, x, tid;
1062 struct turnstile *ts;
1065 if (SCHEDULER_STOPPED())
1070 KASSERT(rw->rw_lock != RW_DESTROYED,
1071 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1072 __rw_assert(c, RA_RLOCKED, file, line);
1075 * Attempt to switch from one reader to a writer. If there
1076 * are any write waiters, then we will have to lock the
1077 * turnstile first to prevent races with another writer
1078 * calling turnstile_wait() before we have claimed this
1079 * turnstile. So, do the simple case of no waiters first.
1081 tid = (uintptr_t)curthread;
1085 if (RW_READERS(v) > 1)
1087 if (!(v & RW_LOCK_WAITERS)) {
1088 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
1095 * Ok, we think we have waiters, so lock the turnstile.
1097 ts = turnstile_trywait(&rw->lock_object);
1099 if (RW_READERS(v) > 1) {
1100 turnstile_cancel(ts);
1104 * Try to switch from one reader to a writer again. This time
1105 * we honor the current state of the waiters flags.
1106 * If we obtain the lock with the flags set, then claim
1107 * ownership of the turnstile.
1109 x = rw->rw_lock & RW_LOCK_WAITERS;
1110 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1113 turnstile_claim(ts);
1115 turnstile_cancel(ts);
1118 turnstile_cancel(ts);
1120 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1122 curthread->td_rw_rlocks--;
1123 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1125 LOCKSTAT_RECORD0(rw__upgrade, rw);
1131 * Downgrade a write lock into a single read lock.
1134 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1137 struct turnstile *ts;
1141 if (SCHEDULER_STOPPED())
1146 KASSERT(rw->rw_lock != RW_DESTROYED,
1147 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1148 __rw_assert(c, RA_WLOCKED | RA_NOTRECURSED, file, line);
1150 if (rw_recursed(rw))
1151 panic("downgrade of a recursed lock");
1154 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1157 * Convert from a writer to a single reader. First we handle
1158 * the easy case with no waiters. If there are any waiters, we
1159 * lock the turnstile and "disown" the lock.
1161 tid = (uintptr_t)curthread;
1162 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1166 * Ok, we think we have waiters, so lock the turnstile so we can
1167 * read the waiter flags without any races.
1169 turnstile_chain_lock(&rw->lock_object);
1170 v = rw->rw_lock & RW_LOCK_WAITERS;
1171 rwait = v & RW_LOCK_READ_WAITERS;
1172 wwait = v & RW_LOCK_WRITE_WAITERS;
1173 MPASS(rwait | wwait);
1176 * Downgrade from a write lock while preserving waiters flag
1177 * and give up ownership of the turnstile.
1179 ts = turnstile_lookup(&rw->lock_object);
1182 v &= ~RW_LOCK_READ_WAITERS;
1183 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1185 * Wake other readers if there are no writers pending. Otherwise they
1186 * won't be able to acquire the lock anyway.
1188 if (rwait && !wwait) {
1189 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1190 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1192 turnstile_disown(ts);
1193 turnstile_chain_unlock(&rw->lock_object);
1195 curthread->td_rw_rlocks++;
1196 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1197 LOCKSTAT_RECORD0(rw__downgrade, rw);
1200 #ifdef INVARIANT_SUPPORT
1206 * In the non-WITNESS case, rw_assert() can only detect that at least
1207 * *some* thread owns an rlock, but it cannot guarantee that *this*
1208 * thread owns an rlock.
1211 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1213 const struct rwlock *rw;
1215 if (panicstr != NULL)
1222 case RA_LOCKED | RA_RECURSED:
1223 case RA_LOCKED | RA_NOTRECURSED:
1225 case RA_RLOCKED | RA_RECURSED:
1226 case RA_RLOCKED | RA_NOTRECURSED:
1228 witness_assert(&rw->lock_object, what, file, line);
1231 * If some other thread has a write lock or we have one
1232 * and are asserting a read lock, fail. Also, if no one
1233 * has a lock at all, fail.
1235 if (rw->rw_lock == RW_UNLOCKED ||
1236 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1237 rw_wowner(rw) != curthread)))
1238 panic("Lock %s not %slocked @ %s:%d\n",
1239 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1240 "read " : "", file, line);
1242 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1243 if (rw_recursed(rw)) {
1244 if (what & RA_NOTRECURSED)
1245 panic("Lock %s recursed @ %s:%d\n",
1246 rw->lock_object.lo_name, file,
1248 } else if (what & RA_RECURSED)
1249 panic("Lock %s not recursed @ %s:%d\n",
1250 rw->lock_object.lo_name, file, line);
1255 case RA_WLOCKED | RA_RECURSED:
1256 case RA_WLOCKED | RA_NOTRECURSED:
1257 if (rw_wowner(rw) != curthread)
1258 panic("Lock %s not exclusively locked @ %s:%d\n",
1259 rw->lock_object.lo_name, file, line);
1260 if (rw_recursed(rw)) {
1261 if (what & RA_NOTRECURSED)
1262 panic("Lock %s recursed @ %s:%d\n",
1263 rw->lock_object.lo_name, file, line);
1264 } else if (what & RA_RECURSED)
1265 panic("Lock %s not recursed @ %s:%d\n",
1266 rw->lock_object.lo_name, file, line);
1270 witness_assert(&rw->lock_object, what, file, line);
1273 * If we hold a write lock fail. We can't reliably check
1274 * to see if we hold a read lock or not.
1276 if (rw_wowner(rw) == curthread)
1277 panic("Lock %s exclusively locked @ %s:%d\n",
1278 rw->lock_object.lo_name, file, line);
1282 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1286 #endif /* INVARIANT_SUPPORT */
1290 db_show_rwlock(const struct lock_object *lock)
1292 const struct rwlock *rw;
1295 rw = (const struct rwlock *)lock;
1297 db_printf(" state: ");
1298 if (rw->rw_lock == RW_UNLOCKED)
1299 db_printf("UNLOCKED\n");
1300 else if (rw->rw_lock == RW_DESTROYED) {
1301 db_printf("DESTROYED\n");
1303 } else if (rw->rw_lock & RW_LOCK_READ)
1304 db_printf("RLOCK: %ju locks\n",
1305 (uintmax_t)(RW_READERS(rw->rw_lock)));
1308 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1309 td->td_tid, td->td_proc->p_pid, td->td_name);
1310 if (rw_recursed(rw))
1311 db_printf(" recursed: %u\n", rw->rw_recurse);
1313 db_printf(" waiters: ");
1314 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1315 case RW_LOCK_READ_WAITERS:
1316 db_printf("readers\n");
1318 case RW_LOCK_WRITE_WAITERS:
1319 db_printf("writers\n");
1321 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1322 db_printf("readers and writers\n");
1325 db_printf("none\n");