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 curthread->td_locks++;
309 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
313 if (SCHEDULER_STOPPED())
318 KASSERT(rw->rw_lock != RW_DESTROYED,
319 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
320 __rw_assert(c, RA_WLOCKED, file, line);
321 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
322 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
324 __rw_wunlock(rw, curthread, file, line);
325 curthread->td_locks--;
328 * Determines whether a new reader can acquire a lock. Succeeds if the
329 * reader already owns a read lock and the lock is locked for read to
330 * prevent deadlock from reader recursion. Also succeeds if the lock
331 * is unlocked and has no writer waiters or spinners. Failing otherwise
332 * prioritizes writers before readers.
334 #define RW_CAN_READ(_rw) \
335 ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) & \
336 (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) == \
340 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
343 struct turnstile *ts;
344 #ifdef ADAPTIVE_RWLOCKS
345 volatile struct thread *owner;
349 #ifdef LOCK_PROFILING
350 uint64_t waittime = 0;
355 uint64_t spin_cnt = 0;
356 uint64_t sleep_cnt = 0;
357 int64_t sleep_time = 0;
360 if (SCHEDULER_STOPPED())
365 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
366 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
367 curthread, rw->lock_object.lo_name, file, line));
368 KASSERT(rw->rw_lock != RW_DESTROYED,
369 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
370 KASSERT(rw_wowner(rw) != curthread,
371 ("rw_rlock: wlock already held for %s @ %s:%d",
372 rw->lock_object.lo_name, file, line));
373 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
380 * Handle the easy case. If no other thread has a write
381 * lock, then try to bump up the count of read locks. Note
382 * that we have to preserve the current state of the
383 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
384 * read lock, then rw_lock must have changed, so restart
385 * the loop. Note that this handles the case of a
386 * completely unlocked rwlock since such a lock is encoded
387 * as a read lock with no waiters.
390 if (RW_CAN_READ(v)) {
392 * The RW_LOCK_READ_WAITERS flag should only be set
393 * if the lock has been unlocked and write waiters
396 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
397 v + RW_ONE_READER)) {
398 if (LOCK_LOG_TEST(&rw->lock_object, 0))
400 "%s: %p succeed %p -> %p", __func__,
402 (void *)(v + RW_ONE_READER));
408 PMC_SOFT_CALL( , , lock, failed);
410 lock_profile_obtain_lock_failed(&rw->lock_object,
411 &contested, &waittime);
413 #ifdef ADAPTIVE_RWLOCKS
415 * If the owner is running on another CPU, spin until
416 * the owner stops running or the state of the lock
419 if ((v & RW_LOCK_READ) == 0) {
420 owner = (struct thread *)RW_OWNER(v);
421 if (TD_IS_RUNNING(owner)) {
422 if (LOCK_LOG_TEST(&rw->lock_object, 0))
424 "%s: spinning on %p held by %p",
425 __func__, rw, owner);
426 KTR_STATE1(KTR_SCHED, "thread",
427 sched_tdname(curthread), "spinning",
428 "lockname:\"%s\"", rw->lock_object.lo_name);
429 while ((struct thread*)RW_OWNER(rw->rw_lock) ==
430 owner && TD_IS_RUNNING(owner)) {
436 KTR_STATE0(KTR_SCHED, "thread",
437 sched_tdname(curthread), "running");
440 } else if (spintries < rowner_retries) {
442 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
443 "spinning", "lockname:\"%s\"",
444 rw->lock_object.lo_name);
445 for (i = 0; i < rowner_loops; i++) {
447 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
452 spin_cnt += rowner_loops - i;
454 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
456 if (i != rowner_loops)
462 * Okay, now it's the hard case. Some other thread already
463 * has a write lock or there are write waiters present,
464 * acquire the turnstile lock so we can begin the process
467 ts = turnstile_trywait(&rw->lock_object);
470 * The lock might have been released while we spun, so
471 * recheck its state and restart the loop if needed.
474 if (RW_CAN_READ(v)) {
475 turnstile_cancel(ts);
479 #ifdef ADAPTIVE_RWLOCKS
481 * The current lock owner might have started executing
482 * on another CPU (or the lock could have changed
483 * owners) while we were waiting on the turnstile
484 * chain lock. If so, drop the turnstile lock and try
487 if ((v & RW_LOCK_READ) == 0) {
488 owner = (struct thread *)RW_OWNER(v);
489 if (TD_IS_RUNNING(owner)) {
490 turnstile_cancel(ts);
497 * The lock is held in write mode or it already has waiters.
499 MPASS(!RW_CAN_READ(v));
502 * If the RW_LOCK_READ_WAITERS flag is already set, then
503 * we can go ahead and block. If it is not set then try
504 * to set it. If we fail to set it drop the turnstile
505 * lock and restart the loop.
507 if (!(v & RW_LOCK_READ_WAITERS)) {
508 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
509 v | RW_LOCK_READ_WAITERS)) {
510 turnstile_cancel(ts);
513 if (LOCK_LOG_TEST(&rw->lock_object, 0))
514 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
519 * We were unable to acquire the lock and the read waiters
520 * flag is set, so we must block on the turnstile.
522 if (LOCK_LOG_TEST(&rw->lock_object, 0))
523 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
526 sleep_time -= lockstat_nsecs();
528 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
530 sleep_time += lockstat_nsecs();
533 if (LOCK_LOG_TEST(&rw->lock_object, 0))
534 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
539 * TODO: acquire "owner of record" here. Here be turnstile dragons
540 * however. turnstiles don't like owners changing between calls to
541 * turnstile_wait() currently.
543 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
544 waittime, file, line);
545 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
546 WITNESS_LOCK(&rw->lock_object, 0, file, line);
547 curthread->td_locks++;
548 curthread->td_rw_rlocks++;
551 LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
554 * Record only the loops spinning and not sleeping.
556 if (spin_cnt > sleep_cnt)
557 LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
562 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
567 if (SCHEDULER_STOPPED())
572 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
573 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
574 curthread, rw->lock_object.lo_name, file, line));
578 KASSERT(rw->rw_lock != RW_DESTROYED,
579 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
580 if (!(x & RW_LOCK_READ))
582 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
583 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
585 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
586 curthread->td_locks++;
587 curthread->td_rw_rlocks++;
592 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
597 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
600 struct turnstile *ts;
601 uintptr_t x, v, queue;
603 if (SCHEDULER_STOPPED())
608 KASSERT(rw->rw_lock != RW_DESTROYED,
609 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
610 __rw_assert(c, RA_RLOCKED, file, line);
611 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
612 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
614 /* TODO: drop "owner of record" here. */
618 * See if there is more than one read lock held. If so,
619 * just drop one and return.
622 if (RW_READERS(x) > 1) {
623 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
624 x - RW_ONE_READER)) {
625 if (LOCK_LOG_TEST(&rw->lock_object, 0))
627 "%s: %p succeeded %p -> %p",
628 __func__, rw, (void *)x,
629 (void *)(x - RW_ONE_READER));
635 * If there aren't any waiters for a write lock, then try
636 * to drop it quickly.
638 if (!(x & RW_LOCK_WAITERS)) {
639 MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
641 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
643 if (LOCK_LOG_TEST(&rw->lock_object, 0))
644 CTR2(KTR_LOCK, "%s: %p last succeeded",
651 * Ok, we know we have waiters and we think we are the
652 * last reader, so grab the turnstile lock.
654 turnstile_chain_lock(&rw->lock_object);
655 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
656 MPASS(v & RW_LOCK_WAITERS);
659 * Try to drop our lock leaving the lock in a unlocked
662 * If you wanted to do explicit lock handoff you'd have to
663 * do it here. You'd also want to use turnstile_signal()
664 * and you'd have to handle the race where a higher
665 * priority thread blocks on the write lock before the
666 * thread you wakeup actually runs and have the new thread
667 * "steal" the lock. For now it's a lot simpler to just
668 * wakeup all of the waiters.
670 * As above, if we fail, then another thread might have
671 * acquired a read lock, so drop the turnstile lock and
675 if (v & RW_LOCK_WRITE_WAITERS) {
676 queue = TS_EXCLUSIVE_QUEUE;
677 x |= (v & RW_LOCK_READ_WAITERS);
679 queue = TS_SHARED_QUEUE;
680 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
682 turnstile_chain_unlock(&rw->lock_object);
685 if (LOCK_LOG_TEST(&rw->lock_object, 0))
686 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
690 * Ok. The lock is released and all that's left is to
691 * wake up the waiters. Note that the lock might not be
692 * free anymore, but in that case the writers will just
693 * block again if they run before the new lock holder(s)
696 ts = turnstile_lookup(&rw->lock_object);
698 turnstile_broadcast(ts, queue);
699 turnstile_unpend(ts, TS_SHARED_LOCK);
700 turnstile_chain_unlock(&rw->lock_object);
703 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
704 curthread->td_locks--;
705 curthread->td_rw_rlocks--;
709 * This function is called when we are unable to obtain a write lock on the
710 * first try. This means that at least one other thread holds either a
711 * read or write lock.
714 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
718 struct turnstile *ts;
719 #ifdef ADAPTIVE_RWLOCKS
720 volatile struct thread *owner;
725 #ifdef LOCK_PROFILING
726 uint64_t waittime = 0;
730 uint64_t spin_cnt = 0;
731 uint64_t sleep_cnt = 0;
732 int64_t sleep_time = 0;
735 if (SCHEDULER_STOPPED())
740 if (rw_wlocked(rw)) {
741 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
742 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
743 __func__, rw->lock_object.lo_name, file, line));
745 if (LOCK_LOG_TEST(&rw->lock_object, 0))
746 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
750 if (LOCK_LOG_TEST(&rw->lock_object, 0))
751 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
752 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
754 while (!_rw_write_lock(rw, tid)) {
759 PMC_SOFT_CALL( , , lock, failed);
761 lock_profile_obtain_lock_failed(&rw->lock_object,
762 &contested, &waittime);
763 #ifdef ADAPTIVE_RWLOCKS
765 * If the lock is write locked and the owner is
766 * running on another CPU, spin until the owner stops
767 * running or the state of the lock changes.
770 owner = (struct thread *)RW_OWNER(v);
771 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
772 if (LOCK_LOG_TEST(&rw->lock_object, 0))
773 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
774 __func__, rw, owner);
775 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
776 "spinning", "lockname:\"%s\"",
777 rw->lock_object.lo_name);
778 while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
779 TD_IS_RUNNING(owner)) {
785 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
789 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
790 spintries < rowner_retries) {
791 if (!(v & RW_LOCK_WRITE_SPINNER)) {
792 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
793 v | RW_LOCK_WRITE_SPINNER)) {
798 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
799 "spinning", "lockname:\"%s\"",
800 rw->lock_object.lo_name);
801 for (i = 0; i < rowner_loops; i++) {
802 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
806 KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
809 spin_cnt += rowner_loops - i;
811 if (i != rowner_loops)
815 ts = turnstile_trywait(&rw->lock_object);
818 #ifdef ADAPTIVE_RWLOCKS
820 * The current lock owner might have started executing
821 * on another CPU (or the lock could have changed
822 * owners) while we were waiting on the turnstile
823 * chain lock. If so, drop the turnstile lock and try
826 if (!(v & RW_LOCK_READ)) {
827 owner = (struct thread *)RW_OWNER(v);
828 if (TD_IS_RUNNING(owner)) {
829 turnstile_cancel(ts);
835 * Check for the waiters flags about this rwlock.
836 * If the lock was released, without maintain any pending
837 * waiters queue, simply try to acquire it.
838 * If a pending waiters queue is present, claim the lock
839 * ownership and maintain the pending queue.
841 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
842 if ((v & ~x) == RW_UNLOCKED) {
843 x &= ~RW_LOCK_WRITE_SPINNER;
844 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
848 turnstile_cancel(ts);
851 turnstile_cancel(ts);
855 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
856 * set it. If we fail to set it, then loop back and try
859 if (!(v & RW_LOCK_WRITE_WAITERS)) {
860 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
861 v | RW_LOCK_WRITE_WAITERS)) {
862 turnstile_cancel(ts);
865 if (LOCK_LOG_TEST(&rw->lock_object, 0))
866 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
870 * We were unable to acquire the lock and the write waiters
871 * flag is set, so we must block on the turnstile.
873 if (LOCK_LOG_TEST(&rw->lock_object, 0))
874 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
877 sleep_time -= lockstat_nsecs();
879 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
881 sleep_time += lockstat_nsecs();
884 if (LOCK_LOG_TEST(&rw->lock_object, 0))
885 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
887 #ifdef ADAPTIVE_RWLOCKS
891 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
892 waittime, file, line);
895 LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
898 * Record only the loops spinning and not sleeping.
900 if (spin_cnt > sleep_cnt)
901 LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
906 * This function is called if the first try at releasing a write lock failed.
907 * This means that one of the 2 waiter bits must be set indicating that at
908 * least one thread is waiting on this lock.
911 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
915 struct turnstile *ts;
919 if (SCHEDULER_STOPPED())
924 if (rw_wlocked(rw) && rw_recursed(rw)) {
926 if (LOCK_LOG_TEST(&rw->lock_object, 0))
927 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
931 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
932 ("%s: neither of the waiter flags are set", __func__));
934 if (LOCK_LOG_TEST(&rw->lock_object, 0))
935 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
937 turnstile_chain_lock(&rw->lock_object);
938 ts = turnstile_lookup(&rw->lock_object);
942 * Use the same algo as sx locks for now. Prefer waking up shared
943 * waiters if we have any over writers. This is probably not ideal.
945 * 'v' is the value we are going to write back to rw_lock. If we
946 * have waiters on both queues, we need to preserve the state of
947 * the waiter flag for the queue we don't wake up. For now this is
948 * hardcoded for the algorithm mentioned above.
950 * In the case of both readers and writers waiting we wakeup the
951 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
952 * new writer comes in before a reader it will claim the lock up
953 * above. There is probably a potential priority inversion in
954 * there that could be worked around either by waking both queues
955 * of waiters or doing some complicated lock handoff gymnastics.
958 if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
959 queue = TS_EXCLUSIVE_QUEUE;
960 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
962 queue = TS_SHARED_QUEUE;
964 /* Wake up all waiters for the specific queue. */
965 if (LOCK_LOG_TEST(&rw->lock_object, 0))
966 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
967 queue == TS_SHARED_QUEUE ? "read" : "write");
968 turnstile_broadcast(ts, queue);
969 atomic_store_rel_ptr(&rw->rw_lock, v);
970 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
971 turnstile_chain_unlock(&rw->lock_object);
975 * Attempt to do a non-blocking upgrade from a read lock to a write
976 * lock. This will only succeed if this thread holds a single read
977 * lock. Returns true if the upgrade succeeded and false otherwise.
980 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
984 struct turnstile *ts;
987 if (SCHEDULER_STOPPED())
992 KASSERT(rw->rw_lock != RW_DESTROYED,
993 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
994 __rw_assert(c, RA_RLOCKED, file, line);
997 * Attempt to switch from one reader to a writer. If there
998 * are any write waiters, then we will have to lock the
999 * turnstile first to prevent races with another writer
1000 * calling turnstile_wait() before we have claimed this
1001 * turnstile. So, do the simple case of no waiters first.
1003 tid = (uintptr_t)curthread;
1007 if (RW_READERS(v) > 1)
1009 if (!(v & RW_LOCK_WAITERS)) {
1010 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
1017 * Ok, we think we have waiters, so lock the turnstile.
1019 ts = turnstile_trywait(&rw->lock_object);
1021 if (RW_READERS(v) > 1) {
1022 turnstile_cancel(ts);
1026 * Try to switch from one reader to a writer again. This time
1027 * we honor the current state of the waiters flags.
1028 * If we obtain the lock with the flags set, then claim
1029 * ownership of the turnstile.
1031 x = rw->rw_lock & RW_LOCK_WAITERS;
1032 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1035 turnstile_claim(ts);
1037 turnstile_cancel(ts);
1040 turnstile_cancel(ts);
1042 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1044 curthread->td_rw_rlocks--;
1045 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1047 LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
1053 * Downgrade a write lock into a single read lock.
1056 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1059 struct turnstile *ts;
1063 if (SCHEDULER_STOPPED())
1068 KASSERT(rw->rw_lock != RW_DESTROYED,
1069 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1070 __rw_assert(c, RA_WLOCKED | RA_NOTRECURSED, file, line);
1072 if (rw_recursed(rw))
1073 panic("downgrade of a recursed lock");
1076 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1079 * Convert from a writer to a single reader. First we handle
1080 * the easy case with no waiters. If there are any waiters, we
1081 * lock the turnstile and "disown" the lock.
1083 tid = (uintptr_t)curthread;
1084 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1088 * Ok, we think we have waiters, so lock the turnstile so we can
1089 * read the waiter flags without any races.
1091 turnstile_chain_lock(&rw->lock_object);
1092 v = rw->rw_lock & RW_LOCK_WAITERS;
1093 rwait = v & RW_LOCK_READ_WAITERS;
1094 wwait = v & RW_LOCK_WRITE_WAITERS;
1095 MPASS(rwait | wwait);
1098 * Downgrade from a write lock while preserving waiters flag
1099 * and give up ownership of the turnstile.
1101 ts = turnstile_lookup(&rw->lock_object);
1104 v &= ~RW_LOCK_READ_WAITERS;
1105 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1107 * Wake other readers if there are no writers pending. Otherwise they
1108 * won't be able to acquire the lock anyway.
1110 if (rwait && !wwait) {
1111 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1112 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1114 turnstile_disown(ts);
1115 turnstile_chain_unlock(&rw->lock_object);
1117 curthread->td_rw_rlocks++;
1118 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1119 LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1122 #ifdef INVARIANT_SUPPORT
1128 * In the non-WITNESS case, rw_assert() can only detect that at least
1129 * *some* thread owns an rlock, but it cannot guarantee that *this*
1130 * thread owns an rlock.
1133 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1135 const struct rwlock *rw;
1137 if (panicstr != NULL)
1144 case RA_LOCKED | RA_RECURSED:
1145 case RA_LOCKED | RA_NOTRECURSED:
1147 case RA_RLOCKED | RA_RECURSED:
1148 case RA_RLOCKED | RA_NOTRECURSED:
1150 witness_assert(&rw->lock_object, what, file, line);
1153 * If some other thread has a write lock or we have one
1154 * and are asserting a read lock, fail. Also, if no one
1155 * has a lock at all, fail.
1157 if (rw->rw_lock == RW_UNLOCKED ||
1158 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1159 rw_wowner(rw) != curthread)))
1160 panic("Lock %s not %slocked @ %s:%d\n",
1161 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1162 "read " : "", file, line);
1164 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1165 if (rw_recursed(rw)) {
1166 if (what & RA_NOTRECURSED)
1167 panic("Lock %s recursed @ %s:%d\n",
1168 rw->lock_object.lo_name, file,
1170 } else if (what & RA_RECURSED)
1171 panic("Lock %s not recursed @ %s:%d\n",
1172 rw->lock_object.lo_name, file, line);
1177 case RA_WLOCKED | RA_RECURSED:
1178 case RA_WLOCKED | RA_NOTRECURSED:
1179 if (rw_wowner(rw) != curthread)
1180 panic("Lock %s not exclusively locked @ %s:%d\n",
1181 rw->lock_object.lo_name, file, line);
1182 if (rw_recursed(rw)) {
1183 if (what & RA_NOTRECURSED)
1184 panic("Lock %s recursed @ %s:%d\n",
1185 rw->lock_object.lo_name, file, line);
1186 } else if (what & RA_RECURSED)
1187 panic("Lock %s not recursed @ %s:%d\n",
1188 rw->lock_object.lo_name, file, line);
1192 witness_assert(&rw->lock_object, what, file, line);
1195 * If we hold a write lock fail. We can't reliably check
1196 * to see if we hold a read lock or not.
1198 if (rw_wowner(rw) == curthread)
1199 panic("Lock %s exclusively locked @ %s:%d\n",
1200 rw->lock_object.lo_name, file, line);
1204 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1208 #endif /* INVARIANT_SUPPORT */
1212 db_show_rwlock(const struct lock_object *lock)
1214 const struct rwlock *rw;
1217 rw = (const struct rwlock *)lock;
1219 db_printf(" state: ");
1220 if (rw->rw_lock == RW_UNLOCKED)
1221 db_printf("UNLOCKED\n");
1222 else if (rw->rw_lock == RW_DESTROYED) {
1223 db_printf("DESTROYED\n");
1225 } else if (rw->rw_lock & RW_LOCK_READ)
1226 db_printf("RLOCK: %ju locks\n",
1227 (uintmax_t)(RW_READERS(rw->rw_lock)));
1230 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1231 td->td_tid, td->td_proc->p_pid, td->td_name);
1232 if (rw_recursed(rw))
1233 db_printf(" recursed: %u\n", rw->rw_recurse);
1235 db_printf(" waiters: ");
1236 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1237 case RW_LOCK_READ_WAITERS:
1238 db_printf("readers\n");
1240 case RW_LOCK_WRITE_WAITERS:
1241 db_printf("writers\n");
1243 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1244 db_printf("readers and writers\n");
1247 db_printf("none\n");