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