xref: /freebsd/sys/kern/kern_rwlock.c (revision 5bf5ca772c6de2d53344a78cf461447cc322ccea)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 /*
30  * Machine independent bits of reader/writer lock implementation.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_ddb.h"
37 #include "opt_hwpmc_hooks.h"
38 #include "opt_no_adaptive_rwlocks.h"
39 
40 #include <sys/param.h>
41 #include <sys/kdb.h>
42 #include <sys/ktr.h>
43 #include <sys/kernel.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/proc.h>
47 #include <sys/rwlock.h>
48 #include <sys/sched.h>
49 #include <sys/smp.h>
50 #include <sys/sysctl.h>
51 #include <sys/systm.h>
52 #include <sys/turnstile.h>
53 
54 #include <machine/cpu.h>
55 
56 #if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
57 #define	ADAPTIVE_RWLOCKS
58 #endif
59 
60 #ifdef HWPMC_HOOKS
61 #include <sys/pmckern.h>
62 PMC_SOFT_DECLARE( , , lock, failed);
63 #endif
64 
65 /*
66  * Return the rwlock address when the lock cookie address is provided.
67  * This functionality assumes that struct rwlock* have a member named rw_lock.
68  */
69 #define	rwlock2rw(c)	(__containerof(c, struct rwlock, rw_lock))
70 
71 #ifdef DDB
72 #include <ddb/ddb.h>
73 
74 static void	db_show_rwlock(const struct lock_object *lock);
75 #endif
76 static void	assert_rw(const struct lock_object *lock, int what);
77 static void	lock_rw(struct lock_object *lock, uintptr_t how);
78 #ifdef KDTRACE_HOOKS
79 static int	owner_rw(const struct lock_object *lock, struct thread **owner);
80 #endif
81 static uintptr_t unlock_rw(struct lock_object *lock);
82 
83 struct lock_class lock_class_rw = {
84 	.lc_name = "rw",
85 	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
86 	.lc_assert = assert_rw,
87 #ifdef DDB
88 	.lc_ddb_show = db_show_rwlock,
89 #endif
90 	.lc_lock = lock_rw,
91 	.lc_unlock = unlock_rw,
92 #ifdef KDTRACE_HOOKS
93 	.lc_owner = owner_rw,
94 #endif
95 };
96 
97 #ifdef ADAPTIVE_RWLOCKS
98 static int __read_frequently rowner_retries = 10;
99 static int __read_frequently rowner_loops = 10000;
100 static SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL,
101     "rwlock debugging");
102 SYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
103 SYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
104 
105 static struct lock_delay_config __read_frequently rw_delay;
106 
107 SYSCTL_INT(_debug_rwlock, OID_AUTO, delay_base, CTLFLAG_RW, &rw_delay.base,
108     0, "");
109 SYSCTL_INT(_debug_rwlock, OID_AUTO, delay_max, CTLFLAG_RW, &rw_delay.max,
110     0, "");
111 
112 LOCK_DELAY_SYSINIT_DEFAULT(rw_delay);
113 #endif
114 
115 /*
116  * Return a pointer to the owning thread if the lock is write-locked or
117  * NULL if the lock is unlocked or read-locked.
118  */
119 
120 #define	lv_rw_wowner(v)							\
121 	((v) & RW_LOCK_READ ? NULL :					\
122 	 (struct thread *)RW_OWNER((v)))
123 
124 #define	rw_wowner(rw)	lv_rw_wowner(RW_READ_VALUE(rw))
125 
126 /*
127  * Returns if a write owner is recursed.  Write ownership is not assured
128  * here and should be previously checked.
129  */
130 #define	rw_recursed(rw)		((rw)->rw_recurse != 0)
131 
132 /*
133  * Return true if curthread helds the lock.
134  */
135 #define	rw_wlocked(rw)		(rw_wowner((rw)) == curthread)
136 
137 /*
138  * Return a pointer to the owning thread for this lock who should receive
139  * any priority lent by threads that block on this lock.  Currently this
140  * is identical to rw_wowner().
141  */
142 #define	rw_owner(rw)		rw_wowner(rw)
143 
144 #ifndef INVARIANTS
145 #define	__rw_assert(c, what, file, line)
146 #endif
147 
148 void
149 assert_rw(const struct lock_object *lock, int what)
150 {
151 
152 	rw_assert((const struct rwlock *)lock, what);
153 }
154 
155 void
156 lock_rw(struct lock_object *lock, uintptr_t how)
157 {
158 	struct rwlock *rw;
159 
160 	rw = (struct rwlock *)lock;
161 	if (how)
162 		rw_rlock(rw);
163 	else
164 		rw_wlock(rw);
165 }
166 
167 uintptr_t
168 unlock_rw(struct lock_object *lock)
169 {
170 	struct rwlock *rw;
171 
172 	rw = (struct rwlock *)lock;
173 	rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
174 	if (rw->rw_lock & RW_LOCK_READ) {
175 		rw_runlock(rw);
176 		return (1);
177 	} else {
178 		rw_wunlock(rw);
179 		return (0);
180 	}
181 }
182 
183 #ifdef KDTRACE_HOOKS
184 int
185 owner_rw(const struct lock_object *lock, struct thread **owner)
186 {
187 	const struct rwlock *rw = (const struct rwlock *)lock;
188 	uintptr_t x = rw->rw_lock;
189 
190 	*owner = rw_wowner(rw);
191 	return ((x & RW_LOCK_READ) != 0 ?  (RW_READERS(x) != 0) :
192 	    (*owner != NULL));
193 }
194 #endif
195 
196 void
197 _rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
198 {
199 	struct rwlock *rw;
200 	int flags;
201 
202 	rw = rwlock2rw(c);
203 
204 	MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
205 	    RW_RECURSE | RW_NEW)) == 0);
206 	ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
207 	    ("%s: rw_lock not aligned for %s: %p", __func__, name,
208 	    &rw->rw_lock));
209 
210 	flags = LO_UPGRADABLE;
211 	if (opts & RW_DUPOK)
212 		flags |= LO_DUPOK;
213 	if (opts & RW_NOPROFILE)
214 		flags |= LO_NOPROFILE;
215 	if (!(opts & RW_NOWITNESS))
216 		flags |= LO_WITNESS;
217 	if (opts & RW_RECURSE)
218 		flags |= LO_RECURSABLE;
219 	if (opts & RW_QUIET)
220 		flags |= LO_QUIET;
221 	if (opts & RW_NEW)
222 		flags |= LO_NEW;
223 
224 	lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
225 	rw->rw_lock = RW_UNLOCKED;
226 	rw->rw_recurse = 0;
227 }
228 
229 void
230 _rw_destroy(volatile uintptr_t *c)
231 {
232 	struct rwlock *rw;
233 
234 	rw = rwlock2rw(c);
235 
236 	KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
237 	KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
238 	rw->rw_lock = RW_DESTROYED;
239 	lock_destroy(&rw->lock_object);
240 }
241 
242 void
243 rw_sysinit(void *arg)
244 {
245 	struct rw_args *args;
246 
247 	args = arg;
248 	rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
249 	    args->ra_flags);
250 }
251 
252 int
253 _rw_wowned(const volatile uintptr_t *c)
254 {
255 
256 	return (rw_wowner(rwlock2rw(c)) == curthread);
257 }
258 
259 void
260 _rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
261 {
262 	struct rwlock *rw;
263 	uintptr_t tid, v;
264 
265 	rw = rwlock2rw(c);
266 
267 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED() ||
268 	    !TD_IS_IDLETHREAD(curthread),
269 	    ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
270 	    curthread, rw->lock_object.lo_name, file, line));
271 	KASSERT(rw->rw_lock != RW_DESTROYED,
272 	    ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
273 	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
274 	    line, NULL);
275 	tid = (uintptr_t)curthread;
276 	v = RW_UNLOCKED;
277 	if (!_rw_write_lock_fetch(rw, &v, tid))
278 		_rw_wlock_hard(rw, v, file, line);
279 	else
280 		LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw,
281 		    0, 0, file, line, LOCKSTAT_WRITER);
282 
283 	LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
284 	WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
285 	TD_LOCKS_INC(curthread);
286 }
287 
288 int
289 __rw_try_wlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
290 {
291 	struct thread *td;
292 	uintptr_t tid, v;
293 	int rval;
294 	bool recursed;
295 
296 	td = curthread;
297 	tid = (uintptr_t)td;
298 	if (SCHEDULER_STOPPED_TD(td))
299 		return (1);
300 
301 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(td),
302 	    ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
303 	    curthread, rw->lock_object.lo_name, file, line));
304 	KASSERT(rw->rw_lock != RW_DESTROYED,
305 	    ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
306 
307 	rval = 1;
308 	recursed = false;
309 	v = RW_UNLOCKED;
310 	for (;;) {
311 		if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
312 			break;
313 		if (v == RW_UNLOCKED)
314 			continue;
315 		if (v == tid && (rw->lock_object.lo_flags & LO_RECURSABLE)) {
316 			rw->rw_recurse++;
317 			atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
318 			break;
319 		}
320 		rval = 0;
321 		break;
322 	}
323 
324 	LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
325 	if (rval) {
326 		WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
327 		    file, line);
328 		if (!recursed)
329 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
330 			    rw, 0, 0, file, line, LOCKSTAT_WRITER);
331 		TD_LOCKS_INC(curthread);
332 	}
333 	return (rval);
334 }
335 
336 int
337 __rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
338 {
339 	struct rwlock *rw;
340 
341 	rw = rwlock2rw(c);
342 	return (__rw_try_wlock_int(rw LOCK_FILE_LINE_ARG));
343 }
344 
345 void
346 _rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
347 {
348 	struct rwlock *rw;
349 
350 	rw = rwlock2rw(c);
351 
352 	KASSERT(rw->rw_lock != RW_DESTROYED,
353 	    ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
354 	__rw_assert(c, RA_WLOCKED, file, line);
355 	WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
356 	LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
357 	    line);
358 
359 #ifdef LOCK_PROFILING
360 	_rw_wunlock_hard(rw, (uintptr_t)curthread, file, line);
361 #else
362 	__rw_wunlock(rw, curthread, file, line);
363 #endif
364 
365 	TD_LOCKS_DEC(curthread);
366 }
367 
368 /*
369  * Determines whether a new reader can acquire a lock.  Succeeds if the
370  * reader already owns a read lock and the lock is locked for read to
371  * prevent deadlock from reader recursion.  Also succeeds if the lock
372  * is unlocked and has no writer waiters or spinners.  Failing otherwise
373  * prioritizes writers before readers.
374  */
375 static bool __always_inline
376 __rw_can_read(struct thread *td, uintptr_t v, bool fp)
377 {
378 
379 	if ((v & (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER))
380 	    == RW_LOCK_READ)
381 		return (true);
382 	if (!fp && td->td_rw_rlocks && (v & RW_LOCK_READ))
383 		return (true);
384 	return (false);
385 }
386 
387 static bool __always_inline
388 __rw_rlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp, bool fp
389     LOCK_FILE_LINE_ARG_DEF)
390 {
391 
392 	/*
393 	 * Handle the easy case.  If no other thread has a write
394 	 * lock, then try to bump up the count of read locks.  Note
395 	 * that we have to preserve the current state of the
396 	 * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
397 	 * read lock, then rw_lock must have changed, so restart
398 	 * the loop.  Note that this handles the case of a
399 	 * completely unlocked rwlock since such a lock is encoded
400 	 * as a read lock with no waiters.
401 	 */
402 	while (__rw_can_read(td, *vp, fp)) {
403 		if (atomic_fcmpset_acq_ptr(&rw->rw_lock, vp,
404 			*vp + RW_ONE_READER)) {
405 			if (LOCK_LOG_TEST(&rw->lock_object, 0))
406 				CTR4(KTR_LOCK,
407 				    "%s: %p succeed %p -> %p", __func__,
408 				    rw, (void *)*vp,
409 				    (void *)(*vp + RW_ONE_READER));
410 			td->td_rw_rlocks++;
411 			return (true);
412 		}
413 	}
414 	return (false);
415 }
416 
417 static void __noinline
418 __rw_rlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
419     LOCK_FILE_LINE_ARG_DEF)
420 {
421 	struct turnstile *ts;
422 	struct thread *owner;
423 #ifdef ADAPTIVE_RWLOCKS
424 	int spintries = 0;
425 	int i, n;
426 #endif
427 #ifdef LOCK_PROFILING
428 	uint64_t waittime = 0;
429 	int contested = 0;
430 #endif
431 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
432 	struct lock_delay_arg lda;
433 #endif
434 #ifdef KDTRACE_HOOKS
435 	u_int sleep_cnt = 0;
436 	int64_t sleep_time = 0;
437 	int64_t all_time = 0;
438 #endif
439 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
440 	uintptr_t state;
441 	int doing_lockprof;
442 #endif
443 
444 	if (SCHEDULER_STOPPED())
445 		return;
446 
447 #if defined(ADAPTIVE_RWLOCKS)
448 	lock_delay_arg_init(&lda, &rw_delay);
449 #elif defined(KDTRACE_HOOKS)
450 	lock_delay_arg_init(&lda, NULL);
451 #endif
452 
453 #ifdef HWPMC_HOOKS
454 	PMC_SOFT_CALL( , , lock, failed);
455 #endif
456 	lock_profile_obtain_lock_failed(&rw->lock_object,
457 	    &contested, &waittime);
458 
459 #ifdef LOCK_PROFILING
460 	doing_lockprof = 1;
461 	state = v;
462 #elif defined(KDTRACE_HOOKS)
463 	doing_lockprof = lockstat_enabled;
464 	if (__predict_false(doing_lockprof)) {
465 		all_time -= lockstat_nsecs(&rw->lock_object);
466 		state = v;
467 	}
468 #endif
469 
470 	for (;;) {
471 		if (__rw_rlock_try(rw, td, &v, false LOCK_FILE_LINE_ARG))
472 			break;
473 #ifdef KDTRACE_HOOKS
474 		lda.spin_cnt++;
475 #endif
476 
477 #ifdef ADAPTIVE_RWLOCKS
478 		/*
479 		 * If the owner is running on another CPU, spin until
480 		 * the owner stops running or the state of the lock
481 		 * changes.
482 		 */
483 		if ((v & RW_LOCK_READ) == 0) {
484 			owner = (struct thread *)RW_OWNER(v);
485 			if (TD_IS_RUNNING(owner)) {
486 				if (LOCK_LOG_TEST(&rw->lock_object, 0))
487 					CTR3(KTR_LOCK,
488 					    "%s: spinning on %p held by %p",
489 					    __func__, rw, owner);
490 				KTR_STATE1(KTR_SCHED, "thread",
491 				    sched_tdname(curthread), "spinning",
492 				    "lockname:\"%s\"", rw->lock_object.lo_name);
493 				do {
494 					lock_delay(&lda);
495 					v = RW_READ_VALUE(rw);
496 					owner = lv_rw_wowner(v);
497 				} while (owner != NULL && TD_IS_RUNNING(owner));
498 				KTR_STATE0(KTR_SCHED, "thread",
499 				    sched_tdname(curthread), "running");
500 				continue;
501 			}
502 		} else if (spintries < rowner_retries) {
503 			spintries++;
504 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
505 			    "spinning", "lockname:\"%s\"",
506 			    rw->lock_object.lo_name);
507 			for (i = 0; i < rowner_loops; i += n) {
508 				n = RW_READERS(v);
509 				lock_delay_spin(n);
510 				v = RW_READ_VALUE(rw);
511 				if ((v & RW_LOCK_READ) == 0 || __rw_can_read(td, v, false))
512 					break;
513 			}
514 #ifdef KDTRACE_HOOKS
515 			lda.spin_cnt += rowner_loops - i;
516 #endif
517 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
518 			    "running");
519 			if (i < rowner_loops)
520 				continue;
521 		}
522 #endif
523 
524 		/*
525 		 * Okay, now it's the hard case.  Some other thread already
526 		 * has a write lock or there are write waiters present,
527 		 * acquire the turnstile lock so we can begin the process
528 		 * of blocking.
529 		 */
530 		ts = turnstile_trywait(&rw->lock_object);
531 
532 		/*
533 		 * The lock might have been released while we spun, so
534 		 * recheck its state and restart the loop if needed.
535 		 */
536 		v = RW_READ_VALUE(rw);
537 retry_ts:
538 		if (__rw_can_read(td, v, false)) {
539 			turnstile_cancel(ts);
540 			continue;
541 		}
542 
543 		owner = lv_rw_wowner(v);
544 
545 #ifdef ADAPTIVE_RWLOCKS
546 		/*
547 		 * The current lock owner might have started executing
548 		 * on another CPU (or the lock could have changed
549 		 * owners) while we were waiting on the turnstile
550 		 * chain lock.  If so, drop the turnstile lock and try
551 		 * again.
552 		 */
553 		if (owner != NULL) {
554 			if (TD_IS_RUNNING(owner)) {
555 				turnstile_cancel(ts);
556 				continue;
557 			}
558 		}
559 #endif
560 
561 		/*
562 		 * The lock is held in write mode or it already has waiters.
563 		 */
564 		MPASS(!__rw_can_read(td, v, false));
565 
566 		/*
567 		 * If the RW_LOCK_READ_WAITERS flag is already set, then
568 		 * we can go ahead and block.  If it is not set then try
569 		 * to set it.  If we fail to set it drop the turnstile
570 		 * lock and restart the loop.
571 		 */
572 		if (!(v & RW_LOCK_READ_WAITERS)) {
573 			if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
574 			    v | RW_LOCK_READ_WAITERS))
575 				goto retry_ts;
576 			if (LOCK_LOG_TEST(&rw->lock_object, 0))
577 				CTR2(KTR_LOCK, "%s: %p set read waiters flag",
578 				    __func__, rw);
579 		}
580 
581 		/*
582 		 * We were unable to acquire the lock and the read waiters
583 		 * flag is set, so we must block on the turnstile.
584 		 */
585 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
586 			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
587 			    rw);
588 #ifdef KDTRACE_HOOKS
589 		sleep_time -= lockstat_nsecs(&rw->lock_object);
590 #endif
591 		MPASS(owner == rw_owner(rw));
592 		turnstile_wait(ts, owner, TS_SHARED_QUEUE);
593 #ifdef KDTRACE_HOOKS
594 		sleep_time += lockstat_nsecs(&rw->lock_object);
595 		sleep_cnt++;
596 #endif
597 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
598 			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
599 			    __func__, rw);
600 		v = RW_READ_VALUE(rw);
601 	}
602 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
603 	if (__predict_true(!doing_lockprof))
604 		return;
605 #endif
606 #ifdef KDTRACE_HOOKS
607 	all_time += lockstat_nsecs(&rw->lock_object);
608 	if (sleep_time)
609 		LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
610 		    LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
611 		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
612 
613 	/* Record only the loops spinning and not sleeping. */
614 	if (lda.spin_cnt > sleep_cnt)
615 		LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
616 		    LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
617 		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
618 #endif
619 	/*
620 	 * TODO: acquire "owner of record" here.  Here be turnstile dragons
621 	 * however.  turnstiles don't like owners changing between calls to
622 	 * turnstile_wait() currently.
623 	 */
624 	LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
625 	    waittime, file, line, LOCKSTAT_READER);
626 }
627 
628 void
629 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
630 {
631 	struct thread *td;
632 	uintptr_t v;
633 
634 	td = curthread;
635 
636 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
637 	    !TD_IS_IDLETHREAD(td),
638 	    ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
639 	    td, rw->lock_object.lo_name, file, line));
640 	KASSERT(rw->rw_lock != RW_DESTROYED,
641 	    ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
642 	KASSERT(rw_wowner(rw) != td,
643 	    ("rw_rlock: wlock already held for %s @ %s:%d",
644 	    rw->lock_object.lo_name, file, line));
645 	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
646 
647 	v = RW_READ_VALUE(rw);
648 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__acquire) ||
649 	    !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
650 		__rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
651 	else
652 		lock_profile_obtain_lock_success(&rw->lock_object, 0, 0,
653 		    file, line);
654 
655 	LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
656 	WITNESS_LOCK(&rw->lock_object, 0, file, line);
657 	TD_LOCKS_INC(curthread);
658 }
659 
660 void
661 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
662 {
663 	struct rwlock *rw;
664 
665 	rw = rwlock2rw(c);
666 	__rw_rlock_int(rw LOCK_FILE_LINE_ARG);
667 }
668 
669 int
670 __rw_try_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
671 {
672 	uintptr_t x;
673 
674 	if (SCHEDULER_STOPPED())
675 		return (1);
676 
677 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
678 	    ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
679 	    curthread, rw->lock_object.lo_name, file, line));
680 
681 	x = rw->rw_lock;
682 	for (;;) {
683 		KASSERT(rw->rw_lock != RW_DESTROYED,
684 		    ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
685 		if (!(x & RW_LOCK_READ))
686 			break;
687 		if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
688 			LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
689 			    line);
690 			WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
691 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
692 			    rw, 0, 0, file, line, LOCKSTAT_READER);
693 			TD_LOCKS_INC(curthread);
694 			curthread->td_rw_rlocks++;
695 			return (1);
696 		}
697 	}
698 
699 	LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
700 	return (0);
701 }
702 
703 int
704 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
705 {
706 	struct rwlock *rw;
707 
708 	rw = rwlock2rw(c);
709 	return (__rw_try_rlock_int(rw LOCK_FILE_LINE_ARG));
710 }
711 
712 static bool __always_inline
713 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
714 {
715 
716 	for (;;) {
717 		/*
718 		 * See if there is more than one read lock held.  If so,
719 		 * just drop one and return.
720 		 */
721 		if (RW_READERS(*vp) > 1) {
722 			if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
723 			    *vp - RW_ONE_READER)) {
724 				if (LOCK_LOG_TEST(&rw->lock_object, 0))
725 					CTR4(KTR_LOCK,
726 					    "%s: %p succeeded %p -> %p",
727 					    __func__, rw, (void *)*vp,
728 					    (void *)(*vp - RW_ONE_READER));
729 				td->td_rw_rlocks--;
730 				return (true);
731 			}
732 			continue;
733 		}
734 		/*
735 		 * If there aren't any waiters for a write lock, then try
736 		 * to drop it quickly.
737 		 */
738 		if (!(*vp & RW_LOCK_WAITERS)) {
739 			MPASS((*vp & ~RW_LOCK_WRITE_SPINNER) ==
740 			    RW_READERS_LOCK(1));
741 			if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
742 			    RW_UNLOCKED)) {
743 				if (LOCK_LOG_TEST(&rw->lock_object, 0))
744 					CTR2(KTR_LOCK, "%s: %p last succeeded",
745 					    __func__, rw);
746 				td->td_rw_rlocks--;
747 				return (true);
748 			}
749 			continue;
750 		}
751 		break;
752 	}
753 	return (false);
754 }
755 
756 static void __noinline
757 __rw_runlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
758     LOCK_FILE_LINE_ARG_DEF)
759 {
760 	struct turnstile *ts;
761 	uintptr_t setv, queue;
762 
763 	if (SCHEDULER_STOPPED())
764 		return;
765 
766 	if (__rw_runlock_try(rw, td, &v))
767 		goto out_lockstat;
768 
769 	/*
770 	 * Ok, we know we have waiters and we think we are the
771 	 * last reader, so grab the turnstile lock.
772 	 */
773 	turnstile_chain_lock(&rw->lock_object);
774 	v = RW_READ_VALUE(rw);
775 	for (;;) {
776 		if (__rw_runlock_try(rw, td, &v))
777 			break;
778 
779 		v &= (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
780 		MPASS(v & RW_LOCK_WAITERS);
781 
782 		/*
783 		 * Try to drop our lock leaving the lock in a unlocked
784 		 * state.
785 		 *
786 		 * If you wanted to do explicit lock handoff you'd have to
787 		 * do it here.  You'd also want to use turnstile_signal()
788 		 * and you'd have to handle the race where a higher
789 		 * priority thread blocks on the write lock before the
790 		 * thread you wakeup actually runs and have the new thread
791 		 * "steal" the lock.  For now it's a lot simpler to just
792 		 * wakeup all of the waiters.
793 		 *
794 		 * As above, if we fail, then another thread might have
795 		 * acquired a read lock, so drop the turnstile lock and
796 		 * restart.
797 		 */
798 		setv = RW_UNLOCKED;
799 		queue = TS_SHARED_QUEUE;
800 		if (v & RW_LOCK_WRITE_WAITERS) {
801 			queue = TS_EXCLUSIVE_QUEUE;
802 			setv |= (v & RW_LOCK_READ_WAITERS);
803 		}
804 		v |= RW_READERS_LOCK(1);
805 		if (!atomic_fcmpset_rel_ptr(&rw->rw_lock, &v, setv))
806 			continue;
807 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
808 			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
809 			    __func__, rw);
810 
811 		/*
812 		 * Ok.  The lock is released and all that's left is to
813 		 * wake up the waiters.  Note that the lock might not be
814 		 * free anymore, but in that case the writers will just
815 		 * block again if they run before the new lock holder(s)
816 		 * release the lock.
817 		 */
818 		ts = turnstile_lookup(&rw->lock_object);
819 		MPASS(ts != NULL);
820 		turnstile_broadcast(ts, queue);
821 		turnstile_unpend(ts, TS_SHARED_LOCK);
822 		td->td_rw_rlocks--;
823 		break;
824 	}
825 	turnstile_chain_unlock(&rw->lock_object);
826 out_lockstat:
827 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
828 }
829 
830 void
831 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
832 {
833 	struct thread *td;
834 	uintptr_t v;
835 
836 	KASSERT(rw->rw_lock != RW_DESTROYED,
837 	    ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
838 	__rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
839 	WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
840 	LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
841 
842 	td = curthread;
843 	v = RW_READ_VALUE(rw);
844 
845 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__release) ||
846 	    !__rw_runlock_try(rw, td, &v)))
847 		__rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
848 	else
849 		lock_profile_release_lock(&rw->lock_object);
850 
851 	TD_LOCKS_DEC(curthread);
852 }
853 
854 void
855 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
856 {
857 	struct rwlock *rw;
858 
859 	rw = rwlock2rw(c);
860 	_rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
861 }
862 
863 /*
864  * This function is called when we are unable to obtain a write lock on the
865  * first try.  This means that at least one other thread holds either a
866  * read or write lock.
867  */
868 void
869 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
870 {
871 	uintptr_t tid;
872 	struct rwlock *rw;
873 	struct turnstile *ts;
874 	struct thread *owner;
875 #ifdef ADAPTIVE_RWLOCKS
876 	int spintries = 0;
877 	int i, n;
878 	enum { READERS, WRITER } sleep_reason;
879 #endif
880 	uintptr_t x;
881 #ifdef LOCK_PROFILING
882 	uint64_t waittime = 0;
883 	int contested = 0;
884 #endif
885 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
886 	struct lock_delay_arg lda;
887 #endif
888 #ifdef KDTRACE_HOOKS
889 	u_int sleep_cnt = 0;
890 	int64_t sleep_time = 0;
891 	int64_t all_time = 0;
892 #endif
893 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
894 	uintptr_t state;
895 	int doing_lockprof;
896 #endif
897 
898 	tid = (uintptr_t)curthread;
899 	if (SCHEDULER_STOPPED())
900 		return;
901 
902 #if defined(ADAPTIVE_RWLOCKS)
903 	lock_delay_arg_init(&lda, &rw_delay);
904 #elif defined(KDTRACE_HOOKS)
905 	lock_delay_arg_init(&lda, NULL);
906 #endif
907 	rw = rwlock2rw(c);
908 	if (__predict_false(v == RW_UNLOCKED))
909 		v = RW_READ_VALUE(rw);
910 
911 	if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
912 		KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
913 		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
914 		    __func__, rw->lock_object.lo_name, file, line));
915 		rw->rw_recurse++;
916 		atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
917 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
918 			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
919 		return;
920 	}
921 
922 	if (LOCK_LOG_TEST(&rw->lock_object, 0))
923 		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
924 		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
925 
926 #ifdef HWPMC_HOOKS
927 	PMC_SOFT_CALL( , , lock, failed);
928 #endif
929 	lock_profile_obtain_lock_failed(&rw->lock_object,
930 	    &contested, &waittime);
931 
932 #ifdef LOCK_PROFILING
933 	doing_lockprof = 1;
934 	state = v;
935 #elif defined(KDTRACE_HOOKS)
936 	doing_lockprof = lockstat_enabled;
937 	if (__predict_false(doing_lockprof)) {
938 		all_time -= lockstat_nsecs(&rw->lock_object);
939 		state = v;
940 	}
941 #endif
942 
943 	for (;;) {
944 		if (v == RW_UNLOCKED) {
945 			if (_rw_write_lock_fetch(rw, &v, tid))
946 				break;
947 			continue;
948 		}
949 #ifdef KDTRACE_HOOKS
950 		lda.spin_cnt++;
951 #endif
952 
953 #ifdef ADAPTIVE_RWLOCKS
954 		/*
955 		 * If the lock is write locked and the owner is
956 		 * running on another CPU, spin until the owner stops
957 		 * running or the state of the lock changes.
958 		 */
959 		if (!(v & RW_LOCK_READ)) {
960 			sleep_reason = WRITER;
961 			owner = lv_rw_wowner(v);
962 			if (!TD_IS_RUNNING(owner))
963 				goto ts;
964 			if (LOCK_LOG_TEST(&rw->lock_object, 0))
965 				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
966 				    __func__, rw, owner);
967 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
968 			    "spinning", "lockname:\"%s\"",
969 			    rw->lock_object.lo_name);
970 			do {
971 				lock_delay(&lda);
972 				v = RW_READ_VALUE(rw);
973 				owner = lv_rw_wowner(v);
974 			} while (owner != NULL && TD_IS_RUNNING(owner));
975 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
976 			    "running");
977 			continue;
978 		} else if (RW_READERS(v) > 0) {
979 			sleep_reason = READERS;
980 			if (spintries == rowner_retries)
981 				goto ts;
982 			if (!(v & RW_LOCK_WRITE_SPINNER)) {
983 				if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
984 				    v | RW_LOCK_WRITE_SPINNER)) {
985 					continue;
986 				}
987 			}
988 			spintries++;
989 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
990 			    "spinning", "lockname:\"%s\"",
991 			    rw->lock_object.lo_name);
992 			for (i = 0; i < rowner_loops; i += n) {
993 				n = RW_READERS(v);
994 				lock_delay_spin(n);
995 				v = RW_READ_VALUE(rw);
996 				if ((v & RW_LOCK_WRITE_SPINNER) == 0)
997 					break;
998 			}
999 #ifdef KDTRACE_HOOKS
1000 			lda.spin_cnt += i;
1001 #endif
1002 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1003 			    "running");
1004 			if (i < rowner_loops)
1005 				continue;
1006 		}
1007 ts:
1008 #endif
1009 		ts = turnstile_trywait(&rw->lock_object);
1010 		v = RW_READ_VALUE(rw);
1011 retry_ts:
1012 		owner = lv_rw_wowner(v);
1013 
1014 #ifdef ADAPTIVE_RWLOCKS
1015 		/*
1016 		 * The current lock owner might have started executing
1017 		 * on another CPU (or the lock could have changed
1018 		 * owners) while we were waiting on the turnstile
1019 		 * chain lock.  If so, drop the turnstile lock and try
1020 		 * again.
1021 		 */
1022 		if (owner != NULL) {
1023 			if (TD_IS_RUNNING(owner)) {
1024 				turnstile_cancel(ts);
1025 				continue;
1026 			}
1027 		} else if (RW_READERS(v) > 0 && sleep_reason == WRITER) {
1028 			turnstile_cancel(ts);
1029 			continue;
1030 		}
1031 #endif
1032 		/*
1033 		 * Check for the waiters flags about this rwlock.
1034 		 * If the lock was released, without maintain any pending
1035 		 * waiters queue, simply try to acquire it.
1036 		 * If a pending waiters queue is present, claim the lock
1037 		 * ownership and maintain the pending queue.
1038 		 */
1039 		x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1040 		if ((v & ~x) == RW_UNLOCKED) {
1041 			x &= ~RW_LOCK_WRITE_SPINNER;
1042 			if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid | x)) {
1043 				if (x)
1044 					turnstile_claim(ts);
1045 				else
1046 					turnstile_cancel(ts);
1047 				break;
1048 			}
1049 			goto retry_ts;
1050 		}
1051 		/*
1052 		 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1053 		 * set it.  If we fail to set it, then loop back and try
1054 		 * again.
1055 		 */
1056 		if (!(v & RW_LOCK_WRITE_WAITERS)) {
1057 			if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1058 			    v | RW_LOCK_WRITE_WAITERS))
1059 				goto retry_ts;
1060 			if (LOCK_LOG_TEST(&rw->lock_object, 0))
1061 				CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1062 				    __func__, rw);
1063 		}
1064 		/*
1065 		 * We were unable to acquire the lock and the write waiters
1066 		 * flag is set, so we must block on the turnstile.
1067 		 */
1068 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
1069 			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1070 			    rw);
1071 #ifdef KDTRACE_HOOKS
1072 		sleep_time -= lockstat_nsecs(&rw->lock_object);
1073 #endif
1074 		MPASS(owner == rw_owner(rw));
1075 		turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
1076 #ifdef KDTRACE_HOOKS
1077 		sleep_time += lockstat_nsecs(&rw->lock_object);
1078 		sleep_cnt++;
1079 #endif
1080 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
1081 			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1082 			    __func__, rw);
1083 #ifdef ADAPTIVE_RWLOCKS
1084 		spintries = 0;
1085 #endif
1086 		v = RW_READ_VALUE(rw);
1087 	}
1088 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1089 	if (__predict_true(!doing_lockprof))
1090 		return;
1091 #endif
1092 #ifdef KDTRACE_HOOKS
1093 	all_time += lockstat_nsecs(&rw->lock_object);
1094 	if (sleep_time)
1095 		LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1096 		    LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1097 		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1098 
1099 	/* Record only the loops spinning and not sleeping. */
1100 	if (lda.spin_cnt > sleep_cnt)
1101 		LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1102 		    LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1103 		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1104 #endif
1105 	LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1106 	    waittime, file, line, LOCKSTAT_WRITER);
1107 }
1108 
1109 /*
1110  * This function is called if lockstat is active or the first try at releasing
1111  * a write lock failed.  The latter means that the lock is recursed or one of
1112  * the 2 waiter bits must be set indicating that at least one thread is waiting
1113  * on this lock.
1114  */
1115 void
1116 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1117 {
1118 	struct rwlock *rw;
1119 	struct turnstile *ts;
1120 	uintptr_t tid, setv;
1121 	int queue;
1122 
1123 	tid = (uintptr_t)curthread;
1124 	if (SCHEDULER_STOPPED())
1125 		return;
1126 
1127 	rw = rwlock2rw(c);
1128 	if (__predict_false(v == tid))
1129 		v = RW_READ_VALUE(rw);
1130 
1131 	if (v & RW_LOCK_WRITER_RECURSED) {
1132 		if (--(rw->rw_recurse) == 0)
1133 			atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1134 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
1135 			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1136 		return;
1137 	}
1138 
1139 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1140 	if (v == tid && _rw_write_unlock(rw, tid))
1141 		return;
1142 
1143 	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1144 	    ("%s: neither of the waiter flags are set", __func__));
1145 
1146 	if (LOCK_LOG_TEST(&rw->lock_object, 0))
1147 		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1148 
1149 	turnstile_chain_lock(&rw->lock_object);
1150 
1151 	/*
1152 	 * Use the same algo as sx locks for now.  Prefer waking up shared
1153 	 * waiters if we have any over writers.  This is probably not ideal.
1154 	 *
1155 	 * 'v' is the value we are going to write back to rw_lock.  If we
1156 	 * have waiters on both queues, we need to preserve the state of
1157 	 * the waiter flag for the queue we don't wake up.  For now this is
1158 	 * hardcoded for the algorithm mentioned above.
1159 	 *
1160 	 * In the case of both readers and writers waiting we wakeup the
1161 	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
1162 	 * new writer comes in before a reader it will claim the lock up
1163 	 * above.  There is probably a potential priority inversion in
1164 	 * there that could be worked around either by waking both queues
1165 	 * of waiters or doing some complicated lock handoff gymnastics.
1166 	 */
1167 	setv = RW_UNLOCKED;
1168 	v = RW_READ_VALUE(rw);
1169 	queue = TS_SHARED_QUEUE;
1170 	if (v & RW_LOCK_WRITE_WAITERS) {
1171 		queue = TS_EXCLUSIVE_QUEUE;
1172 		setv |= (v & RW_LOCK_READ_WAITERS);
1173 	}
1174 	atomic_store_rel_ptr(&rw->rw_lock, setv);
1175 
1176 	/* Wake up all waiters for the specific queue. */
1177 	if (LOCK_LOG_TEST(&rw->lock_object, 0))
1178 		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1179 		    queue == TS_SHARED_QUEUE ? "read" : "write");
1180 
1181 	ts = turnstile_lookup(&rw->lock_object);
1182 	MPASS(ts != NULL);
1183 	turnstile_broadcast(ts, queue);
1184 	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1185 	turnstile_chain_unlock(&rw->lock_object);
1186 }
1187 
1188 /*
1189  * Attempt to do a non-blocking upgrade from a read lock to a write
1190  * lock.  This will only succeed if this thread holds a single read
1191  * lock.  Returns true if the upgrade succeeded and false otherwise.
1192  */
1193 int
1194 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1195 {
1196 	uintptr_t v, x, tid;
1197 	struct turnstile *ts;
1198 	int success;
1199 
1200 	if (SCHEDULER_STOPPED())
1201 		return (1);
1202 
1203 	KASSERT(rw->rw_lock != RW_DESTROYED,
1204 	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1205 	__rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1206 
1207 	/*
1208 	 * Attempt to switch from one reader to a writer.  If there
1209 	 * are any write waiters, then we will have to lock the
1210 	 * turnstile first to prevent races with another writer
1211 	 * calling turnstile_wait() before we have claimed this
1212 	 * turnstile.  So, do the simple case of no waiters first.
1213 	 */
1214 	tid = (uintptr_t)curthread;
1215 	success = 0;
1216 	for (;;) {
1217 		v = rw->rw_lock;
1218 		if (RW_READERS(v) > 1)
1219 			break;
1220 		if (!(v & RW_LOCK_WAITERS)) {
1221 			success = atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid);
1222 			if (!success)
1223 				continue;
1224 			break;
1225 		}
1226 
1227 		/*
1228 		 * Ok, we think we have waiters, so lock the turnstile.
1229 		 */
1230 		ts = turnstile_trywait(&rw->lock_object);
1231 		v = rw->rw_lock;
1232 		if (RW_READERS(v) > 1) {
1233 			turnstile_cancel(ts);
1234 			break;
1235 		}
1236 		/*
1237 		 * Try to switch from one reader to a writer again.  This time
1238 		 * we honor the current state of the waiters flags.
1239 		 * If we obtain the lock with the flags set, then claim
1240 		 * ownership of the turnstile.
1241 		 */
1242 		x = rw->rw_lock & RW_LOCK_WAITERS;
1243 		success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1244 		if (success) {
1245 			if (x)
1246 				turnstile_claim(ts);
1247 			else
1248 				turnstile_cancel(ts);
1249 			break;
1250 		}
1251 		turnstile_cancel(ts);
1252 	}
1253 	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1254 	if (success) {
1255 		curthread->td_rw_rlocks--;
1256 		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1257 		    file, line);
1258 		LOCKSTAT_RECORD0(rw__upgrade, rw);
1259 	}
1260 	return (success);
1261 }
1262 
1263 int
1264 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1265 {
1266 	struct rwlock *rw;
1267 
1268 	rw = rwlock2rw(c);
1269 	return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1270 }
1271 
1272 /*
1273  * Downgrade a write lock into a single read lock.
1274  */
1275 void
1276 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1277 {
1278 	struct turnstile *ts;
1279 	uintptr_t tid, v;
1280 	int rwait, wwait;
1281 
1282 	if (SCHEDULER_STOPPED())
1283 		return;
1284 
1285 	KASSERT(rw->rw_lock != RW_DESTROYED,
1286 	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1287 	__rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1288 #ifndef INVARIANTS
1289 	if (rw_recursed(rw))
1290 		panic("downgrade of a recursed lock");
1291 #endif
1292 
1293 	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1294 
1295 	/*
1296 	 * Convert from a writer to a single reader.  First we handle
1297 	 * the easy case with no waiters.  If there are any waiters, we
1298 	 * lock the turnstile and "disown" the lock.
1299 	 */
1300 	tid = (uintptr_t)curthread;
1301 	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1302 		goto out;
1303 
1304 	/*
1305 	 * Ok, we think we have waiters, so lock the turnstile so we can
1306 	 * read the waiter flags without any races.
1307 	 */
1308 	turnstile_chain_lock(&rw->lock_object);
1309 	v = rw->rw_lock & RW_LOCK_WAITERS;
1310 	rwait = v & RW_LOCK_READ_WAITERS;
1311 	wwait = v & RW_LOCK_WRITE_WAITERS;
1312 	MPASS(rwait | wwait);
1313 
1314 	/*
1315 	 * Downgrade from a write lock while preserving waiters flag
1316 	 * and give up ownership of the turnstile.
1317 	 */
1318 	ts = turnstile_lookup(&rw->lock_object);
1319 	MPASS(ts != NULL);
1320 	if (!wwait)
1321 		v &= ~RW_LOCK_READ_WAITERS;
1322 	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1323 	/*
1324 	 * Wake other readers if there are no writers pending.  Otherwise they
1325 	 * won't be able to acquire the lock anyway.
1326 	 */
1327 	if (rwait && !wwait) {
1328 		turnstile_broadcast(ts, TS_SHARED_QUEUE);
1329 		turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1330 	} else
1331 		turnstile_disown(ts);
1332 	turnstile_chain_unlock(&rw->lock_object);
1333 out:
1334 	curthread->td_rw_rlocks++;
1335 	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1336 	LOCKSTAT_RECORD0(rw__downgrade, rw);
1337 }
1338 
1339 void
1340 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1341 {
1342 	struct rwlock *rw;
1343 
1344 	rw = rwlock2rw(c);
1345 	__rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1346 }
1347 
1348 #ifdef INVARIANT_SUPPORT
1349 #ifndef INVARIANTS
1350 #undef __rw_assert
1351 #endif
1352 
1353 /*
1354  * In the non-WITNESS case, rw_assert() can only detect that at least
1355  * *some* thread owns an rlock, but it cannot guarantee that *this*
1356  * thread owns an rlock.
1357  */
1358 void
1359 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1360 {
1361 	const struct rwlock *rw;
1362 
1363 	if (panicstr != NULL)
1364 		return;
1365 
1366 	rw = rwlock2rw(c);
1367 
1368 	switch (what) {
1369 	case RA_LOCKED:
1370 	case RA_LOCKED | RA_RECURSED:
1371 	case RA_LOCKED | RA_NOTRECURSED:
1372 	case RA_RLOCKED:
1373 	case RA_RLOCKED | RA_RECURSED:
1374 	case RA_RLOCKED | RA_NOTRECURSED:
1375 #ifdef WITNESS
1376 		witness_assert(&rw->lock_object, what, file, line);
1377 #else
1378 		/*
1379 		 * If some other thread has a write lock or we have one
1380 		 * and are asserting a read lock, fail.  Also, if no one
1381 		 * has a lock at all, fail.
1382 		 */
1383 		if (rw->rw_lock == RW_UNLOCKED ||
1384 		    (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1385 		    rw_wowner(rw) != curthread)))
1386 			panic("Lock %s not %slocked @ %s:%d\n",
1387 			    rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1388 			    "read " : "", file, line);
1389 
1390 		if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1391 			if (rw_recursed(rw)) {
1392 				if (what & RA_NOTRECURSED)
1393 					panic("Lock %s recursed @ %s:%d\n",
1394 					    rw->lock_object.lo_name, file,
1395 					    line);
1396 			} else if (what & RA_RECURSED)
1397 				panic("Lock %s not recursed @ %s:%d\n",
1398 				    rw->lock_object.lo_name, file, line);
1399 		}
1400 #endif
1401 		break;
1402 	case RA_WLOCKED:
1403 	case RA_WLOCKED | RA_RECURSED:
1404 	case RA_WLOCKED | RA_NOTRECURSED:
1405 		if (rw_wowner(rw) != curthread)
1406 			panic("Lock %s not exclusively locked @ %s:%d\n",
1407 			    rw->lock_object.lo_name, file, line);
1408 		if (rw_recursed(rw)) {
1409 			if (what & RA_NOTRECURSED)
1410 				panic("Lock %s recursed @ %s:%d\n",
1411 				    rw->lock_object.lo_name, file, line);
1412 		} else if (what & RA_RECURSED)
1413 			panic("Lock %s not recursed @ %s:%d\n",
1414 			    rw->lock_object.lo_name, file, line);
1415 		break;
1416 	case RA_UNLOCKED:
1417 #ifdef WITNESS
1418 		witness_assert(&rw->lock_object, what, file, line);
1419 #else
1420 		/*
1421 		 * If we hold a write lock fail.  We can't reliably check
1422 		 * to see if we hold a read lock or not.
1423 		 */
1424 		if (rw_wowner(rw) == curthread)
1425 			panic("Lock %s exclusively locked @ %s:%d\n",
1426 			    rw->lock_object.lo_name, file, line);
1427 #endif
1428 		break;
1429 	default:
1430 		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1431 		    line);
1432 	}
1433 }
1434 #endif /* INVARIANT_SUPPORT */
1435 
1436 #ifdef DDB
1437 void
1438 db_show_rwlock(const struct lock_object *lock)
1439 {
1440 	const struct rwlock *rw;
1441 	struct thread *td;
1442 
1443 	rw = (const struct rwlock *)lock;
1444 
1445 	db_printf(" state: ");
1446 	if (rw->rw_lock == RW_UNLOCKED)
1447 		db_printf("UNLOCKED\n");
1448 	else if (rw->rw_lock == RW_DESTROYED) {
1449 		db_printf("DESTROYED\n");
1450 		return;
1451 	} else if (rw->rw_lock & RW_LOCK_READ)
1452 		db_printf("RLOCK: %ju locks\n",
1453 		    (uintmax_t)(RW_READERS(rw->rw_lock)));
1454 	else {
1455 		td = rw_wowner(rw);
1456 		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1457 		    td->td_tid, td->td_proc->p_pid, td->td_name);
1458 		if (rw_recursed(rw))
1459 			db_printf(" recursed: %u\n", rw->rw_recurse);
1460 	}
1461 	db_printf(" waiters: ");
1462 	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1463 	case RW_LOCK_READ_WAITERS:
1464 		db_printf("readers\n");
1465 		break;
1466 	case RW_LOCK_WRITE_WAITERS:
1467 		db_printf("writers\n");
1468 		break;
1469 	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1470 		db_printf("readers and writers\n");
1471 		break;
1472 	default:
1473 		db_printf("none\n");
1474 		break;
1475 	}
1476 }
1477 
1478 #endif
1479