kern_rwlock.c revision 189846
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 189846 2009-03-15 08:03:54Z jeff $");
36154941Sjhb
37154941Sjhb#include "opt_ddb.h"
38167801Sjhb#include "opt_no_adaptive_rwlocks.h"
39154941Sjhb
40154941Sjhb#include <sys/param.h>
41154941Sjhb#include <sys/ktr.h>
42177912Sjeff#include <sys/kernel.h>
43154941Sjhb#include <sys/lock.h>
44154941Sjhb#include <sys/mutex.h>
45154941Sjhb#include <sys/proc.h>
46154941Sjhb#include <sys/rwlock.h>
47177912Sjeff#include <sys/sysctl.h>
48154941Sjhb#include <sys/systm.h>
49154941Sjhb#include <sys/turnstile.h>
50171516Sattilio
51154941Sjhb#include <machine/cpu.h>
52154941Sjhb
53171052SattilioCTASSERT((RW_RECURSE & LO_CLASSFLAGS) == RW_RECURSE);
54171052Sattilio
55167801Sjhb#if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
56167801Sjhb#define	ADAPTIVE_RWLOCKS
57167801Sjhb#endif
58167801Sjhb
59177912Sjeff#ifdef ADAPTIVE_RWLOCKS
60177912Sjeffstatic int rowner_retries = 10;
61177912Sjeffstatic int rowner_loops = 10000;
62177912SjeffSYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL, "rwlock debugging");
63177912SjeffSYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
64177912SjeffSYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
65177912Sjeff#endif
66177912Sjeff
67154941Sjhb#ifdef DDB
68154941Sjhb#include <ddb/ddb.h>
69154941Sjhb
70154941Sjhbstatic void	db_show_rwlock(struct lock_object *lock);
71154941Sjhb#endif
72173733Sattiliostatic void	assert_rw(struct lock_object *lock, int what);
73167368Sjhbstatic void	lock_rw(struct lock_object *lock, int how);
74167368Sjhbstatic int	unlock_rw(struct lock_object *lock);
75154941Sjhb
76154941Sjhbstruct lock_class lock_class_rw = {
77167365Sjhb	.lc_name = "rw",
78167365Sjhb	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
79173733Sattilio	.lc_assert = assert_rw,
80154941Sjhb#ifdef DDB
81167365Sjhb	.lc_ddb_show = db_show_rwlock,
82154941Sjhb#endif
83167368Sjhb	.lc_lock = lock_rw,
84167368Sjhb	.lc_unlock = unlock_rw,
85154941Sjhb};
86154941Sjhb
87157826Sjhb/*
88157826Sjhb * Return a pointer to the owning thread if the lock is write-locked or
89157826Sjhb * NULL if the lock is unlocked or read-locked.
90157826Sjhb */
91157826Sjhb#define	rw_wowner(rw)							\
92154941Sjhb	((rw)->rw_lock & RW_LOCK_READ ? NULL :				\
93154941Sjhb	    (struct thread *)RW_OWNER((rw)->rw_lock))
94154941Sjhb
95157826Sjhb/*
96171052Sattilio * Returns if a write owner is recursed.  Write ownership is not assured
97171052Sattilio * here and should be previously checked.
98171052Sattilio */
99171052Sattilio#define	rw_recursed(rw)		((rw)->rw_recurse != 0)
100171052Sattilio
101171052Sattilio/*
102171052Sattilio * Return true if curthread helds the lock.
103171052Sattilio */
104171052Sattilio#define	rw_wlocked(rw)		(rw_wowner((rw)) == curthread)
105171052Sattilio
106171052Sattilio/*
107157826Sjhb * Return a pointer to the owning thread for this lock who should receive
108157826Sjhb * any priority lent by threads that block on this lock.  Currently this
109157826Sjhb * is identical to rw_wowner().
110157826Sjhb */
111157826Sjhb#define	rw_owner(rw)		rw_wowner(rw)
112157826Sjhb
113154941Sjhb#ifndef INVARIANTS
114154941Sjhb#define	_rw_assert(rw, what, file, line)
115154941Sjhb#endif
116154941Sjhb
117154941Sjhbvoid
118173733Sattilioassert_rw(struct lock_object *lock, int what)
119173733Sattilio{
120173733Sattilio
121173733Sattilio	rw_assert((struct rwlock *)lock, what);
122173733Sattilio}
123173733Sattilio
124173733Sattiliovoid
125167368Sjhblock_rw(struct lock_object *lock, int how)
126167368Sjhb{
127167368Sjhb	struct rwlock *rw;
128167368Sjhb
129167368Sjhb	rw = (struct rwlock *)lock;
130167368Sjhb	if (how)
131167368Sjhb		rw_wlock(rw);
132167368Sjhb	else
133167368Sjhb		rw_rlock(rw);
134167368Sjhb}
135167368Sjhb
136167368Sjhbint
137167368Sjhbunlock_rw(struct lock_object *lock)
138167368Sjhb{
139167368Sjhb	struct rwlock *rw;
140167368Sjhb
141167368Sjhb	rw = (struct rwlock *)lock;
142167368Sjhb	rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
143167368Sjhb	if (rw->rw_lock & RW_LOCK_READ) {
144167368Sjhb		rw_runlock(rw);
145167368Sjhb		return (0);
146167368Sjhb	} else {
147167368Sjhb		rw_wunlock(rw);
148167368Sjhb		return (1);
149167368Sjhb	}
150167368Sjhb}
151167368Sjhb
152167368Sjhbvoid
153171052Sattiliorw_init_flags(struct rwlock *rw, const char *name, int opts)
154154941Sjhb{
155171052Sattilio	int flags;
156154941Sjhb
157171052Sattilio	MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
158171052Sattilio	    RW_RECURSE)) == 0);
159171052Sattilio
160171052Sattilio	flags = LO_UPGRADABLE | LO_RECURSABLE;
161171052Sattilio	if (opts & RW_DUPOK)
162171052Sattilio		flags |= LO_DUPOK;
163171052Sattilio	if (opts & RW_NOPROFILE)
164171052Sattilio		flags |= LO_NOPROFILE;
165171052Sattilio	if (!(opts & RW_NOWITNESS))
166171052Sattilio		flags |= LO_WITNESS;
167171052Sattilio	if (opts & RW_QUIET)
168171052Sattilio		flags |= LO_QUIET;
169171052Sattilio	flags |= opts & RW_RECURSE;
170171052Sattilio
171154941Sjhb	rw->rw_lock = RW_UNLOCKED;
172171052Sattilio	rw->rw_recurse = 0;
173171052Sattilio	lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
174154941Sjhb}
175154941Sjhb
176154941Sjhbvoid
177154941Sjhbrw_destroy(struct rwlock *rw)
178154941Sjhb{
179154941Sjhb
180154941Sjhb	KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock not unlocked"));
181171052Sattilio	KASSERT(rw->rw_recurse == 0, ("rw lock still recursed"));
182169394Sjhb	rw->rw_lock = RW_DESTROYED;
183167787Sjhb	lock_destroy(&rw->lock_object);
184154941Sjhb}
185154941Sjhb
186154941Sjhbvoid
187154941Sjhbrw_sysinit(void *arg)
188154941Sjhb{
189154941Sjhb	struct rw_args *args = arg;
190154941Sjhb
191154941Sjhb	rw_init(args->ra_rw, args->ra_desc);
192154941Sjhb}
193154941Sjhb
194185778Skmacyvoid
195185778Skmacyrw_sysinit_flags(void *arg)
196185778Skmacy{
197185778Skmacy	struct rw_args_flags *args = arg;
198185778Skmacy
199185778Skmacy	rw_init_flags(args->ra_rw, args->ra_desc, args->ra_flags);
200185778Skmacy}
201185778Skmacy
202167024Srwatsonint
203167024Srwatsonrw_wowned(struct rwlock *rw)
204167024Srwatson{
205167024Srwatson
206167024Srwatson	return (rw_wowner(rw) == curthread);
207167024Srwatson}
208167024Srwatson
209154941Sjhbvoid
210154941Sjhb_rw_wlock(struct rwlock *rw, const char *file, int line)
211154941Sjhb{
212154941Sjhb
213154941Sjhb	MPASS(curthread != NULL);
214169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
215169394Sjhb	    ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
216167787Sjhb	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
217182914Sjhb	    line, NULL);
218154941Sjhb	__rw_wlock(rw, curthread, file, line);
219171052Sattilio	LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
220167787Sjhb	WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
221160771Sjhb	curthread->td_locks++;
222154941Sjhb}
223154941Sjhb
224177843Sattilioint
225177843Sattilio_rw_try_wlock(struct rwlock *rw, const char *file, int line)
226177843Sattilio{
227177843Sattilio	int rval;
228177843Sattilio
229177843Sattilio	KASSERT(rw->rw_lock != RW_DESTROYED,
230177843Sattilio	    ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
231177843Sattilio
232177843Sattilio	if (rw_wlocked(rw) && (rw->lock_object.lo_flags & RW_RECURSE) != 0) {
233177843Sattilio		rw->rw_recurse++;
234177843Sattilio		rval = 1;
235177843Sattilio	} else
236177843Sattilio		rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
237177843Sattilio		    (uintptr_t)curthread);
238177843Sattilio
239177843Sattilio	LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
240177843Sattilio	if (rval) {
241177843Sattilio		WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
242177843Sattilio		    file, line);
243177843Sattilio		curthread->td_locks++;
244177843Sattilio	}
245177843Sattilio	return (rval);
246177843Sattilio}
247177843Sattilio
248154941Sjhbvoid
249154941Sjhb_rw_wunlock(struct rwlock *rw, const char *file, int line)
250154941Sjhb{
251154941Sjhb
252154941Sjhb	MPASS(curthread != NULL);
253169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
254169394Sjhb	    ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
255154941Sjhb	_rw_assert(rw, RA_WLOCKED, file, line);
256160771Sjhb	curthread->td_locks--;
257167787Sjhb	WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
258171052Sattilio	LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
259171052Sattilio	    line);
260171052Sattilio	if (!rw_recursed(rw))
261171052Sattilio		lock_profile_release_lock(&rw->lock_object);
262154941Sjhb	__rw_wunlock(rw, curthread, file, line);
263154941Sjhb}
264176017Sjeff/*
265176017Sjeff * Determines whether a new reader can acquire a lock.  Succeeds if the
266176017Sjeff * reader already owns a read lock and the lock is locked for read to
267176017Sjeff * prevent deadlock from reader recursion.  Also succeeds if the lock
268176017Sjeff * is unlocked and has no writer waiters or spinners.  Failing otherwise
269176017Sjeff * prioritizes writers before readers.
270176017Sjeff */
271176017Sjeff#define	RW_CAN_READ(_rw)						\
272176017Sjeff    ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) &	\
273176017Sjeff    (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) ==	\
274176017Sjeff    RW_LOCK_READ)
275154941Sjhb
276154941Sjhbvoid
277154941Sjhb_rw_rlock(struct rwlock *rw, const char *file, int line)
278154941Sjhb{
279170295Sjeff	struct turnstile *ts;
280167801Sjhb#ifdef ADAPTIVE_RWLOCKS
281157846Sjhb	volatile struct thread *owner;
282177912Sjeff	int spintries = 0;
283177912Sjeff	int i;
284157851Swkoszek#endif
285189846Sjeff#ifdef LOCK_PROFILING
286167307Sjhb	uint64_t waittime = 0;
287167054Skmacy	int contested = 0;
288189846Sjeff#endif
289176017Sjeff	uintptr_t v;
290154941Sjhb
291169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
292169394Sjhb	    ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
293157826Sjhb	KASSERT(rw_wowner(rw) != curthread,
294154941Sjhb	    ("%s (%s): wlock already held @ %s:%d", __func__,
295167787Sjhb	    rw->lock_object.lo_name, file, line));
296182914Sjhb	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
297154941Sjhb
298154941Sjhb	for (;;) {
299154941Sjhb		/*
300154941Sjhb		 * Handle the easy case.  If no other thread has a write
301154941Sjhb		 * lock, then try to bump up the count of read locks.  Note
302154941Sjhb		 * that we have to preserve the current state of the
303154941Sjhb		 * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
304154941Sjhb		 * read lock, then rw_lock must have changed, so restart
305154941Sjhb		 * the loop.  Note that this handles the case of a
306154941Sjhb		 * completely unlocked rwlock since such a lock is encoded
307154941Sjhb		 * as a read lock with no waiters.
308154941Sjhb		 */
309176017Sjeff		v = rw->rw_lock;
310176017Sjeff		if (RW_CAN_READ(v)) {
311154941Sjhb			/*
312154941Sjhb			 * The RW_LOCK_READ_WAITERS flag should only be set
313176017Sjeff			 * if the lock has been unlocked and write waiters
314176017Sjeff			 * were present.
315154941Sjhb			 */
316176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
317176017Sjeff			    v + RW_ONE_READER)) {
318167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
319154941Sjhb					CTR4(KTR_LOCK,
320154941Sjhb					    "%s: %p succeed %p -> %p", __func__,
321176017Sjeff					    rw, (void *)v,
322176017Sjeff					    (void *)(v + RW_ONE_READER));
323154941Sjhb				break;
324154941Sjhb			}
325157846Sjhb			cpu_spinwait();
326154941Sjhb			continue;
327154941Sjhb		}
328174629Sjeff		lock_profile_obtain_lock_failed(&rw->lock_object,
329174629Sjeff		    &contested, &waittime);
330154941Sjhb
331173960Sattilio#ifdef ADAPTIVE_RWLOCKS
332154941Sjhb		/*
333173960Sattilio		 * If the owner is running on another CPU, spin until
334173960Sattilio		 * the owner stops running or the state of the lock
335173960Sattilio		 * changes.
336173960Sattilio		 */
337176017Sjeff		if ((v & RW_LOCK_READ) == 0) {
338176017Sjeff			owner = (struct thread *)RW_OWNER(v);
339176017Sjeff			if (TD_IS_RUNNING(owner)) {
340176017Sjeff				if (LOCK_LOG_TEST(&rw->lock_object, 0))
341176017Sjeff					CTR3(KTR_LOCK,
342176017Sjeff					    "%s: spinning on %p held by %p",
343176017Sjeff					    __func__, rw, owner);
344176017Sjeff				while ((struct thread*)RW_OWNER(rw->rw_lock) ==
345176017Sjeff				    owner && TD_IS_RUNNING(owner))
346176017Sjeff					cpu_spinwait();
347176017Sjeff				continue;
348176017Sjeff			}
349177912Sjeff		} else if (spintries < rowner_retries) {
350177912Sjeff			spintries++;
351177912Sjeff			for (i = 0; i < rowner_loops; i++) {
352177912Sjeff				v = rw->rw_lock;
353177912Sjeff				if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
354177912Sjeff					break;
355177912Sjeff				cpu_spinwait();
356177912Sjeff			}
357177912Sjeff			if (i != rowner_loops)
358177912Sjeff				continue;
359173960Sattilio		}
360173960Sattilio#endif
361173960Sattilio
362173960Sattilio		/*
363154941Sjhb		 * Okay, now it's the hard case.  Some other thread already
364176017Sjeff		 * has a write lock or there are write waiters present,
365176017Sjeff		 * acquire the turnstile lock so we can begin the process
366176017Sjeff		 * of blocking.
367154941Sjhb		 */
368170295Sjeff		ts = turnstile_trywait(&rw->lock_object);
369154941Sjhb
370154941Sjhb		/*
371154941Sjhb		 * The lock might have been released while we spun, so
372176017Sjeff		 * recheck its state and restart the loop if needed.
373154941Sjhb		 */
374176017Sjeff		v = rw->rw_lock;
375176017Sjeff		if (RW_CAN_READ(v)) {
376170295Sjeff			turnstile_cancel(ts);
377157846Sjhb			cpu_spinwait();
378154941Sjhb			continue;
379154941Sjhb		}
380154941Sjhb
381173960Sattilio#ifdef ADAPTIVE_RWLOCKS
382154941Sjhb		/*
383173960Sattilio		 * If the current owner of the lock is executing on another
384173960Sattilio		 * CPU quit the hard path and try to spin.
385173960Sattilio		 */
386176017Sjeff		if ((v & RW_LOCK_READ) == 0) {
387176017Sjeff			owner = (struct thread *)RW_OWNER(v);
388176017Sjeff			if (TD_IS_RUNNING(owner)) {
389176017Sjeff				turnstile_cancel(ts);
390176017Sjeff				cpu_spinwait();
391176017Sjeff				continue;
392176017Sjeff			}
393173960Sattilio		}
394173960Sattilio#endif
395173960Sattilio
396173960Sattilio		/*
397176017Sjeff		 * The lock is held in write mode or it already has waiters.
398154941Sjhb		 */
399176017Sjeff		MPASS(!RW_CAN_READ(v));
400176017Sjeff
401176017Sjeff		/*
402176017Sjeff		 * If the RW_LOCK_READ_WAITERS flag is already set, then
403176017Sjeff		 * we can go ahead and block.  If it is not set then try
404176017Sjeff		 * to set it.  If we fail to set it drop the turnstile
405176017Sjeff		 * lock and restart the loop.
406176017Sjeff		 */
407176017Sjeff		if (!(v & RW_LOCK_READ_WAITERS)) {
408176017Sjeff			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
409176017Sjeff			    v | RW_LOCK_READ_WAITERS)) {
410170295Sjeff				turnstile_cancel(ts);
411157826Sjhb				cpu_spinwait();
412157826Sjhb				continue;
413157826Sjhb			}
414167787Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
415157826Sjhb				CTR2(KTR_LOCK, "%s: %p set read waiters flag",
416157826Sjhb				    __func__, rw);
417154941Sjhb		}
418154941Sjhb
419154941Sjhb		/*
420154941Sjhb		 * We were unable to acquire the lock and the read waiters
421154941Sjhb		 * flag is set, so we must block on the turnstile.
422154941Sjhb		 */
423167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
424154941Sjhb			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
425154941Sjhb			    rw);
426170295Sjeff		turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
427167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
428154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
429154941Sjhb			    __func__, rw);
430154941Sjhb	}
431154941Sjhb
432154941Sjhb	/*
433154941Sjhb	 * TODO: acquire "owner of record" here.  Here be turnstile dragons
434154941Sjhb	 * however.  turnstiles don't like owners changing between calls to
435154941Sjhb	 * turnstile_wait() currently.
436154941Sjhb	 */
437174629Sjeff	lock_profile_obtain_lock_success( &rw->lock_object, contested,
438174629Sjeff	    waittime, file, line);
439167787Sjhb	LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
440167787Sjhb	WITNESS_LOCK(&rw->lock_object, 0, file, line);
441160771Sjhb	curthread->td_locks++;
442176017Sjeff	curthread->td_rw_rlocks++;
443154941Sjhb}
444154941Sjhb
445177843Sattilioint
446177843Sattilio_rw_try_rlock(struct rwlock *rw, const char *file, int line)
447177843Sattilio{
448177843Sattilio	uintptr_t x;
449177843Sattilio
450177843Sattilio	for (;;) {
451177843Sattilio		x = rw->rw_lock;
452177843Sattilio		KASSERT(rw->rw_lock != RW_DESTROYED,
453177843Sattilio		    ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
454177843Sattilio		if (!(x & RW_LOCK_READ))
455177843Sattilio			break;
456177843Sattilio		if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
457177843Sattilio			LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
458177843Sattilio			    line);
459177843Sattilio			WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
460177843Sattilio			curthread->td_locks++;
461177843Sattilio			curthread->td_rw_rlocks++;
462177843Sattilio			return (1);
463177843Sattilio		}
464177843Sattilio	}
465177843Sattilio
466177843Sattilio	LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
467177843Sattilio	return (0);
468177843Sattilio}
469177843Sattilio
470154941Sjhbvoid
471154941Sjhb_rw_runlock(struct rwlock *rw, const char *file, int line)
472154941Sjhb{
473154941Sjhb	struct turnstile *ts;
474176017Sjeff	uintptr_t x, v, queue;
475154941Sjhb
476169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
477169394Sjhb	    ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
478154941Sjhb	_rw_assert(rw, RA_RLOCKED, file, line);
479160771Sjhb	curthread->td_locks--;
480176017Sjeff	curthread->td_rw_rlocks--;
481167787Sjhb	WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
482167787Sjhb	LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
483154941Sjhb
484154941Sjhb	/* TODO: drop "owner of record" here. */
485154941Sjhb
486154941Sjhb	for (;;) {
487154941Sjhb		/*
488154941Sjhb		 * See if there is more than one read lock held.  If so,
489154941Sjhb		 * just drop one and return.
490154941Sjhb		 */
491154941Sjhb		x = rw->rw_lock;
492154941Sjhb		if (RW_READERS(x) > 1) {
493154941Sjhb			if (atomic_cmpset_ptr(&rw->rw_lock, x,
494154941Sjhb			    x - RW_ONE_READER)) {
495167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
496154941Sjhb					CTR4(KTR_LOCK,
497154941Sjhb					    "%s: %p succeeded %p -> %p",
498154941Sjhb					    __func__, rw, (void *)x,
499154941Sjhb					    (void *)(x - RW_ONE_READER));
500154941Sjhb				break;
501154941Sjhb			}
502154941Sjhb			continue;
503167307Sjhb		}
504154941Sjhb		/*
505154941Sjhb		 * If there aren't any waiters for a write lock, then try
506154941Sjhb		 * to drop it quickly.
507154941Sjhb		 */
508176017Sjeff		if (!(x & RW_LOCK_WAITERS)) {
509176017Sjeff			MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
510176017Sjeff			    RW_READERS_LOCK(1));
511176017Sjeff			if (atomic_cmpset_ptr(&rw->rw_lock, x, RW_UNLOCKED)) {
512167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
513154941Sjhb					CTR2(KTR_LOCK, "%s: %p last succeeded",
514154941Sjhb					    __func__, rw);
515154941Sjhb				break;
516154941Sjhb			}
517154941Sjhb			continue;
518154941Sjhb		}
519154941Sjhb		/*
520176017Sjeff		 * Ok, we know we have waiters and we think we are the
521176017Sjeff		 * last reader, so grab the turnstile lock.
522154941Sjhb		 */
523170295Sjeff		turnstile_chain_lock(&rw->lock_object);
524176017Sjeff		v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
525176017Sjeff		MPASS(v & RW_LOCK_WAITERS);
526154941Sjhb
527154941Sjhb		/*
528154941Sjhb		 * Try to drop our lock leaving the lock in a unlocked
529154941Sjhb		 * state.
530154941Sjhb		 *
531154941Sjhb		 * If you wanted to do explicit lock handoff you'd have to
532154941Sjhb		 * do it here.  You'd also want to use turnstile_signal()
533154941Sjhb		 * and you'd have to handle the race where a higher
534154941Sjhb		 * priority thread blocks on the write lock before the
535154941Sjhb		 * thread you wakeup actually runs and have the new thread
536154941Sjhb		 * "steal" the lock.  For now it's a lot simpler to just
537154941Sjhb		 * wakeup all of the waiters.
538154941Sjhb		 *
539154941Sjhb		 * As above, if we fail, then another thread might have
540154941Sjhb		 * acquired a read lock, so drop the turnstile lock and
541154941Sjhb		 * restart.
542154941Sjhb		 */
543176017Sjeff		x = RW_UNLOCKED;
544176017Sjeff		if (v & RW_LOCK_WRITE_WAITERS) {
545176017Sjeff			queue = TS_EXCLUSIVE_QUEUE;
546176017Sjeff			x |= (v & RW_LOCK_READ_WAITERS);
547176017Sjeff		} else
548176017Sjeff			queue = TS_SHARED_QUEUE;
549176017Sjeff		if (!atomic_cmpset_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
550176017Sjeff		    x)) {
551170295Sjeff			turnstile_chain_unlock(&rw->lock_object);
552154941Sjhb			continue;
553154941Sjhb		}
554167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
555154941Sjhb			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
556154941Sjhb			    __func__, rw);
557154941Sjhb
558154941Sjhb		/*
559154941Sjhb		 * Ok.  The lock is released and all that's left is to
560154941Sjhb		 * wake up the waiters.  Note that the lock might not be
561154941Sjhb		 * free anymore, but in that case the writers will just
562154941Sjhb		 * block again if they run before the new lock holder(s)
563154941Sjhb		 * release the lock.
564154941Sjhb		 */
565167787Sjhb		ts = turnstile_lookup(&rw->lock_object);
566157846Sjhb		MPASS(ts != NULL);
567176017Sjeff		turnstile_broadcast(ts, queue);
568154941Sjhb		turnstile_unpend(ts, TS_SHARED_LOCK);
569170295Sjeff		turnstile_chain_unlock(&rw->lock_object);
570154941Sjhb		break;
571154941Sjhb	}
572174629Sjeff	lock_profile_release_lock(&rw->lock_object);
573154941Sjhb}
574154941Sjhb
575154941Sjhb/*
576154941Sjhb * This function is called when we are unable to obtain a write lock on the
577154941Sjhb * first try.  This means that at least one other thread holds either a
578154941Sjhb * read or write lock.
579154941Sjhb */
580154941Sjhbvoid
581154941Sjhb_rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
582154941Sjhb{
583170295Sjeff	struct turnstile *ts;
584167801Sjhb#ifdef ADAPTIVE_RWLOCKS
585157846Sjhb	volatile struct thread *owner;
586176017Sjeff	int spintries = 0;
587176017Sjeff	int i;
588157851Swkoszek#endif
589189846Sjeff	uintptr_t v, x;
590189846Sjeff#ifdef LOCK_PROFILING
591171516Sattilio	uint64_t waittime = 0;
592171516Sattilio	int contested = 0;
593189846Sjeff#endif
594154941Sjhb
595171052Sattilio	if (rw_wlocked(rw)) {
596171052Sattilio		KASSERT(rw->lock_object.lo_flags & RW_RECURSE,
597171052Sattilio		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
598171052Sattilio		    __func__, rw->lock_object.lo_name, file, line));
599171052Sattilio		rw->rw_recurse++;
600171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
601171052Sattilio			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
602171052Sattilio		return;
603171052Sattilio	}
604171052Sattilio
605167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
606154941Sjhb		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
607167787Sjhb		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
608154941Sjhb
609154941Sjhb	while (!_rw_write_lock(rw, tid)) {
610174629Sjeff		lock_profile_obtain_lock_failed(&rw->lock_object,
611174629Sjeff		    &contested, &waittime);
612173960Sattilio#ifdef ADAPTIVE_RWLOCKS
613173960Sattilio		/*
614173960Sattilio		 * If the lock is write locked and the owner is
615173960Sattilio		 * running on another CPU, spin until the owner stops
616173960Sattilio		 * running or the state of the lock changes.
617173960Sattilio		 */
618173960Sattilio		v = rw->rw_lock;
619173960Sattilio		owner = (struct thread *)RW_OWNER(v);
620173960Sattilio		if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
621173960Sattilio			if (LOCK_LOG_TEST(&rw->lock_object, 0))
622173960Sattilio				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
623173960Sattilio				    __func__, rw, owner);
624173960Sattilio			while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
625173960Sattilio			    TD_IS_RUNNING(owner))
626173960Sattilio				cpu_spinwait();
627173960Sattilio			continue;
628173960Sattilio		}
629177912Sjeff		if ((v & RW_LOCK_READ) && RW_READERS(v) &&
630177912Sjeff		    spintries < rowner_retries) {
631176017Sjeff			if (!(v & RW_LOCK_WRITE_SPINNER)) {
632176017Sjeff				if (!atomic_cmpset_ptr(&rw->rw_lock, v,
633176017Sjeff				    v | RW_LOCK_WRITE_SPINNER)) {
634176017Sjeff					cpu_spinwait();
635176017Sjeff					continue;
636176017Sjeff				}
637176017Sjeff			}
638176017Sjeff			spintries++;
639177912Sjeff			for (i = 0; i < rowner_loops; i++) {
640176017Sjeff				if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
641176017Sjeff					break;
642176017Sjeff				cpu_spinwait();
643176017Sjeff			}
644177912Sjeff			if (i != rowner_loops)
645176017Sjeff				continue;
646176017Sjeff		}
647173960Sattilio#endif
648170295Sjeff		ts = turnstile_trywait(&rw->lock_object);
649154941Sjhb		v = rw->rw_lock;
650154941Sjhb
651173960Sattilio#ifdef ADAPTIVE_RWLOCKS
652154941Sjhb		/*
653173960Sattilio		 * If the current owner of the lock is executing on another
654173960Sattilio		 * CPU quit the hard path and try to spin.
655173960Sattilio		 */
656173960Sattilio		if (!(v & RW_LOCK_READ)) {
657173960Sattilio			owner = (struct thread *)RW_OWNER(v);
658173960Sattilio			if (TD_IS_RUNNING(owner)) {
659173960Sattilio				turnstile_cancel(ts);
660173960Sattilio				cpu_spinwait();
661173960Sattilio				continue;
662173960Sattilio			}
663173960Sattilio		}
664173960Sattilio#endif
665173960Sattilio		/*
666179334Sattilio		 * Check for the waiters flags about this rwlock.
667179334Sattilio		 * If the lock was released, without maintain any pending
668179334Sattilio		 * waiters queue, simply try to acquire it.
669179334Sattilio		 * If a pending waiters queue is present, claim the lock
670179334Sattilio		 * ownership and maintain the pending queue.
671154941Sjhb		 */
672176017Sjeff		x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
673176017Sjeff		if ((v & ~x) == RW_UNLOCKED) {
674176017Sjeff			x &= ~RW_LOCK_WRITE_SPINNER;
675176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
676176017Sjeff				if (x)
677176017Sjeff					turnstile_claim(ts);
678176017Sjeff				else
679176017Sjeff					turnstile_cancel(ts);
680154941Sjhb				break;
681154941Sjhb			}
682170295Sjeff			turnstile_cancel(ts);
683154941Sjhb			cpu_spinwait();
684154941Sjhb			continue;
685154941Sjhb		}
686154941Sjhb		/*
687154941Sjhb		 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
688154941Sjhb		 * set it.  If we fail to set it, then loop back and try
689154941Sjhb		 * again.
690154941Sjhb		 */
691157826Sjhb		if (!(v & RW_LOCK_WRITE_WAITERS)) {
692157826Sjhb			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
693157826Sjhb			    v | RW_LOCK_WRITE_WAITERS)) {
694170295Sjeff				turnstile_cancel(ts);
695157826Sjhb				cpu_spinwait();
696157826Sjhb				continue;
697157826Sjhb			}
698167787Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
699157826Sjhb				CTR2(KTR_LOCK, "%s: %p set write waiters flag",
700157826Sjhb				    __func__, rw);
701154941Sjhb		}
702157846Sjhb		/*
703154941Sjhb		 * We were unable to acquire the lock and the write waiters
704154941Sjhb		 * flag is set, so we must block on the turnstile.
705154941Sjhb		 */
706167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
707154941Sjhb			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
708154941Sjhb			    rw);
709170295Sjeff		turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
710167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
711154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
712154941Sjhb			    __func__, rw);
713176017Sjeff#ifdef ADAPTIVE_RWLOCKS
714176017Sjeff		spintries = 0;
715176017Sjeff#endif
716154941Sjhb	}
717171516Sattilio	lock_profile_obtain_lock_success(&rw->lock_object, contested, waittime,
718171516Sattilio	    file, line);
719154941Sjhb}
720154941Sjhb
721154941Sjhb/*
722154941Sjhb * This function is called if the first try at releasing a write lock failed.
723154941Sjhb * This means that one of the 2 waiter bits must be set indicating that at
724154941Sjhb * least one thread is waiting on this lock.
725154941Sjhb */
726154941Sjhbvoid
727154941Sjhb_rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
728154941Sjhb{
729154941Sjhb	struct turnstile *ts;
730154941Sjhb	uintptr_t v;
731154941Sjhb	int queue;
732154941Sjhb
733171052Sattilio	if (rw_wlocked(rw) && rw_recursed(rw)) {
734176017Sjeff		rw->rw_recurse--;
735171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
736171052Sattilio			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
737171052Sattilio		return;
738171052Sattilio	}
739171052Sattilio
740154941Sjhb	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
741154941Sjhb	    ("%s: neither of the waiter flags are set", __func__));
742154941Sjhb
743167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
744154941Sjhb		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
745154941Sjhb
746170295Sjeff	turnstile_chain_lock(&rw->lock_object);
747167787Sjhb	ts = turnstile_lookup(&rw->lock_object);
748154941Sjhb	MPASS(ts != NULL);
749154941Sjhb
750154941Sjhb	/*
751154941Sjhb	 * Use the same algo as sx locks for now.  Prefer waking up shared
752154941Sjhb	 * waiters if we have any over writers.  This is probably not ideal.
753154941Sjhb	 *
754154941Sjhb	 * 'v' is the value we are going to write back to rw_lock.  If we
755154941Sjhb	 * have waiters on both queues, we need to preserve the state of
756154941Sjhb	 * the waiter flag for the queue we don't wake up.  For now this is
757154941Sjhb	 * hardcoded for the algorithm mentioned above.
758154941Sjhb	 *
759154941Sjhb	 * In the case of both readers and writers waiting we wakeup the
760154941Sjhb	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
761154941Sjhb	 * new writer comes in before a reader it will claim the lock up
762154941Sjhb	 * above.  There is probably a potential priority inversion in
763154941Sjhb	 * there that could be worked around either by waking both queues
764154941Sjhb	 * of waiters or doing some complicated lock handoff gymnastics.
765154941Sjhb	 */
766157846Sjhb	v = RW_UNLOCKED;
767176076Sjeff	if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
768176076Sjeff		queue = TS_EXCLUSIVE_QUEUE;
769176076Sjeff		v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
770176076Sjeff	} else
771154941Sjhb		queue = TS_SHARED_QUEUE;
772157846Sjhb
773157846Sjhb	/* Wake up all waiters for the specific queue. */
774167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
775154941Sjhb		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
776154941Sjhb		    queue == TS_SHARED_QUEUE ? "read" : "write");
777154941Sjhb	turnstile_broadcast(ts, queue);
778154941Sjhb	atomic_store_rel_ptr(&rw->rw_lock, v);
779154941Sjhb	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
780170295Sjeff	turnstile_chain_unlock(&rw->lock_object);
781154941Sjhb}
782154941Sjhb
783157882Sjhb/*
784157882Sjhb * Attempt to do a non-blocking upgrade from a read lock to a write
785157882Sjhb * lock.  This will only succeed if this thread holds a single read
786157882Sjhb * lock.  Returns true if the upgrade succeeded and false otherwise.
787157882Sjhb */
788157882Sjhbint
789157882Sjhb_rw_try_upgrade(struct rwlock *rw, const char *file, int line)
790157882Sjhb{
791176017Sjeff	uintptr_t v, x, tid;
792170295Sjeff	struct turnstile *ts;
793157882Sjhb	int success;
794157882Sjhb
795169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
796169394Sjhb	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
797157882Sjhb	_rw_assert(rw, RA_RLOCKED, file, line);
798157882Sjhb
799157882Sjhb	/*
800157882Sjhb	 * Attempt to switch from one reader to a writer.  If there
801157882Sjhb	 * are any write waiters, then we will have to lock the
802157882Sjhb	 * turnstile first to prevent races with another writer
803157882Sjhb	 * calling turnstile_wait() before we have claimed this
804157882Sjhb	 * turnstile.  So, do the simple case of no waiters first.
805157882Sjhb	 */
806157882Sjhb	tid = (uintptr_t)curthread;
807176017Sjeff	success = 0;
808176017Sjeff	for (;;) {
809176017Sjeff		v = rw->rw_lock;
810176017Sjeff		if (RW_READERS(v) > 1)
811176017Sjeff			break;
812176017Sjeff		if (!(v & RW_LOCK_WAITERS)) {
813176017Sjeff			success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
814176017Sjeff			if (!success)
815176017Sjeff				continue;
816176017Sjeff			break;
817176017Sjeff		}
818157882Sjhb
819176017Sjeff		/*
820176017Sjeff		 * Ok, we think we have waiters, so lock the turnstile.
821176017Sjeff		 */
822176017Sjeff		ts = turnstile_trywait(&rw->lock_object);
823176017Sjeff		v = rw->rw_lock;
824176017Sjeff		if (RW_READERS(v) > 1) {
825176017Sjeff			turnstile_cancel(ts);
826176017Sjeff			break;
827176017Sjeff		}
828176017Sjeff		/*
829176017Sjeff		 * Try to switch from one reader to a writer again.  This time
830176017Sjeff		 * we honor the current state of the waiters flags.
831176017Sjeff		 * If we obtain the lock with the flags set, then claim
832176017Sjeff		 * ownership of the turnstile.
833176017Sjeff		 */
834176017Sjeff		x = rw->rw_lock & RW_LOCK_WAITERS;
835176017Sjeff		success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
836176017Sjeff		if (success) {
837176017Sjeff			if (x)
838176017Sjeff				turnstile_claim(ts);
839176017Sjeff			else
840176017Sjeff				turnstile_cancel(ts);
841176017Sjeff			break;
842176017Sjeff		}
843170295Sjeff		turnstile_cancel(ts);
844176017Sjeff	}
845167787Sjhb	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
846176017Sjeff	if (success) {
847176017Sjeff		curthread->td_rw_rlocks--;
848167787Sjhb		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
849157882Sjhb		    file, line);
850176017Sjeff	}
851157882Sjhb	return (success);
852157882Sjhb}
853157882Sjhb
854157882Sjhb/*
855157882Sjhb * Downgrade a write lock into a single read lock.
856157882Sjhb */
857157882Sjhbvoid
858157882Sjhb_rw_downgrade(struct rwlock *rw, const char *file, int line)
859157882Sjhb{
860157882Sjhb	struct turnstile *ts;
861157882Sjhb	uintptr_t tid, v;
862176017Sjeff	int rwait, wwait;
863157882Sjhb
864169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
865169394Sjhb	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
866171052Sattilio	_rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
867171052Sattilio#ifndef INVARIANTS
868171052Sattilio	if (rw_recursed(rw))
869171052Sattilio		panic("downgrade of a recursed lock");
870171052Sattilio#endif
871157882Sjhb
872167787Sjhb	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
873157882Sjhb
874157882Sjhb	/*
875157882Sjhb	 * Convert from a writer to a single reader.  First we handle
876157882Sjhb	 * the easy case with no waiters.  If there are any waiters, we
877176017Sjeff	 * lock the turnstile and "disown" the lock.
878157882Sjhb	 */
879157882Sjhb	tid = (uintptr_t)curthread;
880157882Sjhb	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
881157882Sjhb		goto out;
882157882Sjhb
883157882Sjhb	/*
884157882Sjhb	 * Ok, we think we have waiters, so lock the turnstile so we can
885157882Sjhb	 * read the waiter flags without any races.
886157882Sjhb	 */
887170295Sjeff	turnstile_chain_lock(&rw->lock_object);
888176017Sjeff	v = rw->rw_lock & RW_LOCK_WAITERS;
889176017Sjeff	rwait = v & RW_LOCK_READ_WAITERS;
890176017Sjeff	wwait = v & RW_LOCK_WRITE_WAITERS;
891176017Sjeff	MPASS(rwait | wwait);
892157882Sjhb
893157882Sjhb	/*
894176017Sjeff	 * Downgrade from a write lock while preserving waiters flag
895176017Sjeff	 * and give up ownership of the turnstile.
896157882Sjhb	 */
897167787Sjhb	ts = turnstile_lookup(&rw->lock_object);
898157882Sjhb	MPASS(ts != NULL);
899176017Sjeff	if (!wwait)
900176017Sjeff		v &= ~RW_LOCK_READ_WAITERS;
901176017Sjeff	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
902176017Sjeff	/*
903176017Sjeff	 * Wake other readers if there are no writers pending.  Otherwise they
904176017Sjeff	 * won't be able to acquire the lock anyway.
905176017Sjeff	 */
906176017Sjeff	if (rwait && !wwait) {
907157882Sjhb		turnstile_broadcast(ts, TS_SHARED_QUEUE);
908157882Sjhb		turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
909176017Sjeff	} else
910157882Sjhb		turnstile_disown(ts);
911170295Sjeff	turnstile_chain_unlock(&rw->lock_object);
912157882Sjhbout:
913176017Sjeff	curthread->td_rw_rlocks++;
914167787Sjhb	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
915157882Sjhb}
916157882Sjhb
917154941Sjhb#ifdef INVARIANT_SUPPORT
918155162Sscottl#ifndef INVARIANTS
919154941Sjhb#undef _rw_assert
920154941Sjhb#endif
921154941Sjhb
922154941Sjhb/*
923154941Sjhb * In the non-WITNESS case, rw_assert() can only detect that at least
924154941Sjhb * *some* thread owns an rlock, but it cannot guarantee that *this*
925154941Sjhb * thread owns an rlock.
926154941Sjhb */
927154941Sjhbvoid
928154941Sjhb_rw_assert(struct rwlock *rw, int what, const char *file, int line)
929154941Sjhb{
930154941Sjhb
931154941Sjhb	if (panicstr != NULL)
932154941Sjhb		return;
933154941Sjhb	switch (what) {
934154941Sjhb	case RA_LOCKED:
935171052Sattilio	case RA_LOCKED | RA_RECURSED:
936171052Sattilio	case RA_LOCKED | RA_NOTRECURSED:
937154941Sjhb	case RA_RLOCKED:
938154941Sjhb#ifdef WITNESS
939167787Sjhb		witness_assert(&rw->lock_object, what, file, line);
940154941Sjhb#else
941154941Sjhb		/*
942154941Sjhb		 * If some other thread has a write lock or we have one
943154941Sjhb		 * and are asserting a read lock, fail.  Also, if no one
944154941Sjhb		 * has a lock at all, fail.
945154941Sjhb		 */
946155061Sscottl		if (rw->rw_lock == RW_UNLOCKED ||
947155061Sscottl		    (!(rw->rw_lock & RW_LOCK_READ) && (what == RA_RLOCKED ||
948157826Sjhb		    rw_wowner(rw) != curthread)))
949154941Sjhb			panic("Lock %s not %slocked @ %s:%d\n",
950167787Sjhb			    rw->lock_object.lo_name, (what == RA_RLOCKED) ?
951154941Sjhb			    "read " : "", file, line);
952171052Sattilio
953171052Sattilio		if (!(rw->rw_lock & RW_LOCK_READ)) {
954171052Sattilio			if (rw_recursed(rw)) {
955171052Sattilio				if (what & RA_NOTRECURSED)
956171052Sattilio					panic("Lock %s recursed @ %s:%d\n",
957171052Sattilio					    rw->lock_object.lo_name, file,
958171052Sattilio					    line);
959171052Sattilio			} else if (what & RA_RECURSED)
960171052Sattilio				panic("Lock %s not recursed @ %s:%d\n",
961171052Sattilio				    rw->lock_object.lo_name, file, line);
962171052Sattilio		}
963154941Sjhb#endif
964154941Sjhb		break;
965154941Sjhb	case RA_WLOCKED:
966171052Sattilio	case RA_WLOCKED | RA_RECURSED:
967171052Sattilio	case RA_WLOCKED | RA_NOTRECURSED:
968157826Sjhb		if (rw_wowner(rw) != curthread)
969154941Sjhb			panic("Lock %s not exclusively locked @ %s:%d\n",
970167787Sjhb			    rw->lock_object.lo_name, file, line);
971171052Sattilio		if (rw_recursed(rw)) {
972171052Sattilio			if (what & RA_NOTRECURSED)
973171052Sattilio				panic("Lock %s recursed @ %s:%d\n",
974171052Sattilio				    rw->lock_object.lo_name, file, line);
975171052Sattilio		} else if (what & RA_RECURSED)
976171052Sattilio			panic("Lock %s not recursed @ %s:%d\n",
977171052Sattilio			    rw->lock_object.lo_name, file, line);
978154941Sjhb		break;
979154941Sjhb	case RA_UNLOCKED:
980154941Sjhb#ifdef WITNESS
981167787Sjhb		witness_assert(&rw->lock_object, what, file, line);
982154941Sjhb#else
983154941Sjhb		/*
984154941Sjhb		 * If we hold a write lock fail.  We can't reliably check
985154941Sjhb		 * to see if we hold a read lock or not.
986154941Sjhb		 */
987157826Sjhb		if (rw_wowner(rw) == curthread)
988154941Sjhb			panic("Lock %s exclusively locked @ %s:%d\n",
989167787Sjhb			    rw->lock_object.lo_name, file, line);
990154941Sjhb#endif
991154941Sjhb		break;
992154941Sjhb	default:
993154941Sjhb		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
994154941Sjhb		    line);
995154941Sjhb	}
996154941Sjhb}
997154941Sjhb#endif /* INVARIANT_SUPPORT */
998154941Sjhb
999154941Sjhb#ifdef DDB
1000154941Sjhbvoid
1001154941Sjhbdb_show_rwlock(struct lock_object *lock)
1002154941Sjhb{
1003154941Sjhb	struct rwlock *rw;
1004154941Sjhb	struct thread *td;
1005154941Sjhb
1006154941Sjhb	rw = (struct rwlock *)lock;
1007154941Sjhb
1008154941Sjhb	db_printf(" state: ");
1009154941Sjhb	if (rw->rw_lock == RW_UNLOCKED)
1010154941Sjhb		db_printf("UNLOCKED\n");
1011169394Sjhb	else if (rw->rw_lock == RW_DESTROYED) {
1012169394Sjhb		db_printf("DESTROYED\n");
1013169394Sjhb		return;
1014169394Sjhb	} else if (rw->rw_lock & RW_LOCK_READ)
1015167504Sjhb		db_printf("RLOCK: %ju locks\n",
1016167504Sjhb		    (uintmax_t)(RW_READERS(rw->rw_lock)));
1017154941Sjhb	else {
1018157826Sjhb		td = rw_wowner(rw);
1019154941Sjhb		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1020173600Sjulian		    td->td_tid, td->td_proc->p_pid, td->td_name);
1021171052Sattilio		if (rw_recursed(rw))
1022171052Sattilio			db_printf(" recursed: %u\n", rw->rw_recurse);
1023154941Sjhb	}
1024154941Sjhb	db_printf(" waiters: ");
1025154941Sjhb	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1026154941Sjhb	case RW_LOCK_READ_WAITERS:
1027154941Sjhb		db_printf("readers\n");
1028154941Sjhb		break;
1029154941Sjhb	case RW_LOCK_WRITE_WAITERS:
1030154941Sjhb		db_printf("writers\n");
1031154941Sjhb		break;
1032154941Sjhb	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1033167492Sjhb		db_printf("readers and writers\n");
1034154941Sjhb		break;
1035154941Sjhb	default:
1036154941Sjhb		db_printf("none\n");
1037154941Sjhb		break;
1038154941Sjhb	}
1039154941Sjhb}
1040154941Sjhb
1041154941Sjhb#endif
1042