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 TD_LOCKS_INC(curthread);
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_RWLOCK_SUCCESS(rw__acquire,
305 rw, 0, 0, file, line, LOCKSTAT_WRITER);
306 TD_LOCKS_INC(curthread);
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 TD_LOCKS_DEC(curthread);
332 * Determines whether a new reader can acquire a lock. Succeeds if the
333 * reader already owns a read lock and the lock is locked for read to
334 * prevent deadlock from reader recursion. Also succeeds if the lock
335 * is unlocked and has no writer waiters or spinners. Failing otherwise
336 * prioritizes writers before readers.
338 #define RW_CAN_READ(_rw) \
339 ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) & \
340 (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) == \
344 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
347 struct turnstile *ts;
348 #ifdef ADAPTIVE_RWLOCKS
349 volatile struct thread *owner;
353 #ifdef LOCK_PROFILING
354 uint64_t waittime = 0;
360 uint64_t spin_cnt = 0;
361 uint64_t sleep_cnt = 0;
362 int64_t sleep_time = 0;
363 int64_t all_time = 0;
366 if (SCHEDULER_STOPPED())
371 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
372 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
373 curthread, rw->lock_object.lo_name, file, line));
374 KASSERT(rw->rw_lock != RW_DESTROYED,
375 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
376 KASSERT(rw_wowner(rw) != curthread,
377 ("rw_rlock: wlock already held for %s @ %s:%d",
378 rw->lock_object.lo_name, file, line));
379 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
382 all_time -= lockstat_nsecs(&rw->lock_object);
387 * Handle the easy case. If no other thread has a write
388 * lock, then try to bump up the count of read locks. Note
389 * that we have to preserve the current state of the
390 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
391 * read lock, then rw_lock must have changed, so restart
392 * the loop. Note that this handles the case of a
393 * completely unlocked rwlock since such a lock is encoded
394 * as a read lock with no waiters.
397 if (RW_CAN_READ(v)) {
399 * The RW_LOCK_READ_WAITERS flag should only be set
400 * if the lock has been unlocked and write waiters
403 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
404 v + RW_ONE_READER)) {
405 if (LOCK_LOG_TEST(&rw->lock_object, 0))
407 "%s: %p succeed %p -> %p", __func__,
409 (void *)(v + RW_ONE_READER));
418 PMC_SOFT_CALL( , , lock, failed);
420 lock_profile_obtain_lock_failed(&rw->lock_object,
421 &contested, &waittime);
423 #ifdef ADAPTIVE_RWLOCKS
425 * If the owner is running on another CPU, spin until
426 * the owner stops running or the state of the lock
429 if ((v & RW_LOCK_READ) == 0) {
430 owner = (struct thread *)RW_OWNER(v);
431 if (TD_IS_RUNNING(owner)) {
432 if (LOCK_LOG_TEST(&rw->lock_object, 0))
434 "%s: spinning on %p held by %p",
435 __func__, rw, owner);
436 KTR_STATE1(KTR_SCHED, "thread",
437 sched_tdname(curthread), "spinning",
438 "lockname:\"%s\"", rw->lock_object.lo_name);
439 while ((struct thread*)RW_OWNER(rw->rw_lock) ==
440 owner && TD_IS_RUNNING(owner)) {
446 KTR_STATE0(KTR_SCHED, "thread",
447 sched_tdname(curthread), "running");
450 } else if (spintries < rowner_retries) {
452 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
453 "spinning", "lockname:\"%s\"",
454 rw->lock_object.lo_name);
455 for (i = 0; i < rowner_loops; i++) {
457 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
462 spin_cnt += rowner_loops - i;
464 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
466 if (i != rowner_loops)
472 * Okay, now it's the hard case. Some other thread already
473 * has a write lock or there are write waiters present,
474 * acquire the turnstile lock so we can begin the process
477 ts = turnstile_trywait(&rw->lock_object);
480 * The lock might have been released while we spun, so
481 * recheck its state and restart the loop if needed.
484 if (RW_CAN_READ(v)) {
485 turnstile_cancel(ts);
489 #ifdef ADAPTIVE_RWLOCKS
491 * The current lock owner might have started executing
492 * on another CPU (or the lock could have changed
493 * owners) while we were waiting on the turnstile
494 * chain lock. If so, drop the turnstile lock and try
497 if ((v & RW_LOCK_READ) == 0) {
498 owner = (struct thread *)RW_OWNER(v);
499 if (TD_IS_RUNNING(owner)) {
500 turnstile_cancel(ts);
507 * The lock is held in write mode or it already has waiters.
509 MPASS(!RW_CAN_READ(v));
512 * If the RW_LOCK_READ_WAITERS flag is already set, then
513 * we can go ahead and block. If it is not set then try
514 * to set it. If we fail to set it drop the turnstile
515 * lock and restart the loop.
517 if (!(v & RW_LOCK_READ_WAITERS)) {
518 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
519 v | RW_LOCK_READ_WAITERS)) {
520 turnstile_cancel(ts);
523 if (LOCK_LOG_TEST(&rw->lock_object, 0))
524 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
529 * We were unable to acquire the lock and the read waiters
530 * flag is set, so we must block on the turnstile.
532 if (LOCK_LOG_TEST(&rw->lock_object, 0))
533 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
536 sleep_time -= lockstat_nsecs(&rw->lock_object);
538 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
540 sleep_time += lockstat_nsecs(&rw->lock_object);
543 if (LOCK_LOG_TEST(&rw->lock_object, 0))
544 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
548 all_time += lockstat_nsecs(&rw->lock_object);
550 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
551 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
552 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
554 /* Record only the loops spinning and not sleeping. */
555 if (spin_cnt > sleep_cnt)
556 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
557 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
558 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
561 * TODO: acquire "owner of record" here. Here be turnstile dragons
562 * however. turnstiles don't like owners changing between calls to
563 * turnstile_wait() currently.
565 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
566 waittime, file, line, LOCKSTAT_READER);
567 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
568 WITNESS_LOCK(&rw->lock_object, 0, file, line);
569 TD_LOCKS_INC(curthread);
570 curthread->td_rw_rlocks++;
574 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
579 if (SCHEDULER_STOPPED())
584 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
585 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
586 curthread, rw->lock_object.lo_name, file, line));
590 KASSERT(rw->rw_lock != RW_DESTROYED,
591 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
592 if (!(x & RW_LOCK_READ))
594 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
595 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
597 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
598 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
599 rw, 0, 0, file, line, LOCKSTAT_READER);
600 TD_LOCKS_INC(curthread);
601 curthread->td_rw_rlocks++;
606 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
611 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
614 struct turnstile *ts;
615 uintptr_t x, v, queue;
617 if (SCHEDULER_STOPPED())
622 KASSERT(rw->rw_lock != RW_DESTROYED,
623 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
624 __rw_assert(c, RA_RLOCKED, file, line);
625 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
626 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
628 /* TODO: drop "owner of record" here. */
632 * See if there is more than one read lock held. If so,
633 * just drop one and return.
636 if (RW_READERS(x) > 1) {
637 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
638 x - RW_ONE_READER)) {
639 if (LOCK_LOG_TEST(&rw->lock_object, 0))
641 "%s: %p succeeded %p -> %p",
642 __func__, rw, (void *)x,
643 (void *)(x - RW_ONE_READER));
649 * If there aren't any waiters for a write lock, then try
650 * to drop it quickly.
652 if (!(x & RW_LOCK_WAITERS)) {
653 MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
655 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
657 if (LOCK_LOG_TEST(&rw->lock_object, 0))
658 CTR2(KTR_LOCK, "%s: %p last succeeded",
665 * Ok, we know we have waiters and we think we are the
666 * last reader, so grab the turnstile lock.
668 turnstile_chain_lock(&rw->lock_object);
669 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
670 MPASS(v & RW_LOCK_WAITERS);
673 * Try to drop our lock leaving the lock in a unlocked
676 * If you wanted to do explicit lock handoff you'd have to
677 * do it here. You'd also want to use turnstile_signal()
678 * and you'd have to handle the race where a higher
679 * priority thread blocks on the write lock before the
680 * thread you wakeup actually runs and have the new thread
681 * "steal" the lock. For now it's a lot simpler to just
682 * wakeup all of the waiters.
684 * As above, if we fail, then another thread might have
685 * acquired a read lock, so drop the turnstile lock and
689 if (v & RW_LOCK_WRITE_WAITERS) {
690 queue = TS_EXCLUSIVE_QUEUE;
691 x |= (v & RW_LOCK_READ_WAITERS);
693 queue = TS_SHARED_QUEUE;
694 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
696 turnstile_chain_unlock(&rw->lock_object);
699 if (LOCK_LOG_TEST(&rw->lock_object, 0))
700 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
704 * Ok. The lock is released and all that's left is to
705 * wake up the waiters. Note that the lock might not be
706 * free anymore, but in that case the writers will just
707 * block again if they run before the new lock holder(s)
710 ts = turnstile_lookup(&rw->lock_object);
712 turnstile_broadcast(ts, queue);
713 turnstile_unpend(ts, TS_SHARED_LOCK);
714 turnstile_chain_unlock(&rw->lock_object);
717 LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
718 TD_LOCKS_DEC(curthread);
719 curthread->td_rw_rlocks--;
723 * This function is called when we are unable to obtain a write lock on the
724 * first try. This means that at least one other thread holds either a
725 * read or write lock.
728 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
732 struct turnstile *ts;
733 #ifdef ADAPTIVE_RWLOCKS
734 volatile struct thread *owner;
739 #ifdef LOCK_PROFILING
740 uint64_t waittime = 0;
745 uint64_t spin_cnt = 0;
746 uint64_t sleep_cnt = 0;
747 int64_t sleep_time = 0;
748 int64_t all_time = 0;
751 if (SCHEDULER_STOPPED())
756 if (rw_wlocked(rw)) {
757 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
758 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
759 __func__, rw->lock_object.lo_name, file, line));
761 if (LOCK_LOG_TEST(&rw->lock_object, 0))
762 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
766 if (LOCK_LOG_TEST(&rw->lock_object, 0))
767 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
768 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
771 all_time -= lockstat_nsecs(&rw->lock_object);
774 while (!_rw_write_lock(rw, tid)) {
779 PMC_SOFT_CALL( , , lock, failed);
781 lock_profile_obtain_lock_failed(&rw->lock_object,
782 &contested, &waittime);
783 #ifdef ADAPTIVE_RWLOCKS
785 * If the lock is write locked and the owner is
786 * running on another CPU, spin until the owner stops
787 * running or the state of the lock changes.
790 owner = (struct thread *)RW_OWNER(v);
791 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
792 if (LOCK_LOG_TEST(&rw->lock_object, 0))
793 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
794 __func__, rw, owner);
795 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
796 "spinning", "lockname:\"%s\"",
797 rw->lock_object.lo_name);
798 while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
799 TD_IS_RUNNING(owner)) {
805 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
809 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
810 spintries < rowner_retries) {
811 if (!(v & RW_LOCK_WRITE_SPINNER)) {
812 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
813 v | RW_LOCK_WRITE_SPINNER)) {
818 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
819 "spinning", "lockname:\"%s\"",
820 rw->lock_object.lo_name);
821 for (i = 0; i < rowner_loops; i++) {
822 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
826 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
829 spin_cnt += rowner_loops - i;
831 if (i != rowner_loops)
835 ts = turnstile_trywait(&rw->lock_object);
838 #ifdef ADAPTIVE_RWLOCKS
840 * The current lock owner might have started executing
841 * on another CPU (or the lock could have changed
842 * owners) while we were waiting on the turnstile
843 * chain lock. If so, drop the turnstile lock and try
846 if (!(v & RW_LOCK_READ)) {
847 owner = (struct thread *)RW_OWNER(v);
848 if (TD_IS_RUNNING(owner)) {
849 turnstile_cancel(ts);
855 * Check for the waiters flags about this rwlock.
856 * If the lock was released, without maintain any pending
857 * waiters queue, simply try to acquire it.
858 * If a pending waiters queue is present, claim the lock
859 * ownership and maintain the pending queue.
861 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
862 if ((v & ~x) == RW_UNLOCKED) {
863 x &= ~RW_LOCK_WRITE_SPINNER;
864 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
868 turnstile_cancel(ts);
871 turnstile_cancel(ts);
875 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
876 * set it. If we fail to set it, then loop back and try
879 if (!(v & RW_LOCK_WRITE_WAITERS)) {
880 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
881 v | RW_LOCK_WRITE_WAITERS)) {
882 turnstile_cancel(ts);
885 if (LOCK_LOG_TEST(&rw->lock_object, 0))
886 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
890 * We were unable to acquire the lock and the write waiters
891 * flag is set, so we must block on the turnstile.
893 if (LOCK_LOG_TEST(&rw->lock_object, 0))
894 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
897 sleep_time -= lockstat_nsecs(&rw->lock_object);
899 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
901 sleep_time += lockstat_nsecs(&rw->lock_object);
904 if (LOCK_LOG_TEST(&rw->lock_object, 0))
905 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
907 #ifdef ADAPTIVE_RWLOCKS
912 all_time += lockstat_nsecs(&rw->lock_object);
914 LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
915 LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
916 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
918 /* Record only the loops spinning and not sleeping. */
919 if (spin_cnt > sleep_cnt)
920 LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
921 LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
922 (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
924 LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
925 waittime, file, line, LOCKSTAT_WRITER);
929 * This function is called if the first try at releasing a write lock failed.
930 * This means that one of the 2 waiter bits must be set indicating that at
931 * least one thread is waiting on this lock.
934 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
938 struct turnstile *ts;
942 if (SCHEDULER_STOPPED())
947 if (rw_wlocked(rw) && rw_recursed(rw)) {
949 if (LOCK_LOG_TEST(&rw->lock_object, 0))
950 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
954 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
955 ("%s: neither of the waiter flags are set", __func__));
957 if (LOCK_LOG_TEST(&rw->lock_object, 0))
958 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
960 turnstile_chain_lock(&rw->lock_object);
961 ts = turnstile_lookup(&rw->lock_object);
965 * Use the same algo as sx locks for now. Prefer waking up shared
966 * waiters if we have any over writers. This is probably not ideal.
968 * 'v' is the value we are going to write back to rw_lock. If we
969 * have waiters on both queues, we need to preserve the state of
970 * the waiter flag for the queue we don't wake up. For now this is
971 * hardcoded for the algorithm mentioned above.
973 * In the case of both readers and writers waiting we wakeup the
974 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
975 * new writer comes in before a reader it will claim the lock up
976 * above. There is probably a potential priority inversion in
977 * there that could be worked around either by waking both queues
978 * of waiters or doing some complicated lock handoff gymnastics.
981 if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
982 queue = TS_EXCLUSIVE_QUEUE;
983 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
985 queue = TS_SHARED_QUEUE;
987 /* Wake up all waiters for the specific queue. */
988 if (LOCK_LOG_TEST(&rw->lock_object, 0))
989 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
990 queue == TS_SHARED_QUEUE ? "read" : "write");
991 turnstile_broadcast(ts, queue);
992 atomic_store_rel_ptr(&rw->rw_lock, v);
993 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
994 turnstile_chain_unlock(&rw->lock_object);
998 * Attempt to do a non-blocking upgrade from a read lock to a write
999 * lock. This will only succeed if this thread holds a single read
1000 * lock. Returns true if the upgrade succeeded and false otherwise.
1003 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1006 uintptr_t v, x, tid;
1007 struct turnstile *ts;
1010 if (SCHEDULER_STOPPED())
1015 KASSERT(rw->rw_lock != RW_DESTROYED,
1016 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1017 __rw_assert(c, RA_RLOCKED, file, line);
1020 * Attempt to switch from one reader to a writer. If there
1021 * are any write waiters, then we will have to lock the
1022 * turnstile first to prevent races with another writer
1023 * calling turnstile_wait() before we have claimed this
1024 * turnstile. So, do the simple case of no waiters first.
1026 tid = (uintptr_t)curthread;
1030 if (RW_READERS(v) > 1)
1032 if (!(v & RW_LOCK_WAITERS)) {
1033 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
1040 * Ok, we think we have waiters, so lock the turnstile.
1042 ts = turnstile_trywait(&rw->lock_object);
1044 if (RW_READERS(v) > 1) {
1045 turnstile_cancel(ts);
1049 * Try to switch from one reader to a writer again. This time
1050 * we honor the current state of the waiters flags.
1051 * If we obtain the lock with the flags set, then claim
1052 * ownership of the turnstile.
1054 x = rw->rw_lock & RW_LOCK_WAITERS;
1055 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1058 turnstile_claim(ts);
1060 turnstile_cancel(ts);
1063 turnstile_cancel(ts);
1065 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1067 curthread->td_rw_rlocks--;
1068 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1070 LOCKSTAT_RECORD0(rw__upgrade, rw);
1076 * Downgrade a write lock into a single read lock.
1079 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1082 struct turnstile *ts;
1086 if (SCHEDULER_STOPPED())
1091 KASSERT(rw->rw_lock != RW_DESTROYED,
1092 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1093 __rw_assert(c, RA_WLOCKED | RA_NOTRECURSED, file, line);
1095 if (rw_recursed(rw))
1096 panic("downgrade of a recursed lock");
1099 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1102 * Convert from a writer to a single reader. First we handle
1103 * the easy case with no waiters. If there are any waiters, we
1104 * lock the turnstile and "disown" the lock.
1106 tid = (uintptr_t)curthread;
1107 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1111 * Ok, we think we have waiters, so lock the turnstile so we can
1112 * read the waiter flags without any races.
1114 turnstile_chain_lock(&rw->lock_object);
1115 v = rw->rw_lock & RW_LOCK_WAITERS;
1116 rwait = v & RW_LOCK_READ_WAITERS;
1117 wwait = v & RW_LOCK_WRITE_WAITERS;
1118 MPASS(rwait | wwait);
1121 * Downgrade from a write lock while preserving waiters flag
1122 * and give up ownership of the turnstile.
1124 ts = turnstile_lookup(&rw->lock_object);
1127 v &= ~RW_LOCK_READ_WAITERS;
1128 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1130 * Wake other readers if there are no writers pending. Otherwise they
1131 * won't be able to acquire the lock anyway.
1133 if (rwait && !wwait) {
1134 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1135 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1137 turnstile_disown(ts);
1138 turnstile_chain_unlock(&rw->lock_object);
1140 curthread->td_rw_rlocks++;
1141 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1142 LOCKSTAT_RECORD0(rw__downgrade, rw);
1145 #ifdef INVARIANT_SUPPORT
1151 * In the non-WITNESS case, rw_assert() can only detect that at least
1152 * *some* thread owns an rlock, but it cannot guarantee that *this*
1153 * thread owns an rlock.
1156 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1158 const struct rwlock *rw;
1160 if (panicstr != NULL)
1167 case RA_LOCKED | RA_RECURSED:
1168 case RA_LOCKED | RA_NOTRECURSED:
1170 case RA_RLOCKED | RA_RECURSED:
1171 case RA_RLOCKED | RA_NOTRECURSED:
1173 witness_assert(&rw->lock_object, what, file, line);
1176 * If some other thread has a write lock or we have one
1177 * and are asserting a read lock, fail. Also, if no one
1178 * has a lock at all, fail.
1180 if (rw->rw_lock == RW_UNLOCKED ||
1181 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1182 rw_wowner(rw) != curthread)))
1183 panic("Lock %s not %slocked @ %s:%d\n",
1184 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1185 "read " : "", file, line);
1187 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1188 if (rw_recursed(rw)) {
1189 if (what & RA_NOTRECURSED)
1190 panic("Lock %s recursed @ %s:%d\n",
1191 rw->lock_object.lo_name, file,
1193 } else if (what & RA_RECURSED)
1194 panic("Lock %s not recursed @ %s:%d\n",
1195 rw->lock_object.lo_name, file, line);
1200 case RA_WLOCKED | RA_RECURSED:
1201 case RA_WLOCKED | RA_NOTRECURSED:
1202 if (rw_wowner(rw) != curthread)
1203 panic("Lock %s not exclusively locked @ %s:%d\n",
1204 rw->lock_object.lo_name, file, line);
1205 if (rw_recursed(rw)) {
1206 if (what & RA_NOTRECURSED)
1207 panic("Lock %s recursed @ %s:%d\n",
1208 rw->lock_object.lo_name, file, line);
1209 } else if (what & RA_RECURSED)
1210 panic("Lock %s not recursed @ %s:%d\n",
1211 rw->lock_object.lo_name, file, line);
1215 witness_assert(&rw->lock_object, what, file, line);
1218 * If we hold a write lock fail. We can't reliably check
1219 * to see if we hold a read lock or not.
1221 if (rw_wowner(rw) == curthread)
1222 panic("Lock %s exclusively locked @ %s:%d\n",
1223 rw->lock_object.lo_name, file, line);
1227 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1231 #endif /* INVARIANT_SUPPORT */
1235 db_show_rwlock(const struct lock_object *lock)
1237 const struct rwlock *rw;
1240 rw = (const struct rwlock *)lock;
1242 db_printf(" state: ");
1243 if (rw->rw_lock == RW_UNLOCKED)
1244 db_printf("UNLOCKED\n");
1245 else if (rw->rw_lock == RW_DESTROYED) {
1246 db_printf("DESTROYED\n");
1248 } else if (rw->rw_lock & RW_LOCK_READ)
1249 db_printf("RLOCK: %ju locks\n",
1250 (uintmax_t)(RW_READERS(rw->rw_lock)));
1253 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1254 td->td_tid, td->td_proc->p_pid, td->td_name);
1255 if (rw_recursed(rw))
1256 db_printf(" recursed: %u\n", rw->rw_recurse);
1258 db_printf(" waiters: ");
1259 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1260 case RW_LOCK_READ_WAITERS:
1261 db_printf("readers\n");
1263 case RW_LOCK_WRITE_WAITERS:
1264 db_printf("writers\n");
1266 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1267 db_printf("readers and writers\n");
1270 db_printf("none\n");