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