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