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