xref: /freebsd/sys/kern/kern_rwlock.c (revision 190cef3d52236565eb22e18b33e9e865ec634aa3)
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 {
514 			if ((v & RW_LOCK_WRITE_SPINNER) && RW_READERS(v) == 0) {
515 				MPASS(!__rw_can_read(td, v, false));
516 				lock_delay_spin(2);
517 				v = RW_READ_VALUE(rw);
518 				continue;
519 			}
520 			if (spintries < rowner_retries) {
521 				spintries++;
522 				KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
523 				    "spinning", "lockname:\"%s\"",
524 				    rw->lock_object.lo_name);
525 				n = RW_READERS(v);
526 				for (i = 0; i < rowner_loops; i += n) {
527 					lock_delay_spin(n);
528 					v = RW_READ_VALUE(rw);
529 					if (!(v & RW_LOCK_READ))
530 						break;
531 					n = RW_READERS(v);
532 					if (n == 0)
533 						break;
534 					if (__rw_can_read(td, v, false))
535 						break;
536 				}
537 #ifdef KDTRACE_HOOKS
538 				lda.spin_cnt += rowner_loops - i;
539 #endif
540 				KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
541 				    "running");
542 				if (i < rowner_loops)
543 					continue;
544 			}
545 		}
546 #endif
547 
548 		/*
549 		 * Okay, now it's the hard case.  Some other thread already
550 		 * has a write lock or there are write waiters present,
551 		 * acquire the turnstile lock so we can begin the process
552 		 * of blocking.
553 		 */
554 		ts = turnstile_trywait(&rw->lock_object);
555 
556 		/*
557 		 * The lock might have been released while we spun, so
558 		 * recheck its state and restart the loop if needed.
559 		 */
560 		v = RW_READ_VALUE(rw);
561 retry_ts:
562 		if (((v & RW_LOCK_WRITE_SPINNER) && RW_READERS(v) == 0) ||
563 		    __rw_can_read(td, v, false)) {
564 			turnstile_cancel(ts);
565 			continue;
566 		}
567 
568 		owner = lv_rw_wowner(v);
569 
570 #ifdef ADAPTIVE_RWLOCKS
571 		/*
572 		 * The current lock owner might have started executing
573 		 * on another CPU (or the lock could have changed
574 		 * owners) while we were waiting on the turnstile
575 		 * chain lock.  If so, drop the turnstile lock and try
576 		 * again.
577 		 */
578 		if (owner != NULL) {
579 			if (TD_IS_RUNNING(owner)) {
580 				turnstile_cancel(ts);
581 				continue;
582 			}
583 		}
584 #endif
585 
586 		/*
587 		 * The lock is held in write mode or it already has waiters.
588 		 */
589 		MPASS(!__rw_can_read(td, v, false));
590 
591 		/*
592 		 * If the RW_LOCK_READ_WAITERS flag is already set, then
593 		 * we can go ahead and block.  If it is not set then try
594 		 * to set it.  If we fail to set it drop the turnstile
595 		 * lock and restart the loop.
596 		 */
597 		if (!(v & RW_LOCK_READ_WAITERS)) {
598 			if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
599 			    v | RW_LOCK_READ_WAITERS))
600 				goto retry_ts;
601 			if (LOCK_LOG_TEST(&rw->lock_object, 0))
602 				CTR2(KTR_LOCK, "%s: %p set read waiters flag",
603 				    __func__, rw);
604 		}
605 
606 		/*
607 		 * We were unable to acquire the lock and the read waiters
608 		 * flag is set, so we must block on the turnstile.
609 		 */
610 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
611 			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
612 			    rw);
613 #ifdef KDTRACE_HOOKS
614 		sleep_time -= lockstat_nsecs(&rw->lock_object);
615 #endif
616 		MPASS(owner == rw_owner(rw));
617 		turnstile_wait(ts, owner, TS_SHARED_QUEUE);
618 #ifdef KDTRACE_HOOKS
619 		sleep_time += lockstat_nsecs(&rw->lock_object);
620 		sleep_cnt++;
621 #endif
622 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
623 			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
624 			    __func__, rw);
625 		v = RW_READ_VALUE(rw);
626 	}
627 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
628 	if (__predict_true(!doing_lockprof))
629 		return;
630 #endif
631 #ifdef KDTRACE_HOOKS
632 	all_time += lockstat_nsecs(&rw->lock_object);
633 	if (sleep_time)
634 		LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
635 		    LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
636 		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
637 
638 	/* Record only the loops spinning and not sleeping. */
639 	if (lda.spin_cnt > sleep_cnt)
640 		LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
641 		    LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
642 		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
643 out_lockstat:
644 #endif
645 	/*
646 	 * TODO: acquire "owner of record" here.  Here be turnstile dragons
647 	 * however.  turnstiles don't like owners changing between calls to
648 	 * turnstile_wait() currently.
649 	 */
650 	LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
651 	    waittime, file, line, LOCKSTAT_READER);
652 }
653 
654 void
655 __rw_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
656 {
657 	struct thread *td;
658 	uintptr_t v;
659 
660 	td = curthread;
661 
662 	KASSERT(kdb_active != 0 || SCHEDULER_STOPPED_TD(td) ||
663 	    !TD_IS_IDLETHREAD(td),
664 	    ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
665 	    td, rw->lock_object.lo_name, file, line));
666 	KASSERT(rw->rw_lock != RW_DESTROYED,
667 	    ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
668 	KASSERT(rw_wowner(rw) != td,
669 	    ("rw_rlock: wlock already held for %s @ %s:%d",
670 	    rw->lock_object.lo_name, file, line));
671 	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
672 
673 	v = RW_READ_VALUE(rw);
674 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__acquire) ||
675 	    !__rw_rlock_try(rw, td, &v, true LOCK_FILE_LINE_ARG)))
676 		__rw_rlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
677 	else
678 		lock_profile_obtain_lock_success(&rw->lock_object, 0, 0,
679 		    file, line);
680 
681 	LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
682 	WITNESS_LOCK(&rw->lock_object, 0, file, line);
683 	TD_LOCKS_INC(curthread);
684 }
685 
686 void
687 __rw_rlock(volatile uintptr_t *c, const char *file, int line)
688 {
689 	struct rwlock *rw;
690 
691 	rw = rwlock2rw(c);
692 	__rw_rlock_int(rw LOCK_FILE_LINE_ARG);
693 }
694 
695 int
696 __rw_try_rlock_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
697 {
698 	uintptr_t x;
699 
700 	if (SCHEDULER_STOPPED())
701 		return (1);
702 
703 	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
704 	    ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
705 	    curthread, rw->lock_object.lo_name, file, line));
706 
707 	x = rw->rw_lock;
708 	for (;;) {
709 		KASSERT(rw->rw_lock != RW_DESTROYED,
710 		    ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
711 		if (!(x & RW_LOCK_READ))
712 			break;
713 		if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &x, x + RW_ONE_READER)) {
714 			LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
715 			    line);
716 			WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
717 			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
718 			    rw, 0, 0, file, line, LOCKSTAT_READER);
719 			TD_LOCKS_INC(curthread);
720 			curthread->td_rw_rlocks++;
721 			return (1);
722 		}
723 	}
724 
725 	LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
726 	return (0);
727 }
728 
729 int
730 __rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
731 {
732 	struct rwlock *rw;
733 
734 	rw = rwlock2rw(c);
735 	return (__rw_try_rlock_int(rw LOCK_FILE_LINE_ARG));
736 }
737 
738 static bool __always_inline
739 __rw_runlock_try(struct rwlock *rw, struct thread *td, uintptr_t *vp)
740 {
741 
742 	for (;;) {
743 		if (RW_READERS(*vp) > 1 || !(*vp & RW_LOCK_WAITERS)) {
744 			if (atomic_fcmpset_rel_ptr(&rw->rw_lock, vp,
745 			    *vp - RW_ONE_READER)) {
746 				if (LOCK_LOG_TEST(&rw->lock_object, 0))
747 					CTR4(KTR_LOCK,
748 					    "%s: %p succeeded %p -> %p",
749 					    __func__, rw, (void *)*vp,
750 					    (void *)(*vp - RW_ONE_READER));
751 				td->td_rw_rlocks--;
752 				return (true);
753 			}
754 			continue;
755 		}
756 		break;
757 	}
758 	return (false);
759 }
760 
761 static void __noinline
762 __rw_runlock_hard(struct rwlock *rw, struct thread *td, uintptr_t v
763     LOCK_FILE_LINE_ARG_DEF)
764 {
765 	struct turnstile *ts;
766 	uintptr_t setv, queue;
767 
768 	if (SCHEDULER_STOPPED())
769 		return;
770 
771 	if (__rw_runlock_try(rw, td, &v))
772 		goto out_lockstat;
773 
774 	/*
775 	 * Ok, we know we have waiters and we think we are the
776 	 * last reader, so grab the turnstile lock.
777 	 */
778 	turnstile_chain_lock(&rw->lock_object);
779 	v = RW_READ_VALUE(rw);
780 	for (;;) {
781 		if (__rw_runlock_try(rw, td, &v))
782 			break;
783 
784 		MPASS(v & RW_LOCK_WAITERS);
785 
786 		/*
787 		 * Try to drop our lock leaving the lock in a unlocked
788 		 * state.
789 		 *
790 		 * If you wanted to do explicit lock handoff you'd have to
791 		 * do it here.  You'd also want to use turnstile_signal()
792 		 * and you'd have to handle the race where a higher
793 		 * priority thread blocks on the write lock before the
794 		 * thread you wakeup actually runs and have the new thread
795 		 * "steal" the lock.  For now it's a lot simpler to just
796 		 * wakeup all of the waiters.
797 		 *
798 		 * As above, if we fail, then another thread might have
799 		 * acquired a read lock, so drop the turnstile lock and
800 		 * restart.
801 		 */
802 		setv = RW_UNLOCKED;
803 		queue = TS_SHARED_QUEUE;
804 		if (v & RW_LOCK_WRITE_WAITERS) {
805 			queue = TS_EXCLUSIVE_QUEUE;
806 			setv |= (v & RW_LOCK_READ_WAITERS);
807 		}
808 		setv |= (v & RW_LOCK_WRITE_SPINNER);
809 		if (!atomic_fcmpset_rel_ptr(&rw->rw_lock, &v, setv))
810 			continue;
811 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
812 			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
813 			    __func__, rw);
814 
815 		/*
816 		 * Ok.  The lock is released and all that's left is to
817 		 * wake up the waiters.  Note that the lock might not be
818 		 * free anymore, but in that case the writers will just
819 		 * block again if they run before the new lock holder(s)
820 		 * release the lock.
821 		 */
822 		ts = turnstile_lookup(&rw->lock_object);
823 		MPASS(ts != NULL);
824 		turnstile_broadcast(ts, queue);
825 		turnstile_unpend(ts);
826 		td->td_rw_rlocks--;
827 		break;
828 	}
829 	turnstile_chain_unlock(&rw->lock_object);
830 out_lockstat:
831 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
832 }
833 
834 void
835 _rw_runlock_cookie_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
836 {
837 	struct thread *td;
838 	uintptr_t v;
839 
840 	KASSERT(rw->rw_lock != RW_DESTROYED,
841 	    ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
842 	__rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
843 	WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
844 	LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
845 
846 	td = curthread;
847 	v = RW_READ_VALUE(rw);
848 
849 	if (__predict_false(LOCKSTAT_PROFILE_ENABLED(rw__release) ||
850 	    !__rw_runlock_try(rw, td, &v)))
851 		__rw_runlock_hard(rw, td, v LOCK_FILE_LINE_ARG);
852 	else
853 		lock_profile_release_lock(&rw->lock_object);
854 
855 	TD_LOCKS_DEC(curthread);
856 }
857 
858 void
859 _rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
860 {
861 	struct rwlock *rw;
862 
863 	rw = rwlock2rw(c);
864 	_rw_runlock_cookie_int(rw LOCK_FILE_LINE_ARG);
865 }
866 
867 #ifdef ADAPTIVE_RWLOCKS
868 static inline void
869 rw_drop_critical(uintptr_t v, bool *in_critical, int *extra_work)
870 {
871 
872 	if (v & RW_LOCK_WRITE_SPINNER)
873 		return;
874 	if (*in_critical) {
875 		critical_exit();
876 		*in_critical = false;
877 		(*extra_work)--;
878 	}
879 }
880 #else
881 #define rw_drop_critical(v, in_critical, extra_work) do { } while (0)
882 #endif
883 
884 /*
885  * This function is called when we are unable to obtain a write lock on the
886  * first try.  This means that at least one other thread holds either a
887  * read or write lock.
888  */
889 void
890 __rw_wlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
891 {
892 	uintptr_t tid;
893 	struct rwlock *rw;
894 	struct turnstile *ts;
895 	struct thread *owner;
896 #ifdef ADAPTIVE_RWLOCKS
897 	int spintries = 0;
898 	int i, n;
899 	enum { READERS, WRITER } sleep_reason = READERS;
900 	bool in_critical = false;
901 #endif
902 	uintptr_t setv;
903 #ifdef LOCK_PROFILING
904 	uint64_t waittime = 0;
905 	int contested = 0;
906 #endif
907 #if defined(ADAPTIVE_RWLOCKS) || defined(KDTRACE_HOOKS)
908 	struct lock_delay_arg lda;
909 #endif
910 #ifdef KDTRACE_HOOKS
911 	u_int sleep_cnt = 0;
912 	int64_t sleep_time = 0;
913 	int64_t all_time = 0;
914 #endif
915 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
916 	uintptr_t state;
917 	int doing_lockprof = 0;
918 #endif
919 	int extra_work = 0;
920 
921 	tid = (uintptr_t)curthread;
922 	rw = rwlock2rw(c);
923 
924 #ifdef KDTRACE_HOOKS
925 	if (LOCKSTAT_PROFILE_ENABLED(rw__acquire)) {
926 		while (v == RW_UNLOCKED) {
927 			if (_rw_write_lock_fetch(rw, &v, tid))
928 				goto out_lockstat;
929 		}
930 		extra_work = 1;
931 		doing_lockprof = 1;
932 		all_time -= lockstat_nsecs(&rw->lock_object);
933 		state = v;
934 	}
935 #endif
936 #ifdef LOCK_PROFILING
937 	extra_work = 1;
938 	doing_lockprof = 1;
939 	state = v;
940 #endif
941 
942 	if (SCHEDULER_STOPPED())
943 		return;
944 
945 #if defined(ADAPTIVE_RWLOCKS)
946 	lock_delay_arg_init(&lda, &rw_delay);
947 #elif defined(KDTRACE_HOOKS)
948 	lock_delay_arg_init(&lda, NULL);
949 #endif
950 	if (__predict_false(v == RW_UNLOCKED))
951 		v = RW_READ_VALUE(rw);
952 
953 	if (__predict_false(lv_rw_wowner(v) == (struct thread *)tid)) {
954 		KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
955 		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
956 		    __func__, rw->lock_object.lo_name, file, line));
957 		rw->rw_recurse++;
958 		atomic_set_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
959 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
960 			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
961 		return;
962 	}
963 
964 	if (LOCK_LOG_TEST(&rw->lock_object, 0))
965 		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
966 		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
967 
968 #ifdef HWPMC_HOOKS
969 	PMC_SOFT_CALL( , , lock, failed);
970 #endif
971 	lock_profile_obtain_lock_failed(&rw->lock_object,
972 	    &contested, &waittime);
973 
974 	for (;;) {
975 		if (v == RW_UNLOCKED) {
976 			if (_rw_write_lock_fetch(rw, &v, tid))
977 				break;
978 			continue;
979 		}
980 #ifdef KDTRACE_HOOKS
981 		lda.spin_cnt++;
982 #endif
983 
984 #ifdef ADAPTIVE_RWLOCKS
985 		if (v == (RW_LOCK_READ | RW_LOCK_WRITE_SPINNER)) {
986 			if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid))
987 				break;
988 			continue;
989 		}
990 
991 		/*
992 		 * If the lock is write locked and the owner is
993 		 * running on another CPU, spin until the owner stops
994 		 * running or the state of the lock changes.
995 		 */
996 		if (!(v & RW_LOCK_READ)) {
997 			rw_drop_critical(v, &in_critical, &extra_work);
998 			sleep_reason = WRITER;
999 			owner = lv_rw_wowner(v);
1000 			if (!TD_IS_RUNNING(owner))
1001 				goto ts;
1002 			if (LOCK_LOG_TEST(&rw->lock_object, 0))
1003 				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
1004 				    __func__, rw, owner);
1005 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1006 			    "spinning", "lockname:\"%s\"",
1007 			    rw->lock_object.lo_name);
1008 			do {
1009 				lock_delay(&lda);
1010 				v = RW_READ_VALUE(rw);
1011 				owner = lv_rw_wowner(v);
1012 			} while (owner != NULL && TD_IS_RUNNING(owner));
1013 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1014 			    "running");
1015 			continue;
1016 		} else if (RW_READERS(v) > 0) {
1017 			sleep_reason = READERS;
1018 			if (spintries == rowner_retries)
1019 				goto ts;
1020 			if (!(v & RW_LOCK_WRITE_SPINNER)) {
1021 				if (!in_critical) {
1022 					critical_enter();
1023 					in_critical = true;
1024 					extra_work++;
1025 				}
1026 				if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1027 				    v | RW_LOCK_WRITE_SPINNER)) {
1028 					critical_exit();
1029 					in_critical = false;
1030 					extra_work--;
1031 					continue;
1032 				}
1033 			}
1034 			spintries++;
1035 			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
1036 			    "spinning", "lockname:\"%s\"",
1037 			    rw->lock_object.lo_name);
1038 			n = RW_READERS(v);
1039 			for (i = 0; i < rowner_loops; i += n) {
1040 				lock_delay_spin(n);
1041 				v = RW_READ_VALUE(rw);
1042 				if (!(v & RW_LOCK_WRITE_SPINNER))
1043 					break;
1044 				if (!(v & RW_LOCK_READ))
1045 					break;
1046 				n = RW_READERS(v);
1047 				if (n == 0)
1048 					break;
1049 			}
1050 #ifdef KDTRACE_HOOKS
1051 			lda.spin_cnt += i;
1052 #endif
1053 			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
1054 			    "running");
1055 			if (i < rowner_loops)
1056 				continue;
1057 		}
1058 ts:
1059 #endif
1060 		ts = turnstile_trywait(&rw->lock_object);
1061 		v = RW_READ_VALUE(rw);
1062 retry_ts:
1063 		owner = lv_rw_wowner(v);
1064 
1065 #ifdef ADAPTIVE_RWLOCKS
1066 		/*
1067 		 * The current lock owner might have started executing
1068 		 * on another CPU (or the lock could have changed
1069 		 * owners) while we were waiting on the turnstile
1070 		 * chain lock.  If so, drop the turnstile lock and try
1071 		 * again.
1072 		 */
1073 		if (owner != NULL) {
1074 			if (TD_IS_RUNNING(owner)) {
1075 				turnstile_cancel(ts);
1076 				rw_drop_critical(v, &in_critical, &extra_work);
1077 				continue;
1078 			}
1079 		} else if (RW_READERS(v) > 0 && sleep_reason == WRITER) {
1080 			turnstile_cancel(ts);
1081 			rw_drop_critical(v, &in_critical, &extra_work);
1082 			continue;
1083 		}
1084 #endif
1085 		/*
1086 		 * Check for the waiters flags about this rwlock.
1087 		 * If the lock was released, without maintain any pending
1088 		 * waiters queue, simply try to acquire it.
1089 		 * If a pending waiters queue is present, claim the lock
1090 		 * ownership and maintain the pending queue.
1091 		 */
1092 		setv = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
1093 		if ((v & ~setv) == RW_UNLOCKED) {
1094 			setv &= ~RW_LOCK_WRITE_SPINNER;
1095 			if (atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid | setv)) {
1096 				if (setv)
1097 					turnstile_claim(ts);
1098 				else
1099 					turnstile_cancel(ts);
1100 				break;
1101 			}
1102 			goto retry_ts;
1103 		}
1104 
1105 #ifdef ADAPTIVE_RWLOCKS
1106 		if (in_critical) {
1107 			if ((v & RW_LOCK_WRITE_SPINNER) ||
1108 			    !((v & RW_LOCK_WRITE_WAITERS))) {
1109 				setv = v & ~RW_LOCK_WRITE_SPINNER;
1110 				setv |= RW_LOCK_WRITE_WAITERS;
1111 				if (!atomic_fcmpset_ptr(&rw->rw_lock, &v, setv))
1112 					goto retry_ts;
1113 			}
1114 			critical_exit();
1115 			in_critical = false;
1116 			extra_work--;
1117 		} else {
1118 #endif
1119 			/*
1120 			 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
1121 			 * set it.  If we fail to set it, then loop back and try
1122 			 * again.
1123 			 */
1124 			if (!(v & RW_LOCK_WRITE_WAITERS)) {
1125 				if (!atomic_fcmpset_ptr(&rw->rw_lock, &v,
1126 				    v | RW_LOCK_WRITE_WAITERS))
1127 					goto retry_ts;
1128 				if (LOCK_LOG_TEST(&rw->lock_object, 0))
1129 					CTR2(KTR_LOCK, "%s: %p set write waiters flag",
1130 					    __func__, rw);
1131 			}
1132 #ifdef ADAPTIVE_RWLOCKS
1133 		}
1134 #endif
1135 		/*
1136 		 * We were unable to acquire the lock and the write waiters
1137 		 * flag is set, so we must block on the turnstile.
1138 		 */
1139 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
1140 			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
1141 			    rw);
1142 #ifdef KDTRACE_HOOKS
1143 		sleep_time -= lockstat_nsecs(&rw->lock_object);
1144 #endif
1145 		MPASS(owner == rw_owner(rw));
1146 		turnstile_wait(ts, owner, TS_EXCLUSIVE_QUEUE);
1147 #ifdef KDTRACE_HOOKS
1148 		sleep_time += lockstat_nsecs(&rw->lock_object);
1149 		sleep_cnt++;
1150 #endif
1151 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
1152 			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
1153 			    __func__, rw);
1154 #ifdef ADAPTIVE_RWLOCKS
1155 		spintries = 0;
1156 #endif
1157 		v = RW_READ_VALUE(rw);
1158 	}
1159 	if (__predict_true(!extra_work))
1160 		return;
1161 #ifdef ADAPTIVE_RWLOCKS
1162 	if (in_critical)
1163 		critical_exit();
1164 #endif
1165 #if defined(KDTRACE_HOOKS) || defined(LOCK_PROFILING)
1166 	if (__predict_true(!doing_lockprof))
1167 		return;
1168 #endif
1169 #ifdef KDTRACE_HOOKS
1170 	all_time += lockstat_nsecs(&rw->lock_object);
1171 	if (sleep_time)
1172 		LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
1173 		    LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1174 		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1175 
1176 	/* Record only the loops spinning and not sleeping. */
1177 	if (lda.spin_cnt > sleep_cnt)
1178 		LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
1179 		    LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
1180 		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
1181 out_lockstat:
1182 #endif
1183 	LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
1184 	    waittime, file, line, LOCKSTAT_WRITER);
1185 }
1186 
1187 /*
1188  * This function is called if lockstat is active or the first try at releasing
1189  * a write lock failed.  The latter means that the lock is recursed or one of
1190  * the 2 waiter bits must be set indicating that at least one thread is waiting
1191  * on this lock.
1192  */
1193 void
1194 __rw_wunlock_hard(volatile uintptr_t *c, uintptr_t v LOCK_FILE_LINE_ARG_DEF)
1195 {
1196 	struct rwlock *rw;
1197 	struct turnstile *ts;
1198 	uintptr_t tid, setv;
1199 	int queue;
1200 
1201 	tid = (uintptr_t)curthread;
1202 	if (SCHEDULER_STOPPED())
1203 		return;
1204 
1205 	rw = rwlock2rw(c);
1206 	if (__predict_false(v == tid))
1207 		v = RW_READ_VALUE(rw);
1208 
1209 	if (v & RW_LOCK_WRITER_RECURSED) {
1210 		if (--(rw->rw_recurse) == 0)
1211 			atomic_clear_ptr(&rw->rw_lock, RW_LOCK_WRITER_RECURSED);
1212 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
1213 			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
1214 		return;
1215 	}
1216 
1217 	LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_WRITER);
1218 	if (v == tid && _rw_write_unlock(rw, tid))
1219 		return;
1220 
1221 	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
1222 	    ("%s: neither of the waiter flags are set", __func__));
1223 
1224 	if (LOCK_LOG_TEST(&rw->lock_object, 0))
1225 		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
1226 
1227 	turnstile_chain_lock(&rw->lock_object);
1228 
1229 	/*
1230 	 * Use the same algo as sx locks for now.  Prefer waking up shared
1231 	 * waiters if we have any over writers.  This is probably not ideal.
1232 	 *
1233 	 * 'v' is the value we are going to write back to rw_lock.  If we
1234 	 * have waiters on both queues, we need to preserve the state of
1235 	 * the waiter flag for the queue we don't wake up.  For now this is
1236 	 * hardcoded for the algorithm mentioned above.
1237 	 *
1238 	 * In the case of both readers and writers waiting we wakeup the
1239 	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
1240 	 * new writer comes in before a reader it will claim the lock up
1241 	 * above.  There is probably a potential priority inversion in
1242 	 * there that could be worked around either by waking both queues
1243 	 * of waiters or doing some complicated lock handoff gymnastics.
1244 	 */
1245 	setv = RW_UNLOCKED;
1246 	v = RW_READ_VALUE(rw);
1247 	queue = TS_SHARED_QUEUE;
1248 	if (v & RW_LOCK_WRITE_WAITERS) {
1249 		queue = TS_EXCLUSIVE_QUEUE;
1250 		setv |= (v & RW_LOCK_READ_WAITERS);
1251 	}
1252 	atomic_store_rel_ptr(&rw->rw_lock, setv);
1253 
1254 	/* Wake up all waiters for the specific queue. */
1255 	if (LOCK_LOG_TEST(&rw->lock_object, 0))
1256 		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
1257 		    queue == TS_SHARED_QUEUE ? "read" : "write");
1258 
1259 	ts = turnstile_lookup(&rw->lock_object);
1260 	MPASS(ts != NULL);
1261 	turnstile_broadcast(ts, queue);
1262 	turnstile_unpend(ts);
1263 	turnstile_chain_unlock(&rw->lock_object);
1264 }
1265 
1266 /*
1267  * Attempt to do a non-blocking upgrade from a read lock to a write
1268  * lock.  This will only succeed if this thread holds a single read
1269  * lock.  Returns true if the upgrade succeeded and false otherwise.
1270  */
1271 int
1272 __rw_try_upgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1273 {
1274 	uintptr_t v, setv, tid;
1275 	struct turnstile *ts;
1276 	int success;
1277 
1278 	if (SCHEDULER_STOPPED())
1279 		return (1);
1280 
1281 	KASSERT(rw->rw_lock != RW_DESTROYED,
1282 	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1283 	__rw_assert(&rw->rw_lock, RA_RLOCKED, file, line);
1284 
1285 	/*
1286 	 * Attempt to switch from one reader to a writer.  If there
1287 	 * are any write waiters, then we will have to lock the
1288 	 * turnstile first to prevent races with another writer
1289 	 * calling turnstile_wait() before we have claimed this
1290 	 * turnstile.  So, do the simple case of no waiters first.
1291 	 */
1292 	tid = (uintptr_t)curthread;
1293 	success = 0;
1294 	v = RW_READ_VALUE(rw);
1295 	for (;;) {
1296 		if (RW_READERS(v) > 1)
1297 			break;
1298 		if (!(v & RW_LOCK_WAITERS)) {
1299 			success = atomic_fcmpset_acq_ptr(&rw->rw_lock, &v, tid);
1300 			if (!success)
1301 				continue;
1302 			break;
1303 		}
1304 
1305 		/*
1306 		 * Ok, we think we have waiters, so lock the turnstile.
1307 		 */
1308 		ts = turnstile_trywait(&rw->lock_object);
1309 		v = RW_READ_VALUE(rw);
1310 retry_ts:
1311 		if (RW_READERS(v) > 1) {
1312 			turnstile_cancel(ts);
1313 			break;
1314 		}
1315 		/*
1316 		 * Try to switch from one reader to a writer again.  This time
1317 		 * we honor the current state of the waiters flags.
1318 		 * If we obtain the lock with the flags set, then claim
1319 		 * ownership of the turnstile.
1320 		 */
1321 		setv = tid | (v & RW_LOCK_WAITERS);
1322 		success = atomic_fcmpset_ptr(&rw->rw_lock, &v, setv);
1323 		if (success) {
1324 			if (v & RW_LOCK_WAITERS)
1325 				turnstile_claim(ts);
1326 			else
1327 				turnstile_cancel(ts);
1328 			break;
1329 		}
1330 		goto retry_ts;
1331 	}
1332 	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1333 	if (success) {
1334 		curthread->td_rw_rlocks--;
1335 		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1336 		    file, line);
1337 		LOCKSTAT_RECORD0(rw__upgrade, rw);
1338 	}
1339 	return (success);
1340 }
1341 
1342 int
1343 __rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1344 {
1345 	struct rwlock *rw;
1346 
1347 	rw = rwlock2rw(c);
1348 	return (__rw_try_upgrade_int(rw LOCK_FILE_LINE_ARG));
1349 }
1350 
1351 /*
1352  * Downgrade a write lock into a single read lock.
1353  */
1354 void
1355 __rw_downgrade_int(struct rwlock *rw LOCK_FILE_LINE_ARG_DEF)
1356 {
1357 	struct turnstile *ts;
1358 	uintptr_t tid, v;
1359 	int rwait, wwait;
1360 
1361 	if (SCHEDULER_STOPPED())
1362 		return;
1363 
1364 	KASSERT(rw->rw_lock != RW_DESTROYED,
1365 	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1366 	__rw_assert(&rw->rw_lock, RA_WLOCKED | RA_NOTRECURSED, file, line);
1367 #ifndef INVARIANTS
1368 	if (rw_recursed(rw))
1369 		panic("downgrade of a recursed lock");
1370 #endif
1371 
1372 	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1373 
1374 	/*
1375 	 * Convert from a writer to a single reader.  First we handle
1376 	 * the easy case with no waiters.  If there are any waiters, we
1377 	 * lock the turnstile and "disown" the lock.
1378 	 */
1379 	tid = (uintptr_t)curthread;
1380 	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1381 		goto out;
1382 
1383 	/*
1384 	 * Ok, we think we have waiters, so lock the turnstile so we can
1385 	 * read the waiter flags without any races.
1386 	 */
1387 	turnstile_chain_lock(&rw->lock_object);
1388 	v = rw->rw_lock & RW_LOCK_WAITERS;
1389 	rwait = v & RW_LOCK_READ_WAITERS;
1390 	wwait = v & RW_LOCK_WRITE_WAITERS;
1391 	MPASS(rwait | wwait);
1392 
1393 	/*
1394 	 * Downgrade from a write lock while preserving waiters flag
1395 	 * and give up ownership of the turnstile.
1396 	 */
1397 	ts = turnstile_lookup(&rw->lock_object);
1398 	MPASS(ts != NULL);
1399 	if (!wwait)
1400 		v &= ~RW_LOCK_READ_WAITERS;
1401 	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1402 	/*
1403 	 * Wake other readers if there are no writers pending.  Otherwise they
1404 	 * won't be able to acquire the lock anyway.
1405 	 */
1406 	if (rwait && !wwait) {
1407 		turnstile_broadcast(ts, TS_SHARED_QUEUE);
1408 		turnstile_unpend(ts);
1409 	} else
1410 		turnstile_disown(ts);
1411 	turnstile_chain_unlock(&rw->lock_object);
1412 out:
1413 	curthread->td_rw_rlocks++;
1414 	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1415 	LOCKSTAT_RECORD0(rw__downgrade, rw);
1416 }
1417 
1418 void
1419 __rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1420 {
1421 	struct rwlock *rw;
1422 
1423 	rw = rwlock2rw(c);
1424 	__rw_downgrade_int(rw LOCK_FILE_LINE_ARG);
1425 }
1426 
1427 #ifdef INVARIANT_SUPPORT
1428 #ifndef INVARIANTS
1429 #undef __rw_assert
1430 #endif
1431 
1432 /*
1433  * In the non-WITNESS case, rw_assert() can only detect that at least
1434  * *some* thread owns an rlock, but it cannot guarantee that *this*
1435  * thread owns an rlock.
1436  */
1437 void
1438 __rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1439 {
1440 	const struct rwlock *rw;
1441 
1442 	if (panicstr != NULL)
1443 		return;
1444 
1445 	rw = rwlock2rw(c);
1446 
1447 	switch (what) {
1448 	case RA_LOCKED:
1449 	case RA_LOCKED | RA_RECURSED:
1450 	case RA_LOCKED | RA_NOTRECURSED:
1451 	case RA_RLOCKED:
1452 	case RA_RLOCKED | RA_RECURSED:
1453 	case RA_RLOCKED | RA_NOTRECURSED:
1454 #ifdef WITNESS
1455 		witness_assert(&rw->lock_object, what, file, line);
1456 #else
1457 		/*
1458 		 * If some other thread has a write lock or we have one
1459 		 * and are asserting a read lock, fail.  Also, if no one
1460 		 * has a lock at all, fail.
1461 		 */
1462 		if (rw->rw_lock == RW_UNLOCKED ||
1463 		    (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1464 		    rw_wowner(rw) != curthread)))
1465 			panic("Lock %s not %slocked @ %s:%d\n",
1466 			    rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1467 			    "read " : "", file, line);
1468 
1469 		if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1470 			if (rw_recursed(rw)) {
1471 				if (what & RA_NOTRECURSED)
1472 					panic("Lock %s recursed @ %s:%d\n",
1473 					    rw->lock_object.lo_name, file,
1474 					    line);
1475 			} else if (what & RA_RECURSED)
1476 				panic("Lock %s not recursed @ %s:%d\n",
1477 				    rw->lock_object.lo_name, file, line);
1478 		}
1479 #endif
1480 		break;
1481 	case RA_WLOCKED:
1482 	case RA_WLOCKED | RA_RECURSED:
1483 	case RA_WLOCKED | RA_NOTRECURSED:
1484 		if (rw_wowner(rw) != curthread)
1485 			panic("Lock %s not exclusively locked @ %s:%d\n",
1486 			    rw->lock_object.lo_name, file, line);
1487 		if (rw_recursed(rw)) {
1488 			if (what & RA_NOTRECURSED)
1489 				panic("Lock %s recursed @ %s:%d\n",
1490 				    rw->lock_object.lo_name, file, line);
1491 		} else if (what & RA_RECURSED)
1492 			panic("Lock %s not recursed @ %s:%d\n",
1493 			    rw->lock_object.lo_name, file, line);
1494 		break;
1495 	case RA_UNLOCKED:
1496 #ifdef WITNESS
1497 		witness_assert(&rw->lock_object, what, file, line);
1498 #else
1499 		/*
1500 		 * If we hold a write lock fail.  We can't reliably check
1501 		 * to see if we hold a read lock or not.
1502 		 */
1503 		if (rw_wowner(rw) == curthread)
1504 			panic("Lock %s exclusively locked @ %s:%d\n",
1505 			    rw->lock_object.lo_name, file, line);
1506 #endif
1507 		break;
1508 	default:
1509 		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1510 		    line);
1511 	}
1512 }
1513 #endif /* INVARIANT_SUPPORT */
1514 
1515 #ifdef DDB
1516 void
1517 db_show_rwlock(const struct lock_object *lock)
1518 {
1519 	const struct rwlock *rw;
1520 	struct thread *td;
1521 
1522 	rw = (const struct rwlock *)lock;
1523 
1524 	db_printf(" state: ");
1525 	if (rw->rw_lock == RW_UNLOCKED)
1526 		db_printf("UNLOCKED\n");
1527 	else if (rw->rw_lock == RW_DESTROYED) {
1528 		db_printf("DESTROYED\n");
1529 		return;
1530 	} else if (rw->rw_lock & RW_LOCK_READ)
1531 		db_printf("RLOCK: %ju locks\n",
1532 		    (uintmax_t)(RW_READERS(rw->rw_lock)));
1533 	else {
1534 		td = rw_wowner(rw);
1535 		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1536 		    td->td_tid, td->td_proc->p_pid, td->td_name);
1537 		if (rw_recursed(rw))
1538 			db_printf(" recursed: %u\n", rw->rw_recurse);
1539 	}
1540 	db_printf(" waiters: ");
1541 	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1542 	case RW_LOCK_READ_WAITERS:
1543 		db_printf("readers\n");
1544 		break;
1545 	case RW_LOCK_WRITE_WAITERS:
1546 		db_printf("writers\n");
1547 		break;
1548 	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1549 		db_printf("readers and writers\n");
1550 		break;
1551 	default:
1552 		db_printf("none\n");
1553 		break;
1554 	}
1555 }
1556 
1557 #endif
1558