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.
13 * 3. Neither the name of the author nor the names of any co-contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * Machine independent bits of reader/writer lock implementation.
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
38 #include "opt_kdtrace.h"
39 #include "opt_no_adaptive_rwlocks.h"
41 #include <sys/param.h>
43 #include <sys/kernel.h>
45 #include <sys/mutex.h>
47 #include <sys/rwlock.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
58 #ifdef ADAPTIVE_RWLOCKS
59 #define ROWNER_RETRIES 10
60 #define ROWNER_LOOPS 10000
66 static void db_show_rwlock(struct lock_object *lock);
68 static void assert_rw(struct lock_object *lock, int what);
69 static void lock_rw(struct lock_object *lock, int how);
71 static int owner_rw(struct lock_object *lock, struct thread **owner);
73 static int unlock_rw(struct lock_object *lock);
75 struct lock_class lock_class_rw = {
77 .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
78 .lc_assert = assert_rw,
80 .lc_ddb_show = db_show_rwlock,
83 .lc_unlock = unlock_rw,
90 * Return a pointer to the owning thread if the lock is write-locked or
91 * NULL if the lock is unlocked or read-locked.
93 #define rw_wowner(rw) \
94 ((rw)->rw_lock & RW_LOCK_READ ? NULL : \
95 (struct thread *)RW_OWNER((rw)->rw_lock))
98 * Returns if a write owner is recursed. Write ownership is not assured
99 * here and should be previously checked.
101 #define rw_recursed(rw) ((rw)->rw_recurse != 0)
104 * Return true if curthread helds the lock.
106 #define rw_wlocked(rw) (rw_wowner((rw)) == curthread)
109 * Return a pointer to the owning thread for this lock who should receive
110 * any priority lent by threads that block on this lock. Currently this
111 * is identical to rw_wowner().
113 #define rw_owner(rw) rw_wowner(rw)
116 #define _rw_assert(rw, what, file, line)
120 assert_rw(struct lock_object *lock, int what)
123 rw_assert((struct rwlock *)lock, what);
127 lock_rw(struct lock_object *lock, int how)
131 rw = (struct rwlock *)lock;
139 unlock_rw(struct lock_object *lock)
143 rw = (struct rwlock *)lock;
144 rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
145 if (rw->rw_lock & RW_LOCK_READ) {
156 owner_rw(struct lock_object *lock, struct thread **owner)
158 struct rwlock *rw = (struct rwlock *)lock;
159 uintptr_t x = rw->rw_lock;
161 *owner = rw_wowner(rw);
162 return ((x & RW_LOCK_READ) != 0 ? (RW_READERS(x) != 0) :
168 rw_init_flags(struct rwlock *rw, const char *name, int opts)
172 MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
174 ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
175 ("%s: rw_lock not aligned for %s: %p", __func__, name,
178 flags = LO_UPGRADABLE;
181 if (opts & RW_NOPROFILE)
182 flags |= LO_NOPROFILE;
183 if (!(opts & RW_NOWITNESS))
185 if (opts & RW_RECURSE)
186 flags |= LO_RECURSABLE;
190 rw->rw_lock = RW_UNLOCKED;
192 lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
196 rw_destroy(struct rwlock *rw)
199 KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
200 KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
201 rw->rw_lock = RW_DESTROYED;
202 lock_destroy(&rw->lock_object);
206 rw_sysinit(void *arg)
208 struct rw_args *args = arg;
210 rw_init(args->ra_rw, args->ra_desc);
214 rw_sysinit_flags(void *arg)
216 struct rw_args_flags *args = arg;
218 rw_init_flags(args->ra_rw, args->ra_desc, args->ra_flags);
222 rw_wowned(struct rwlock *rw)
225 return (rw_wowner(rw) == curthread);
229 _rw_wlock(struct rwlock *rw, const char *file, int line)
232 if (SCHEDULER_STOPPED())
234 MPASS(curthread != NULL);
235 KASSERT(rw->rw_lock != RW_DESTROYED,
236 ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
237 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
239 __rw_wlock(rw, curthread, file, line);
240 LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
241 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
242 curthread->td_locks++;
246 _rw_try_wlock(struct rwlock *rw, const char *file, int line)
250 if (SCHEDULER_STOPPED())
253 KASSERT(rw->rw_lock != RW_DESTROYED,
254 ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
256 if (rw_wlocked(rw) &&
257 (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
261 rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
262 (uintptr_t)curthread);
264 LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
266 WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
268 curthread->td_locks++;
274 _rw_wunlock(struct rwlock *rw, const char *file, int line)
277 if (SCHEDULER_STOPPED())
279 MPASS(curthread != NULL);
280 KASSERT(rw->rw_lock != RW_DESTROYED,
281 ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
282 _rw_assert(rw, RA_WLOCKED, file, line);
283 curthread->td_locks--;
284 WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
285 LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
287 if (!rw_recursed(rw))
288 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_WUNLOCK_RELEASE, rw);
289 __rw_wunlock(rw, curthread, file, line);
292 * Determines whether a new reader can acquire a lock. Succeeds if the
293 * reader already owns a read lock and the lock is locked for read to
294 * prevent deadlock from reader recursion. Also succeeds if the lock
295 * is unlocked and has no writer waiters or spinners. Failing otherwise
296 * prioritizes writers before readers.
298 #define RW_CAN_READ(_rw) \
299 ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) & \
300 (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) == \
304 _rw_rlock(struct rwlock *rw, const char *file, int line)
306 struct turnstile *ts;
307 #ifdef ADAPTIVE_RWLOCKS
308 volatile struct thread *owner;
312 #ifdef LOCK_PROFILING
313 uint64_t waittime = 0;
318 uint64_t spin_cnt = 0;
319 uint64_t sleep_cnt = 0;
320 int64_t sleep_time = 0;
323 if (SCHEDULER_STOPPED())
326 KASSERT(rw->rw_lock != RW_DESTROYED,
327 ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
328 KASSERT(rw_wowner(rw) != curthread,
329 ("%s (%s): wlock already held @ %s:%d", __func__,
330 rw->lock_object.lo_name, file, line));
331 WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
338 * Handle the easy case. If no other thread has a write
339 * lock, then try to bump up the count of read locks. Note
340 * that we have to preserve the current state of the
341 * RW_LOCK_WRITE_WAITERS flag. If we fail to acquire a
342 * read lock, then rw_lock must have changed, so restart
343 * the loop. Note that this handles the case of a
344 * completely unlocked rwlock since such a lock is encoded
345 * as a read lock with no waiters.
348 if (RW_CAN_READ(v)) {
350 * The RW_LOCK_READ_WAITERS flag should only be set
351 * if the lock has been unlocked and write waiters
354 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
355 v + RW_ONE_READER)) {
356 if (LOCK_LOG_TEST(&rw->lock_object, 0))
358 "%s: %p succeed %p -> %p", __func__,
360 (void *)(v + RW_ONE_READER));
365 lock_profile_obtain_lock_failed(&rw->lock_object,
366 &contested, &waittime);
368 #ifdef ADAPTIVE_RWLOCKS
370 * If the owner is running on another CPU, spin until
371 * the owner stops running or the state of the lock
374 if ((v & RW_LOCK_READ) == 0) {
375 owner = (struct thread *)RW_OWNER(v);
376 if (TD_IS_RUNNING(owner)) {
377 if (LOCK_LOG_TEST(&rw->lock_object, 0))
379 "%s: spinning on %p held by %p",
380 __func__, rw, owner);
381 while ((struct thread*)RW_OWNER(rw->rw_lock) ==
382 owner && TD_IS_RUNNING(owner)) {
390 } else if (spintries < ROWNER_RETRIES) {
392 for (i = 0; i < ROWNER_LOOPS; i++) {
394 if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
398 if (i != ROWNER_LOOPS)
404 * Okay, now it's the hard case. Some other thread already
405 * has a write lock or there are write waiters present,
406 * acquire the turnstile lock so we can begin the process
409 ts = turnstile_trywait(&rw->lock_object);
412 * The lock might have been released while we spun, so
413 * recheck its state and restart the loop if needed.
416 if (RW_CAN_READ(v)) {
417 turnstile_cancel(ts);
421 #ifdef ADAPTIVE_RWLOCKS
423 * The current lock owner might have started executing
424 * on another CPU (or the lock could have changed
425 * owners) while we were waiting on the turnstile
426 * chain lock. If so, drop the turnstile lock and try
429 if ((v & RW_LOCK_READ) == 0) {
430 owner = (struct thread *)RW_OWNER(v);
431 if (TD_IS_RUNNING(owner)) {
432 turnstile_cancel(ts);
439 * The lock is held in write mode or it already has waiters.
441 MPASS(!RW_CAN_READ(v));
444 * If the RW_LOCK_READ_WAITERS flag is already set, then
445 * we can go ahead and block. If it is not set then try
446 * to set it. If we fail to set it drop the turnstile
447 * lock and restart the loop.
449 if (!(v & RW_LOCK_READ_WAITERS)) {
450 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
451 v | RW_LOCK_READ_WAITERS)) {
452 turnstile_cancel(ts);
455 if (LOCK_LOG_TEST(&rw->lock_object, 0))
456 CTR2(KTR_LOCK, "%s: %p set read waiters flag",
461 * We were unable to acquire the lock and the read waiters
462 * flag is set, so we must block on the turnstile.
464 if (LOCK_LOG_TEST(&rw->lock_object, 0))
465 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
468 sleep_time -= lockstat_nsecs();
470 turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
472 sleep_time += lockstat_nsecs();
475 if (LOCK_LOG_TEST(&rw->lock_object, 0))
476 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
481 * TODO: acquire "owner of record" here. Here be turnstile dragons
482 * however. turnstiles don't like owners changing between calls to
483 * turnstile_wait() currently.
485 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
486 waittime, file, line);
487 LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
488 WITNESS_LOCK(&rw->lock_object, 0, file, line);
489 curthread->td_locks++;
490 curthread->td_rw_rlocks++;
493 LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
496 * Record only the loops spinning and not sleeping.
498 if (spin_cnt > sleep_cnt)
499 LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
504 _rw_try_rlock(struct rwlock *rw, const char *file, int line)
508 if (SCHEDULER_STOPPED())
513 KASSERT(rw->rw_lock != RW_DESTROYED,
514 ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
515 if (!(x & RW_LOCK_READ))
517 if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
518 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
520 WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
521 curthread->td_locks++;
522 curthread->td_rw_rlocks++;
527 LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
532 _rw_runlock(struct rwlock *rw, const char *file, int line)
534 struct turnstile *ts;
535 uintptr_t x, v, queue;
537 if (SCHEDULER_STOPPED())
540 KASSERT(rw->rw_lock != RW_DESTROYED,
541 ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
542 _rw_assert(rw, RA_RLOCKED, file, line);
543 curthread->td_locks--;
544 curthread->td_rw_rlocks--;
545 WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
546 LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
548 /* TODO: drop "owner of record" here. */
552 * See if there is more than one read lock held. If so,
553 * just drop one and return.
556 if (RW_READERS(x) > 1) {
557 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
558 x - RW_ONE_READER)) {
559 if (LOCK_LOG_TEST(&rw->lock_object, 0))
561 "%s: %p succeeded %p -> %p",
562 __func__, rw, (void *)x,
563 (void *)(x - RW_ONE_READER));
569 * If there aren't any waiters for a write lock, then try
570 * to drop it quickly.
572 if (!(x & RW_LOCK_WAITERS)) {
573 MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
575 if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
577 if (LOCK_LOG_TEST(&rw->lock_object, 0))
578 CTR2(KTR_LOCK, "%s: %p last succeeded",
585 * Ok, we know we have waiters and we think we are the
586 * last reader, so grab the turnstile lock.
588 turnstile_chain_lock(&rw->lock_object);
589 v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
590 MPASS(v & RW_LOCK_WAITERS);
593 * Try to drop our lock leaving the lock in a unlocked
596 * If you wanted to do explicit lock handoff you'd have to
597 * do it here. You'd also want to use turnstile_signal()
598 * and you'd have to handle the race where a higher
599 * priority thread blocks on the write lock before the
600 * thread you wakeup actually runs and have the new thread
601 * "steal" the lock. For now it's a lot simpler to just
602 * wakeup all of the waiters.
604 * As above, if we fail, then another thread might have
605 * acquired a read lock, so drop the turnstile lock and
609 if (v & RW_LOCK_WRITE_WAITERS) {
610 queue = TS_EXCLUSIVE_QUEUE;
611 x |= (v & RW_LOCK_READ_WAITERS);
613 queue = TS_SHARED_QUEUE;
614 if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
616 turnstile_chain_unlock(&rw->lock_object);
619 if (LOCK_LOG_TEST(&rw->lock_object, 0))
620 CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
624 * Ok. The lock is released and all that's left is to
625 * wake up the waiters. Note that the lock might not be
626 * free anymore, but in that case the writers will just
627 * block again if they run before the new lock holder(s)
630 ts = turnstile_lookup(&rw->lock_object);
632 turnstile_broadcast(ts, queue);
633 turnstile_unpend(ts, TS_SHARED_LOCK);
634 turnstile_chain_unlock(&rw->lock_object);
637 LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
641 * This function is called when we are unable to obtain a write lock on the
642 * first try. This means that at least one other thread holds either a
643 * read or write lock.
646 _rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
648 struct turnstile *ts;
649 #ifdef ADAPTIVE_RWLOCKS
650 volatile struct thread *owner;
655 #ifdef LOCK_PROFILING
656 uint64_t waittime = 0;
660 uint64_t spin_cnt = 0;
661 uint64_t sleep_cnt = 0;
662 int64_t sleep_time = 0;
665 if (SCHEDULER_STOPPED())
668 if (rw_wlocked(rw)) {
669 KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
670 ("%s: recursing but non-recursive rw %s @ %s:%d\n",
671 __func__, rw->lock_object.lo_name, file, line));
673 if (LOCK_LOG_TEST(&rw->lock_object, 0))
674 CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
678 if (LOCK_LOG_TEST(&rw->lock_object, 0))
679 CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
680 rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
682 while (!_rw_write_lock(rw, tid)) {
686 lock_profile_obtain_lock_failed(&rw->lock_object,
687 &contested, &waittime);
688 #ifdef ADAPTIVE_RWLOCKS
690 * If the lock is write locked and the owner is
691 * running on another CPU, spin until the owner stops
692 * running or the state of the lock changes.
695 owner = (struct thread *)RW_OWNER(v);
696 if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
697 if (LOCK_LOG_TEST(&rw->lock_object, 0))
698 CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
699 __func__, rw, owner);
700 while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
701 TD_IS_RUNNING(owner)) {
709 if ((v & RW_LOCK_READ) && RW_READERS(v) &&
710 spintries < ROWNER_RETRIES) {
711 if (!(v & RW_LOCK_WRITE_SPINNER)) {
712 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
713 v | RW_LOCK_WRITE_SPINNER)) {
718 for (i = 0; i < ROWNER_LOOPS; i++) {
719 if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
724 spin_cnt += ROWNER_LOOPS - i;
726 if (i != ROWNER_LOOPS)
730 ts = turnstile_trywait(&rw->lock_object);
733 #ifdef ADAPTIVE_RWLOCKS
735 * The current lock owner might have started executing
736 * on another CPU (or the lock could have changed
737 * owners) while we were waiting on the turnstile
738 * chain lock. If so, drop the turnstile lock and try
741 if (!(v & RW_LOCK_READ)) {
742 owner = (struct thread *)RW_OWNER(v);
743 if (TD_IS_RUNNING(owner)) {
744 turnstile_cancel(ts);
750 * Check for the waiters flags about this rwlock.
751 * If the lock was released, without maintain any pending
752 * waiters queue, simply try to acquire it.
753 * If a pending waiters queue is present, claim the lock
754 * ownership and maintain the pending queue.
756 x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
757 if ((v & ~x) == RW_UNLOCKED) {
758 x &= ~RW_LOCK_WRITE_SPINNER;
759 if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
763 turnstile_cancel(ts);
766 turnstile_cancel(ts);
770 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
771 * set it. If we fail to set it, then loop back and try
774 if (!(v & RW_LOCK_WRITE_WAITERS)) {
775 if (!atomic_cmpset_ptr(&rw->rw_lock, v,
776 v | RW_LOCK_WRITE_WAITERS)) {
777 turnstile_cancel(ts);
780 if (LOCK_LOG_TEST(&rw->lock_object, 0))
781 CTR2(KTR_LOCK, "%s: %p set write waiters flag",
785 * We were unable to acquire the lock and the write waiters
786 * flag is set, so we must block on the turnstile.
788 if (LOCK_LOG_TEST(&rw->lock_object, 0))
789 CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
792 sleep_time -= lockstat_nsecs();
794 turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
796 sleep_time += lockstat_nsecs();
799 if (LOCK_LOG_TEST(&rw->lock_object, 0))
800 CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
802 #ifdef ADAPTIVE_RWLOCKS
806 LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
807 waittime, file, line);
810 LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
813 * Record only the loops spinning and not sleeping.
815 if (spin_cnt > sleep_cnt)
816 LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
821 * This function is called if the first try at releasing a write lock failed.
822 * This means that one of the 2 waiter bits must be set indicating that at
823 * least one thread is waiting on this lock.
826 _rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
828 struct turnstile *ts;
832 if (SCHEDULER_STOPPED())
835 if (rw_wlocked(rw) && rw_recursed(rw)) {
837 if (LOCK_LOG_TEST(&rw->lock_object, 0))
838 CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
842 KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
843 ("%s: neither of the waiter flags are set", __func__));
845 if (LOCK_LOG_TEST(&rw->lock_object, 0))
846 CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
848 turnstile_chain_lock(&rw->lock_object);
849 ts = turnstile_lookup(&rw->lock_object);
853 * Use the same algo as sx locks for now. Prefer waking up shared
854 * waiters if we have any over writers. This is probably not ideal.
856 * 'v' is the value we are going to write back to rw_lock. If we
857 * have waiters on both queues, we need to preserve the state of
858 * the waiter flag for the queue we don't wake up. For now this is
859 * hardcoded for the algorithm mentioned above.
861 * In the case of both readers and writers waiting we wakeup the
862 * readers but leave the RW_LOCK_WRITE_WAITERS flag set. If a
863 * new writer comes in before a reader it will claim the lock up
864 * above. There is probably a potential priority inversion in
865 * there that could be worked around either by waking both queues
866 * of waiters or doing some complicated lock handoff gymnastics.
869 if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
870 queue = TS_EXCLUSIVE_QUEUE;
871 v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
873 queue = TS_SHARED_QUEUE;
875 /* Wake up all waiters for the specific queue. */
876 if (LOCK_LOG_TEST(&rw->lock_object, 0))
877 CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
878 queue == TS_SHARED_QUEUE ? "read" : "write");
879 turnstile_broadcast(ts, queue);
880 atomic_store_rel_ptr(&rw->rw_lock, v);
881 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
882 turnstile_chain_unlock(&rw->lock_object);
886 * Attempt to do a non-blocking upgrade from a read lock to a write
887 * lock. This will only succeed if this thread holds a single read
888 * lock. Returns true if the upgrade succeeded and false otherwise.
891 _rw_try_upgrade(struct rwlock *rw, const char *file, int line)
894 struct turnstile *ts;
897 if (SCHEDULER_STOPPED())
900 KASSERT(rw->rw_lock != RW_DESTROYED,
901 ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
902 _rw_assert(rw, RA_RLOCKED, file, line);
905 * Attempt to switch from one reader to a writer. If there
906 * are any write waiters, then we will have to lock the
907 * turnstile first to prevent races with another writer
908 * calling turnstile_wait() before we have claimed this
909 * turnstile. So, do the simple case of no waiters first.
911 tid = (uintptr_t)curthread;
915 if (RW_READERS(v) > 1)
917 if (!(v & RW_LOCK_WAITERS)) {
918 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
925 * Ok, we think we have waiters, so lock the turnstile.
927 ts = turnstile_trywait(&rw->lock_object);
929 if (RW_READERS(v) > 1) {
930 turnstile_cancel(ts);
934 * Try to switch from one reader to a writer again. This time
935 * we honor the current state of the waiters flags.
936 * If we obtain the lock with the flags set, then claim
937 * ownership of the turnstile.
939 x = rw->rw_lock & RW_LOCK_WAITERS;
940 success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
945 turnstile_cancel(ts);
948 turnstile_cancel(ts);
950 LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
952 curthread->td_rw_rlocks--;
953 WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
955 LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
961 * Downgrade a write lock into a single read lock.
964 _rw_downgrade(struct rwlock *rw, const char *file, int line)
966 struct turnstile *ts;
970 if (SCHEDULER_STOPPED())
973 KASSERT(rw->rw_lock != RW_DESTROYED,
974 ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
975 _rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
978 panic("downgrade of a recursed lock");
981 WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
984 * Convert from a writer to a single reader. First we handle
985 * the easy case with no waiters. If there are any waiters, we
986 * lock the turnstile and "disown" the lock.
988 tid = (uintptr_t)curthread;
989 if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
993 * Ok, we think we have waiters, so lock the turnstile so we can
994 * read the waiter flags without any races.
996 turnstile_chain_lock(&rw->lock_object);
997 v = rw->rw_lock & RW_LOCK_WAITERS;
998 rwait = v & RW_LOCK_READ_WAITERS;
999 wwait = v & RW_LOCK_WRITE_WAITERS;
1000 MPASS(rwait | wwait);
1003 * Downgrade from a write lock while preserving waiters flag
1004 * and give up ownership of the turnstile.
1006 ts = turnstile_lookup(&rw->lock_object);
1009 v &= ~RW_LOCK_READ_WAITERS;
1010 atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1012 * Wake other readers if there are no writers pending. Otherwise they
1013 * won't be able to acquire the lock anyway.
1015 if (rwait && !wwait) {
1016 turnstile_broadcast(ts, TS_SHARED_QUEUE);
1017 turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1019 turnstile_disown(ts);
1020 turnstile_chain_unlock(&rw->lock_object);
1022 curthread->td_rw_rlocks++;
1023 LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1024 LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1027 #ifdef INVARIANT_SUPPORT
1033 * In the non-WITNESS case, rw_assert() can only detect that at least
1034 * *some* thread owns an rlock, but it cannot guarantee that *this*
1035 * thread owns an rlock.
1038 _rw_assert(struct rwlock *rw, int what, const char *file, int line)
1041 if (panicstr != NULL)
1045 case RA_LOCKED | RA_RECURSED:
1046 case RA_LOCKED | RA_NOTRECURSED:
1049 witness_assert(&rw->lock_object, what, file, line);
1052 * If some other thread has a write lock or we have one
1053 * and are asserting a read lock, fail. Also, if no one
1054 * has a lock at all, fail.
1056 if (rw->rw_lock == RW_UNLOCKED ||
1057 (!(rw->rw_lock & RW_LOCK_READ) && (what == RA_RLOCKED ||
1058 rw_wowner(rw) != curthread)))
1059 panic("Lock %s not %slocked @ %s:%d\n",
1060 rw->lock_object.lo_name, (what == RA_RLOCKED) ?
1061 "read " : "", file, line);
1063 if (!(rw->rw_lock & RW_LOCK_READ)) {
1064 if (rw_recursed(rw)) {
1065 if (what & RA_NOTRECURSED)
1066 panic("Lock %s recursed @ %s:%d\n",
1067 rw->lock_object.lo_name, file,
1069 } else if (what & RA_RECURSED)
1070 panic("Lock %s not recursed @ %s:%d\n",
1071 rw->lock_object.lo_name, file, line);
1076 case RA_WLOCKED | RA_RECURSED:
1077 case RA_WLOCKED | RA_NOTRECURSED:
1078 if (rw_wowner(rw) != curthread)
1079 panic("Lock %s not exclusively locked @ %s:%d\n",
1080 rw->lock_object.lo_name, file, line);
1081 if (rw_recursed(rw)) {
1082 if (what & RA_NOTRECURSED)
1083 panic("Lock %s recursed @ %s:%d\n",
1084 rw->lock_object.lo_name, file, line);
1085 } else if (what & RA_RECURSED)
1086 panic("Lock %s not recursed @ %s:%d\n",
1087 rw->lock_object.lo_name, file, line);
1091 witness_assert(&rw->lock_object, what, file, line);
1094 * If we hold a write lock fail. We can't reliably check
1095 * to see if we hold a read lock or not.
1097 if (rw_wowner(rw) == curthread)
1098 panic("Lock %s exclusively locked @ %s:%d\n",
1099 rw->lock_object.lo_name, file, line);
1103 panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1107 #endif /* INVARIANT_SUPPORT */
1111 db_show_rwlock(struct lock_object *lock)
1116 rw = (struct rwlock *)lock;
1118 db_printf(" state: ");
1119 if (rw->rw_lock == RW_UNLOCKED)
1120 db_printf("UNLOCKED\n");
1121 else if (rw->rw_lock == RW_DESTROYED) {
1122 db_printf("DESTROYED\n");
1124 } else if (rw->rw_lock & RW_LOCK_READ)
1125 db_printf("RLOCK: %ju locks\n",
1126 (uintmax_t)(RW_READERS(rw->rw_lock)));
1129 db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1130 td->td_tid, td->td_proc->p_pid, td->td_name);
1131 if (rw_recursed(rw))
1132 db_printf(" recursed: %u\n", rw->rw_recurse);
1134 db_printf(" waiters: ");
1135 switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1136 case RW_LOCK_READ_WAITERS:
1137 db_printf("readers\n");
1139 case RW_LOCK_WRITE_WAITERS:
1140 db_printf("writers\n");
1142 case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1143 db_printf("readers and writers\n");
1146 db_printf("none\n");