xref: /freebsd/sys/kern/kern_rwlock.c (revision d5fc25e5d6c52b306312784663ccad85923a9c76)
1 /*-
2  * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the author nor the names of any co-contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * Machine independent bits of reader/writer lock implementation.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_ddb.h"
38 #include "opt_kdtrace.h"
39 #include "opt_no_adaptive_rwlocks.h"
40 
41 #include <sys/param.h>
42 #include <sys/ktr.h>
43 #include <sys/kernel.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/proc.h>
47 #include <sys/rwlock.h>
48 #include <sys/sysctl.h>
49 #include <sys/systm.h>
50 #include <sys/turnstile.h>
51 
52 #include <machine/cpu.h>
53 
54 #if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
55 #define	ADAPTIVE_RWLOCKS
56 #endif
57 
58 #ifdef ADAPTIVE_RWLOCKS
59 static int rowner_retries = 10;
60 static int rowner_loops = 10000;
61 SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL, "rwlock debugging");
62 SYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
63 SYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
64 #endif
65 
66 #ifdef DDB
67 #include <ddb/ddb.h>
68 
69 static void	db_show_rwlock(struct lock_object *lock);
70 #endif
71 static void	assert_rw(struct lock_object *lock, int what);
72 static void	lock_rw(struct lock_object *lock, int how);
73 #ifdef KDTRACE_HOOKS
74 static int	owner_rw(struct lock_object *lock, struct thread **owner);
75 #endif
76 static int	unlock_rw(struct lock_object *lock);
77 
78 struct lock_class lock_class_rw = {
79 	.lc_name = "rw",
80 	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
81 	.lc_assert = assert_rw,
82 #ifdef DDB
83 	.lc_ddb_show = db_show_rwlock,
84 #endif
85 	.lc_lock = lock_rw,
86 	.lc_unlock = unlock_rw,
87 #ifdef KDTRACE_HOOKS
88 	.lc_owner = owner_rw,
89 #endif
90 };
91 
92 /*
93  * Return a pointer to the owning thread if the lock is write-locked or
94  * NULL if the lock is unlocked or read-locked.
95  */
96 #define	rw_wowner(rw)							\
97 	((rw)->rw_lock & RW_LOCK_READ ? NULL :				\
98 	    (struct thread *)RW_OWNER((rw)->rw_lock))
99 
100 /*
101  * Returns if a write owner is recursed.  Write ownership is not assured
102  * here and should be previously checked.
103  */
104 #define	rw_recursed(rw)		((rw)->rw_recurse != 0)
105 
106 /*
107  * Return true if curthread helds the lock.
108  */
109 #define	rw_wlocked(rw)		(rw_wowner((rw)) == curthread)
110 
111 /*
112  * Return a pointer to the owning thread for this lock who should receive
113  * any priority lent by threads that block on this lock.  Currently this
114  * is identical to rw_wowner().
115  */
116 #define	rw_owner(rw)		rw_wowner(rw)
117 
118 #ifndef INVARIANTS
119 #define	_rw_assert(rw, what, file, line)
120 #endif
121 
122 void
123 assert_rw(struct lock_object *lock, int what)
124 {
125 
126 	rw_assert((struct rwlock *)lock, what);
127 }
128 
129 void
130 lock_rw(struct lock_object *lock, int how)
131 {
132 	struct rwlock *rw;
133 
134 	rw = (struct rwlock *)lock;
135 	if (how)
136 		rw_wlock(rw);
137 	else
138 		rw_rlock(rw);
139 }
140 
141 int
142 unlock_rw(struct lock_object *lock)
143 {
144 	struct rwlock *rw;
145 
146 	rw = (struct rwlock *)lock;
147 	rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
148 	if (rw->rw_lock & RW_LOCK_READ) {
149 		rw_runlock(rw);
150 		return (0);
151 	} else {
152 		rw_wunlock(rw);
153 		return (1);
154 	}
155 }
156 
157 #ifdef KDTRACE_HOOKS
158 int
159 owner_rw(struct lock_object *lock, struct thread **owner)
160 {
161 	struct rwlock *rw = (struct rwlock *)lock;
162 	uintptr_t x = rw->rw_lock;
163 
164 	*owner = rw_wowner(rw);
165 	return ((x & RW_LOCK_READ) != 0 ?  (RW_READERS(x) != 0) :
166 	    (*owner != NULL));
167 }
168 #endif
169 
170 void
171 rw_init_flags(struct rwlock *rw, const char *name, int opts)
172 {
173 	int flags;
174 
175 	MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
176 	    RW_RECURSE)) == 0);
177 
178 	flags = LO_UPGRADABLE;
179 	if (opts & RW_DUPOK)
180 		flags |= LO_DUPOK;
181 	if (opts & RW_NOPROFILE)
182 		flags |= LO_NOPROFILE;
183 	if (!(opts & RW_NOWITNESS))
184 		flags |= LO_WITNESS;
185 	if (opts & RW_RECURSE)
186 		flags |= LO_RECURSABLE;
187 	if (opts & RW_QUIET)
188 		flags |= LO_QUIET;
189 
190 	rw->rw_lock = RW_UNLOCKED;
191 	rw->rw_recurse = 0;
192 	lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
193 }
194 
195 void
196 rw_destroy(struct rwlock *rw)
197 {
198 
199 	KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock not unlocked"));
200 	KASSERT(rw->rw_recurse == 0, ("rw lock still recursed"));
201 	rw->rw_lock = RW_DESTROYED;
202 	lock_destroy(&rw->lock_object);
203 }
204 
205 void
206 rw_sysinit(void *arg)
207 {
208 	struct rw_args *args = arg;
209 
210 	rw_init(args->ra_rw, args->ra_desc);
211 }
212 
213 void
214 rw_sysinit_flags(void *arg)
215 {
216 	struct rw_args_flags *args = arg;
217 
218 	rw_init_flags(args->ra_rw, args->ra_desc, args->ra_flags);
219 }
220 
221 int
222 rw_wowned(struct rwlock *rw)
223 {
224 
225 	return (rw_wowner(rw) == curthread);
226 }
227 
228 void
229 _rw_wlock(struct rwlock *rw, const char *file, int line)
230 {
231 
232 	MPASS(curthread != NULL);
233 	KASSERT(rw->rw_lock != RW_DESTROYED,
234 	    ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
235 	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
236 	    line, NULL);
237 	__rw_wlock(rw, curthread, file, line);
238 	LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
239 	WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
240 	curthread->td_locks++;
241 }
242 
243 int
244 _rw_try_wlock(struct rwlock *rw, const char *file, int line)
245 {
246 	int rval;
247 
248 	KASSERT(rw->rw_lock != RW_DESTROYED,
249 	    ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
250 
251 	if (rw_wlocked(rw) &&
252 	    (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
253 		rw->rw_recurse++;
254 		rval = 1;
255 	} else
256 		rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
257 		    (uintptr_t)curthread);
258 
259 	LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
260 	if (rval) {
261 		WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
262 		    file, line);
263 		curthread->td_locks++;
264 	}
265 	return (rval);
266 }
267 
268 void
269 _rw_wunlock(struct rwlock *rw, const char *file, int line)
270 {
271 
272 	MPASS(curthread != NULL);
273 	KASSERT(rw->rw_lock != RW_DESTROYED,
274 	    ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
275 	_rw_assert(rw, RA_WLOCKED, file, line);
276 	curthread->td_locks--;
277 	WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
278 	LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
279 	    line);
280 	if (!rw_recursed(rw))
281 		LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_WUNLOCK_RELEASE, rw);
282 	__rw_wunlock(rw, curthread, file, line);
283 }
284 /*
285  * Determines whether a new reader can acquire a lock.  Succeeds if the
286  * reader already owns a read lock and the lock is locked for read to
287  * prevent deadlock from reader recursion.  Also succeeds if the lock
288  * is unlocked and has no writer waiters or spinners.  Failing otherwise
289  * prioritizes writers before readers.
290  */
291 #define	RW_CAN_READ(_rw)						\
292     ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) &	\
293     (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) ==	\
294     RW_LOCK_READ)
295 
296 void
297 _rw_rlock(struct rwlock *rw, const char *file, int line)
298 {
299 	struct turnstile *ts;
300 #ifdef ADAPTIVE_RWLOCKS
301 	volatile struct thread *owner;
302 	int spintries = 0;
303 	int i;
304 #endif
305 #ifdef LOCK_PROFILING
306 	uint64_t waittime = 0;
307 	int contested = 0;
308 #endif
309 	uintptr_t v;
310 #ifdef KDTRACE_HOOKS
311 	uint64_t spin_cnt = 0;
312 	uint64_t sleep_cnt = 0;
313 	int64_t sleep_time = 0;
314 #endif
315 
316 	KASSERT(rw->rw_lock != RW_DESTROYED,
317 	    ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
318 	KASSERT(rw_wowner(rw) != curthread,
319 	    ("%s (%s): wlock already held @ %s:%d", __func__,
320 	    rw->lock_object.lo_name, file, line));
321 	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
322 
323 	for (;;) {
324 #ifdef KDTRACE_HOOKS
325 		spin_cnt++;
326 #endif
327 		/*
328 		 * Handle the easy case.  If no other thread has a write
329 		 * lock, then try to bump up the count of read locks.  Note
330 		 * that we have to preserve the current state of the
331 		 * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
332 		 * read lock, then rw_lock must have changed, so restart
333 		 * the loop.  Note that this handles the case of a
334 		 * completely unlocked rwlock since such a lock is encoded
335 		 * as a read lock with no waiters.
336 		 */
337 		v = rw->rw_lock;
338 		if (RW_CAN_READ(v)) {
339 			/*
340 			 * The RW_LOCK_READ_WAITERS flag should only be set
341 			 * if the lock has been unlocked and write waiters
342 			 * were present.
343 			 */
344 			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
345 			    v + RW_ONE_READER)) {
346 				if (LOCK_LOG_TEST(&rw->lock_object, 0))
347 					CTR4(KTR_LOCK,
348 					    "%s: %p succeed %p -> %p", __func__,
349 					    rw, (void *)v,
350 					    (void *)(v + RW_ONE_READER));
351 				break;
352 			}
353 			continue;
354 		}
355 		lock_profile_obtain_lock_failed(&rw->lock_object,
356 		    &contested, &waittime);
357 
358 #ifdef ADAPTIVE_RWLOCKS
359 		/*
360 		 * If the owner is running on another CPU, spin until
361 		 * the owner stops running or the state of the lock
362 		 * changes.
363 		 */
364 		if ((v & RW_LOCK_READ) == 0) {
365 			owner = (struct thread *)RW_OWNER(v);
366 			if (TD_IS_RUNNING(owner)) {
367 				if (LOCK_LOG_TEST(&rw->lock_object, 0))
368 					CTR3(KTR_LOCK,
369 					    "%s: spinning on %p held by %p",
370 					    __func__, rw, owner);
371 				while ((struct thread*)RW_OWNER(rw->rw_lock) ==
372 				    owner && TD_IS_RUNNING(owner)) {
373 					cpu_spinwait();
374 #ifdef KDTRACE_HOOKS
375 					spin_cnt++;
376 #endif
377 				}
378 				continue;
379 			}
380 		} else if (spintries < rowner_retries) {
381 			spintries++;
382 			for (i = 0; i < rowner_loops; i++) {
383 				v = rw->rw_lock;
384 				if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
385 					break;
386 				cpu_spinwait();
387 			}
388 			if (i != rowner_loops)
389 				continue;
390 		}
391 #endif
392 
393 		/*
394 		 * Okay, now it's the hard case.  Some other thread already
395 		 * has a write lock or there are write waiters present,
396 		 * acquire the turnstile lock so we can begin the process
397 		 * of blocking.
398 		 */
399 		ts = turnstile_trywait(&rw->lock_object);
400 
401 		/*
402 		 * The lock might have been released while we spun, so
403 		 * recheck its state and restart the loop if needed.
404 		 */
405 		v = rw->rw_lock;
406 		if (RW_CAN_READ(v)) {
407 			turnstile_cancel(ts);
408 			continue;
409 		}
410 
411 #ifdef ADAPTIVE_RWLOCKS
412 		/*
413 		 * The current lock owner might have started executing
414 		 * on another CPU (or the lock could have changed
415 		 * owners) while we were waiting on the turnstile
416 		 * chain lock.  If so, drop the turnstile lock and try
417 		 * again.
418 		 */
419 		if ((v & RW_LOCK_READ) == 0) {
420 			owner = (struct thread *)RW_OWNER(v);
421 			if (TD_IS_RUNNING(owner)) {
422 				turnstile_cancel(ts);
423 				continue;
424 			}
425 		}
426 #endif
427 
428 		/*
429 		 * The lock is held in write mode or it already has waiters.
430 		 */
431 		MPASS(!RW_CAN_READ(v));
432 
433 		/*
434 		 * If the RW_LOCK_READ_WAITERS flag is already set, then
435 		 * we can go ahead and block.  If it is not set then try
436 		 * to set it.  If we fail to set it drop the turnstile
437 		 * lock and restart the loop.
438 		 */
439 		if (!(v & RW_LOCK_READ_WAITERS)) {
440 			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
441 			    v | RW_LOCK_READ_WAITERS)) {
442 				turnstile_cancel(ts);
443 				continue;
444 			}
445 			if (LOCK_LOG_TEST(&rw->lock_object, 0))
446 				CTR2(KTR_LOCK, "%s: %p set read waiters flag",
447 				    __func__, rw);
448 		}
449 
450 		/*
451 		 * We were unable to acquire the lock and the read waiters
452 		 * flag is set, so we must block on the turnstile.
453 		 */
454 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
455 			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
456 			    rw);
457 #ifdef KDTRACE_HOOKS
458 		sleep_time -= lockstat_nsecs();
459 #endif
460 		turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
461 #ifdef KDTRACE_HOOKS
462 		sleep_time += lockstat_nsecs();
463 		sleep_cnt++;
464 #endif
465 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
466 			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
467 			    __func__, rw);
468 	}
469 
470 	/*
471 	 * TODO: acquire "owner of record" here.  Here be turnstile dragons
472 	 * however.  turnstiles don't like owners changing between calls to
473 	 * turnstile_wait() currently.
474 	 */
475 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
476 	    waittime, file, line);
477 	LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
478 	WITNESS_LOCK(&rw->lock_object, 0, file, line);
479 	curthread->td_locks++;
480 	curthread->td_rw_rlocks++;
481 #ifdef KDTRACE_HOOKS
482 	if (sleep_time)
483 		LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
484 
485 	/*
486 	 * Record only the loops spinning and not sleeping.
487 	 */
488 	if (spin_cnt > sleep_cnt)
489 		LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
490 #endif
491 }
492 
493 int
494 _rw_try_rlock(struct rwlock *rw, const char *file, int line)
495 {
496 	uintptr_t x;
497 
498 	for (;;) {
499 		x = rw->rw_lock;
500 		KASSERT(rw->rw_lock != RW_DESTROYED,
501 		    ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
502 		if (!(x & RW_LOCK_READ))
503 			break;
504 		if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
505 			LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
506 			    line);
507 			WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
508 			curthread->td_locks++;
509 			curthread->td_rw_rlocks++;
510 			return (1);
511 		}
512 	}
513 
514 	LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
515 	return (0);
516 }
517 
518 void
519 _rw_runlock(struct rwlock *rw, const char *file, int line)
520 {
521 	struct turnstile *ts;
522 	uintptr_t x, v, queue;
523 
524 	KASSERT(rw->rw_lock != RW_DESTROYED,
525 	    ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
526 	_rw_assert(rw, RA_RLOCKED, file, line);
527 	curthread->td_locks--;
528 	curthread->td_rw_rlocks--;
529 	WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
530 	LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
531 
532 	/* TODO: drop "owner of record" here. */
533 
534 	for (;;) {
535 		/*
536 		 * See if there is more than one read lock held.  If so,
537 		 * just drop one and return.
538 		 */
539 		x = rw->rw_lock;
540 		if (RW_READERS(x) > 1) {
541 			if (atomic_cmpset_ptr(&rw->rw_lock, x,
542 			    x - RW_ONE_READER)) {
543 				if (LOCK_LOG_TEST(&rw->lock_object, 0))
544 					CTR4(KTR_LOCK,
545 					    "%s: %p succeeded %p -> %p",
546 					    __func__, rw, (void *)x,
547 					    (void *)(x - RW_ONE_READER));
548 				break;
549 			}
550 			continue;
551 		}
552 		/*
553 		 * If there aren't any waiters for a write lock, then try
554 		 * to drop it quickly.
555 		 */
556 		if (!(x & RW_LOCK_WAITERS)) {
557 			MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
558 			    RW_READERS_LOCK(1));
559 			if (atomic_cmpset_ptr(&rw->rw_lock, x, RW_UNLOCKED)) {
560 				if (LOCK_LOG_TEST(&rw->lock_object, 0))
561 					CTR2(KTR_LOCK, "%s: %p last succeeded",
562 					    __func__, rw);
563 				break;
564 			}
565 			continue;
566 		}
567 		/*
568 		 * Ok, we know we have waiters and we think we are the
569 		 * last reader, so grab the turnstile lock.
570 		 */
571 		turnstile_chain_lock(&rw->lock_object);
572 		v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
573 		MPASS(v & RW_LOCK_WAITERS);
574 
575 		/*
576 		 * Try to drop our lock leaving the lock in a unlocked
577 		 * state.
578 		 *
579 		 * If you wanted to do explicit lock handoff you'd have to
580 		 * do it here.  You'd also want to use turnstile_signal()
581 		 * and you'd have to handle the race where a higher
582 		 * priority thread blocks on the write lock before the
583 		 * thread you wakeup actually runs and have the new thread
584 		 * "steal" the lock.  For now it's a lot simpler to just
585 		 * wakeup all of the waiters.
586 		 *
587 		 * As above, if we fail, then another thread might have
588 		 * acquired a read lock, so drop the turnstile lock and
589 		 * restart.
590 		 */
591 		x = RW_UNLOCKED;
592 		if (v & RW_LOCK_WRITE_WAITERS) {
593 			queue = TS_EXCLUSIVE_QUEUE;
594 			x |= (v & RW_LOCK_READ_WAITERS);
595 		} else
596 			queue = TS_SHARED_QUEUE;
597 		if (!atomic_cmpset_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
598 		    x)) {
599 			turnstile_chain_unlock(&rw->lock_object);
600 			continue;
601 		}
602 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
603 			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
604 			    __func__, rw);
605 
606 		/*
607 		 * Ok.  The lock is released and all that's left is to
608 		 * wake up the waiters.  Note that the lock might not be
609 		 * free anymore, but in that case the writers will just
610 		 * block again if they run before the new lock holder(s)
611 		 * release the lock.
612 		 */
613 		ts = turnstile_lookup(&rw->lock_object);
614 		MPASS(ts != NULL);
615 		turnstile_broadcast(ts, queue);
616 		turnstile_unpend(ts, TS_SHARED_LOCK);
617 		turnstile_chain_unlock(&rw->lock_object);
618 		break;
619 	}
620 	LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
621 }
622 
623 /*
624  * This function is called when we are unable to obtain a write lock on the
625  * first try.  This means that at least one other thread holds either a
626  * read or write lock.
627  */
628 void
629 _rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
630 {
631 	struct turnstile *ts;
632 #ifdef ADAPTIVE_RWLOCKS
633 	volatile struct thread *owner;
634 	int spintries = 0;
635 	int i;
636 #endif
637 	uintptr_t v, x;
638 #ifdef LOCK_PROFILING
639 	uint64_t waittime = 0;
640 	int contested = 0;
641 #endif
642 #ifdef KDTRACE_HOOKS
643 	uint64_t spin_cnt = 0;
644 	uint64_t sleep_cnt = 0;
645 	int64_t sleep_time = 0;
646 #endif
647 
648 	if (rw_wlocked(rw)) {
649 		KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
650 		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
651 		    __func__, rw->lock_object.lo_name, file, line));
652 		rw->rw_recurse++;
653 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
654 			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
655 		return;
656 	}
657 
658 	if (LOCK_LOG_TEST(&rw->lock_object, 0))
659 		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
660 		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
661 
662 	while (!_rw_write_lock(rw, tid)) {
663 #ifdef KDTRACE_HOOKS
664 		spin_cnt++;
665 #endif
666 		lock_profile_obtain_lock_failed(&rw->lock_object,
667 		    &contested, &waittime);
668 #ifdef ADAPTIVE_RWLOCKS
669 		/*
670 		 * If the lock is write locked and the owner is
671 		 * running on another CPU, spin until the owner stops
672 		 * running or the state of the lock changes.
673 		 */
674 		v = rw->rw_lock;
675 		owner = (struct thread *)RW_OWNER(v);
676 		if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
677 			if (LOCK_LOG_TEST(&rw->lock_object, 0))
678 				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
679 				    __func__, rw, owner);
680 			while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
681 			    TD_IS_RUNNING(owner)) {
682 				cpu_spinwait();
683 #ifdef KDTRACE_HOOKS
684 				spin_cnt++;
685 #endif
686 			}
687 			continue;
688 		}
689 		if ((v & RW_LOCK_READ) && RW_READERS(v) &&
690 		    spintries < rowner_retries) {
691 			if (!(v & RW_LOCK_WRITE_SPINNER)) {
692 				if (!atomic_cmpset_ptr(&rw->rw_lock, v,
693 				    v | RW_LOCK_WRITE_SPINNER)) {
694 					continue;
695 				}
696 			}
697 			spintries++;
698 			for (i = 0; i < rowner_loops; i++) {
699 				if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
700 					break;
701 				cpu_spinwait();
702 			}
703 #ifdef KDTRACE_HOOKS
704 			spin_cnt += rowner_loops - i;
705 #endif
706 			if (i != rowner_loops)
707 				continue;
708 		}
709 #endif
710 		ts = turnstile_trywait(&rw->lock_object);
711 		v = rw->rw_lock;
712 
713 #ifdef ADAPTIVE_RWLOCKS
714 		/*
715 		 * The current lock owner might have started executing
716 		 * on another CPU (or the lock could have changed
717 		 * owners) while we were waiting on the turnstile
718 		 * chain lock.  If so, drop the turnstile lock and try
719 		 * again.
720 		 */
721 		if (!(v & RW_LOCK_READ)) {
722 			owner = (struct thread *)RW_OWNER(v);
723 			if (TD_IS_RUNNING(owner)) {
724 				turnstile_cancel(ts);
725 				continue;
726 			}
727 		}
728 #endif
729 		/*
730 		 * Check for the waiters flags about this rwlock.
731 		 * If the lock was released, without maintain any pending
732 		 * waiters queue, simply try to acquire it.
733 		 * If a pending waiters queue is present, claim the lock
734 		 * ownership and maintain the pending queue.
735 		 */
736 		x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
737 		if ((v & ~x) == RW_UNLOCKED) {
738 			x &= ~RW_LOCK_WRITE_SPINNER;
739 			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
740 				if (x)
741 					turnstile_claim(ts);
742 				else
743 					turnstile_cancel(ts);
744 				break;
745 			}
746 			turnstile_cancel(ts);
747 			continue;
748 		}
749 		/*
750 		 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
751 		 * set it.  If we fail to set it, then loop back and try
752 		 * again.
753 		 */
754 		if (!(v & RW_LOCK_WRITE_WAITERS)) {
755 			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
756 			    v | RW_LOCK_WRITE_WAITERS)) {
757 				turnstile_cancel(ts);
758 				continue;
759 			}
760 			if (LOCK_LOG_TEST(&rw->lock_object, 0))
761 				CTR2(KTR_LOCK, "%s: %p set write waiters flag",
762 				    __func__, rw);
763 		}
764 		/*
765 		 * We were unable to acquire the lock and the write waiters
766 		 * flag is set, so we must block on the turnstile.
767 		 */
768 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
769 			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
770 			    rw);
771 #ifdef KDTRACE_HOOKS
772 		sleep_time -= lockstat_nsecs();
773 #endif
774 		turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
775 #ifdef KDTRACE_HOOKS
776 		sleep_time += lockstat_nsecs();
777 		sleep_cnt++;
778 #endif
779 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
780 			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
781 			    __func__, rw);
782 #ifdef ADAPTIVE_RWLOCKS
783 		spintries = 0;
784 #endif
785 	}
786 	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
787 	    waittime, file, line);
788 #ifdef KDTRACE_HOOKS
789 	if (sleep_time)
790 		LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
791 
792 	/*
793 	 * Record only the loops spinning and not sleeping.
794 	 */
795 	if (spin_cnt > sleep_cnt)
796 		LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
797 #endif
798 }
799 
800 /*
801  * This function is called if the first try at releasing a write lock failed.
802  * This means that one of the 2 waiter bits must be set indicating that at
803  * least one thread is waiting on this lock.
804  */
805 void
806 _rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
807 {
808 	struct turnstile *ts;
809 	uintptr_t v;
810 	int queue;
811 
812 	if (rw_wlocked(rw) && rw_recursed(rw)) {
813 		rw->rw_recurse--;
814 		if (LOCK_LOG_TEST(&rw->lock_object, 0))
815 			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
816 		return;
817 	}
818 
819 	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
820 	    ("%s: neither of the waiter flags are set", __func__));
821 
822 	if (LOCK_LOG_TEST(&rw->lock_object, 0))
823 		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
824 
825 	turnstile_chain_lock(&rw->lock_object);
826 	ts = turnstile_lookup(&rw->lock_object);
827 	MPASS(ts != NULL);
828 
829 	/*
830 	 * Use the same algo as sx locks for now.  Prefer waking up shared
831 	 * waiters if we have any over writers.  This is probably not ideal.
832 	 *
833 	 * 'v' is the value we are going to write back to rw_lock.  If we
834 	 * have waiters on both queues, we need to preserve the state of
835 	 * the waiter flag for the queue we don't wake up.  For now this is
836 	 * hardcoded for the algorithm mentioned above.
837 	 *
838 	 * In the case of both readers and writers waiting we wakeup the
839 	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
840 	 * new writer comes in before a reader it will claim the lock up
841 	 * above.  There is probably a potential priority inversion in
842 	 * there that could be worked around either by waking both queues
843 	 * of waiters or doing some complicated lock handoff gymnastics.
844 	 */
845 	v = RW_UNLOCKED;
846 	if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
847 		queue = TS_EXCLUSIVE_QUEUE;
848 		v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
849 	} else
850 		queue = TS_SHARED_QUEUE;
851 
852 	/* Wake up all waiters for the specific queue. */
853 	if (LOCK_LOG_TEST(&rw->lock_object, 0))
854 		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
855 		    queue == TS_SHARED_QUEUE ? "read" : "write");
856 	turnstile_broadcast(ts, queue);
857 	atomic_store_rel_ptr(&rw->rw_lock, v);
858 	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
859 	turnstile_chain_unlock(&rw->lock_object);
860 }
861 
862 /*
863  * Attempt to do a non-blocking upgrade from a read lock to a write
864  * lock.  This will only succeed if this thread holds a single read
865  * lock.  Returns true if the upgrade succeeded and false otherwise.
866  */
867 int
868 _rw_try_upgrade(struct rwlock *rw, const char *file, int line)
869 {
870 	uintptr_t v, x, tid;
871 	struct turnstile *ts;
872 	int success;
873 
874 	KASSERT(rw->rw_lock != RW_DESTROYED,
875 	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
876 	_rw_assert(rw, RA_RLOCKED, file, line);
877 
878 	/*
879 	 * Attempt to switch from one reader to a writer.  If there
880 	 * are any write waiters, then we will have to lock the
881 	 * turnstile first to prevent races with another writer
882 	 * calling turnstile_wait() before we have claimed this
883 	 * turnstile.  So, do the simple case of no waiters first.
884 	 */
885 	tid = (uintptr_t)curthread;
886 	success = 0;
887 	for (;;) {
888 		v = rw->rw_lock;
889 		if (RW_READERS(v) > 1)
890 			break;
891 		if (!(v & RW_LOCK_WAITERS)) {
892 			success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
893 			if (!success)
894 				continue;
895 			break;
896 		}
897 
898 		/*
899 		 * Ok, we think we have waiters, so lock the turnstile.
900 		 */
901 		ts = turnstile_trywait(&rw->lock_object);
902 		v = rw->rw_lock;
903 		if (RW_READERS(v) > 1) {
904 			turnstile_cancel(ts);
905 			break;
906 		}
907 		/*
908 		 * Try to switch from one reader to a writer again.  This time
909 		 * we honor the current state of the waiters flags.
910 		 * If we obtain the lock with the flags set, then claim
911 		 * ownership of the turnstile.
912 		 */
913 		x = rw->rw_lock & RW_LOCK_WAITERS;
914 		success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
915 		if (success) {
916 			if (x)
917 				turnstile_claim(ts);
918 			else
919 				turnstile_cancel(ts);
920 			break;
921 		}
922 		turnstile_cancel(ts);
923 	}
924 	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
925 	if (success) {
926 		curthread->td_rw_rlocks--;
927 		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
928 		    file, line);
929 		LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
930 	}
931 	return (success);
932 }
933 
934 /*
935  * Downgrade a write lock into a single read lock.
936  */
937 void
938 _rw_downgrade(struct rwlock *rw, const char *file, int line)
939 {
940 	struct turnstile *ts;
941 	uintptr_t tid, v;
942 	int rwait, wwait;
943 
944 	KASSERT(rw->rw_lock != RW_DESTROYED,
945 	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
946 	_rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
947 #ifndef INVARIANTS
948 	if (rw_recursed(rw))
949 		panic("downgrade of a recursed lock");
950 #endif
951 
952 	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
953 
954 	/*
955 	 * Convert from a writer to a single reader.  First we handle
956 	 * the easy case with no waiters.  If there are any waiters, we
957 	 * lock the turnstile and "disown" the lock.
958 	 */
959 	tid = (uintptr_t)curthread;
960 	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
961 		goto out;
962 
963 	/*
964 	 * Ok, we think we have waiters, so lock the turnstile so we can
965 	 * read the waiter flags without any races.
966 	 */
967 	turnstile_chain_lock(&rw->lock_object);
968 	v = rw->rw_lock & RW_LOCK_WAITERS;
969 	rwait = v & RW_LOCK_READ_WAITERS;
970 	wwait = v & RW_LOCK_WRITE_WAITERS;
971 	MPASS(rwait | wwait);
972 
973 	/*
974 	 * Downgrade from a write lock while preserving waiters flag
975 	 * and give up ownership of the turnstile.
976 	 */
977 	ts = turnstile_lookup(&rw->lock_object);
978 	MPASS(ts != NULL);
979 	if (!wwait)
980 		v &= ~RW_LOCK_READ_WAITERS;
981 	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
982 	/*
983 	 * Wake other readers if there are no writers pending.  Otherwise they
984 	 * won't be able to acquire the lock anyway.
985 	 */
986 	if (rwait && !wwait) {
987 		turnstile_broadcast(ts, TS_SHARED_QUEUE);
988 		turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
989 	} else
990 		turnstile_disown(ts);
991 	turnstile_chain_unlock(&rw->lock_object);
992 out:
993 	curthread->td_rw_rlocks++;
994 	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
995 	LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
996 }
997 
998 #ifdef INVARIANT_SUPPORT
999 #ifndef INVARIANTS
1000 #undef _rw_assert
1001 #endif
1002 
1003 /*
1004  * In the non-WITNESS case, rw_assert() can only detect that at least
1005  * *some* thread owns an rlock, but it cannot guarantee that *this*
1006  * thread owns an rlock.
1007  */
1008 void
1009 _rw_assert(struct rwlock *rw, int what, const char *file, int line)
1010 {
1011 
1012 	if (panicstr != NULL)
1013 		return;
1014 	switch (what) {
1015 	case RA_LOCKED:
1016 	case RA_LOCKED | RA_RECURSED:
1017 	case RA_LOCKED | RA_NOTRECURSED:
1018 	case RA_RLOCKED:
1019 #ifdef WITNESS
1020 		witness_assert(&rw->lock_object, what, file, line);
1021 #else
1022 		/*
1023 		 * If some other thread has a write lock or we have one
1024 		 * and are asserting a read lock, fail.  Also, if no one
1025 		 * has a lock at all, fail.
1026 		 */
1027 		if (rw->rw_lock == RW_UNLOCKED ||
1028 		    (!(rw->rw_lock & RW_LOCK_READ) && (what == RA_RLOCKED ||
1029 		    rw_wowner(rw) != curthread)))
1030 			panic("Lock %s not %slocked @ %s:%d\n",
1031 			    rw->lock_object.lo_name, (what == RA_RLOCKED) ?
1032 			    "read " : "", file, line);
1033 
1034 		if (!(rw->rw_lock & RW_LOCK_READ)) {
1035 			if (rw_recursed(rw)) {
1036 				if (what & RA_NOTRECURSED)
1037 					panic("Lock %s recursed @ %s:%d\n",
1038 					    rw->lock_object.lo_name, file,
1039 					    line);
1040 			} else if (what & RA_RECURSED)
1041 				panic("Lock %s not recursed @ %s:%d\n",
1042 				    rw->lock_object.lo_name, file, line);
1043 		}
1044 #endif
1045 		break;
1046 	case RA_WLOCKED:
1047 	case RA_WLOCKED | RA_RECURSED:
1048 	case RA_WLOCKED | RA_NOTRECURSED:
1049 		if (rw_wowner(rw) != curthread)
1050 			panic("Lock %s not exclusively locked @ %s:%d\n",
1051 			    rw->lock_object.lo_name, file, line);
1052 		if (rw_recursed(rw)) {
1053 			if (what & RA_NOTRECURSED)
1054 				panic("Lock %s recursed @ %s:%d\n",
1055 				    rw->lock_object.lo_name, file, line);
1056 		} else if (what & RA_RECURSED)
1057 			panic("Lock %s not recursed @ %s:%d\n",
1058 			    rw->lock_object.lo_name, file, line);
1059 		break;
1060 	case RA_UNLOCKED:
1061 #ifdef WITNESS
1062 		witness_assert(&rw->lock_object, what, file, line);
1063 #else
1064 		/*
1065 		 * If we hold a write lock fail.  We can't reliably check
1066 		 * to see if we hold a read lock or not.
1067 		 */
1068 		if (rw_wowner(rw) == curthread)
1069 			panic("Lock %s exclusively locked @ %s:%d\n",
1070 			    rw->lock_object.lo_name, file, line);
1071 #endif
1072 		break;
1073 	default:
1074 		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1075 		    line);
1076 	}
1077 }
1078 #endif /* INVARIANT_SUPPORT */
1079 
1080 #ifdef DDB
1081 void
1082 db_show_rwlock(struct lock_object *lock)
1083 {
1084 	struct rwlock *rw;
1085 	struct thread *td;
1086 
1087 	rw = (struct rwlock *)lock;
1088 
1089 	db_printf(" state: ");
1090 	if (rw->rw_lock == RW_UNLOCKED)
1091 		db_printf("UNLOCKED\n");
1092 	else if (rw->rw_lock == RW_DESTROYED) {
1093 		db_printf("DESTROYED\n");
1094 		return;
1095 	} else if (rw->rw_lock & RW_LOCK_READ)
1096 		db_printf("RLOCK: %ju locks\n",
1097 		    (uintmax_t)(RW_READERS(rw->rw_lock)));
1098 	else {
1099 		td = rw_wowner(rw);
1100 		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1101 		    td->td_tid, td->td_proc->p_pid, td->td_name);
1102 		if (rw_recursed(rw))
1103 			db_printf(" recursed: %u\n", rw->rw_recurse);
1104 	}
1105 	db_printf(" waiters: ");
1106 	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1107 	case RW_LOCK_READ_WAITERS:
1108 		db_printf("readers\n");
1109 		break;
1110 	case RW_LOCK_WRITE_WAITERS:
1111 		db_printf("writers\n");
1112 		break;
1113 	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1114 		db_printf("readers and writers\n");
1115 		break;
1116 	default:
1117 		db_printf("none\n");
1118 		break;
1119 	}
1120 }
1121 
1122 #endif
1123