kern_rwlock.c revision 197643
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 197643 2009-09-30 13:26:31Z 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) {
544197643Sattilio			if (atomic_cmpset_rel_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));
562197643Sattilio			if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
563197643Sattilio			    RW_UNLOCKED)) {
564167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
565154941Sjhb					CTR2(KTR_LOCK, "%s: %p last succeeded",
566154941Sjhb					    __func__, rw);
567154941Sjhb				break;
568154941Sjhb			}
569154941Sjhb			continue;
570154941Sjhb		}
571154941Sjhb		/*
572176017Sjeff		 * Ok, we know we have waiters and we think we are the
573176017Sjeff		 * last reader, so grab the turnstile lock.
574154941Sjhb		 */
575170295Sjeff		turnstile_chain_lock(&rw->lock_object);
576176017Sjeff		v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
577176017Sjeff		MPASS(v & RW_LOCK_WAITERS);
578154941Sjhb
579154941Sjhb		/*
580154941Sjhb		 * Try to drop our lock leaving the lock in a unlocked
581154941Sjhb		 * state.
582154941Sjhb		 *
583154941Sjhb		 * If you wanted to do explicit lock handoff you'd have to
584154941Sjhb		 * do it here.  You'd also want to use turnstile_signal()
585154941Sjhb		 * and you'd have to handle the race where a higher
586154941Sjhb		 * priority thread blocks on the write lock before the
587154941Sjhb		 * thread you wakeup actually runs and have the new thread
588154941Sjhb		 * "steal" the lock.  For now it's a lot simpler to just
589154941Sjhb		 * wakeup all of the waiters.
590154941Sjhb		 *
591154941Sjhb		 * As above, if we fail, then another thread might have
592154941Sjhb		 * acquired a read lock, so drop the turnstile lock and
593154941Sjhb		 * restart.
594154941Sjhb		 */
595176017Sjeff		x = RW_UNLOCKED;
596176017Sjeff		if (v & RW_LOCK_WRITE_WAITERS) {
597176017Sjeff			queue = TS_EXCLUSIVE_QUEUE;
598176017Sjeff			x |= (v & RW_LOCK_READ_WAITERS);
599176017Sjeff		} else
600176017Sjeff			queue = TS_SHARED_QUEUE;
601197643Sattilio		if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
602176017Sjeff		    x)) {
603170295Sjeff			turnstile_chain_unlock(&rw->lock_object);
604154941Sjhb			continue;
605154941Sjhb		}
606167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
607154941Sjhb			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
608154941Sjhb			    __func__, rw);
609154941Sjhb
610154941Sjhb		/*
611154941Sjhb		 * Ok.  The lock is released and all that's left is to
612154941Sjhb		 * wake up the waiters.  Note that the lock might not be
613154941Sjhb		 * free anymore, but in that case the writers will just
614154941Sjhb		 * block again if they run before the new lock holder(s)
615154941Sjhb		 * release the lock.
616154941Sjhb		 */
617167787Sjhb		ts = turnstile_lookup(&rw->lock_object);
618157846Sjhb		MPASS(ts != NULL);
619176017Sjeff		turnstile_broadcast(ts, queue);
620154941Sjhb		turnstile_unpend(ts, TS_SHARED_LOCK);
621170295Sjeff		turnstile_chain_unlock(&rw->lock_object);
622154941Sjhb		break;
623154941Sjhb	}
624192853Ssson	LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
625154941Sjhb}
626154941Sjhb
627154941Sjhb/*
628154941Sjhb * This function is called when we are unable to obtain a write lock on the
629154941Sjhb * first try.  This means that at least one other thread holds either a
630154941Sjhb * read or write lock.
631154941Sjhb */
632154941Sjhbvoid
633154941Sjhb_rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
634154941Sjhb{
635170295Sjeff	struct turnstile *ts;
636167801Sjhb#ifdef ADAPTIVE_RWLOCKS
637157846Sjhb	volatile struct thread *owner;
638176017Sjeff	int spintries = 0;
639176017Sjeff	int i;
640157851Swkoszek#endif
641189846Sjeff	uintptr_t v, x;
642189846Sjeff#ifdef LOCK_PROFILING
643171516Sattilio	uint64_t waittime = 0;
644171516Sattilio	int contested = 0;
645189846Sjeff#endif
646192853Ssson#ifdef KDTRACE_HOOKS
647192853Ssson	uint64_t spin_cnt = 0;
648192853Ssson	uint64_t sleep_cnt = 0;
649192853Ssson	int64_t sleep_time = 0;
650192853Ssson#endif
651154941Sjhb
652171052Sattilio	if (rw_wlocked(rw)) {
653193307Sattilio		KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
654171052Sattilio		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
655171052Sattilio		    __func__, rw->lock_object.lo_name, file, line));
656171052Sattilio		rw->rw_recurse++;
657171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
658171052Sattilio			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
659171052Sattilio		return;
660171052Sattilio	}
661171052Sattilio
662167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
663154941Sjhb		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
664167787Sjhb		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
665154941Sjhb
666154941Sjhb	while (!_rw_write_lock(rw, tid)) {
667192853Ssson#ifdef KDTRACE_HOOKS
668192853Ssson		spin_cnt++;
669192853Ssson#endif
670174629Sjeff		lock_profile_obtain_lock_failed(&rw->lock_object,
671174629Sjeff		    &contested, &waittime);
672173960Sattilio#ifdef ADAPTIVE_RWLOCKS
673173960Sattilio		/*
674173960Sattilio		 * If the lock is write locked and the owner is
675173960Sattilio		 * running on another CPU, spin until the owner stops
676173960Sattilio		 * running or the state of the lock changes.
677173960Sattilio		 */
678173960Sattilio		v = rw->rw_lock;
679173960Sattilio		owner = (struct thread *)RW_OWNER(v);
680173960Sattilio		if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
681173960Sattilio			if (LOCK_LOG_TEST(&rw->lock_object, 0))
682173960Sattilio				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
683173960Sattilio				    __func__, rw, owner);
684173960Sattilio			while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
685192853Ssson			    TD_IS_RUNNING(owner)) {
686173960Sattilio				cpu_spinwait();
687192853Ssson#ifdef KDTRACE_HOOKS
688192853Ssson				spin_cnt++;
689192853Ssson#endif
690192853Ssson			}
691173960Sattilio			continue;
692173960Sattilio		}
693177912Sjeff		if ((v & RW_LOCK_READ) && RW_READERS(v) &&
694177912Sjeff		    spintries < rowner_retries) {
695176017Sjeff			if (!(v & RW_LOCK_WRITE_SPINNER)) {
696176017Sjeff				if (!atomic_cmpset_ptr(&rw->rw_lock, v,
697176017Sjeff				    v | RW_LOCK_WRITE_SPINNER)) {
698176017Sjeff					continue;
699176017Sjeff				}
700176017Sjeff			}
701176017Sjeff			spintries++;
702177912Sjeff			for (i = 0; i < rowner_loops; i++) {
703176017Sjeff				if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
704176017Sjeff					break;
705176017Sjeff				cpu_spinwait();
706176017Sjeff			}
707192853Ssson#ifdef KDTRACE_HOOKS
708192853Ssson			spin_cnt += rowner_loops - i;
709192853Ssson#endif
710177912Sjeff			if (i != rowner_loops)
711176017Sjeff				continue;
712176017Sjeff		}
713173960Sattilio#endif
714170295Sjeff		ts = turnstile_trywait(&rw->lock_object);
715154941Sjhb		v = rw->rw_lock;
716154941Sjhb
717173960Sattilio#ifdef ADAPTIVE_RWLOCKS
718154941Sjhb		/*
719193035Sjhb		 * The current lock owner might have started executing
720193035Sjhb		 * on another CPU (or the lock could have changed
721193035Sjhb		 * owners) while we were waiting on the turnstile
722193035Sjhb		 * chain lock.  If so, drop the turnstile lock and try
723193035Sjhb		 * again.
724173960Sattilio		 */
725173960Sattilio		if (!(v & RW_LOCK_READ)) {
726173960Sattilio			owner = (struct thread *)RW_OWNER(v);
727173960Sattilio			if (TD_IS_RUNNING(owner)) {
728173960Sattilio				turnstile_cancel(ts);
729173960Sattilio				continue;
730173960Sattilio			}
731173960Sattilio		}
732173960Sattilio#endif
733173960Sattilio		/*
734179334Sattilio		 * Check for the waiters flags about this rwlock.
735179334Sattilio		 * If the lock was released, without maintain any pending
736179334Sattilio		 * waiters queue, simply try to acquire it.
737179334Sattilio		 * If a pending waiters queue is present, claim the lock
738179334Sattilio		 * ownership and maintain the pending queue.
739154941Sjhb		 */
740176017Sjeff		x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
741176017Sjeff		if ((v & ~x) == RW_UNLOCKED) {
742176017Sjeff			x &= ~RW_LOCK_WRITE_SPINNER;
743176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
744176017Sjeff				if (x)
745176017Sjeff					turnstile_claim(ts);
746176017Sjeff				else
747176017Sjeff					turnstile_cancel(ts);
748154941Sjhb				break;
749154941Sjhb			}
750170295Sjeff			turnstile_cancel(ts);
751154941Sjhb			continue;
752154941Sjhb		}
753154941Sjhb		/*
754154941Sjhb		 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
755154941Sjhb		 * set it.  If we fail to set it, then loop back and try
756154941Sjhb		 * again.
757154941Sjhb		 */
758157826Sjhb		if (!(v & RW_LOCK_WRITE_WAITERS)) {
759157826Sjhb			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
760157826Sjhb			    v | RW_LOCK_WRITE_WAITERS)) {
761170295Sjeff				turnstile_cancel(ts);
762157826Sjhb				continue;
763157826Sjhb			}
764167787Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
765157826Sjhb				CTR2(KTR_LOCK, "%s: %p set write waiters flag",
766157826Sjhb				    __func__, rw);
767154941Sjhb		}
768157846Sjhb		/*
769154941Sjhb		 * We were unable to acquire the lock and the write waiters
770154941Sjhb		 * flag is set, so we must block on the turnstile.
771154941Sjhb		 */
772167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
773154941Sjhb			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
774154941Sjhb			    rw);
775192853Ssson#ifdef KDTRACE_HOOKS
776192853Ssson		sleep_time -= lockstat_nsecs();
777192853Ssson#endif
778170295Sjeff		turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
779192853Ssson#ifdef KDTRACE_HOOKS
780192853Ssson		sleep_time += lockstat_nsecs();
781192853Ssson		sleep_cnt++;
782192853Ssson#endif
783167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
784154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
785154941Sjhb			    __func__, rw);
786176017Sjeff#ifdef ADAPTIVE_RWLOCKS
787176017Sjeff		spintries = 0;
788176017Sjeff#endif
789154941Sjhb	}
790192853Ssson	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
791192853Ssson	    waittime, file, line);
792192853Ssson#ifdef KDTRACE_HOOKS
793192853Ssson	if (sleep_time)
794192853Ssson		LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
795192853Ssson
796192853Ssson	/*
797192853Ssson	 * Record only the loops spinning and not sleeping.
798192853Ssson	 */
799192853Ssson	if (spin_cnt > sleep_cnt)
800192853Ssson		LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
801192853Ssson#endif
802154941Sjhb}
803154941Sjhb
804154941Sjhb/*
805154941Sjhb * This function is called if the first try at releasing a write lock failed.
806154941Sjhb * This means that one of the 2 waiter bits must be set indicating that at
807154941Sjhb * least one thread is waiting on this lock.
808154941Sjhb */
809154941Sjhbvoid
810154941Sjhb_rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
811154941Sjhb{
812154941Sjhb	struct turnstile *ts;
813154941Sjhb	uintptr_t v;
814154941Sjhb	int queue;
815154941Sjhb
816171052Sattilio	if (rw_wlocked(rw) && rw_recursed(rw)) {
817176017Sjeff		rw->rw_recurse--;
818171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
819171052Sattilio			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
820171052Sattilio		return;
821171052Sattilio	}
822171052Sattilio
823154941Sjhb	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
824154941Sjhb	    ("%s: neither of the waiter flags are set", __func__));
825154941Sjhb
826167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
827154941Sjhb		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
828154941Sjhb
829170295Sjeff	turnstile_chain_lock(&rw->lock_object);
830167787Sjhb	ts = turnstile_lookup(&rw->lock_object);
831154941Sjhb	MPASS(ts != NULL);
832154941Sjhb
833154941Sjhb	/*
834154941Sjhb	 * Use the same algo as sx locks for now.  Prefer waking up shared
835154941Sjhb	 * waiters if we have any over writers.  This is probably not ideal.
836154941Sjhb	 *
837154941Sjhb	 * 'v' is the value we are going to write back to rw_lock.  If we
838154941Sjhb	 * have waiters on both queues, we need to preserve the state of
839154941Sjhb	 * the waiter flag for the queue we don't wake up.  For now this is
840154941Sjhb	 * hardcoded for the algorithm mentioned above.
841154941Sjhb	 *
842154941Sjhb	 * In the case of both readers and writers waiting we wakeup the
843154941Sjhb	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
844154941Sjhb	 * new writer comes in before a reader it will claim the lock up
845154941Sjhb	 * above.  There is probably a potential priority inversion in
846154941Sjhb	 * there that could be worked around either by waking both queues
847154941Sjhb	 * of waiters or doing some complicated lock handoff gymnastics.
848154941Sjhb	 */
849157846Sjhb	v = RW_UNLOCKED;
850176076Sjeff	if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
851176076Sjeff		queue = TS_EXCLUSIVE_QUEUE;
852176076Sjeff		v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
853176076Sjeff	} else
854154941Sjhb		queue = TS_SHARED_QUEUE;
855157846Sjhb
856157846Sjhb	/* Wake up all waiters for the specific queue. */
857167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
858154941Sjhb		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
859154941Sjhb		    queue == TS_SHARED_QUEUE ? "read" : "write");
860154941Sjhb	turnstile_broadcast(ts, queue);
861154941Sjhb	atomic_store_rel_ptr(&rw->rw_lock, v);
862154941Sjhb	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
863170295Sjeff	turnstile_chain_unlock(&rw->lock_object);
864154941Sjhb}
865154941Sjhb
866157882Sjhb/*
867157882Sjhb * Attempt to do a non-blocking upgrade from a read lock to a write
868157882Sjhb * lock.  This will only succeed if this thread holds a single read
869157882Sjhb * lock.  Returns true if the upgrade succeeded and false otherwise.
870157882Sjhb */
871157882Sjhbint
872157882Sjhb_rw_try_upgrade(struct rwlock *rw, const char *file, int line)
873157882Sjhb{
874176017Sjeff	uintptr_t v, x, tid;
875170295Sjeff	struct turnstile *ts;
876157882Sjhb	int success;
877157882Sjhb
878169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
879169394Sjhb	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
880157882Sjhb	_rw_assert(rw, RA_RLOCKED, file, line);
881157882Sjhb
882157882Sjhb	/*
883157882Sjhb	 * Attempt to switch from one reader to a writer.  If there
884157882Sjhb	 * are any write waiters, then we will have to lock the
885157882Sjhb	 * turnstile first to prevent races with another writer
886157882Sjhb	 * calling turnstile_wait() before we have claimed this
887157882Sjhb	 * turnstile.  So, do the simple case of no waiters first.
888157882Sjhb	 */
889157882Sjhb	tid = (uintptr_t)curthread;
890176017Sjeff	success = 0;
891176017Sjeff	for (;;) {
892176017Sjeff		v = rw->rw_lock;
893176017Sjeff		if (RW_READERS(v) > 1)
894176017Sjeff			break;
895176017Sjeff		if (!(v & RW_LOCK_WAITERS)) {
896176017Sjeff			success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
897176017Sjeff			if (!success)
898176017Sjeff				continue;
899176017Sjeff			break;
900176017Sjeff		}
901157882Sjhb
902176017Sjeff		/*
903176017Sjeff		 * Ok, we think we have waiters, so lock the turnstile.
904176017Sjeff		 */
905176017Sjeff		ts = turnstile_trywait(&rw->lock_object);
906176017Sjeff		v = rw->rw_lock;
907176017Sjeff		if (RW_READERS(v) > 1) {
908176017Sjeff			turnstile_cancel(ts);
909176017Sjeff			break;
910176017Sjeff		}
911176017Sjeff		/*
912176017Sjeff		 * Try to switch from one reader to a writer again.  This time
913176017Sjeff		 * we honor the current state of the waiters flags.
914176017Sjeff		 * If we obtain the lock with the flags set, then claim
915176017Sjeff		 * ownership of the turnstile.
916176017Sjeff		 */
917176017Sjeff		x = rw->rw_lock & RW_LOCK_WAITERS;
918176017Sjeff		success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
919176017Sjeff		if (success) {
920176017Sjeff			if (x)
921176017Sjeff				turnstile_claim(ts);
922176017Sjeff			else
923176017Sjeff				turnstile_cancel(ts);
924176017Sjeff			break;
925176017Sjeff		}
926170295Sjeff		turnstile_cancel(ts);
927176017Sjeff	}
928167787Sjhb	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
929176017Sjeff	if (success) {
930176017Sjeff		curthread->td_rw_rlocks--;
931167787Sjhb		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
932157882Sjhb		    file, line);
933192853Ssson		LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
934176017Sjeff	}
935157882Sjhb	return (success);
936157882Sjhb}
937157882Sjhb
938157882Sjhb/*
939157882Sjhb * Downgrade a write lock into a single read lock.
940157882Sjhb */
941157882Sjhbvoid
942157882Sjhb_rw_downgrade(struct rwlock *rw, const char *file, int line)
943157882Sjhb{
944157882Sjhb	struct turnstile *ts;
945157882Sjhb	uintptr_t tid, v;
946176017Sjeff	int rwait, wwait;
947157882Sjhb
948169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
949169394Sjhb	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
950171052Sattilio	_rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
951171052Sattilio#ifndef INVARIANTS
952171052Sattilio	if (rw_recursed(rw))
953171052Sattilio		panic("downgrade of a recursed lock");
954171052Sattilio#endif
955157882Sjhb
956167787Sjhb	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
957157882Sjhb
958157882Sjhb	/*
959157882Sjhb	 * Convert from a writer to a single reader.  First we handle
960157882Sjhb	 * the easy case with no waiters.  If there are any waiters, we
961176017Sjeff	 * lock the turnstile and "disown" the lock.
962157882Sjhb	 */
963157882Sjhb	tid = (uintptr_t)curthread;
964157882Sjhb	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
965157882Sjhb		goto out;
966157882Sjhb
967157882Sjhb	/*
968157882Sjhb	 * Ok, we think we have waiters, so lock the turnstile so we can
969157882Sjhb	 * read the waiter flags without any races.
970157882Sjhb	 */
971170295Sjeff	turnstile_chain_lock(&rw->lock_object);
972176017Sjeff	v = rw->rw_lock & RW_LOCK_WAITERS;
973176017Sjeff	rwait = v & RW_LOCK_READ_WAITERS;
974176017Sjeff	wwait = v & RW_LOCK_WRITE_WAITERS;
975176017Sjeff	MPASS(rwait | wwait);
976157882Sjhb
977157882Sjhb	/*
978176017Sjeff	 * Downgrade from a write lock while preserving waiters flag
979176017Sjeff	 * and give up ownership of the turnstile.
980157882Sjhb	 */
981167787Sjhb	ts = turnstile_lookup(&rw->lock_object);
982157882Sjhb	MPASS(ts != NULL);
983176017Sjeff	if (!wwait)
984176017Sjeff		v &= ~RW_LOCK_READ_WAITERS;
985176017Sjeff	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
986176017Sjeff	/*
987176017Sjeff	 * Wake other readers if there are no writers pending.  Otherwise they
988176017Sjeff	 * won't be able to acquire the lock anyway.
989176017Sjeff	 */
990176017Sjeff	if (rwait && !wwait) {
991157882Sjhb		turnstile_broadcast(ts, TS_SHARED_QUEUE);
992157882Sjhb		turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
993176017Sjeff	} else
994157882Sjhb		turnstile_disown(ts);
995170295Sjeff	turnstile_chain_unlock(&rw->lock_object);
996157882Sjhbout:
997176017Sjeff	curthread->td_rw_rlocks++;
998167787Sjhb	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
999192853Ssson	LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1000157882Sjhb}
1001157882Sjhb
1002154941Sjhb#ifdef INVARIANT_SUPPORT
1003155162Sscottl#ifndef INVARIANTS
1004154941Sjhb#undef _rw_assert
1005154941Sjhb#endif
1006154941Sjhb
1007154941Sjhb/*
1008154941Sjhb * In the non-WITNESS case, rw_assert() can only detect that at least
1009154941Sjhb * *some* thread owns an rlock, but it cannot guarantee that *this*
1010154941Sjhb * thread owns an rlock.
1011154941Sjhb */
1012154941Sjhbvoid
1013154941Sjhb_rw_assert(struct rwlock *rw, int what, const char *file, int line)
1014154941Sjhb{
1015154941Sjhb
1016154941Sjhb	if (panicstr != NULL)
1017154941Sjhb		return;
1018154941Sjhb	switch (what) {
1019154941Sjhb	case RA_LOCKED:
1020171052Sattilio	case RA_LOCKED | RA_RECURSED:
1021171052Sattilio	case RA_LOCKED | RA_NOTRECURSED:
1022154941Sjhb	case RA_RLOCKED:
1023154941Sjhb#ifdef WITNESS
1024167787Sjhb		witness_assert(&rw->lock_object, what, file, line);
1025154941Sjhb#else
1026154941Sjhb		/*
1027154941Sjhb		 * If some other thread has a write lock or we have one
1028154941Sjhb		 * and are asserting a read lock, fail.  Also, if no one
1029154941Sjhb		 * has a lock at all, fail.
1030154941Sjhb		 */
1031155061Sscottl		if (rw->rw_lock == RW_UNLOCKED ||
1032155061Sscottl		    (!(rw->rw_lock & RW_LOCK_READ) && (what == RA_RLOCKED ||
1033157826Sjhb		    rw_wowner(rw) != curthread)))
1034154941Sjhb			panic("Lock %s not %slocked @ %s:%d\n",
1035167787Sjhb			    rw->lock_object.lo_name, (what == RA_RLOCKED) ?
1036154941Sjhb			    "read " : "", file, line);
1037171052Sattilio
1038171052Sattilio		if (!(rw->rw_lock & RW_LOCK_READ)) {
1039171052Sattilio			if (rw_recursed(rw)) {
1040171052Sattilio				if (what & RA_NOTRECURSED)
1041171052Sattilio					panic("Lock %s recursed @ %s:%d\n",
1042171052Sattilio					    rw->lock_object.lo_name, file,
1043171052Sattilio					    line);
1044171052Sattilio			} else if (what & RA_RECURSED)
1045171052Sattilio				panic("Lock %s not recursed @ %s:%d\n",
1046171052Sattilio				    rw->lock_object.lo_name, file, line);
1047171052Sattilio		}
1048154941Sjhb#endif
1049154941Sjhb		break;
1050154941Sjhb	case RA_WLOCKED:
1051171052Sattilio	case RA_WLOCKED | RA_RECURSED:
1052171052Sattilio	case RA_WLOCKED | RA_NOTRECURSED:
1053157826Sjhb		if (rw_wowner(rw) != curthread)
1054154941Sjhb			panic("Lock %s not exclusively locked @ %s:%d\n",
1055167787Sjhb			    rw->lock_object.lo_name, file, line);
1056171052Sattilio		if (rw_recursed(rw)) {
1057171052Sattilio			if (what & RA_NOTRECURSED)
1058171052Sattilio				panic("Lock %s recursed @ %s:%d\n",
1059171052Sattilio				    rw->lock_object.lo_name, file, line);
1060171052Sattilio		} else if (what & RA_RECURSED)
1061171052Sattilio			panic("Lock %s not recursed @ %s:%d\n",
1062171052Sattilio			    rw->lock_object.lo_name, file, line);
1063154941Sjhb		break;
1064154941Sjhb	case RA_UNLOCKED:
1065154941Sjhb#ifdef WITNESS
1066167787Sjhb		witness_assert(&rw->lock_object, what, file, line);
1067154941Sjhb#else
1068154941Sjhb		/*
1069154941Sjhb		 * If we hold a write lock fail.  We can't reliably check
1070154941Sjhb		 * to see if we hold a read lock or not.
1071154941Sjhb		 */
1072157826Sjhb		if (rw_wowner(rw) == curthread)
1073154941Sjhb			panic("Lock %s exclusively locked @ %s:%d\n",
1074167787Sjhb			    rw->lock_object.lo_name, file, line);
1075154941Sjhb#endif
1076154941Sjhb		break;
1077154941Sjhb	default:
1078154941Sjhb		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1079154941Sjhb		    line);
1080154941Sjhb	}
1081154941Sjhb}
1082154941Sjhb#endif /* INVARIANT_SUPPORT */
1083154941Sjhb
1084154941Sjhb#ifdef DDB
1085154941Sjhbvoid
1086154941Sjhbdb_show_rwlock(struct lock_object *lock)
1087154941Sjhb{
1088154941Sjhb	struct rwlock *rw;
1089154941Sjhb	struct thread *td;
1090154941Sjhb
1091154941Sjhb	rw = (struct rwlock *)lock;
1092154941Sjhb
1093154941Sjhb	db_printf(" state: ");
1094154941Sjhb	if (rw->rw_lock == RW_UNLOCKED)
1095154941Sjhb		db_printf("UNLOCKED\n");
1096169394Sjhb	else if (rw->rw_lock == RW_DESTROYED) {
1097169394Sjhb		db_printf("DESTROYED\n");
1098169394Sjhb		return;
1099169394Sjhb	} else if (rw->rw_lock & RW_LOCK_READ)
1100167504Sjhb		db_printf("RLOCK: %ju locks\n",
1101167504Sjhb		    (uintmax_t)(RW_READERS(rw->rw_lock)));
1102154941Sjhb	else {
1103157826Sjhb		td = rw_wowner(rw);
1104154941Sjhb		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1105173600Sjulian		    td->td_tid, td->td_proc->p_pid, td->td_name);
1106171052Sattilio		if (rw_recursed(rw))
1107171052Sattilio			db_printf(" recursed: %u\n", rw->rw_recurse);
1108154941Sjhb	}
1109154941Sjhb	db_printf(" waiters: ");
1110154941Sjhb	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1111154941Sjhb	case RW_LOCK_READ_WAITERS:
1112154941Sjhb		db_printf("readers\n");
1113154941Sjhb		break;
1114154941Sjhb	case RW_LOCK_WRITE_WAITERS:
1115154941Sjhb		db_printf("writers\n");
1116154941Sjhb		break;
1117154941Sjhb	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1118167492Sjhb		db_printf("readers and writers\n");
1119154941Sjhb		break;
1120154941Sjhb	default:
1121154941Sjhb		db_printf("none\n");
1122154941Sjhb		break;
1123154941Sjhb	}
1124154941Sjhb}
1125154941Sjhb
1126154941Sjhb#endif
1127