2 * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * Machine independent bits of reader/writer lock implementation.
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
35 #include "opt_hwpmc_hooks.h"
36 #include "opt_kdtrace.h"
37 #include "opt_no_adaptive_rwlocks.h"
39 #include <sys/param.h>
42 #include <sys/kernel.h>
44 #include <sys/mutex.h>
46 #include <sys/rwlock.h>
47 #include <sys/sysctl.h>
48 #include <sys/systm.h>
49 #include <sys/turnstile.h>
51 #include <machine/cpu.h>
53 #if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
54 #define ADAPTIVE_RWLOCKS
58 #include <sys/pmckern.h>
59 PMC_SOFT_DECLARE( , , lock, failed);
62 #ifdef ADAPTIVE_RWLOCKS
63 #define ROWNER_RETRIES 10
64 #define ROWNER_LOOPS 10000
70 static void db_show_rwlock(struct lock_object *lock);
72 static void assert_rw(struct lock_object *lock, int what);
73 static void lock_rw(struct lock_object *lock, int how);
75 static int owner_rw(struct lock_object *lock, struct thread **owner);
77 static int unlock_rw(struct lock_object *lock);
79 struct lock_class lock_class_rw = {
81 .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
82 .lc_assert = assert_rw,
84 .lc_ddb_show = db_show_rwlock,
87 .lc_unlock = unlock_rw,
94 * Return a pointer to the owning thread if the lock is write-locked or
95 * NULL if the lock is unlocked or read-locked.
97 #define rw_wowner(rw) \
98 ((rw)->rw_lock & RW_LOCK_READ ? NULL : \
99 (struct thread *)RW_OWNER((rw)->rw_lock))
102 * Returns if a write owner is recursed. Write ownership is not assured
103 * here and should be previously checked.
105 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
108 * Return true if curthread helds the lock.
110 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
113 * Return a pointer to the owning thread for this lock who should receive
114 * any priority lent by threads that block on this lock. Currently this
115 * is identical to rw_wowner().
117 #define rw_owner(rw) rw_wowner(rw)
120 #define _rw_assert(rw, what, file, line)
124 assert_rw(struct lock_object *lock, int what)
127 rw_assert((struct rwlock *)lock, what);
131 lock_rw(struct lock_object *lock, int how)
135 rw = (struct rwlock *)lock;
143 unlock_rw(struct lock_object *lock)
147 rw = (struct rwlock *)lock;
148 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
149 if (rw->rw_lock & RW_LOCK_READ) {
160 owner_rw(struct lock_object *lock, struct thread **owner)
162 struct rwlock *rw = (struct rwlock *)lock;
163 uintptr_t x = rw->rw_lock;
165 *owner = rw_wowner(rw);
166 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
172 rw_init_flags(struct rwlock *rw, const char *name, int opts)
176 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
178 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
179 ("%s: rw_lock not aligned for %s: %p", __func__, name,
182 flags = LO_UPGRADABLE;
185 if (opts & RW_NOPROFILE)
186 flags |= LO_NOPROFILE;
187 if (!(opts & RW_NOWITNESS))
189 if (opts & RW_RECURSE)
190 flags |= LO_RECURSABLE;
194 rw->rw_lock = RW_UNLOCKED;
196 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
200 rw_destroy(struct rwlock *rw)
203 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
204 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
205 rw->rw_lock = RW_DESTROYED;
206 lock_destroy(&rw->lock_object);
210 rw_sysinit(void *arg)
212 struct rw_args *args = arg;
214 rw_init(args->ra_rw, args->ra_desc);
218 rw_sysinit_flags(void *arg)
220 struct rw_args_flags *args = arg;
222 rw_init_flags(args->ra_rw, args->ra_desc, args->ra_flags);
226 rw_wowned(struct rwlock *rw)
229 return (rw_wowner(rw) == curthread);
233 _rw_wlock(struct rwlock *rw, const char *file, int line)
236 if (SCHEDULER_STOPPED())
238 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
239 ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
240 curthread, rw->lock_object.lo_name, file, line));
241 KASSERT(rw->rw_lock != RW_DESTROYED,
242 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
243 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
245 __rw_wlock(rw, curthread, file, line);
246 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
247 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
248 curthread->td_locks++;
252 _rw_try_wlock(struct rwlock *rw, const char *file, int line)
256 if (SCHEDULER_STOPPED())
259 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
260 ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
261 curthread, rw->lock_object.lo_name, file, line));
262 KASSERT(rw->rw_lock != RW_DESTROYED,
263 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
265 if (rw_wlocked(rw) &&
266 (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
270 rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
271 (uintptr_t)curthread);
273 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
275 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
277 curthread->td_locks++;
283 _rw_wunlock(struct rwlock *rw, const char *file, int line)
286 if (SCHEDULER_STOPPED())
288 KASSERT(rw->rw_lock != RW_DESTROYED,
289 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
290 _rw_assert(rw, RA_WLOCKED, file, line);
291 curthread->td_locks--;
292 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
293 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
295 if (!rw_recursed(rw))
296 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_WUNLOCK_RELEASE, rw);
297 __rw_wunlock(rw, curthread, file, line);
300 * Determines whether a new reader can acquire a lock. Succeeds if the
301 * reader already owns a read lock and the lock is locked for read to
302 * prevent deadlock from reader recursion. Also succeeds if the lock
303 * is unlocked and has no writer waiters or spinners. Failing otherwise
304 * prioritizes writers before readers.
306 #define RW_CAN_READ(_rw) \
307 ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) & \
308 (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) == \
312 _rw_rlock(struct rwlock *rw, const char *file, int line)
314 struct turnstile *ts;
315 #ifdef ADAPTIVE_RWLOCKS
316 volatile struct thread *owner;
320 #ifdef LOCK_PROFILING
321 uint64_t waittime = 0;
326 uint64_t spin_cnt = 0;
327 uint64_t sleep_cnt = 0;
328 int64_t sleep_time = 0;
331 if (SCHEDULER_STOPPED())
334 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
335 ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
336 curthread, rw->lock_object.lo_name, file, line));
337 KASSERT(rw->rw_lock != RW_DESTROYED,
338 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
339 KASSERT(rw_wowner(rw) != curthread,
340 ("rw_rlock: wlock already held for %s @ %s:%d",
341 rw->lock_object.lo_name, file, line));
342 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
349 * Handle the easy case. If no other thread has a write
350 * lock, then try to bump up the count of read locks. Note
351 * that we have to preserve the current state of the
352 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
353 * read lock, then rw_lock must have changed, so restart
354 * the loop. Note that this handles the case of a
355 * completely unlocked rwlock since such a lock is encoded
356 * as a read lock with no waiters.
359 if (RW_CAN_READ(v)) {
361 * The RW_LOCK_READ_WAITERS flag should only be set
362 * if the lock has been unlocked and write waiters
365 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
366 v + RW_ONE_READER)) {
367 if (LOCK_LOG_TEST(&rw->lock_object, 0))
369 "%s: %p succeed %p -> %p", __func__,
371 (void *)(v + RW_ONE_READER));
377 PMC_SOFT_CALL( , , lock, failed);
379 lock_profile_obtain_lock_failed(&rw->lock_object,
380 &contested, &waittime);
382 #ifdef ADAPTIVE_RWLOCKS
384 * If the owner is running on another CPU, spin until
385 * the owner stops running or the state of the lock
388 if ((v & RW_LOCK_READ) == 0) {
389 owner = (struct thread *)RW_OWNER(v);
390 if (TD_IS_RUNNING(owner)) {
391 if (LOCK_LOG_TEST(&rw->lock_object, 0))
393 "%s: spinning on %p held by %p",
394 __func__, rw, owner);
395 while ((struct thread*)RW_OWNER(rw->rw_lock) ==
396 owner && TD_IS_RUNNING(owner)) {
404 } else if (spintries < ROWNER_RETRIES) {
406 for (i = 0; i < ROWNER_LOOPS; i++) {
408 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
412 if (i != ROWNER_LOOPS)
418 * Okay, now it's the hard case. Some other thread already
419 * has a write lock or there are write waiters present,
420 * acquire the turnstile lock so we can begin the process
423 ts = turnstile_trywait(&rw->lock_object);
426 * The lock might have been released while we spun, so
427 * recheck its state and restart the loop if needed.
430 if (RW_CAN_READ(v)) {
431 turnstile_cancel(ts);
435 #ifdef ADAPTIVE_RWLOCKS
437 * The current lock owner might have started executing
438 * on another CPU (or the lock could have changed
439 * owners) while we were waiting on the turnstile
440 * chain lock. If so, drop the turnstile lock and try
443 if ((v & RW_LOCK_READ) == 0) {
444 owner = (struct thread *)RW_OWNER(v);
445 if (TD_IS_RUNNING(owner)) {
446 turnstile_cancel(ts);
453 * The lock is held in write mode or it already has waiters.
455 MPASS(!RW_CAN_READ(v));
458 * If the RW_LOCK_READ_WAITERS flag is already set, then
459 * we can go ahead and block. If it is not set then try
460 * to set it. If we fail to set it drop the turnstile
461 * lock and restart the loop.
463 if (!(v & RW_LOCK_READ_WAITERS)) {
464 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
465 v | RW_LOCK_READ_WAITERS)) {
466 turnstile_cancel(ts);
469 if (LOCK_LOG_TEST(&rw->lock_object, 0))
470 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
475 * We were unable to acquire the lock and the read waiters
476 * flag is set, so we must block on the turnstile.
478 if (LOCK_LOG_TEST(&rw->lock_object, 0))
479 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
482 sleep_time -= lockstat_nsecs();
484 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
486 sleep_time += lockstat_nsecs();
489 if (LOCK_LOG_TEST(&rw->lock_object, 0))
490 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
495 * TODO: acquire "owner of record" here. Here be turnstile dragons
496 * however. turnstiles don't like owners changing between calls to
497 * turnstile_wait() currently.
499 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
500 waittime, file, line);
501 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
502 WITNESS_LOCK(&rw->lock_object, 0, file, line);
503 curthread->td_locks++;
504 curthread->td_rw_rlocks++;
507 LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
510 * Record only the loops spinning and not sleeping.
512 if (spin_cnt > sleep_cnt)
513 LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
518 _rw_try_rlock(struct rwlock *rw, const char *file, int line)
522 if (SCHEDULER_STOPPED())
525 KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
526 ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
527 curthread, rw->lock_object.lo_name, file, line));
531 KASSERT(rw->rw_lock != RW_DESTROYED,
532 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
533 if (!(x & RW_LOCK_READ))
535 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
536 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
538 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
539 curthread->td_locks++;
540 curthread->td_rw_rlocks++;
545 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
550 _rw_runlock(struct rwlock *rw, const char *file, int line)
552 struct turnstile *ts;
553 uintptr_t x, v, queue;
555 if (SCHEDULER_STOPPED())
558 KASSERT(rw->rw_lock != RW_DESTROYED,
559 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
560 _rw_assert(rw, RA_RLOCKED, file, line);
561 curthread->td_locks--;
562 curthread->td_rw_rlocks--;
563 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
564 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
566 /* TODO: drop "owner of record" here. */
570 * See if there is more than one read lock held. If so,
571 * just drop one and return.
574 if (RW_READERS(x) > 1) {
575 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
576 x - RW_ONE_READER)) {
577 if (LOCK_LOG_TEST(&rw->lock_object, 0))
579 "%s: %p succeeded %p -> %p",
580 __func__, rw, (void *)x,
581 (void *)(x - RW_ONE_READER));
587 * If there aren't any waiters for a write lock, then try
588 * to drop it quickly.
590 if (!(x & RW_LOCK_WAITERS)) {
591 MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
593 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
595 if (LOCK_LOG_TEST(&rw->lock_object, 0))
596 CTR2(KTR_LOCK, "%s: %p last succeeded",
603 * Ok, we know we have waiters and we think we are the
604 * last reader, so grab the turnstile lock.
606 turnstile_chain_lock(&rw->lock_object);
607 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
608 MPASS(v & RW_LOCK_WAITERS);
611 * Try to drop our lock leaving the lock in a unlocked
614 * If you wanted to do explicit lock handoff you'd have to
615 * do it here. You'd also want to use turnstile_signal()
616 * and you'd have to handle the race where a higher
617 * priority thread blocks on the write lock before the
618 * thread you wakeup actually runs and have the new thread
619 * "steal" the lock. For now it's a lot simpler to just
620 * wakeup all of the waiters.
622 * As above, if we fail, then another thread might have
623 * acquired a read lock, so drop the turnstile lock and
627 if (v & RW_LOCK_WRITE_WAITERS) {
628 queue = TS_EXCLUSIVE_QUEUE;
629 x |= (v & RW_LOCK_READ_WAITERS);
631 queue = TS_SHARED_QUEUE;
632 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
634 turnstile_chain_unlock(&rw->lock_object);
637 if (LOCK_LOG_TEST(&rw->lock_object, 0))
638 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
642 * Ok. The lock is released and all that's left is to
643 * wake up the waiters. Note that the lock might not be
644 * free anymore, but in that case the writers will just
645 * block again if they run before the new lock holder(s)
648 ts = turnstile_lookup(&rw->lock_object);
650 turnstile_broadcast(ts, queue);
651 turnstile_unpend(ts, TS_SHARED_LOCK);
652 turnstile_chain_unlock(&rw->lock_object);
655 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
659 * This function is called when we are unable to obtain a write lock on the
660 * first try. This means that at least one other thread holds either a
661 * read or write lock.
664 _rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
666 struct turnstile *ts;
667 #ifdef ADAPTIVE_RWLOCKS
668 volatile struct thread *owner;
673 #ifdef LOCK_PROFILING
674 uint64_t waittime = 0;
678 uint64_t spin_cnt = 0;
679 uint64_t sleep_cnt = 0;
680 int64_t sleep_time = 0;
683 if (SCHEDULER_STOPPED())
686 if (rw_wlocked(rw)) {
687 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
688 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
689 __func__, rw->lock_object.lo_name, file, line));
691 if (LOCK_LOG_TEST(&rw->lock_object, 0))
692 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
696 if (LOCK_LOG_TEST(&rw->lock_object, 0))
697 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
698 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
700 while (!_rw_write_lock(rw, tid)) {
705 PMC_SOFT_CALL( , , lock, failed);
707 lock_profile_obtain_lock_failed(&rw->lock_object,
708 &contested, &waittime);
709 #ifdef ADAPTIVE_RWLOCKS
711 * If the lock is write locked and the owner is
712 * running on another CPU, spin until the owner stops
713 * running or the state of the lock changes.
716 owner = (struct thread *)RW_OWNER(v);
717 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
718 if (LOCK_LOG_TEST(&rw->lock_object, 0))
719 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
720 __func__, rw, owner);
721 while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
722 TD_IS_RUNNING(owner)) {
730 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
731 spintries < ROWNER_RETRIES) {
732 if (!(v & RW_LOCK_WRITE_SPINNER)) {
733 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
734 v | RW_LOCK_WRITE_SPINNER)) {
739 for (i = 0; i < ROWNER_LOOPS; i++) {
740 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
745 spin_cnt += ROWNER_LOOPS - i;
747 if (i != ROWNER_LOOPS)
751 ts = turnstile_trywait(&rw->lock_object);
754 #ifdef ADAPTIVE_RWLOCKS
756 * The current lock owner might have started executing
757 * on another CPU (or the lock could have changed
758 * owners) while we were waiting on the turnstile
759 * chain lock. If so, drop the turnstile lock and try
762 if (!(v & RW_LOCK_READ)) {
763 owner = (struct thread *)RW_OWNER(v);
764 if (TD_IS_RUNNING(owner)) {
765 turnstile_cancel(ts);
771 * Check for the waiters flags about this rwlock.
772 * If the lock was released, without maintain any pending
773 * waiters queue, simply try to acquire it.
774 * If a pending waiters queue is present, claim the lock
775 * ownership and maintain the pending queue.
777 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
778 if ((v & ~x) == RW_UNLOCKED) {
779 x &= ~RW_LOCK_WRITE_SPINNER;
780 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
784 turnstile_cancel(ts);
787 turnstile_cancel(ts);
791 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
792 * set it. If we fail to set it, then loop back and try
795 if (!(v & RW_LOCK_WRITE_WAITERS)) {
796 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
797 v | RW_LOCK_WRITE_WAITERS)) {
798 turnstile_cancel(ts);
801 if (LOCK_LOG_TEST(&rw->lock_object, 0))
802 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
806 * We were unable to acquire the lock and the write waiters
807 * flag is set, so we must block on the turnstile.
809 if (LOCK_LOG_TEST(&rw->lock_object, 0))
810 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
813 sleep_time -= lockstat_nsecs();
815 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
817 sleep_time += lockstat_nsecs();
820 if (LOCK_LOG_TEST(&rw->lock_object, 0))
821 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
823 #ifdef ADAPTIVE_RWLOCKS
827 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
828 waittime, file, line);
831 LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
834 * Record only the loops spinning and not sleeping.
836 if (spin_cnt > sleep_cnt)
837 LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
842 * This function is called if the first try at releasing a write lock failed.
843 * This means that one of the 2 waiter bits must be set indicating that at
844 * least one thread is waiting on this lock.
847 _rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
849 struct turnstile *ts;
853 if (SCHEDULER_STOPPED())
856 if (rw_wlocked(rw) && rw_recursed(rw)) {
858 if (LOCK_LOG_TEST(&rw->lock_object, 0))
859 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
863 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
864 ("%s: neither of the waiter flags are set", __func__));
866 if (LOCK_LOG_TEST(&rw->lock_object, 0))
867 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
869 turnstile_chain_lock(&rw->lock_object);
870 ts = turnstile_lookup(&rw->lock_object);
874 * Use the same algo as sx locks for now. Prefer waking up shared
875 * waiters if we have any over writers. This is probably not ideal.
877 * 'v' is the value we are going to write back to rw_lock. If we
878 * have waiters on both queues, we need to preserve the state of
879 * the waiter flag for the queue we don't wake up. For now this is
880 * hardcoded for the algorithm mentioned above.
882 * In the case of both readers and writers waiting we wakeup the
883 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
884 * new writer comes in before a reader it will claim the lock up
885 * above. There is probably a potential priority inversion in
886 * there that could be worked around either by waking both queues
887 * of waiters or doing some complicated lock handoff gymnastics.
890 if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
891 queue = TS_EXCLUSIVE_QUEUE;
892 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
894 queue = TS_SHARED_QUEUE;
896 /* Wake up all waiters for the specific queue. */
897 if (LOCK_LOG_TEST(&rw->lock_object, 0))
898 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
899 queue == TS_SHARED_QUEUE ? "read" : "write");
900 turnstile_broadcast(ts, queue);
901 atomic_store_rel_ptr(&rw->rw_lock, v);
902 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
903 turnstile_chain_unlock(&rw->lock_object);
907 * Attempt to do a non-blocking upgrade from a read lock to a write
908 * lock. This will only succeed if this thread holds a single read
909 * lock. Returns true if the upgrade succeeded and false otherwise.
912 _rw_try_upgrade(struct rwlock *rw, const char *file, int line)
915 struct turnstile *ts;
918 if (SCHEDULER_STOPPED())
921 KASSERT(rw->rw_lock != RW_DESTROYED,
922 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
923 _rw_assert(rw, RA_RLOCKED, file, line);
926 * Attempt to switch from one reader to a writer. If there
927 * are any write waiters, then we will have to lock the
928 * turnstile first to prevent races with another writer
929 * calling turnstile_wait() before we have claimed this
930 * turnstile. So, do the simple case of no waiters first.
932 tid = (uintptr_t)curthread;
936 if (RW_READERS(v) > 1)
938 if (!(v & RW_LOCK_WAITERS)) {
939 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
946 * Ok, we think we have waiters, so lock the turnstile.
948 ts = turnstile_trywait(&rw->lock_object);
950 if (RW_READERS(v) > 1) {
951 turnstile_cancel(ts);
955 * Try to switch from one reader to a writer again. This time
956 * we honor the current state of the waiters flags.
957 * If we obtain the lock with the flags set, then claim
958 * ownership of the turnstile.
960 x = rw->rw_lock & RW_LOCK_WAITERS;
961 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
966 turnstile_cancel(ts);
969 turnstile_cancel(ts);
971 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
973 curthread->td_rw_rlocks--;
974 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
976 LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
982 * Downgrade a write lock into a single read lock.
985 _rw_downgrade(struct rwlock *rw, const char *file, int line)
987 struct turnstile *ts;
991 if (SCHEDULER_STOPPED())
994 KASSERT(rw->rw_lock != RW_DESTROYED,
995 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
996 _rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
999 panic("downgrade of a recursed lock");
1002 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1005 * Convert from a writer to a single reader. First we handle
1006 * the easy case with no waiters. If there are any waiters, we
1007 * lock the turnstile and "disown" the lock.
1009 tid = (uintptr_t)curthread;
1010 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1014 * Ok, we think we have waiters, so lock the turnstile so we can
1015 * read the waiter flags without any races.
1017 turnstile_chain_lock(&rw->lock_object);
1018 v = rw->rw_lock & RW_LOCK_WAITERS;
1019 rwait = v & RW_LOCK_READ_WAITERS;
1020 wwait = v & RW_LOCK_WRITE_WAITERS;
1021 MPASS(rwait | wwait);
1024 * Downgrade from a write lock while preserving waiters flag
1025 * and give up ownership of the turnstile.
1027 ts = turnstile_lookup(&rw->lock_object);
1030 v &= ~RW_LOCK_READ_WAITERS;
1031 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1033 * Wake other readers if there are no writers pending. Otherwise they
1034 * won't be able to acquire the lock anyway.
1036 if (rwait && !wwait) {
1037 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1038 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1040 turnstile_disown(ts);
1041 turnstile_chain_unlock(&rw->lock_object);
1043 curthread->td_rw_rlocks++;
1044 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1045 LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1048 #ifdef INVARIANT_SUPPORT
1054 * In the non-WITNESS case, rw_assert() can only detect that at least
1055 * *some* thread owns an rlock, but it cannot guarantee that *this*
1056 * thread owns an rlock.
1059 _rw_assert(struct rwlock *rw, int what, const char *file, int line)
1062 if (panicstr != NULL)
1066 case RA_LOCKED | RA_RECURSED:
1067 case RA_LOCKED | RA_NOTRECURSED:
1069 case RA_RLOCKED | RA_RECURSED:
1070 case RA_RLOCKED | RA_NOTRECURSED:
1072 witness_assert(&rw->lock_object, what, file, line);
1075 * If some other thread has a write lock or we have one
1076 * and are asserting a read lock, fail. Also, if no one
1077 * has a lock at all, fail.
1079 if (rw->rw_lock == RW_UNLOCKED ||
1080 (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1081 rw_wowner(rw) != curthread)))
1082 panic("Lock %s not %slocked @ %s:%d\n",
1083 rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1084 "read " : "", file, line);
1086 if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1087 if (rw_recursed(rw)) {
1088 if (what & RA_NOTRECURSED)
1089 panic("Lock %s recursed @ %s:%d\n",
1090 rw->lock_object.lo_name, file,
1092 } else if (what & RA_RECURSED)
1093 panic("Lock %s not recursed @ %s:%d\n",
1094 rw->lock_object.lo_name, file, line);
1099 case RA_WLOCKED | RA_RECURSED:
1100 case RA_WLOCKED | RA_NOTRECURSED:
1101 if (rw_wowner(rw) != curthread)
1102 panic("Lock %s not exclusively locked @ %s:%d\n",
1103 rw->lock_object.lo_name, file, line);
1104 if (rw_recursed(rw)) {
1105 if (what & RA_NOTRECURSED)
1106 panic("Lock %s recursed @ %s:%d\n",
1107 rw->lock_object.lo_name, file, line);
1108 } else if (what & RA_RECURSED)
1109 panic("Lock %s not recursed @ %s:%d\n",
1110 rw->lock_object.lo_name, file, line);
1114 witness_assert(&rw->lock_object, what, file, line);
1117 * If we hold a write lock fail. We can't reliably check
1118 * to see if we hold a read lock or not.
1120 if (rw_wowner(rw) == curthread)
1121 panic("Lock %s exclusively locked @ %s:%d\n",
1122 rw->lock_object.lo_name, file, line);
1126 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1130 #endif /* INVARIANT_SUPPORT */
1134 db_show_rwlock(struct lock_object *lock)
1139 rw = (struct rwlock *)lock;
1141 db_printf(" state: ");
1142 if (rw->rw_lock == RW_UNLOCKED)
1143 db_printf("UNLOCKED\n");
1144 else if (rw->rw_lock == RW_DESTROYED) {
1145 db_printf("DESTROYED\n");
1147 } else if (rw->rw_lock & RW_LOCK_READ)
1148 db_printf("RLOCK: %ju locks\n",
1149 (uintmax_t)(RW_READERS(rw->rw_lock)));
1152 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1153 td->td_tid, td->td_proc->p_pid, td->td_name);
1154 if (rw_recursed(rw))
1155 db_printf(" recursed: %u\n", rw->rw_recurse);
1157 db_printf(" waiters: ");
1158 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1159 case RW_LOCK_READ_WAITERS:
1160 db_printf("readers\n");
1162 case RW_LOCK_WRITE_WAITERS:
1163 db_printf("writers\n");
1165 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1166 db_printf("readers and writers\n");
1169 db_printf("none\n");