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