kern_rwlock.c revision 193035
1154941Sjhb/*-
2154941Sjhb * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
3154941Sjhb * All rights reserved.
4154941Sjhb *
5154941Sjhb * Redistribution and use in source and binary forms, with or without
6154941Sjhb * modification, are permitted provided that the following conditions
7154941Sjhb * are met:
8154941Sjhb * 1. Redistributions of source code must retain the above copyright
9154941Sjhb *    notice, this list of conditions and the following disclaimer.
10154941Sjhb * 2. Redistributions in binary form must reproduce the above copyright
11154941Sjhb *    notice, this list of conditions and the following disclaimer in the
12154941Sjhb *    documentation and/or other materials provided with the distribution.
13154941Sjhb * 3. Neither the name of the author nor the names of any co-contributors
14154941Sjhb *    may be used to endorse or promote products derived from this software
15154941Sjhb *    without specific prior written permission.
16154941Sjhb *
17154941Sjhb * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18154941Sjhb * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19154941Sjhb * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20154941Sjhb * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21154941Sjhb * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22154941Sjhb * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23154941Sjhb * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24154941Sjhb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25154941Sjhb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26154941Sjhb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27154941Sjhb * SUCH DAMAGE.
28154941Sjhb */
29154941Sjhb
30154941Sjhb/*
31154941Sjhb * Machine independent bits of reader/writer lock implementation.
32154941Sjhb */
33154941Sjhb
34154941Sjhb#include <sys/cdefs.h>
35154941Sjhb__FBSDID("$FreeBSD: head/sys/kern/kern_rwlock.c 193035 2009-05-29 13:56:34Z jhb $");
36154941Sjhb
37154941Sjhb#include "opt_ddb.h"
38192853Ssson#include "opt_kdtrace.h"
39167801Sjhb#include "opt_no_adaptive_rwlocks.h"
40154941Sjhb
41154941Sjhb#include <sys/param.h>
42154941Sjhb#include <sys/ktr.h>
43177912Sjeff#include <sys/kernel.h>
44154941Sjhb#include <sys/lock.h>
45154941Sjhb#include <sys/mutex.h>
46154941Sjhb#include <sys/proc.h>
47154941Sjhb#include <sys/rwlock.h>
48177912Sjeff#include <sys/sysctl.h>
49154941Sjhb#include <sys/systm.h>
50154941Sjhb#include <sys/turnstile.h>
51171516Sattilio
52154941Sjhb#include <machine/cpu.h>
53154941Sjhb
54167801SjhbCTASSERT((RW_RECURSE & LO_CLASSFLAGS) == RW_RECURSE);
55167801Sjhb
56167801Sjhb#if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
57167801Sjhb#define	ADAPTIVE_RWLOCKS
58177912Sjeff#endif
59177912Sjeff
60177912Sjeff#ifdef ADAPTIVE_RWLOCKS
61177912Sjeffstatic int rowner_retries = 10;
62177912Sjeffstatic int rowner_loops = 10000;
63177912SjeffSYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL, "rwlock debugging");
64177912SjeffSYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
65177912SjeffSYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
66154941Sjhb#endif
67154941Sjhb
68154941Sjhb#ifdef DDB
69154941Sjhb#include <ddb/ddb.h>
70154941Sjhb
71173733Sattiliostatic void	db_show_rwlock(struct lock_object *lock);
72167368Sjhb#endif
73192853Sssonstatic void	assert_rw(struct lock_object *lock, int what);
74192853Sssonstatic void	lock_rw(struct lock_object *lock, int how);
75192853Ssson#ifdef KDTRACE_HOOKS
76167368Sjhbstatic int	owner_rw(struct lock_object *lock, struct thread **owner);
77154941Sjhb#endif
78154941Sjhbstatic int	unlock_rw(struct lock_object *lock);
79167365Sjhb
80167365Sjhbstruct lock_class lock_class_rw = {
81173733Sattilio	.lc_name = "rw",
82154941Sjhb	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
83167365Sjhb	.lc_assert = assert_rw,
84154941Sjhb#ifdef DDB
85167368Sjhb	.lc_ddb_show = db_show_rwlock,
86167368Sjhb#endif
87192853Ssson	.lc_lock = lock_rw,
88192853Ssson	.lc_unlock = unlock_rw,
89192853Ssson#ifdef KDTRACE_HOOKS
90154941Sjhb	.lc_owner = owner_rw,
91154941Sjhb#endif
92157826Sjhb};
93157826Sjhb
94157826Sjhb/*
95157826Sjhb * Return a pointer to the owning thread if the lock is write-locked or
96157826Sjhb * NULL if the lock is unlocked or read-locked.
97154941Sjhb */
98154941Sjhb#define	rw_wowner(rw)							\
99154941Sjhb	((rw)->rw_lock & RW_LOCK_READ ? NULL :				\
100157826Sjhb	    (struct thread *)RW_OWNER((rw)->rw_lock))
101171052Sattilio
102171052Sattilio/*
103171052Sattilio * Returns if a write owner is recursed.  Write ownership is not assured
104171052Sattilio * here and should be previously checked.
105171052Sattilio */
106171052Sattilio#define	rw_recursed(rw)		((rw)->rw_recurse != 0)
107171052Sattilio
108171052Sattilio/*
109171052Sattilio * Return true if curthread helds the lock.
110171052Sattilio */
111171052Sattilio#define	rw_wlocked(rw)		(rw_wowner((rw)) == curthread)
112157826Sjhb
113157826Sjhb/*
114157826Sjhb * Return a pointer to the owning thread for this lock who should receive
115157826Sjhb * any priority lent by threads that block on this lock.  Currently this
116157826Sjhb * is identical to rw_wowner().
117157826Sjhb */
118154941Sjhb#define	rw_owner(rw)		rw_wowner(rw)
119154941Sjhb
120154941Sjhb#ifndef INVARIANTS
121154941Sjhb#define	_rw_assert(rw, what, file, line)
122154941Sjhb#endif
123173733Sattilio
124173733Sattiliovoid
125173733Sattilioassert_rw(struct lock_object *lock, int what)
126173733Sattilio{
127173733Sattilio
128173733Sattilio	rw_assert((struct rwlock *)lock, what);
129173733Sattilio}
130167368Sjhb
131167368Sjhbvoid
132167368Sjhblock_rw(struct lock_object *lock, int how)
133167368Sjhb{
134167368Sjhb	struct rwlock *rw;
135167368Sjhb
136167368Sjhb	rw = (struct rwlock *)lock;
137167368Sjhb	if (how)
138167368Sjhb		rw_wlock(rw);
139167368Sjhb	else
140167368Sjhb		rw_rlock(rw);
141167368Sjhb}
142167368Sjhb
143167368Sjhbint
144167368Sjhbunlock_rw(struct lock_object *lock)
145167368Sjhb{
146167368Sjhb	struct rwlock *rw;
147167368Sjhb
148167368Sjhb	rw = (struct rwlock *)lock;
149167368Sjhb	rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
150167368Sjhb	if (rw->rw_lock & RW_LOCK_READ) {
151167368Sjhb		rw_runlock(rw);
152167368Sjhb		return (0);
153167368Sjhb	} else {
154167368Sjhb		rw_wunlock(rw);
155167368Sjhb		return (1);
156167368Sjhb	}
157192853Ssson}
158192853Ssson
159192853Ssson#ifdef KDTRACE_HOOKS
160192853Sssonint
161192853Sssonowner_rw(struct lock_object *lock, struct thread **owner)
162192853Ssson{
163192853Ssson	struct rwlock *rw = (struct rwlock *)lock;
164192853Ssson	uintptr_t x = rw->rw_lock;
165192853Ssson
166192853Ssson	*owner = rw_wowner(rw);
167192853Ssson	return ((x & RW_LOCK_READ) != 0 ?  (RW_READERS(x) != 0) :
168192853Ssson	    (*owner != NULL));
169192853Ssson}
170167368Sjhb#endif
171171052Sattilio
172154941Sjhbvoid
173171052Sattiliorw_init_flags(struct rwlock *rw, const char *name, int opts)
174154941Sjhb{
175171052Sattilio	int flags;
176171052Sattilio
177196334Sattilio	MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
178196334Sattilio	    RW_RECURSE)) == 0);
179196334Sattilio
180171052Sattilio	flags = LO_UPGRADABLE | LO_RECURSABLE;
181193307Sattilio	if (opts & RW_DUPOK)
182171052Sattilio		flags |= LO_DUPOK;
183171052Sattilio	if (opts & RW_NOPROFILE)
184171052Sattilio		flags |= LO_NOPROFILE;
185171052Sattilio	if (!(opts & RW_NOWITNESS))
186171052Sattilio		flags |= LO_WITNESS;
187171052Sattilio	if (opts & RW_QUIET)
188193307Sattilio		flags |= LO_QUIET;
189193307Sattilio	flags |= opts & RW_RECURSE;
190171052Sattilio
191171052Sattilio	rw->rw_lock = RW_UNLOCKED;
192171052Sattilio	rw->rw_recurse = 0;
193154941Sjhb	lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
194171052Sattilio}
195171052Sattilio
196154941Sjhbvoid
197154941Sjhbrw_destroy(struct rwlock *rw)
198154941Sjhb{
199154941Sjhb
200154941Sjhb	KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock not unlocked"));
201154941Sjhb	KASSERT(rw->rw_recurse == 0, ("rw lock still recursed"));
202154941Sjhb	rw->rw_lock = RW_DESTROYED;
203171052Sattilio	lock_destroy(&rw->lock_object);
204169394Sjhb}
205167787Sjhb
206154941Sjhbvoid
207154941Sjhbrw_sysinit(void *arg)
208154941Sjhb{
209154941Sjhb	struct rw_args *args = arg;
210154941Sjhb
211154941Sjhb	rw_init(args->ra_rw, args->ra_desc);
212154941Sjhb}
213154941Sjhb
214154941Sjhbvoid
215154941Sjhbrw_sysinit_flags(void *arg)
216185778Skmacy{
217185778Skmacy	struct rw_args_flags *args = arg;
218185778Skmacy
219185778Skmacy	rw_init_flags(args->ra_rw, args->ra_desc, args->ra_flags);
220185778Skmacy}
221185778Skmacy
222185778Skmacyint
223185778Skmacyrw_wowned(struct rwlock *rw)
224167024Srwatson{
225167024Srwatson
226167024Srwatson	return (rw_wowner(rw) == curthread);
227167024Srwatson}
228167024Srwatson
229167024Srwatsonvoid
230167024Srwatson_rw_wlock(struct rwlock *rw, const char *file, int line)
231154941Sjhb{
232154941Sjhb
233154941Sjhb	MPASS(curthread != NULL);
234154941Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
235154941Sjhb	    ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
236169394Sjhb	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
237169394Sjhb	    line, NULL);
238167787Sjhb	__rw_wlock(rw, curthread, file, line);
239182914Sjhb	LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
240154941Sjhb	WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
241171052Sattilio	curthread->td_locks++;
242167787Sjhb}
243160771Sjhb
244154941Sjhbint
245154941Sjhb_rw_try_wlock(struct rwlock *rw, const char *file, int line)
246177843Sattilio{
247177843Sattilio	int rval;
248177843Sattilio
249177843Sattilio	KASSERT(rw->rw_lock != RW_DESTROYED,
250177843Sattilio	    ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
251177843Sattilio
252177843Sattilio	if (rw_wlocked(rw) && (rw->lock_object.lo_flags & RW_RECURSE) != 0) {
253177843Sattilio		rw->rw_recurse++;
254193307Sattilio		rval = 1;
255193307Sattilio	} else
256177843Sattilio		rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
257177843Sattilio		    (uintptr_t)curthread);
258177843Sattilio
259177843Sattilio	LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
260177843Sattilio	if (rval) {
261177843Sattilio		WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
262177843Sattilio		    file, line);
263177843Sattilio		curthread->td_locks++;
264177843Sattilio	}
265177843Sattilio	return (rval);
266177843Sattilio}
267177843Sattilio
268177843Sattiliovoid
269177843Sattilio_rw_wunlock(struct rwlock *rw, const char *file, int line)
270177843Sattilio{
271154941Sjhb
272154941Sjhb	MPASS(curthread != NULL);
273154941Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
274154941Sjhb	    ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
275154941Sjhb	_rw_assert(rw, RA_WLOCKED, file, line);
276169394Sjhb	curthread->td_locks--;
277169394Sjhb	WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
278154941Sjhb	LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
279160771Sjhb	    line);
280167787Sjhb	if (!rw_recursed(rw))
281171052Sattilio		LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_WUNLOCK_RELEASE, rw);
282171052Sattilio	__rw_wunlock(rw, curthread, file, line);
283171052Sattilio}
284192853Ssson/*
285154941Sjhb * Determines whether a new reader can acquire a lock.  Succeeds if the
286154941Sjhb * reader already owns a read lock and the lock is locked for read to
287176017Sjeff * prevent deadlock from reader recursion.  Also succeeds if the lock
288176017Sjeff * is unlocked and has no writer waiters or spinners.  Failing otherwise
289176017Sjeff * prioritizes writers before readers.
290176017Sjeff */
291176017Sjeff#define	RW_CAN_READ(_rw)						\
292176017Sjeff    ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) &	\
293176017Sjeff    (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) ==	\
294176017Sjeff    RW_LOCK_READ)
295176017Sjeff
296176017Sjeffvoid
297176017Sjeff_rw_rlock(struct rwlock *rw, const char *file, int line)
298154941Sjhb{
299154941Sjhb	struct turnstile *ts;
300154941Sjhb#ifdef ADAPTIVE_RWLOCKS
301154941Sjhb	volatile struct thread *owner;
302170295Sjeff	int spintries = 0;
303167801Sjhb	int i;
304157846Sjhb#endif
305177912Sjeff#ifdef LOCK_PROFILING
306177912Sjeff	uint64_t waittime = 0;
307157851Swkoszek	int contested = 0;
308189846Sjeff#endif
309167307Sjhb	uintptr_t v;
310167054Skmacy#ifdef KDTRACE_HOOKS
311189846Sjeff	uint64_t spin_cnt = 0;
312176017Sjeff	uint64_t sleep_cnt = 0;
313192853Ssson	int64_t sleep_time = 0;
314192853Ssson#endif
315192853Ssson
316192853Ssson	KASSERT(rw->rw_lock != RW_DESTROYED,
317192853Ssson	    ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
318154941Sjhb	KASSERT(rw_wowner(rw) != curthread,
319169394Sjhb	    ("%s (%s): wlock already held @ %s:%d", __func__,
320169394Sjhb	    rw->lock_object.lo_name, file, line));
321157826Sjhb	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
322154941Sjhb
323167787Sjhb	for (;;) {
324182914Sjhb#ifdef KDTRACE_HOOKS
325154941Sjhb		spin_cnt++;
326154941Sjhb#endif
327192853Ssson		/*
328192853Ssson		 * Handle the easy case.  If no other thread has a write
329192853Ssson		 * lock, then try to bump up the count of read locks.  Note
330154941Sjhb		 * that we have to preserve the current state of the
331154941Sjhb		 * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
332154941Sjhb		 * read lock, then rw_lock must have changed, so restart
333154941Sjhb		 * the loop.  Note that this handles the case of a
334154941Sjhb		 * completely unlocked rwlock since such a lock is encoded
335154941Sjhb		 * as a read lock with no waiters.
336154941Sjhb		 */
337154941Sjhb		v = rw->rw_lock;
338154941Sjhb		if (RW_CAN_READ(v)) {
339154941Sjhb			/*
340176017Sjeff			 * The RW_LOCK_READ_WAITERS flag should only be set
341176017Sjeff			 * if the lock has been unlocked and write waiters
342154941Sjhb			 * were present.
343154941Sjhb			 */
344176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
345176017Sjeff			    v + RW_ONE_READER)) {
346154941Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
347176017Sjeff					CTR4(KTR_LOCK,
348176017Sjeff					    "%s: %p succeed %p -> %p", __func__,
349167787Sjhb					    rw, (void *)v,
350154941Sjhb					    (void *)(v + RW_ONE_READER));
351154941Sjhb				break;
352176017Sjeff			}
353176017Sjeff			cpu_spinwait();
354154941Sjhb			continue;
355154941Sjhb		}
356154941Sjhb		lock_profile_obtain_lock_failed(&rw->lock_object,
357154941Sjhb		    &contested, &waittime);
358174629Sjeff
359174629Sjeff#ifdef ADAPTIVE_RWLOCKS
360154941Sjhb		/*
361173960Sattilio		 * If the owner is running on another CPU, spin until
362154941Sjhb		 * the owner stops running or the state of the lock
363173960Sattilio		 * changes.
364173960Sattilio		 */
365173960Sattilio		if ((v & RW_LOCK_READ) == 0) {
366173960Sattilio			owner = (struct thread *)RW_OWNER(v);
367176017Sjeff			if (TD_IS_RUNNING(owner)) {
368176017Sjeff				if (LOCK_LOG_TEST(&rw->lock_object, 0))
369176017Sjeff					CTR3(KTR_LOCK,
370176017Sjeff					    "%s: spinning on %p held by %p",
371176017Sjeff					    __func__, rw, owner);
372176017Sjeff				while ((struct thread*)RW_OWNER(rw->rw_lock) ==
373176017Sjeff				    owner && TD_IS_RUNNING(owner)) {
374176017Sjeff					cpu_spinwait();
375192853Ssson#ifdef KDTRACE_HOOKS
376176017Sjeff					spin_cnt++;
377192853Ssson#endif
378192853Ssson				}
379192853Ssson				continue;
380192853Ssson			}
381176017Sjeff		} else if (spintries < rowner_retries) {
382176017Sjeff			spintries++;
383177912Sjeff			for (i = 0; i < rowner_loops; i++) {
384177912Sjeff				v = rw->rw_lock;
385177912Sjeff				if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
386177912Sjeff					break;
387177912Sjeff				cpu_spinwait();
388177912Sjeff			}
389177912Sjeff			if (i != rowner_loops)
390177912Sjeff				continue;
391177912Sjeff		}
392177912Sjeff#endif
393173960Sattilio
394173960Sattilio		/*
395173960Sattilio		 * Okay, now it's the hard case.  Some other thread already
396173960Sattilio		 * has a write lock or there are write waiters present,
397154941Sjhb		 * acquire the turnstile lock so we can begin the process
398176017Sjeff		 * of blocking.
399176017Sjeff		 */
400176017Sjeff		ts = turnstile_trywait(&rw->lock_object);
401154941Sjhb
402170295Sjeff		/*
403154941Sjhb		 * The lock might have been released while we spun, so
404154941Sjhb		 * recheck its state and restart the loop if needed.
405154941Sjhb		 */
406176017Sjeff		v = rw->rw_lock;
407154941Sjhb		if (RW_CAN_READ(v)) {
408176017Sjeff			turnstile_cancel(ts);
409176017Sjeff			cpu_spinwait();
410170295Sjeff			continue;
411154941Sjhb		}
412154941Sjhb
413154941Sjhb#ifdef ADAPTIVE_RWLOCKS
414173960Sattilio		/*
415154941Sjhb		 * The current lock owner might have started executing
416193035Sjhb		 * on another CPU (or the lock could have changed
417193035Sjhb		 * owners) while we were waiting on the turnstile
418193035Sjhb		 * chain lock.  If so, drop the turnstile lock and try
419193035Sjhb		 * again.
420193035Sjhb		 */
421173960Sattilio		if ((v & RW_LOCK_READ) == 0) {
422176017Sjeff			owner = (struct thread *)RW_OWNER(v);
423176017Sjeff			if (TD_IS_RUNNING(owner)) {
424176017Sjeff				turnstile_cancel(ts);
425176017Sjeff				cpu_spinwait();
426176017Sjeff				continue;
427176017Sjeff			}
428173960Sattilio		}
429173960Sattilio#endif
430173960Sattilio
431173960Sattilio		/*
432176017Sjeff		 * The lock is held in write mode or it already has waiters.
433154941Sjhb		 */
434176017Sjeff		MPASS(!RW_CAN_READ(v));
435176017Sjeff
436176017Sjeff		/*
437176017Sjeff		 * If the RW_LOCK_READ_WAITERS flag is already set, then
438176017Sjeff		 * we can go ahead and block.  If it is not set then try
439176017Sjeff		 * to set it.  If we fail to set it drop the turnstile
440176017Sjeff		 * lock and restart the loop.
441176017Sjeff		 */
442176017Sjeff		if (!(v & RW_LOCK_READ_WAITERS)) {
443176017Sjeff			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
444176017Sjeff			    v | RW_LOCK_READ_WAITERS)) {
445170295Sjeff				turnstile_cancel(ts);
446157826Sjhb				cpu_spinwait();
447157826Sjhb				continue;
448167787Sjhb			}
449157826Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
450157826Sjhb				CTR2(KTR_LOCK, "%s: %p set read waiters flag",
451154941Sjhb				    __func__, rw);
452154941Sjhb		}
453154941Sjhb
454154941Sjhb		/*
455154941Sjhb		 * We were unable to acquire the lock and the read waiters
456154941Sjhb		 * flag is set, so we must block on the turnstile.
457167787Sjhb		 */
458154941Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
459154941Sjhb			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
460192853Ssson			    rw);
461192853Ssson#ifdef KDTRACE_HOOKS
462192853Ssson		sleep_time -= lockstat_nsecs();
463170295Sjeff#endif
464192853Ssson		turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
465192853Ssson#ifdef KDTRACE_HOOKS
466192853Ssson		sleep_time += lockstat_nsecs();
467192853Ssson		sleep_cnt++;
468167787Sjhb#endif
469154941Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
470154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
471154941Sjhb			    __func__, rw);
472154941Sjhb	}
473154941Sjhb
474154941Sjhb	/*
475154941Sjhb	 * TODO: acquire "owner of record" here.  Here be turnstile dragons
476154941Sjhb	 * however.  turnstiles don't like owners changing between calls to
477154941Sjhb	 * turnstile_wait() currently.
478192853Ssson	 */
479174629Sjeff	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
480167787Sjhb	    waittime, file, line);
481167787Sjhb	LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
482160771Sjhb	WITNESS_LOCK(&rw->lock_object, 0, file, line);
483176017Sjeff	curthread->td_locks++;
484192853Ssson	curthread->td_rw_rlocks++;
485192853Ssson#ifdef KDTRACE_HOOKS
486192853Ssson	if (sleep_time)
487192853Ssson		LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
488192853Ssson
489192853Ssson	/*
490192853Ssson	 * Record only the loops spinning and not sleeping.
491192853Ssson	 */
492192853Ssson	if (spin_cnt > sleep_cnt)
493192853Ssson		LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
494154941Sjhb#endif
495154941Sjhb}
496177843Sattilio
497177843Sattilioint
498177843Sattilio_rw_try_rlock(struct rwlock *rw, const char *file, int line)
499177843Sattilio{
500177843Sattilio	uintptr_t x;
501177843Sattilio
502177843Sattilio	for (;;) {
503177843Sattilio		x = rw->rw_lock;
504177843Sattilio		KASSERT(rw->rw_lock != RW_DESTROYED,
505177843Sattilio		    ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
506177843Sattilio		if (!(x & RW_LOCK_READ))
507177843Sattilio			break;
508177843Sattilio		if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
509177843Sattilio			LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
510177843Sattilio			    line);
511177843Sattilio			WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
512177843Sattilio			curthread->td_locks++;
513177843Sattilio			curthread->td_rw_rlocks++;
514177843Sattilio			return (1);
515177843Sattilio		}
516177843Sattilio	}
517177843Sattilio
518177843Sattilio	LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
519177843Sattilio	return (0);
520177843Sattilio}
521154941Sjhb
522154941Sjhbvoid
523154941Sjhb_rw_runlock(struct rwlock *rw, const char *file, int line)
524154941Sjhb{
525176017Sjeff	struct turnstile *ts;
526154941Sjhb	uintptr_t x, v, queue;
527169394Sjhb
528169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
529154941Sjhb	    ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
530160771Sjhb	_rw_assert(rw, RA_RLOCKED, file, line);
531176017Sjeff	curthread->td_locks--;
532167787Sjhb	curthread->td_rw_rlocks--;
533167787Sjhb	WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
534154941Sjhb	LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
535154941Sjhb
536154941Sjhb	/* TODO: drop "owner of record" here. */
537154941Sjhb
538154941Sjhb	for (;;) {
539154941Sjhb		/*
540154941Sjhb		 * See if there is more than one read lock held.  If so,
541154941Sjhb		 * just drop one and return.
542154941Sjhb		 */
543154941Sjhb		x = rw->rw_lock;
544154941Sjhb		if (RW_READERS(x) > 1) {
545154941Sjhb			if (atomic_cmpset_ptr(&rw->rw_lock, x,
546167787Sjhb			    x - RW_ONE_READER)) {
547154941Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
548154941Sjhb					CTR4(KTR_LOCK,
549154941Sjhb					    "%s: %p succeeded %p -> %p",
550154941Sjhb					    __func__, rw, (void *)x,
551154941Sjhb					    (void *)(x - RW_ONE_READER));
552154941Sjhb				break;
553154941Sjhb			}
554167307Sjhb			continue;
555154941Sjhb		}
556154941Sjhb		/*
557154941Sjhb		 * If there aren't any waiters for a write lock, then try
558154941Sjhb		 * to drop it quickly.
559176017Sjeff		 */
560176017Sjeff		if (!(x & RW_LOCK_WAITERS)) {
561176017Sjeff			MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
562176017Sjeff			    RW_READERS_LOCK(1));
563167787Sjhb			if (atomic_cmpset_ptr(&rw->rw_lock, x, RW_UNLOCKED)) {
564154941Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
565154941Sjhb					CTR2(KTR_LOCK, "%s: %p last succeeded",
566154941Sjhb					    __func__, rw);
567154941Sjhb				break;
568154941Sjhb			}
569154941Sjhb			continue;
570154941Sjhb		}
571176017Sjeff		/*
572176017Sjeff		 * Ok, we know we have waiters and we think we are the
573154941Sjhb		 * last reader, so grab the turnstile lock.
574170295Sjeff		 */
575176017Sjeff		turnstile_chain_lock(&rw->lock_object);
576176017Sjeff		v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
577154941Sjhb		MPASS(v & RW_LOCK_WAITERS);
578154941Sjhb
579154941Sjhb		/*
580154941Sjhb		 * Try to drop our lock leaving the lock in a unlocked
581154941Sjhb		 * state.
582154941Sjhb		 *
583154941Sjhb		 * If you wanted to do explicit lock handoff you'd have to
584154941Sjhb		 * do it here.  You'd also want to use turnstile_signal()
585154941Sjhb		 * and you'd have to handle the race where a higher
586154941Sjhb		 * priority thread blocks on the write lock before the
587154941Sjhb		 * thread you wakeup actually runs and have the new thread
588154941Sjhb		 * "steal" the lock.  For now it's a lot simpler to just
589154941Sjhb		 * wakeup all of the waiters.
590154941Sjhb		 *
591154941Sjhb		 * As above, if we fail, then another thread might have
592154941Sjhb		 * acquired a read lock, so drop the turnstile lock and
593154941Sjhb		 * restart.
594176017Sjeff		 */
595176017Sjeff		x = RW_UNLOCKED;
596176017Sjeff		if (v & RW_LOCK_WRITE_WAITERS) {
597176017Sjeff			queue = TS_EXCLUSIVE_QUEUE;
598176017Sjeff			x |= (v & RW_LOCK_READ_WAITERS);
599176017Sjeff		} else
600176017Sjeff			queue = TS_SHARED_QUEUE;
601176017Sjeff		if (!atomic_cmpset_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
602170295Sjeff		    x)) {
603154941Sjhb			turnstile_chain_unlock(&rw->lock_object);
604154941Sjhb			continue;
605167787Sjhb		}
606154941Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
607154941Sjhb			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
608154941Sjhb			    __func__, rw);
609154941Sjhb
610154941Sjhb		/*
611154941Sjhb		 * Ok.  The lock is released and all that's left is to
612154941Sjhb		 * wake up the waiters.  Note that the lock might not be
613154941Sjhb		 * free anymore, but in that case the writers will just
614154941Sjhb		 * block again if they run before the new lock holder(s)
615154941Sjhb		 * release the lock.
616167787Sjhb		 */
617157846Sjhb		ts = turnstile_lookup(&rw->lock_object);
618176017Sjeff		MPASS(ts != NULL);
619154941Sjhb		turnstile_broadcast(ts, queue);
620170295Sjeff		turnstile_unpend(ts, TS_SHARED_LOCK);
621154941Sjhb		turnstile_chain_unlock(&rw->lock_object);
622154941Sjhb		break;
623192853Ssson	}
624154941Sjhb	LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
625154941Sjhb}
626154941Sjhb
627154941Sjhb/*
628154941Sjhb * This function is called when we are unable to obtain a write lock on the
629154941Sjhb * first try.  This means that at least one other thread holds either a
630154941Sjhb * read or write lock.
631154941Sjhb */
632154941Sjhbvoid
633154941Sjhb_rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
634170295Sjeff{
635167801Sjhb	struct turnstile *ts;
636157846Sjhb#ifdef ADAPTIVE_RWLOCKS
637176017Sjeff	volatile struct thread *owner;
638176017Sjeff	int spintries = 0;
639157851Swkoszek	int i;
640189846Sjeff#endif
641189846Sjeff	uintptr_t v, x;
642171516Sattilio#ifdef LOCK_PROFILING
643171516Sattilio	uint64_t waittime = 0;
644189846Sjeff	int contested = 0;
645192853Ssson#endif
646192853Ssson#ifdef KDTRACE_HOOKS
647192853Ssson	uint64_t spin_cnt = 0;
648192853Ssson	uint64_t sleep_cnt = 0;
649192853Ssson	int64_t sleep_time = 0;
650154941Sjhb#endif
651171052Sattilio
652193307Sattilio	if (rw_wlocked(rw)) {
653171052Sattilio		KASSERT(rw->lock_object.lo_flags & RW_RECURSE,
654171052Sattilio		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
655171052Sattilio		    __func__, rw->lock_object.lo_name, file, line));
656171052Sattilio		rw->rw_recurse++;
657171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
658171052Sattilio			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
659171052Sattilio		return;
660171052Sattilio	}
661167787Sjhb
662154941Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
663167787Sjhb		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
664154941Sjhb		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
665154941Sjhb
666192853Ssson	while (!_rw_write_lock(rw, tid)) {
667192853Ssson#ifdef KDTRACE_HOOKS
668192853Ssson		spin_cnt++;
669174629Sjeff#endif
670174629Sjeff		lock_profile_obtain_lock_failed(&rw->lock_object,
671173960Sattilio		    &contested, &waittime);
672173960Sattilio#ifdef ADAPTIVE_RWLOCKS
673173960Sattilio		/*
674173960Sattilio		 * If the lock is write locked and the owner is
675173960Sattilio		 * running on another CPU, spin until the owner stops
676173960Sattilio		 * running or the state of the lock changes.
677173960Sattilio		 */
678173960Sattilio		v = rw->rw_lock;
679173960Sattilio		owner = (struct thread *)RW_OWNER(v);
680173960Sattilio		if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
681173960Sattilio			if (LOCK_LOG_TEST(&rw->lock_object, 0))
682173960Sattilio				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
683173960Sattilio				    __func__, rw, owner);
684192853Ssson			while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
685173960Sattilio			    TD_IS_RUNNING(owner)) {
686192853Ssson				cpu_spinwait();
687192853Ssson#ifdef KDTRACE_HOOKS
688192853Ssson				spin_cnt++;
689192853Ssson#endif
690173960Sattilio			}
691173960Sattilio			continue;
692177912Sjeff		}
693177912Sjeff		if ((v & RW_LOCK_READ) && RW_READERS(v) &&
694176017Sjeff		    spintries < rowner_retries) {
695176017Sjeff			if (!(v & RW_LOCK_WRITE_SPINNER)) {
696176017Sjeff				if (!atomic_cmpset_ptr(&rw->rw_lock, v,
697176017Sjeff				    v | RW_LOCK_WRITE_SPINNER)) {
698176017Sjeff					cpu_spinwait();
699176017Sjeff					continue;
700176017Sjeff				}
701177912Sjeff			}
702176017Sjeff			spintries++;
703176017Sjeff			for (i = 0; i < rowner_loops; i++) {
704176017Sjeff				if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
705176017Sjeff					break;
706192853Ssson				cpu_spinwait();
707192853Ssson			}
708192853Ssson#ifdef KDTRACE_HOOKS
709177912Sjeff			spin_cnt += rowner_loops - i;
710176017Sjeff#endif
711176017Sjeff			if (i != rowner_loops)
712173960Sattilio				continue;
713170295Sjeff		}
714154941Sjhb#endif
715154941Sjhb		ts = turnstile_trywait(&rw->lock_object);
716173960Sattilio		v = rw->rw_lock;
717154941Sjhb
718193035Sjhb#ifdef ADAPTIVE_RWLOCKS
719193035Sjhb		/*
720193035Sjhb		 * The current lock owner might have started executing
721193035Sjhb		 * on another CPU (or the lock could have changed
722193035Sjhb		 * owners) while we were waiting on the turnstile
723173960Sattilio		 * chain lock.  If so, drop the turnstile lock and try
724173960Sattilio		 * again.
725173960Sattilio		 */
726173960Sattilio		if (!(v & RW_LOCK_READ)) {
727173960Sattilio			owner = (struct thread *)RW_OWNER(v);
728173960Sattilio			if (TD_IS_RUNNING(owner)) {
729173960Sattilio				turnstile_cancel(ts);
730173960Sattilio				cpu_spinwait();
731173960Sattilio				continue;
732173960Sattilio			}
733179334Sattilio		}
734179334Sattilio#endif
735179334Sattilio		/*
736179334Sattilio		 * Check for the waiters flags about this rwlock.
737179334Sattilio		 * If the lock was released, without maintain any pending
738154941Sjhb		 * waiters queue, simply try to acquire it.
739176017Sjeff		 * If a pending waiters queue is present, claim the lock
740176017Sjeff		 * ownership and maintain the pending queue.
741176017Sjeff		 */
742176017Sjeff		x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
743176017Sjeff		if ((v & ~x) == RW_UNLOCKED) {
744176017Sjeff			x &= ~RW_LOCK_WRITE_SPINNER;
745176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
746176017Sjeff				if (x)
747154941Sjhb					turnstile_claim(ts);
748154941Sjhb				else
749170295Sjeff					turnstile_cancel(ts);
750154941Sjhb				break;
751154941Sjhb			}
752154941Sjhb			turnstile_cancel(ts);
753154941Sjhb			cpu_spinwait();
754154941Sjhb			continue;
755154941Sjhb		}
756154941Sjhb		/*
757157826Sjhb		 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
758157826Sjhb		 * set it.  If we fail to set it, then loop back and try
759157826Sjhb		 * again.
760170295Sjeff		 */
761157826Sjhb		if (!(v & RW_LOCK_WRITE_WAITERS)) {
762157826Sjhb			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
763167787Sjhb			    v | RW_LOCK_WRITE_WAITERS)) {
764157826Sjhb				turnstile_cancel(ts);
765157826Sjhb				cpu_spinwait();
766154941Sjhb				continue;
767157846Sjhb			}
768154941Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
769154941Sjhb				CTR2(KTR_LOCK, "%s: %p set write waiters flag",
770154941Sjhb				    __func__, rw);
771167787Sjhb		}
772154941Sjhb		/*
773154941Sjhb		 * We were unable to acquire the lock and the write waiters
774192853Ssson		 * flag is set, so we must block on the turnstile.
775192853Ssson		 */
776192853Ssson		if (LOCK_LOG_TEST(&rw->lock_object, 0))
777170295Sjeff			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
778192853Ssson			    rw);
779192853Ssson#ifdef KDTRACE_HOOKS
780192853Ssson		sleep_time -= lockstat_nsecs();
781192853Ssson#endif
782167787Sjhb		turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
783154941Sjhb#ifdef KDTRACE_HOOKS
784154941Sjhb		sleep_time += lockstat_nsecs();
785176017Sjeff		sleep_cnt++;
786176017Sjeff#endif
787176017Sjeff		if (LOCK_LOG_TEST(&rw->lock_object, 0))
788154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
789192853Ssson			    __func__, rw);
790192853Ssson#ifdef ADAPTIVE_RWLOCKS
791192853Ssson		spintries = 0;
792192853Ssson#endif
793192853Ssson	}
794192853Ssson	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
795192853Ssson	    waittime, file, line);
796192853Ssson#ifdef KDTRACE_HOOKS
797192853Ssson	if (sleep_time)
798192853Ssson		LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
799192853Ssson
800192853Ssson	/*
801154941Sjhb	 * Record only the loops spinning and not sleeping.
802154941Sjhb	 */
803154941Sjhb	if (spin_cnt > sleep_cnt)
804154941Sjhb		LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
805154941Sjhb#endif
806154941Sjhb}
807154941Sjhb
808154941Sjhb/*
809154941Sjhb * This function is called if the first try at releasing a write lock failed.
810154941Sjhb * This means that one of the 2 waiter bits must be set indicating that at
811154941Sjhb * least one thread is waiting on this lock.
812154941Sjhb */
813154941Sjhbvoid
814154941Sjhb_rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
815171052Sattilio{
816176017Sjeff	struct turnstile *ts;
817171052Sattilio	uintptr_t v;
818171052Sattilio	int queue;
819171052Sattilio
820171052Sattilio	if (rw_wlocked(rw) && rw_recursed(rw)) {
821171052Sattilio		rw->rw_recurse--;
822154941Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
823154941Sjhb			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
824154941Sjhb		return;
825167787Sjhb	}
826154941Sjhb
827154941Sjhb	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
828170295Sjeff	    ("%s: neither of the waiter flags are set", __func__));
829167787Sjhb
830154941Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
831154941Sjhb		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
832154941Sjhb
833154941Sjhb	turnstile_chain_lock(&rw->lock_object);
834154941Sjhb	ts = turnstile_lookup(&rw->lock_object);
835154941Sjhb	MPASS(ts != NULL);
836154941Sjhb
837154941Sjhb	/*
838154941Sjhb	 * Use the same algo as sx locks for now.  Prefer waking up shared
839154941Sjhb	 * waiters if we have any over writers.  This is probably not ideal.
840154941Sjhb	 *
841154941Sjhb	 * 'v' is the value we are going to write back to rw_lock.  If we
842154941Sjhb	 * have waiters on both queues, we need to preserve the state of
843154941Sjhb	 * the waiter flag for the queue we don't wake up.  For now this is
844154941Sjhb	 * hardcoded for the algorithm mentioned above.
845154941Sjhb	 *
846154941Sjhb	 * In the case of both readers and writers waiting we wakeup the
847154941Sjhb	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
848157846Sjhb	 * new writer comes in before a reader it will claim the lock up
849176076Sjeff	 * above.  There is probably a potential priority inversion in
850176076Sjeff	 * there that could be worked around either by waking both queues
851176076Sjeff	 * of waiters or doing some complicated lock handoff gymnastics.
852176076Sjeff	 */
853154941Sjhb	v = RW_UNLOCKED;
854157846Sjhb	if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
855157846Sjhb		queue = TS_EXCLUSIVE_QUEUE;
856167787Sjhb		v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
857154941Sjhb	} else
858154941Sjhb		queue = TS_SHARED_QUEUE;
859154941Sjhb
860154941Sjhb	/* Wake up all waiters for the specific queue. */
861154941Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
862170295Sjeff		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
863154941Sjhb		    queue == TS_SHARED_QUEUE ? "read" : "write");
864154941Sjhb	turnstile_broadcast(ts, queue);
865157882Sjhb	atomic_store_rel_ptr(&rw->rw_lock, v);
866157882Sjhb	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
867157882Sjhb	turnstile_chain_unlock(&rw->lock_object);
868157882Sjhb}
869157882Sjhb
870157882Sjhb/*
871157882Sjhb * Attempt to do a non-blocking upgrade from a read lock to a write
872157882Sjhb * lock.  This will only succeed if this thread holds a single read
873176017Sjeff * lock.  Returns true if the upgrade succeeded and false otherwise.
874170295Sjeff */
875157882Sjhbint
876157882Sjhb_rw_try_upgrade(struct rwlock *rw, const char *file, int line)
877169394Sjhb{
878169394Sjhb	uintptr_t v, x, tid;
879157882Sjhb	struct turnstile *ts;
880157882Sjhb	int success;
881157882Sjhb
882157882Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
883157882Sjhb	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
884157882Sjhb	_rw_assert(rw, RA_RLOCKED, file, line);
885157882Sjhb
886157882Sjhb	/*
887157882Sjhb	 * Attempt to switch from one reader to a writer.  If there
888157882Sjhb	 * are any write waiters, then we will have to lock the
889176017Sjeff	 * turnstile first to prevent races with another writer
890176017Sjeff	 * calling turnstile_wait() before we have claimed this
891176017Sjeff	 * turnstile.  So, do the simple case of no waiters first.
892176017Sjeff	 */
893176017Sjeff	tid = (uintptr_t)curthread;
894176017Sjeff	success = 0;
895176017Sjeff	for (;;) {
896176017Sjeff		v = rw->rw_lock;
897176017Sjeff		if (RW_READERS(v) > 1)
898176017Sjeff			break;
899176017Sjeff		if (!(v & RW_LOCK_WAITERS)) {
900157882Sjhb			success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
901176017Sjeff			if (!success)
902176017Sjeff				continue;
903176017Sjeff			break;
904176017Sjeff		}
905176017Sjeff
906176017Sjeff		/*
907176017Sjeff		 * Ok, we think we have waiters, so lock the turnstile.
908176017Sjeff		 */
909176017Sjeff		ts = turnstile_trywait(&rw->lock_object);
910176017Sjeff		v = rw->rw_lock;
911176017Sjeff		if (RW_READERS(v) > 1) {
912176017Sjeff			turnstile_cancel(ts);
913176017Sjeff			break;
914176017Sjeff		}
915176017Sjeff		/*
916176017Sjeff		 * Try to switch from one reader to a writer again.  This time
917176017Sjeff		 * we honor the current state of the waiters flags.
918176017Sjeff		 * If we obtain the lock with the flags set, then claim
919176017Sjeff		 * ownership of the turnstile.
920176017Sjeff		 */
921176017Sjeff		x = rw->rw_lock & RW_LOCK_WAITERS;
922176017Sjeff		success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
923176017Sjeff		if (success) {
924176017Sjeff			if (x)
925170295Sjeff				turnstile_claim(ts);
926176017Sjeff			else
927167787Sjhb				turnstile_cancel(ts);
928176017Sjeff			break;
929176017Sjeff		}
930167787Sjhb		turnstile_cancel(ts);
931157882Sjhb	}
932192853Ssson	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
933176017Sjeff	if (success) {
934157882Sjhb		curthread->td_rw_rlocks--;
935157882Sjhb		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
936157882Sjhb		    file, line);
937157882Sjhb		LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
938157882Sjhb	}
939157882Sjhb	return (success);
940157882Sjhb}
941157882Sjhb
942157882Sjhb/*
943157882Sjhb * Downgrade a write lock into a single read lock.
944157882Sjhb */
945176017Sjeffvoid
946157882Sjhb_rw_downgrade(struct rwlock *rw, const char *file, int line)
947169394Sjhb{
948169394Sjhb	struct turnstile *ts;
949171052Sattilio	uintptr_t tid, v;
950171052Sattilio	int rwait, wwait;
951171052Sattilio
952171052Sattilio	KASSERT(rw->rw_lock != RW_DESTROYED,
953171052Sattilio	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
954157882Sjhb	_rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
955167787Sjhb#ifndef INVARIANTS
956157882Sjhb	if (rw_recursed(rw))
957157882Sjhb		panic("downgrade of a recursed lock");
958157882Sjhb#endif
959157882Sjhb
960176017Sjeff	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
961157882Sjhb
962157882Sjhb	/*
963157882Sjhb	 * Convert from a writer to a single reader.  First we handle
964157882Sjhb	 * the easy case with no waiters.  If there are any waiters, we
965157882Sjhb	 * lock the turnstile and "disown" the lock.
966157882Sjhb	 */
967157882Sjhb	tid = (uintptr_t)curthread;
968157882Sjhb	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
969157882Sjhb		goto out;
970170295Sjeff
971176017Sjeff	/*
972176017Sjeff	 * Ok, we think we have waiters, so lock the turnstile so we can
973176017Sjeff	 * read the waiter flags without any races.
974176017Sjeff	 */
975157882Sjhb	turnstile_chain_lock(&rw->lock_object);
976157882Sjhb	v = rw->rw_lock & RW_LOCK_WAITERS;
977176017Sjeff	rwait = v & RW_LOCK_READ_WAITERS;
978176017Sjeff	wwait = v & RW_LOCK_WRITE_WAITERS;
979157882Sjhb	MPASS(rwait | wwait);
980167787Sjhb
981157882Sjhb	/*
982176017Sjeff	 * Downgrade from a write lock while preserving waiters flag
983176017Sjeff	 * and give up ownership of the turnstile.
984176017Sjeff	 */
985176017Sjeff	ts = turnstile_lookup(&rw->lock_object);
986176017Sjeff	MPASS(ts != NULL);
987176017Sjeff	if (!wwait)
988176017Sjeff		v &= ~RW_LOCK_READ_WAITERS;
989176017Sjeff	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
990157882Sjhb	/*
991157882Sjhb	 * Wake other readers if there are no writers pending.  Otherwise they
992176017Sjeff	 * won't be able to acquire the lock anyway.
993157882Sjhb	 */
994170295Sjeff	if (rwait && !wwait) {
995157882Sjhb		turnstile_broadcast(ts, TS_SHARED_QUEUE);
996176017Sjeff		turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
997167787Sjhb	} else
998192853Ssson		turnstile_disown(ts);
999157882Sjhb	turnstile_chain_unlock(&rw->lock_object);
1000157882Sjhbout:
1001154941Sjhb	curthread->td_rw_rlocks++;
1002155162Sscottl	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1003154941Sjhb	LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1004154941Sjhb}
1005154941Sjhb
1006154941Sjhb#ifdef INVARIANT_SUPPORT
1007154941Sjhb#ifndef INVARIANTS
1008154941Sjhb#undef _rw_assert
1009154941Sjhb#endif
1010154941Sjhb
1011154941Sjhb/*
1012154941Sjhb * In the non-WITNESS case, rw_assert() can only detect that at least
1013154941Sjhb * *some* thread owns an rlock, but it cannot guarantee that *this*
1014154941Sjhb * thread owns an rlock.
1015154941Sjhb */
1016154941Sjhbvoid
1017154941Sjhb_rw_assert(struct rwlock *rw, int what, const char *file, int line)
1018154941Sjhb{
1019171052Sattilio
1020171052Sattilio	if (panicstr != NULL)
1021154941Sjhb		return;
1022154941Sjhb	switch (what) {
1023167787Sjhb	case RA_LOCKED:
1024154941Sjhb	case RA_LOCKED | RA_RECURSED:
1025154941Sjhb	case RA_LOCKED | RA_NOTRECURSED:
1026154941Sjhb	case RA_RLOCKED:
1027154941Sjhb#ifdef WITNESS
1028154941Sjhb		witness_assert(&rw->lock_object, what, file, line);
1029154941Sjhb#else
1030155061Sscottl		/*
1031155061Sscottl		 * If some other thread has a write lock or we have one
1032157826Sjhb		 * and are asserting a read lock, fail.  Also, if no one
1033154941Sjhb		 * has a lock at all, fail.
1034167787Sjhb		 */
1035154941Sjhb		if (rw->rw_lock == RW_UNLOCKED ||
1036171052Sattilio		    (!(rw->rw_lock & RW_LOCK_READ) && (what == RA_RLOCKED ||
1037171052Sattilio		    rw_wowner(rw) != curthread)))
1038171052Sattilio			panic("Lock %s not %slocked @ %s:%d\n",
1039171052Sattilio			    rw->lock_object.lo_name, (what == RA_RLOCKED) ?
1040171052Sattilio			    "read " : "", file, line);
1041171052Sattilio
1042171052Sattilio		if (!(rw->rw_lock & RW_LOCK_READ)) {
1043171052Sattilio			if (rw_recursed(rw)) {
1044171052Sattilio				if (what & RA_NOTRECURSED)
1045171052Sattilio					panic("Lock %s recursed @ %s:%d\n",
1046171052Sattilio					    rw->lock_object.lo_name, file,
1047154941Sjhb					    line);
1048154941Sjhb			} else if (what & RA_RECURSED)
1049154941Sjhb				panic("Lock %s not recursed @ %s:%d\n",
1050171052Sattilio				    rw->lock_object.lo_name, file, line);
1051171052Sattilio		}
1052157826Sjhb#endif
1053154941Sjhb		break;
1054167787Sjhb	case RA_WLOCKED:
1055171052Sattilio	case RA_WLOCKED | RA_RECURSED:
1056171052Sattilio	case RA_WLOCKED | RA_NOTRECURSED:
1057171052Sattilio		if (rw_wowner(rw) != curthread)
1058171052Sattilio			panic("Lock %s not exclusively locked @ %s:%d\n",
1059171052Sattilio			    rw->lock_object.lo_name, file, line);
1060171052Sattilio		if (rw_recursed(rw)) {
1061171052Sattilio			if (what & RA_NOTRECURSED)
1062154941Sjhb				panic("Lock %s recursed @ %s:%d\n",
1063154941Sjhb				    rw->lock_object.lo_name, file, line);
1064154941Sjhb		} else if (what & RA_RECURSED)
1065167787Sjhb			panic("Lock %s not recursed @ %s:%d\n",
1066154941Sjhb			    rw->lock_object.lo_name, file, line);
1067154941Sjhb		break;
1068154941Sjhb	case RA_UNLOCKED:
1069154941Sjhb#ifdef WITNESS
1070154941Sjhb		witness_assert(&rw->lock_object, what, file, line);
1071157826Sjhb#else
1072154941Sjhb		/*
1073167787Sjhb		 * If we hold a write lock fail.  We can't reliably check
1074154941Sjhb		 * to see if we hold a read lock or not.
1075154941Sjhb		 */
1076154941Sjhb		if (rw_wowner(rw) == curthread)
1077154941Sjhb			panic("Lock %s exclusively locked @ %s:%d\n",
1078154941Sjhb			    rw->lock_object.lo_name, file, line);
1079154941Sjhb#endif
1080154941Sjhb		break;
1081154941Sjhb	default:
1082154941Sjhb		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1083154941Sjhb		    line);
1084154941Sjhb	}
1085154941Sjhb}
1086154941Sjhb#endif /* INVARIANT_SUPPORT */
1087154941Sjhb
1088154941Sjhb#ifdef DDB
1089154941Sjhbvoid
1090154941Sjhbdb_show_rwlock(struct lock_object *lock)
1091154941Sjhb{
1092154941Sjhb	struct rwlock *rw;
1093154941Sjhb	struct thread *td;
1094154941Sjhb
1095169394Sjhb	rw = (struct rwlock *)lock;
1096169394Sjhb
1097169394Sjhb	db_printf(" state: ");
1098169394Sjhb	if (rw->rw_lock == RW_UNLOCKED)
1099167504Sjhb		db_printf("UNLOCKED\n");
1100167504Sjhb	else if (rw->rw_lock == RW_DESTROYED) {
1101154941Sjhb		db_printf("DESTROYED\n");
1102157826Sjhb		return;
1103154941Sjhb	} else if (rw->rw_lock & RW_LOCK_READ)
1104173600Sjulian		db_printf("RLOCK: %ju locks\n",
1105171052Sattilio		    (uintmax_t)(RW_READERS(rw->rw_lock)));
1106171052Sattilio	else {
1107154941Sjhb		td = rw_wowner(rw);
1108154941Sjhb		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1109154941Sjhb		    td->td_tid, td->td_proc->p_pid, td->td_name);
1110154941Sjhb		if (rw_recursed(rw))
1111154941Sjhb			db_printf(" recursed: %u\n", rw->rw_recurse);
1112154941Sjhb	}
1113154941Sjhb	db_printf(" waiters: ");
1114154941Sjhb	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1115154941Sjhb	case RW_LOCK_READ_WAITERS:
1116154941Sjhb		db_printf("readers\n");
1117167492Sjhb		break;
1118154941Sjhb	case RW_LOCK_WRITE_WAITERS:
1119154941Sjhb		db_printf("writers\n");
1120154941Sjhb		break;
1121154941Sjhb	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1122154941Sjhb		db_printf("readers and writers\n");
1123154941Sjhb		break;
1124154941Sjhb	default:
1125154941Sjhb		db_printf("none\n");
1126		break;
1127	}
1128}
1129
1130#endif
1131