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 *
14154941Sjhb * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15154941Sjhb * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16154941Sjhb * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17154941Sjhb * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18154941Sjhb * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19154941Sjhb * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20154941Sjhb * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21154941Sjhb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22154941Sjhb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23154941Sjhb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24154941Sjhb * SUCH DAMAGE.
25154941Sjhb */
26154941Sjhb
27154941Sjhb/*
28154941Sjhb * Machine independent bits of reader/writer lock implementation.
29154941Sjhb */
30154941Sjhb
31154941Sjhb#include <sys/cdefs.h>
32154941Sjhb__FBSDID("$FreeBSD$");
33154941Sjhb
34154941Sjhb#include "opt_ddb.h"
35236238Sfabient#include "opt_hwpmc_hooks.h"
36192853Ssson#include "opt_kdtrace.h"
37167801Sjhb#include "opt_no_adaptive_rwlocks.h"
38154941Sjhb
39154941Sjhb#include <sys/param.h>
40255862Sjhb#include <sys/kdb.h>
41154941Sjhb#include <sys/ktr.h>
42177912Sjeff#include <sys/kernel.h>
43154941Sjhb#include <sys/lock.h>
44154941Sjhb#include <sys/mutex.h>
45154941Sjhb#include <sys/proc.h>
46154941Sjhb#include <sys/rwlock.h>
47177912Sjeff#include <sys/sysctl.h>
48154941Sjhb#include <sys/systm.h>
49154941Sjhb#include <sys/turnstile.h>
50171516Sattilio
51154941Sjhb#include <machine/cpu.h>
52154941Sjhb
53167801Sjhb#if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
54167801Sjhb#define	ADAPTIVE_RWLOCKS
55167801Sjhb#endif
56167801Sjhb
57236238Sfabient#ifdef HWPMC_HOOKS
58236238Sfabient#include <sys/pmckern.h>
59236238SfabientPMC_SOFT_DECLARE( , , lock, failed);
60236238Sfabient#endif
61236238Sfabient
62177912Sjeff#ifdef ADAPTIVE_RWLOCKS
63226255Sattilio#define	ROWNER_RETRIES	10
64226255Sattilio#define	ROWNER_LOOPS	10000
65177912Sjeff#endif
66177912Sjeff
67154941Sjhb#ifdef DDB
68154941Sjhb#include <ddb/ddb.h>
69154941Sjhb
70154941Sjhbstatic void	db_show_rwlock(struct lock_object *lock);
71154941Sjhb#endif
72173733Sattiliostatic void	assert_rw(struct lock_object *lock, int what);
73167368Sjhbstatic void	lock_rw(struct lock_object *lock, int how);
74192853Ssson#ifdef KDTRACE_HOOKS
75192853Sssonstatic int	owner_rw(struct lock_object *lock, struct thread **owner);
76192853Ssson#endif
77167368Sjhbstatic int	unlock_rw(struct lock_object *lock);
78154941Sjhb
79154941Sjhbstruct lock_class lock_class_rw = {
80167365Sjhb	.lc_name = "rw",
81167365Sjhb	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
82173733Sattilio	.lc_assert = assert_rw,
83154941Sjhb#ifdef DDB
84167365Sjhb	.lc_ddb_show = db_show_rwlock,
85154941Sjhb#endif
86167368Sjhb	.lc_lock = lock_rw,
87167368Sjhb	.lc_unlock = unlock_rw,
88192853Ssson#ifdef KDTRACE_HOOKS
89192853Ssson	.lc_owner = owner_rw,
90192853Ssson#endif
91154941Sjhb};
92154941Sjhb
93157826Sjhb/*
94157826Sjhb * Return a pointer to the owning thread if the lock is write-locked or
95157826Sjhb * NULL if the lock is unlocked or read-locked.
96157826Sjhb */
97157826Sjhb#define	rw_wowner(rw)							\
98154941Sjhb	((rw)->rw_lock & RW_LOCK_READ ? NULL :				\
99154941Sjhb	    (struct thread *)RW_OWNER((rw)->rw_lock))
100154941Sjhb
101157826Sjhb/*
102171052Sattilio * Returns if a write owner is recursed.  Write ownership is not assured
103171052Sattilio * here and should be previously checked.
104171052Sattilio */
105171052Sattilio#define	rw_recursed(rw)		((rw)->rw_recurse != 0)
106171052Sattilio
107171052Sattilio/*
108171052Sattilio * Return true if curthread helds the lock.
109171052Sattilio */
110171052Sattilio#define	rw_wlocked(rw)		(rw_wowner((rw)) == curthread)
111171052Sattilio
112171052Sattilio/*
113157826Sjhb * Return a pointer to the owning thread for this lock who should receive
114157826Sjhb * any priority lent by threads that block on this lock.  Currently this
115157826Sjhb * is identical to rw_wowner().
116157826Sjhb */
117157826Sjhb#define	rw_owner(rw)		rw_wowner(rw)
118157826Sjhb
119154941Sjhb#ifndef INVARIANTS
120154941Sjhb#define	_rw_assert(rw, what, file, line)
121154941Sjhb#endif
122154941Sjhb
123154941Sjhbvoid
124173733Sattilioassert_rw(struct lock_object *lock, int what)
125173733Sattilio{
126173733Sattilio
127173733Sattilio	rw_assert((struct rwlock *)lock, what);
128173733Sattilio}
129173733Sattilio
130173733Sattiliovoid
131167368Sjhblock_rw(struct lock_object *lock, int how)
132167368Sjhb{
133167368Sjhb	struct rwlock *rw;
134167368Sjhb
135167368Sjhb	rw = (struct rwlock *)lock;
136167368Sjhb	if (how)
137167368Sjhb		rw_wlock(rw);
138167368Sjhb	else
139167368Sjhb		rw_rlock(rw);
140167368Sjhb}
141167368Sjhb
142167368Sjhbint
143167368Sjhbunlock_rw(struct lock_object *lock)
144167368Sjhb{
145167368Sjhb	struct rwlock *rw;
146167368Sjhb
147167368Sjhb	rw = (struct rwlock *)lock;
148167368Sjhb	rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
149167368Sjhb	if (rw->rw_lock & RW_LOCK_READ) {
150167368Sjhb		rw_runlock(rw);
151167368Sjhb		return (0);
152167368Sjhb	} else {
153167368Sjhb		rw_wunlock(rw);
154167368Sjhb		return (1);
155167368Sjhb	}
156167368Sjhb}
157167368Sjhb
158192853Ssson#ifdef KDTRACE_HOOKS
159192853Sssonint
160192853Sssonowner_rw(struct lock_object *lock, struct thread **owner)
161192853Ssson{
162192853Ssson	struct rwlock *rw = (struct rwlock *)lock;
163192853Ssson	uintptr_t x = rw->rw_lock;
164192853Ssson
165192853Ssson	*owner = rw_wowner(rw);
166192853Ssson	return ((x & RW_LOCK_READ) != 0 ?  (RW_READERS(x) != 0) :
167192853Ssson	    (*owner != NULL));
168192853Ssson}
169192853Ssson#endif
170192853Ssson
171167368Sjhbvoid
172171052Sattiliorw_init_flags(struct rwlock *rw, const char *name, int opts)
173154941Sjhb{
174171052Sattilio	int flags;
175154941Sjhb
176171052Sattilio	MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
177171052Sattilio	    RW_RECURSE)) == 0);
178196334Sattilio	ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
179196334Sattilio	    ("%s: rw_lock not aligned for %s: %p", __func__, name,
180196334Sattilio	    &rw->rw_lock));
181171052Sattilio
182193307Sattilio	flags = LO_UPGRADABLE;
183171052Sattilio	if (opts & RW_DUPOK)
184171052Sattilio		flags |= LO_DUPOK;
185171052Sattilio	if (opts & RW_NOPROFILE)
186171052Sattilio		flags |= LO_NOPROFILE;
187171052Sattilio	if (!(opts & RW_NOWITNESS))
188171052Sattilio		flags |= LO_WITNESS;
189193307Sattilio	if (opts & RW_RECURSE)
190193307Sattilio		flags |= LO_RECURSABLE;
191171052Sattilio	if (opts & RW_QUIET)
192171052Sattilio		flags |= LO_QUIET;
193171052Sattilio
194154941Sjhb	rw->rw_lock = RW_UNLOCKED;
195171052Sattilio	rw->rw_recurse = 0;
196171052Sattilio	lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
197154941Sjhb}
198154941Sjhb
199154941Sjhbvoid
200154941Sjhbrw_destroy(struct rwlock *rw)
201154941Sjhb{
202154941Sjhb
203205626Sbz	KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
204205626Sbz	KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
205169394Sjhb	rw->rw_lock = RW_DESTROYED;
206167787Sjhb	lock_destroy(&rw->lock_object);
207154941Sjhb}
208154941Sjhb
209154941Sjhbvoid
210154941Sjhbrw_sysinit(void *arg)
211154941Sjhb{
212154941Sjhb	struct rw_args *args = arg;
213154941Sjhb
214154941Sjhb	rw_init(args->ra_rw, args->ra_desc);
215154941Sjhb}
216154941Sjhb
217185778Skmacyvoid
218185778Skmacyrw_sysinit_flags(void *arg)
219185778Skmacy{
220185778Skmacy	struct rw_args_flags *args = arg;
221185778Skmacy
222185778Skmacy	rw_init_flags(args->ra_rw, args->ra_desc, args->ra_flags);
223185778Skmacy}
224185778Skmacy
225167024Srwatsonint
226167024Srwatsonrw_wowned(struct rwlock *rw)
227167024Srwatson{
228167024Srwatson
229167024Srwatson	return (rw_wowner(rw) == curthread);
230167024Srwatson}
231167024Srwatson
232154941Sjhbvoid
233154941Sjhb_rw_wlock(struct rwlock *rw, const char *file, int line)
234154941Sjhb{
235154941Sjhb
236235404Savg	if (SCHEDULER_STOPPED())
237235404Savg		return;
238255862Sjhb	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
239255862Sjhb	    ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
240255862Sjhb	    curthread, rw->lock_object.lo_name, file, line));
241169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
242169394Sjhb	    ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
243167787Sjhb	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
244182914Sjhb	    line, NULL);
245154941Sjhb	__rw_wlock(rw, curthread, file, line);
246171052Sattilio	LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
247167787Sjhb	WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
248160771Sjhb	curthread->td_locks++;
249154941Sjhb}
250154941Sjhb
251177843Sattilioint
252177843Sattilio_rw_try_wlock(struct rwlock *rw, const char *file, int line)
253177843Sattilio{
254177843Sattilio	int rval;
255177843Sattilio
256235404Savg	if (SCHEDULER_STOPPED())
257235404Savg		return (1);
258235404Savg
259255862Sjhb	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
260255862Sjhb	    ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
261255862Sjhb	    curthread, rw->lock_object.lo_name, file, line));
262177843Sattilio	KASSERT(rw->rw_lock != RW_DESTROYED,
263177843Sattilio	    ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
264177843Sattilio
265193307Sattilio	if (rw_wlocked(rw) &&
266193307Sattilio	    (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
267177843Sattilio		rw->rw_recurse++;
268177843Sattilio		rval = 1;
269177843Sattilio	} else
270177843Sattilio		rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
271177843Sattilio		    (uintptr_t)curthread);
272177843Sattilio
273177843Sattilio	LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
274177843Sattilio	if (rval) {
275177843Sattilio		WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
276177843Sattilio		    file, line);
277177843Sattilio		curthread->td_locks++;
278177843Sattilio	}
279177843Sattilio	return (rval);
280177843Sattilio}
281177843Sattilio
282154941Sjhbvoid
283154941Sjhb_rw_wunlock(struct rwlock *rw, const char *file, int line)
284154941Sjhb{
285154941Sjhb
286235404Savg	if (SCHEDULER_STOPPED())
287235404Savg		return;
288169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
289169394Sjhb	    ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
290154941Sjhb	_rw_assert(rw, RA_WLOCKED, file, line);
291160771Sjhb	curthread->td_locks--;
292167787Sjhb	WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
293171052Sattilio	LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
294171052Sattilio	    line);
295171052Sattilio	if (!rw_recursed(rw))
296192853Ssson		LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_WUNLOCK_RELEASE, rw);
297154941Sjhb	__rw_wunlock(rw, curthread, file, line);
298154941Sjhb}
299176017Sjeff/*
300176017Sjeff * Determines whether a new reader can acquire a lock.  Succeeds if the
301176017Sjeff * reader already owns a read lock and the lock is locked for read to
302176017Sjeff * prevent deadlock from reader recursion.  Also succeeds if the lock
303176017Sjeff * is unlocked and has no writer waiters or spinners.  Failing otherwise
304176017Sjeff * prioritizes writers before readers.
305176017Sjeff */
306176017Sjeff#define	RW_CAN_READ(_rw)						\
307176017Sjeff    ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) &	\
308176017Sjeff    (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) ==	\
309176017Sjeff    RW_LOCK_READ)
310154941Sjhb
311154941Sjhbvoid
312154941Sjhb_rw_rlock(struct rwlock *rw, const char *file, int line)
313154941Sjhb{
314170295Sjeff	struct turnstile *ts;
315167801Sjhb#ifdef ADAPTIVE_RWLOCKS
316157846Sjhb	volatile struct thread *owner;
317177912Sjeff	int spintries = 0;
318177912Sjeff	int i;
319157851Swkoszek#endif
320189846Sjeff#ifdef LOCK_PROFILING
321167307Sjhb	uint64_t waittime = 0;
322167054Skmacy	int contested = 0;
323189846Sjeff#endif
324176017Sjeff	uintptr_t v;
325192853Ssson#ifdef KDTRACE_HOOKS
326192853Ssson	uint64_t spin_cnt = 0;
327192853Ssson	uint64_t sleep_cnt = 0;
328192853Ssson	int64_t sleep_time = 0;
329192853Ssson#endif
330154941Sjhb
331235404Savg	if (SCHEDULER_STOPPED())
332235404Savg		return;
333235404Savg
334255862Sjhb	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
335255862Sjhb	    ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
336255862Sjhb	    curthread, rw->lock_object.lo_name, file, line));
337169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
338169394Sjhb	    ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
339157826Sjhb	KASSERT(rw_wowner(rw) != curthread,
340252172Sjhb	    ("rw_rlock: wlock already held for %s @ %s:%d",
341167787Sjhb	    rw->lock_object.lo_name, file, line));
342182914Sjhb	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
343154941Sjhb
344154941Sjhb	for (;;) {
345192853Ssson#ifdef KDTRACE_HOOKS
346192853Ssson		spin_cnt++;
347192853Ssson#endif
348154941Sjhb		/*
349154941Sjhb		 * Handle the easy case.  If no other thread has a write
350154941Sjhb		 * lock, then try to bump up the count of read locks.  Note
351154941Sjhb		 * that we have to preserve the current state of the
352154941Sjhb		 * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
353154941Sjhb		 * read lock, then rw_lock must have changed, so restart
354154941Sjhb		 * the loop.  Note that this handles the case of a
355154941Sjhb		 * completely unlocked rwlock since such a lock is encoded
356154941Sjhb		 * as a read lock with no waiters.
357154941Sjhb		 */
358176017Sjeff		v = rw->rw_lock;
359176017Sjeff		if (RW_CAN_READ(v)) {
360154941Sjhb			/*
361154941Sjhb			 * The RW_LOCK_READ_WAITERS flag should only be set
362176017Sjeff			 * if the lock has been unlocked and write waiters
363176017Sjeff			 * were present.
364154941Sjhb			 */
365176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
366176017Sjeff			    v + RW_ONE_READER)) {
367167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
368154941Sjhb					CTR4(KTR_LOCK,
369154941Sjhb					    "%s: %p succeed %p -> %p", __func__,
370176017Sjeff					    rw, (void *)v,
371176017Sjeff					    (void *)(v + RW_ONE_READER));
372154941Sjhb				break;
373154941Sjhb			}
374154941Sjhb			continue;
375154941Sjhb		}
376236238Sfabient#ifdef HWPMC_HOOKS
377236238Sfabient		PMC_SOFT_CALL( , , lock, failed);
378236238Sfabient#endif
379174629Sjeff		lock_profile_obtain_lock_failed(&rw->lock_object,
380174629Sjeff		    &contested, &waittime);
381154941Sjhb
382173960Sattilio#ifdef ADAPTIVE_RWLOCKS
383154941Sjhb		/*
384173960Sattilio		 * If the owner is running on another CPU, spin until
385173960Sattilio		 * the owner stops running or the state of the lock
386173960Sattilio		 * changes.
387173960Sattilio		 */
388176017Sjeff		if ((v & RW_LOCK_READ) == 0) {
389176017Sjeff			owner = (struct thread *)RW_OWNER(v);
390176017Sjeff			if (TD_IS_RUNNING(owner)) {
391176017Sjeff				if (LOCK_LOG_TEST(&rw->lock_object, 0))
392176017Sjeff					CTR3(KTR_LOCK,
393176017Sjeff					    "%s: spinning on %p held by %p",
394176017Sjeff					    __func__, rw, owner);
395176017Sjeff				while ((struct thread*)RW_OWNER(rw->rw_lock) ==
396192853Ssson				    owner && TD_IS_RUNNING(owner)) {
397176017Sjeff					cpu_spinwait();
398192853Ssson#ifdef KDTRACE_HOOKS
399192853Ssson					spin_cnt++;
400192853Ssson#endif
401192853Ssson				}
402176017Sjeff				continue;
403176017Sjeff			}
404226255Sattilio		} else if (spintries < ROWNER_RETRIES) {
405177912Sjeff			spintries++;
406226255Sattilio			for (i = 0; i < ROWNER_LOOPS; i++) {
407177912Sjeff				v = rw->rw_lock;
408177912Sjeff				if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
409177912Sjeff					break;
410177912Sjeff				cpu_spinwait();
411177912Sjeff			}
412226255Sattilio			if (i != ROWNER_LOOPS)
413177912Sjeff				continue;
414173960Sattilio		}
415173960Sattilio#endif
416173960Sattilio
417173960Sattilio		/*
418154941Sjhb		 * Okay, now it's the hard case.  Some other thread already
419176017Sjeff		 * has a write lock or there are write waiters present,
420176017Sjeff		 * acquire the turnstile lock so we can begin the process
421176017Sjeff		 * of blocking.
422154941Sjhb		 */
423170295Sjeff		ts = turnstile_trywait(&rw->lock_object);
424154941Sjhb
425154941Sjhb		/*
426154941Sjhb		 * The lock might have been released while we spun, so
427176017Sjeff		 * recheck its state and restart the loop if needed.
428154941Sjhb		 */
429176017Sjeff		v = rw->rw_lock;
430176017Sjeff		if (RW_CAN_READ(v)) {
431170295Sjeff			turnstile_cancel(ts);
432154941Sjhb			continue;
433154941Sjhb		}
434154941Sjhb
435173960Sattilio#ifdef ADAPTIVE_RWLOCKS
436154941Sjhb		/*
437193035Sjhb		 * The current lock owner might have started executing
438193035Sjhb		 * on another CPU (or the lock could have changed
439193035Sjhb		 * owners) while we were waiting on the turnstile
440193035Sjhb		 * chain lock.  If so, drop the turnstile lock and try
441193035Sjhb		 * again.
442173960Sattilio		 */
443176017Sjeff		if ((v & RW_LOCK_READ) == 0) {
444176017Sjeff			owner = (struct thread *)RW_OWNER(v);
445176017Sjeff			if (TD_IS_RUNNING(owner)) {
446176017Sjeff				turnstile_cancel(ts);
447176017Sjeff				continue;
448176017Sjeff			}
449173960Sattilio		}
450173960Sattilio#endif
451173960Sattilio
452173960Sattilio		/*
453176017Sjeff		 * The lock is held in write mode or it already has waiters.
454154941Sjhb		 */
455176017Sjeff		MPASS(!RW_CAN_READ(v));
456176017Sjeff
457176017Sjeff		/*
458176017Sjeff		 * If the RW_LOCK_READ_WAITERS flag is already set, then
459176017Sjeff		 * we can go ahead and block.  If it is not set then try
460176017Sjeff		 * to set it.  If we fail to set it drop the turnstile
461176017Sjeff		 * lock and restart the loop.
462176017Sjeff		 */
463176017Sjeff		if (!(v & RW_LOCK_READ_WAITERS)) {
464176017Sjeff			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
465176017Sjeff			    v | RW_LOCK_READ_WAITERS)) {
466170295Sjeff				turnstile_cancel(ts);
467157826Sjhb				continue;
468157826Sjhb			}
469167787Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
470157826Sjhb				CTR2(KTR_LOCK, "%s: %p set read waiters flag",
471157826Sjhb				    __func__, rw);
472154941Sjhb		}
473154941Sjhb
474154941Sjhb		/*
475154941Sjhb		 * We were unable to acquire the lock and the read waiters
476154941Sjhb		 * flag is set, so we must block on the turnstile.
477154941Sjhb		 */
478167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
479154941Sjhb			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
480154941Sjhb			    rw);
481192853Ssson#ifdef KDTRACE_HOOKS
482192853Ssson		sleep_time -= lockstat_nsecs();
483192853Ssson#endif
484170295Sjeff		turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
485192853Ssson#ifdef KDTRACE_HOOKS
486192853Ssson		sleep_time += lockstat_nsecs();
487192853Ssson		sleep_cnt++;
488192853Ssson#endif
489167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
490154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
491154941Sjhb			    __func__, rw);
492154941Sjhb	}
493154941Sjhb
494154941Sjhb	/*
495154941Sjhb	 * TODO: acquire "owner of record" here.  Here be turnstile dragons
496154941Sjhb	 * however.  turnstiles don't like owners changing between calls to
497154941Sjhb	 * turnstile_wait() currently.
498154941Sjhb	 */
499192853Ssson	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
500174629Sjeff	    waittime, file, line);
501167787Sjhb	LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
502167787Sjhb	WITNESS_LOCK(&rw->lock_object, 0, file, line);
503160771Sjhb	curthread->td_locks++;
504176017Sjeff	curthread->td_rw_rlocks++;
505192853Ssson#ifdef KDTRACE_HOOKS
506192853Ssson	if (sleep_time)
507192853Ssson		LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
508192853Ssson
509192853Ssson	/*
510192853Ssson	 * Record only the loops spinning and not sleeping.
511192853Ssson	 */
512192853Ssson	if (spin_cnt > sleep_cnt)
513192853Ssson		LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
514192853Ssson#endif
515154941Sjhb}
516154941Sjhb
517177843Sattilioint
518177843Sattilio_rw_try_rlock(struct rwlock *rw, const char *file, int line)
519177843Sattilio{
520177843Sattilio	uintptr_t x;
521177843Sattilio
522235404Savg	if (SCHEDULER_STOPPED())
523235404Savg		return (1);
524235404Savg
525255862Sjhb	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
526255862Sjhb	    ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
527255862Sjhb	    curthread, rw->lock_object.lo_name, file, line));
528255862Sjhb
529177843Sattilio	for (;;) {
530177843Sattilio		x = rw->rw_lock;
531177843Sattilio		KASSERT(rw->rw_lock != RW_DESTROYED,
532177843Sattilio		    ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
533177843Sattilio		if (!(x & RW_LOCK_READ))
534177843Sattilio			break;
535177843Sattilio		if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
536177843Sattilio			LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
537177843Sattilio			    line);
538177843Sattilio			WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
539177843Sattilio			curthread->td_locks++;
540177843Sattilio			curthread->td_rw_rlocks++;
541177843Sattilio			return (1);
542177843Sattilio		}
543177843Sattilio	}
544177843Sattilio
545177843Sattilio	LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
546177843Sattilio	return (0);
547177843Sattilio}
548177843Sattilio
549154941Sjhbvoid
550154941Sjhb_rw_runlock(struct rwlock *rw, const char *file, int line)
551154941Sjhb{
552154941Sjhb	struct turnstile *ts;
553176017Sjeff	uintptr_t x, v, queue;
554154941Sjhb
555235404Savg	if (SCHEDULER_STOPPED())
556235404Savg		return;
557235404Savg
558169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
559169394Sjhb	    ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
560154941Sjhb	_rw_assert(rw, RA_RLOCKED, file, line);
561160771Sjhb	curthread->td_locks--;
562176017Sjeff	curthread->td_rw_rlocks--;
563167787Sjhb	WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
564167787Sjhb	LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
565154941Sjhb
566154941Sjhb	/* TODO: drop "owner of record" here. */
567154941Sjhb
568154941Sjhb	for (;;) {
569154941Sjhb		/*
570154941Sjhb		 * See if there is more than one read lock held.  If so,
571154941Sjhb		 * just drop one and return.
572154941Sjhb		 */
573154941Sjhb		x = rw->rw_lock;
574154941Sjhb		if (RW_READERS(x) > 1) {
575197643Sattilio			if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
576154941Sjhb			    x - RW_ONE_READER)) {
577167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
578154941Sjhb					CTR4(KTR_LOCK,
579154941Sjhb					    "%s: %p succeeded %p -> %p",
580154941Sjhb					    __func__, rw, (void *)x,
581154941Sjhb					    (void *)(x - RW_ONE_READER));
582154941Sjhb				break;
583154941Sjhb			}
584154941Sjhb			continue;
585167307Sjhb		}
586154941Sjhb		/*
587154941Sjhb		 * If there aren't any waiters for a write lock, then try
588154941Sjhb		 * to drop it quickly.
589154941Sjhb		 */
590176017Sjeff		if (!(x & RW_LOCK_WAITERS)) {
591176017Sjeff			MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
592176017Sjeff			    RW_READERS_LOCK(1));
593197643Sattilio			if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
594197643Sattilio			    RW_UNLOCKED)) {
595167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
596154941Sjhb					CTR2(KTR_LOCK, "%s: %p last succeeded",
597154941Sjhb					    __func__, rw);
598154941Sjhb				break;
599154941Sjhb			}
600154941Sjhb			continue;
601154941Sjhb		}
602154941Sjhb		/*
603176017Sjeff		 * Ok, we know we have waiters and we think we are the
604176017Sjeff		 * last reader, so grab the turnstile lock.
605154941Sjhb		 */
606170295Sjeff		turnstile_chain_lock(&rw->lock_object);
607176017Sjeff		v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
608176017Sjeff		MPASS(v & RW_LOCK_WAITERS);
609154941Sjhb
610154941Sjhb		/*
611154941Sjhb		 * Try to drop our lock leaving the lock in a unlocked
612154941Sjhb		 * state.
613154941Sjhb		 *
614154941Sjhb		 * If you wanted to do explicit lock handoff you'd have to
615154941Sjhb		 * do it here.  You'd also want to use turnstile_signal()
616154941Sjhb		 * and you'd have to handle the race where a higher
617154941Sjhb		 * priority thread blocks on the write lock before the
618154941Sjhb		 * thread you wakeup actually runs and have the new thread
619154941Sjhb		 * "steal" the lock.  For now it's a lot simpler to just
620154941Sjhb		 * wakeup all of the waiters.
621154941Sjhb		 *
622154941Sjhb		 * As above, if we fail, then another thread might have
623154941Sjhb		 * acquired a read lock, so drop the turnstile lock and
624154941Sjhb		 * restart.
625154941Sjhb		 */
626176017Sjeff		x = RW_UNLOCKED;
627176017Sjeff		if (v & RW_LOCK_WRITE_WAITERS) {
628176017Sjeff			queue = TS_EXCLUSIVE_QUEUE;
629176017Sjeff			x |= (v & RW_LOCK_READ_WAITERS);
630176017Sjeff		} else
631176017Sjeff			queue = TS_SHARED_QUEUE;
632197643Sattilio		if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
633176017Sjeff		    x)) {
634170295Sjeff			turnstile_chain_unlock(&rw->lock_object);
635154941Sjhb			continue;
636154941Sjhb		}
637167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
638154941Sjhb			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
639154941Sjhb			    __func__, rw);
640154941Sjhb
641154941Sjhb		/*
642154941Sjhb		 * Ok.  The lock is released and all that's left is to
643154941Sjhb		 * wake up the waiters.  Note that the lock might not be
644154941Sjhb		 * free anymore, but in that case the writers will just
645154941Sjhb		 * block again if they run before the new lock holder(s)
646154941Sjhb		 * release the lock.
647154941Sjhb		 */
648167787Sjhb		ts = turnstile_lookup(&rw->lock_object);
649157846Sjhb		MPASS(ts != NULL);
650176017Sjeff		turnstile_broadcast(ts, queue);
651154941Sjhb		turnstile_unpend(ts, TS_SHARED_LOCK);
652170295Sjeff		turnstile_chain_unlock(&rw->lock_object);
653154941Sjhb		break;
654154941Sjhb	}
655192853Ssson	LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
656154941Sjhb}
657154941Sjhb
658154941Sjhb/*
659154941Sjhb * This function is called when we are unable to obtain a write lock on the
660154941Sjhb * first try.  This means that at least one other thread holds either a
661154941Sjhb * read or write lock.
662154941Sjhb */
663154941Sjhbvoid
664154941Sjhb_rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
665154941Sjhb{
666170295Sjeff	struct turnstile *ts;
667167801Sjhb#ifdef ADAPTIVE_RWLOCKS
668157846Sjhb	volatile struct thread *owner;
669176017Sjeff	int spintries = 0;
670176017Sjeff	int i;
671157851Swkoszek#endif
672189846Sjeff	uintptr_t v, x;
673189846Sjeff#ifdef LOCK_PROFILING
674171516Sattilio	uint64_t waittime = 0;
675171516Sattilio	int contested = 0;
676189846Sjeff#endif
677192853Ssson#ifdef KDTRACE_HOOKS
678192853Ssson	uint64_t spin_cnt = 0;
679192853Ssson	uint64_t sleep_cnt = 0;
680192853Ssson	int64_t sleep_time = 0;
681192853Ssson#endif
682154941Sjhb
683235404Savg	if (SCHEDULER_STOPPED())
684235404Savg		return;
685235404Savg
686171052Sattilio	if (rw_wlocked(rw)) {
687193307Sattilio		KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
688171052Sattilio		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
689171052Sattilio		    __func__, rw->lock_object.lo_name, file, line));
690171052Sattilio		rw->rw_recurse++;
691171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
692171052Sattilio			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
693171052Sattilio		return;
694171052Sattilio	}
695171052Sattilio
696167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
697154941Sjhb		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
698167787Sjhb		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
699154941Sjhb
700154941Sjhb	while (!_rw_write_lock(rw, tid)) {
701192853Ssson#ifdef KDTRACE_HOOKS
702192853Ssson		spin_cnt++;
703192853Ssson#endif
704236238Sfabient#ifdef HWPMC_HOOKS
705236238Sfabient		PMC_SOFT_CALL( , , lock, failed);
706236238Sfabient#endif
707174629Sjeff		lock_profile_obtain_lock_failed(&rw->lock_object,
708174629Sjeff		    &contested, &waittime);
709173960Sattilio#ifdef ADAPTIVE_RWLOCKS
710173960Sattilio		/*
711173960Sattilio		 * If the lock is write locked and the owner is
712173960Sattilio		 * running on another CPU, spin until the owner stops
713173960Sattilio		 * running or the state of the lock changes.
714173960Sattilio		 */
715173960Sattilio		v = rw->rw_lock;
716173960Sattilio		owner = (struct thread *)RW_OWNER(v);
717173960Sattilio		if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
718173960Sattilio			if (LOCK_LOG_TEST(&rw->lock_object, 0))
719173960Sattilio				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
720173960Sattilio				    __func__, rw, owner);
721173960Sattilio			while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
722192853Ssson			    TD_IS_RUNNING(owner)) {
723173960Sattilio				cpu_spinwait();
724192853Ssson#ifdef KDTRACE_HOOKS
725192853Ssson				spin_cnt++;
726192853Ssson#endif
727192853Ssson			}
728173960Sattilio			continue;
729173960Sattilio		}
730177912Sjeff		if ((v & RW_LOCK_READ) && RW_READERS(v) &&
731226255Sattilio		    spintries < ROWNER_RETRIES) {
732176017Sjeff			if (!(v & RW_LOCK_WRITE_SPINNER)) {
733176017Sjeff				if (!atomic_cmpset_ptr(&rw->rw_lock, v,
734176017Sjeff				    v | RW_LOCK_WRITE_SPINNER)) {
735176017Sjeff					continue;
736176017Sjeff				}
737176017Sjeff			}
738176017Sjeff			spintries++;
739226255Sattilio			for (i = 0; i < ROWNER_LOOPS; i++) {
740176017Sjeff				if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
741176017Sjeff					break;
742176017Sjeff				cpu_spinwait();
743176017Sjeff			}
744192853Ssson#ifdef KDTRACE_HOOKS
745226255Sattilio			spin_cnt += ROWNER_LOOPS - i;
746192853Ssson#endif
747226255Sattilio			if (i != ROWNER_LOOPS)
748176017Sjeff				continue;
749176017Sjeff		}
750173960Sattilio#endif
751170295Sjeff		ts = turnstile_trywait(&rw->lock_object);
752154941Sjhb		v = rw->rw_lock;
753154941Sjhb
754173960Sattilio#ifdef ADAPTIVE_RWLOCKS
755154941Sjhb		/*
756193035Sjhb		 * The current lock owner might have started executing
757193035Sjhb		 * on another CPU (or the lock could have changed
758193035Sjhb		 * owners) while we were waiting on the turnstile
759193035Sjhb		 * chain lock.  If so, drop the turnstile lock and try
760193035Sjhb		 * again.
761173960Sattilio		 */
762173960Sattilio		if (!(v & RW_LOCK_READ)) {
763173960Sattilio			owner = (struct thread *)RW_OWNER(v);
764173960Sattilio			if (TD_IS_RUNNING(owner)) {
765173960Sattilio				turnstile_cancel(ts);
766173960Sattilio				continue;
767173960Sattilio			}
768173960Sattilio		}
769173960Sattilio#endif
770173960Sattilio		/*
771179334Sattilio		 * Check for the waiters flags about this rwlock.
772179334Sattilio		 * If the lock was released, without maintain any pending
773179334Sattilio		 * waiters queue, simply try to acquire it.
774179334Sattilio		 * If a pending waiters queue is present, claim the lock
775179334Sattilio		 * ownership and maintain the pending queue.
776154941Sjhb		 */
777176017Sjeff		x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
778176017Sjeff		if ((v & ~x) == RW_UNLOCKED) {
779176017Sjeff			x &= ~RW_LOCK_WRITE_SPINNER;
780176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
781176017Sjeff				if (x)
782176017Sjeff					turnstile_claim(ts);
783176017Sjeff				else
784176017Sjeff					turnstile_cancel(ts);
785154941Sjhb				break;
786154941Sjhb			}
787170295Sjeff			turnstile_cancel(ts);
788154941Sjhb			continue;
789154941Sjhb		}
790154941Sjhb		/*
791154941Sjhb		 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
792154941Sjhb		 * set it.  If we fail to set it, then loop back and try
793154941Sjhb		 * again.
794154941Sjhb		 */
795157826Sjhb		if (!(v & RW_LOCK_WRITE_WAITERS)) {
796157826Sjhb			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
797157826Sjhb			    v | RW_LOCK_WRITE_WAITERS)) {
798170295Sjeff				turnstile_cancel(ts);
799157826Sjhb				continue;
800157826Sjhb			}
801167787Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
802157826Sjhb				CTR2(KTR_LOCK, "%s: %p set write waiters flag",
803157826Sjhb				    __func__, rw);
804154941Sjhb		}
805157846Sjhb		/*
806154941Sjhb		 * We were unable to acquire the lock and the write waiters
807154941Sjhb		 * flag is set, so we must block on the turnstile.
808154941Sjhb		 */
809167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
810154941Sjhb			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
811154941Sjhb			    rw);
812192853Ssson#ifdef KDTRACE_HOOKS
813192853Ssson		sleep_time -= lockstat_nsecs();
814192853Ssson#endif
815170295Sjeff		turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
816192853Ssson#ifdef KDTRACE_HOOKS
817192853Ssson		sleep_time += lockstat_nsecs();
818192853Ssson		sleep_cnt++;
819192853Ssson#endif
820167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
821154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
822154941Sjhb			    __func__, rw);
823176017Sjeff#ifdef ADAPTIVE_RWLOCKS
824176017Sjeff		spintries = 0;
825176017Sjeff#endif
826154941Sjhb	}
827192853Ssson	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
828192853Ssson	    waittime, file, line);
829192853Ssson#ifdef KDTRACE_HOOKS
830192853Ssson	if (sleep_time)
831192853Ssson		LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
832192853Ssson
833192853Ssson	/*
834192853Ssson	 * Record only the loops spinning and not sleeping.
835192853Ssson	 */
836192853Ssson	if (spin_cnt > sleep_cnt)
837192853Ssson		LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
838192853Ssson#endif
839154941Sjhb}
840154941Sjhb
841154941Sjhb/*
842154941Sjhb * This function is called if the first try at releasing a write lock failed.
843154941Sjhb * This means that one of the 2 waiter bits must be set indicating that at
844154941Sjhb * least one thread is waiting on this lock.
845154941Sjhb */
846154941Sjhbvoid
847154941Sjhb_rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
848154941Sjhb{
849154941Sjhb	struct turnstile *ts;
850154941Sjhb	uintptr_t v;
851154941Sjhb	int queue;
852154941Sjhb
853235404Savg	if (SCHEDULER_STOPPED())
854235404Savg		return;
855235404Savg
856171052Sattilio	if (rw_wlocked(rw) && rw_recursed(rw)) {
857176017Sjeff		rw->rw_recurse--;
858171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
859171052Sattilio			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
860171052Sattilio		return;
861171052Sattilio	}
862171052Sattilio
863154941Sjhb	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
864154941Sjhb	    ("%s: neither of the waiter flags are set", __func__));
865154941Sjhb
866167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
867154941Sjhb		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
868154941Sjhb
869170295Sjeff	turnstile_chain_lock(&rw->lock_object);
870167787Sjhb	ts = turnstile_lookup(&rw->lock_object);
871154941Sjhb	MPASS(ts != NULL);
872154941Sjhb
873154941Sjhb	/*
874154941Sjhb	 * Use the same algo as sx locks for now.  Prefer waking up shared
875154941Sjhb	 * waiters if we have any over writers.  This is probably not ideal.
876154941Sjhb	 *
877154941Sjhb	 * 'v' is the value we are going to write back to rw_lock.  If we
878154941Sjhb	 * have waiters on both queues, we need to preserve the state of
879154941Sjhb	 * the waiter flag for the queue we don't wake up.  For now this is
880154941Sjhb	 * hardcoded for the algorithm mentioned above.
881154941Sjhb	 *
882154941Sjhb	 * In the case of both readers and writers waiting we wakeup the
883154941Sjhb	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
884154941Sjhb	 * new writer comes in before a reader it will claim the lock up
885154941Sjhb	 * above.  There is probably a potential priority inversion in
886154941Sjhb	 * there that could be worked around either by waking both queues
887154941Sjhb	 * of waiters or doing some complicated lock handoff gymnastics.
888154941Sjhb	 */
889157846Sjhb	v = RW_UNLOCKED;
890176076Sjeff	if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
891176076Sjeff		queue = TS_EXCLUSIVE_QUEUE;
892176076Sjeff		v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
893176076Sjeff	} else
894154941Sjhb		queue = TS_SHARED_QUEUE;
895157846Sjhb
896157846Sjhb	/* Wake up all waiters for the specific queue. */
897167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
898154941Sjhb		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
899154941Sjhb		    queue == TS_SHARED_QUEUE ? "read" : "write");
900154941Sjhb	turnstile_broadcast(ts, queue);
901154941Sjhb	atomic_store_rel_ptr(&rw->rw_lock, v);
902154941Sjhb	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
903170295Sjeff	turnstile_chain_unlock(&rw->lock_object);
904154941Sjhb}
905154941Sjhb
906157882Sjhb/*
907157882Sjhb * Attempt to do a non-blocking upgrade from a read lock to a write
908157882Sjhb * lock.  This will only succeed if this thread holds a single read
909157882Sjhb * lock.  Returns true if the upgrade succeeded and false otherwise.
910157882Sjhb */
911157882Sjhbint
912157882Sjhb_rw_try_upgrade(struct rwlock *rw, const char *file, int line)
913157882Sjhb{
914176017Sjeff	uintptr_t v, x, tid;
915170295Sjeff	struct turnstile *ts;
916157882Sjhb	int success;
917157882Sjhb
918235404Savg	if (SCHEDULER_STOPPED())
919235404Savg		return (1);
920235404Savg
921169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
922169394Sjhb	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
923157882Sjhb	_rw_assert(rw, RA_RLOCKED, file, line);
924157882Sjhb
925157882Sjhb	/*
926157882Sjhb	 * Attempt to switch from one reader to a writer.  If there
927157882Sjhb	 * are any write waiters, then we will have to lock the
928157882Sjhb	 * turnstile first to prevent races with another writer
929157882Sjhb	 * calling turnstile_wait() before we have claimed this
930157882Sjhb	 * turnstile.  So, do the simple case of no waiters first.
931157882Sjhb	 */
932157882Sjhb	tid = (uintptr_t)curthread;
933176017Sjeff	success = 0;
934176017Sjeff	for (;;) {
935176017Sjeff		v = rw->rw_lock;
936176017Sjeff		if (RW_READERS(v) > 1)
937176017Sjeff			break;
938176017Sjeff		if (!(v & RW_LOCK_WAITERS)) {
939176017Sjeff			success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
940176017Sjeff			if (!success)
941176017Sjeff				continue;
942176017Sjeff			break;
943176017Sjeff		}
944157882Sjhb
945176017Sjeff		/*
946176017Sjeff		 * Ok, we think we have waiters, so lock the turnstile.
947176017Sjeff		 */
948176017Sjeff		ts = turnstile_trywait(&rw->lock_object);
949176017Sjeff		v = rw->rw_lock;
950176017Sjeff		if (RW_READERS(v) > 1) {
951176017Sjeff			turnstile_cancel(ts);
952176017Sjeff			break;
953176017Sjeff		}
954176017Sjeff		/*
955176017Sjeff		 * Try to switch from one reader to a writer again.  This time
956176017Sjeff		 * we honor the current state of the waiters flags.
957176017Sjeff		 * If we obtain the lock with the flags set, then claim
958176017Sjeff		 * ownership of the turnstile.
959176017Sjeff		 */
960176017Sjeff		x = rw->rw_lock & RW_LOCK_WAITERS;
961176017Sjeff		success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
962176017Sjeff		if (success) {
963176017Sjeff			if (x)
964176017Sjeff				turnstile_claim(ts);
965176017Sjeff			else
966176017Sjeff				turnstile_cancel(ts);
967176017Sjeff			break;
968176017Sjeff		}
969170295Sjeff		turnstile_cancel(ts);
970176017Sjeff	}
971167787Sjhb	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
972176017Sjeff	if (success) {
973176017Sjeff		curthread->td_rw_rlocks--;
974167787Sjhb		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
975157882Sjhb		    file, line);
976192853Ssson		LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
977176017Sjeff	}
978157882Sjhb	return (success);
979157882Sjhb}
980157882Sjhb
981157882Sjhb/*
982157882Sjhb * Downgrade a write lock into a single read lock.
983157882Sjhb */
984157882Sjhbvoid
985157882Sjhb_rw_downgrade(struct rwlock *rw, const char *file, int line)
986157882Sjhb{
987157882Sjhb	struct turnstile *ts;
988157882Sjhb	uintptr_t tid, v;
989176017Sjeff	int rwait, wwait;
990157882Sjhb
991235404Savg	if (SCHEDULER_STOPPED())
992235404Savg		return;
993235404Savg
994169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
995169394Sjhb	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
996171052Sattilio	_rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
997171052Sattilio#ifndef INVARIANTS
998171052Sattilio	if (rw_recursed(rw))
999171052Sattilio		panic("downgrade of a recursed lock");
1000171052Sattilio#endif
1001157882Sjhb
1002167787Sjhb	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1003157882Sjhb
1004157882Sjhb	/*
1005157882Sjhb	 * Convert from a writer to a single reader.  First we handle
1006157882Sjhb	 * the easy case with no waiters.  If there are any waiters, we
1007176017Sjeff	 * lock the turnstile and "disown" the lock.
1008157882Sjhb	 */
1009157882Sjhb	tid = (uintptr_t)curthread;
1010157882Sjhb	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1011157882Sjhb		goto out;
1012157882Sjhb
1013157882Sjhb	/*
1014157882Sjhb	 * Ok, we think we have waiters, so lock the turnstile so we can
1015157882Sjhb	 * read the waiter flags without any races.
1016157882Sjhb	 */
1017170295Sjeff	turnstile_chain_lock(&rw->lock_object);
1018176017Sjeff	v = rw->rw_lock & RW_LOCK_WAITERS;
1019176017Sjeff	rwait = v & RW_LOCK_READ_WAITERS;
1020176017Sjeff	wwait = v & RW_LOCK_WRITE_WAITERS;
1021176017Sjeff	MPASS(rwait | wwait);
1022157882Sjhb
1023157882Sjhb	/*
1024176017Sjeff	 * Downgrade from a write lock while preserving waiters flag
1025176017Sjeff	 * and give up ownership of the turnstile.
1026157882Sjhb	 */
1027167787Sjhb	ts = turnstile_lookup(&rw->lock_object);
1028157882Sjhb	MPASS(ts != NULL);
1029176017Sjeff	if (!wwait)
1030176017Sjeff		v &= ~RW_LOCK_READ_WAITERS;
1031176017Sjeff	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1032176017Sjeff	/*
1033176017Sjeff	 * Wake other readers if there are no writers pending.  Otherwise they
1034176017Sjeff	 * won't be able to acquire the lock anyway.
1035176017Sjeff	 */
1036176017Sjeff	if (rwait && !wwait) {
1037157882Sjhb		turnstile_broadcast(ts, TS_SHARED_QUEUE);
1038157882Sjhb		turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1039176017Sjeff	} else
1040157882Sjhb		turnstile_disown(ts);
1041170295Sjeff	turnstile_chain_unlock(&rw->lock_object);
1042157882Sjhbout:
1043176017Sjeff	curthread->td_rw_rlocks++;
1044167787Sjhb	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1045192853Ssson	LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1046157882Sjhb}
1047157882Sjhb
1048154941Sjhb#ifdef INVARIANT_SUPPORT
1049155162Sscottl#ifndef INVARIANTS
1050154941Sjhb#undef _rw_assert
1051154941Sjhb#endif
1052154941Sjhb
1053154941Sjhb/*
1054154941Sjhb * In the non-WITNESS case, rw_assert() can only detect that at least
1055154941Sjhb * *some* thread owns an rlock, but it cannot guarantee that *this*
1056154941Sjhb * thread owns an rlock.
1057154941Sjhb */
1058154941Sjhbvoid
1059154941Sjhb_rw_assert(struct rwlock *rw, int what, const char *file, int line)
1060154941Sjhb{
1061154941Sjhb
1062154941Sjhb	if (panicstr != NULL)
1063154941Sjhb		return;
1064154941Sjhb	switch (what) {
1065154941Sjhb	case RA_LOCKED:
1066171052Sattilio	case RA_LOCKED | RA_RECURSED:
1067171052Sattilio	case RA_LOCKED | RA_NOTRECURSED:
1068154941Sjhb	case RA_RLOCKED:
1069252172Sjhb	case RA_RLOCKED | RA_RECURSED:
1070252172Sjhb	case RA_RLOCKED | RA_NOTRECURSED:
1071154941Sjhb#ifdef WITNESS
1072167787Sjhb		witness_assert(&rw->lock_object, what, file, line);
1073154941Sjhb#else
1074154941Sjhb		/*
1075154941Sjhb		 * If some other thread has a write lock or we have one
1076154941Sjhb		 * and are asserting a read lock, fail.  Also, if no one
1077154941Sjhb		 * has a lock at all, fail.
1078154941Sjhb		 */
1079155061Sscottl		if (rw->rw_lock == RW_UNLOCKED ||
1080252172Sjhb		    (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1081157826Sjhb		    rw_wowner(rw) != curthread)))
1082154941Sjhb			panic("Lock %s not %slocked @ %s:%d\n",
1083252172Sjhb			    rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1084154941Sjhb			    "read " : "", file, line);
1085171052Sattilio
1086252172Sjhb		if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1087171052Sattilio			if (rw_recursed(rw)) {
1088171052Sattilio				if (what & RA_NOTRECURSED)
1089171052Sattilio					panic("Lock %s recursed @ %s:%d\n",
1090171052Sattilio					    rw->lock_object.lo_name, file,
1091171052Sattilio					    line);
1092171052Sattilio			} else if (what & RA_RECURSED)
1093171052Sattilio				panic("Lock %s not recursed @ %s:%d\n",
1094171052Sattilio				    rw->lock_object.lo_name, file, line);
1095171052Sattilio		}
1096154941Sjhb#endif
1097154941Sjhb		break;
1098154941Sjhb	case RA_WLOCKED:
1099171052Sattilio	case RA_WLOCKED | RA_RECURSED:
1100171052Sattilio	case RA_WLOCKED | RA_NOTRECURSED:
1101157826Sjhb		if (rw_wowner(rw) != curthread)
1102154941Sjhb			panic("Lock %s not exclusively locked @ %s:%d\n",
1103167787Sjhb			    rw->lock_object.lo_name, file, line);
1104171052Sattilio		if (rw_recursed(rw)) {
1105171052Sattilio			if (what & RA_NOTRECURSED)
1106171052Sattilio				panic("Lock %s recursed @ %s:%d\n",
1107171052Sattilio				    rw->lock_object.lo_name, file, line);
1108171052Sattilio		} else if (what & RA_RECURSED)
1109171052Sattilio			panic("Lock %s not recursed @ %s:%d\n",
1110171052Sattilio			    rw->lock_object.lo_name, file, line);
1111154941Sjhb		break;
1112154941Sjhb	case RA_UNLOCKED:
1113154941Sjhb#ifdef WITNESS
1114167787Sjhb		witness_assert(&rw->lock_object, what, file, line);
1115154941Sjhb#else
1116154941Sjhb		/*
1117154941Sjhb		 * If we hold a write lock fail.  We can't reliably check
1118154941Sjhb		 * to see if we hold a read lock or not.
1119154941Sjhb		 */
1120157826Sjhb		if (rw_wowner(rw) == curthread)
1121154941Sjhb			panic("Lock %s exclusively locked @ %s:%d\n",
1122167787Sjhb			    rw->lock_object.lo_name, file, line);
1123154941Sjhb#endif
1124154941Sjhb		break;
1125154941Sjhb	default:
1126154941Sjhb		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1127154941Sjhb		    line);
1128154941Sjhb	}
1129154941Sjhb}
1130154941Sjhb#endif /* INVARIANT_SUPPORT */
1131154941Sjhb
1132154941Sjhb#ifdef DDB
1133154941Sjhbvoid
1134154941Sjhbdb_show_rwlock(struct lock_object *lock)
1135154941Sjhb{
1136154941Sjhb	struct rwlock *rw;
1137154941Sjhb	struct thread *td;
1138154941Sjhb
1139154941Sjhb	rw = (struct rwlock *)lock;
1140154941Sjhb
1141154941Sjhb	db_printf(" state: ");
1142154941Sjhb	if (rw->rw_lock == RW_UNLOCKED)
1143154941Sjhb		db_printf("UNLOCKED\n");
1144169394Sjhb	else if (rw->rw_lock == RW_DESTROYED) {
1145169394Sjhb		db_printf("DESTROYED\n");
1146169394Sjhb		return;
1147169394Sjhb	} else if (rw->rw_lock & RW_LOCK_READ)
1148167504Sjhb		db_printf("RLOCK: %ju locks\n",
1149167504Sjhb		    (uintmax_t)(RW_READERS(rw->rw_lock)));
1150154941Sjhb	else {
1151157826Sjhb		td = rw_wowner(rw);
1152154941Sjhb		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1153173600Sjulian		    td->td_tid, td->td_proc->p_pid, td->td_name);
1154171052Sattilio		if (rw_recursed(rw))
1155171052Sattilio			db_printf(" recursed: %u\n", rw->rw_recurse);
1156154941Sjhb	}
1157154941Sjhb	db_printf(" waiters: ");
1158154941Sjhb	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1159154941Sjhb	case RW_LOCK_READ_WAITERS:
1160154941Sjhb		db_printf("readers\n");
1161154941Sjhb		break;
1162154941Sjhb	case RW_LOCK_WRITE_WAITERS:
1163154941Sjhb		db_printf("writers\n");
1164154941Sjhb		break;
1165154941Sjhb	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1166167492Sjhb		db_printf("readers and writers\n");
1167154941Sjhb		break;
1168154941Sjhb	default:
1169154941Sjhb		db_printf("none\n");
1170154941Sjhb		break;
1171154941Sjhb	}
1172154941Sjhb}
1173154941Sjhb
1174154941Sjhb#endif
1175