kern_rwlock.c revision 228424
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 228424 2011-12-11 21:02:01Z avg $");
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;
61227309Sedstatic SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL,
62227309Sed    "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
70227588Spjdstatic void	db_show_rwlock(const struct lock_object *lock);
71154941Sjhb#endif
72227588Spjdstatic void	assert_rw(const struct lock_object *lock, int what);
73167368Sjhbstatic void	lock_rw(struct lock_object *lock, int how);
74192853Ssson#ifdef KDTRACE_HOOKS
75227588Spjdstatic int	owner_rw(const struct lock_object *lock, struct thread **owner);
76192853Ssson#endif
77167368Sjhbstatic int	unlock_rw(struct lock_object *lock);
78154941Sjhb
79154941Sjhbstruct lock_class lock_class_rw = {
80167365Sjhb	.lc_name = "rw",
81167365Sjhb	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
82173733Sattilio	.lc_assert = assert_rw,
83154941Sjhb#ifdef DDB
84167365Sjhb	.lc_ddb_show = db_show_rwlock,
85154941Sjhb#endif
86167368Sjhb	.lc_lock = lock_rw,
87167368Sjhb	.lc_unlock = unlock_rw,
88192853Ssson#ifdef KDTRACE_HOOKS
89192853Ssson	.lc_owner = owner_rw,
90192853Ssson#endif
91154941Sjhb};
92154941Sjhb
93157826Sjhb/*
94157826Sjhb * Return a pointer to the owning thread if the lock is write-locked or
95157826Sjhb * NULL if the lock is unlocked or read-locked.
96157826Sjhb */
97157826Sjhb#define	rw_wowner(rw)							\
98154941Sjhb	((rw)->rw_lock & RW_LOCK_READ ? NULL :				\
99154941Sjhb	    (struct thread *)RW_OWNER((rw)->rw_lock))
100154941Sjhb
101157826Sjhb/*
102171052Sattilio * Returns if a write owner is recursed.  Write ownership is not assured
103171052Sattilio * here and should be previously checked.
104171052Sattilio */
105171052Sattilio#define	rw_recursed(rw)		((rw)->rw_recurse != 0)
106171052Sattilio
107171052Sattilio/*
108171052Sattilio * Return true if curthread helds the lock.
109171052Sattilio */
110171052Sattilio#define	rw_wlocked(rw)		(rw_wowner((rw)) == curthread)
111171052Sattilio
112171052Sattilio/*
113157826Sjhb * Return a pointer to the owning thread for this lock who should receive
114157826Sjhb * any priority lent by threads that block on this lock.  Currently this
115157826Sjhb * is identical to rw_wowner().
116157826Sjhb */
117157826Sjhb#define	rw_owner(rw)		rw_wowner(rw)
118157826Sjhb
119154941Sjhb#ifndef INVARIANTS
120154941Sjhb#define	_rw_assert(rw, what, file, line)
121154941Sjhb#endif
122154941Sjhb
123154941Sjhbvoid
124227588Spjdassert_rw(const struct lock_object *lock, int what)
125173733Sattilio{
126173733Sattilio
127227588Spjd	rw_assert((const struct rwlock *)lock, what);
128173733Sattilio}
129173733Sattilio
130173733Sattiliovoid
131167368Sjhblock_rw(struct lock_object *lock, int how)
132167368Sjhb{
133167368Sjhb	struct rwlock *rw;
134167368Sjhb
135167368Sjhb	rw = (struct rwlock *)lock;
136167368Sjhb	if (how)
137167368Sjhb		rw_wlock(rw);
138167368Sjhb	else
139167368Sjhb		rw_rlock(rw);
140167368Sjhb}
141167368Sjhb
142167368Sjhbint
143167368Sjhbunlock_rw(struct lock_object *lock)
144167368Sjhb{
145167368Sjhb	struct rwlock *rw;
146167368Sjhb
147167368Sjhb	rw = (struct rwlock *)lock;
148167368Sjhb	rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
149167368Sjhb	if (rw->rw_lock & RW_LOCK_READ) {
150167368Sjhb		rw_runlock(rw);
151167368Sjhb		return (0);
152167368Sjhb	} else {
153167368Sjhb		rw_wunlock(rw);
154167368Sjhb		return (1);
155167368Sjhb	}
156167368Sjhb}
157167368Sjhb
158192853Ssson#ifdef KDTRACE_HOOKS
159192853Sssonint
160227588Spjdowner_rw(const struct lock_object *lock, struct thread **owner)
161192853Ssson{
162227588Spjd	const struct rwlock *rw = (const struct rwlock *)lock;
163192853Ssson	uintptr_t x = rw->rw_lock;
164192853Ssson
165192853Ssson	*owner = rw_wowner(rw);
166192853Ssson	return ((x & RW_LOCK_READ) != 0 ?  (RW_READERS(x) != 0) :
167192853Ssson	    (*owner != NULL));
168192853Ssson}
169192853Ssson#endif
170192853Ssson
171167368Sjhbvoid
172171052Sattiliorw_init_flags(struct rwlock *rw, const char *name, int opts)
173154941Sjhb{
174171052Sattilio	int flags;
175154941Sjhb
176171052Sattilio	MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
177171052Sattilio	    RW_RECURSE)) == 0);
178196334Sattilio	ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
179196334Sattilio	    ("%s: rw_lock not aligned for %s: %p", __func__, name,
180196334Sattilio	    &rw->rw_lock));
181171052Sattilio
182193307Sattilio	flags = LO_UPGRADABLE;
183171052Sattilio	if (opts & RW_DUPOK)
184171052Sattilio		flags |= LO_DUPOK;
185171052Sattilio	if (opts & RW_NOPROFILE)
186171052Sattilio		flags |= LO_NOPROFILE;
187171052Sattilio	if (!(opts & RW_NOWITNESS))
188171052Sattilio		flags |= LO_WITNESS;
189193307Sattilio	if (opts & RW_RECURSE)
190193307Sattilio		flags |= LO_RECURSABLE;
191171052Sattilio	if (opts & RW_QUIET)
192171052Sattilio		flags |= LO_QUIET;
193171052Sattilio
194154941Sjhb	rw->rw_lock = RW_UNLOCKED;
195171052Sattilio	rw->rw_recurse = 0;
196171052Sattilio	lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
197154941Sjhb}
198154941Sjhb
199154941Sjhbvoid
200154941Sjhbrw_destroy(struct rwlock *rw)
201154941Sjhb{
202154941Sjhb
203205626Sbz	KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
204205626Sbz	KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
205169394Sjhb	rw->rw_lock = RW_DESTROYED;
206167787Sjhb	lock_destroy(&rw->lock_object);
207154941Sjhb}
208154941Sjhb
209154941Sjhbvoid
210154941Sjhbrw_sysinit(void *arg)
211154941Sjhb{
212154941Sjhb	struct rw_args *args = arg;
213154941Sjhb
214154941Sjhb	rw_init(args->ra_rw, args->ra_desc);
215154941Sjhb}
216154941Sjhb
217185778Skmacyvoid
218185778Skmacyrw_sysinit_flags(void *arg)
219185778Skmacy{
220185778Skmacy	struct rw_args_flags *args = arg;
221185778Skmacy
222185778Skmacy	rw_init_flags(args->ra_rw, args->ra_desc, args->ra_flags);
223185778Skmacy}
224185778Skmacy
225167024Srwatsonint
226227588Spjdrw_wowned(const struct rwlock *rw)
227167024Srwatson{
228167024Srwatson
229167024Srwatson	return (rw_wowner(rw) == curthread);
230167024Srwatson}
231167024Srwatson
232154941Sjhbvoid
233154941Sjhb_rw_wlock(struct rwlock *rw, const char *file, int line)
234154941Sjhb{
235154941Sjhb
236228424Savg	if (SCHEDULER_STOPPED())
237228424Savg		return;
238154941Sjhb	MPASS(curthread != NULL);
239169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
240169394Sjhb	    ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
241167787Sjhb	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
242182914Sjhb	    line, NULL);
243154941Sjhb	__rw_wlock(rw, curthread, file, line);
244171052Sattilio	LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
245167787Sjhb	WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
246160771Sjhb	curthread->td_locks++;
247154941Sjhb}
248154941Sjhb
249177843Sattilioint
250177843Sattilio_rw_try_wlock(struct rwlock *rw, const char *file, int line)
251177843Sattilio{
252177843Sattilio	int rval;
253177843Sattilio
254228424Savg	if (SCHEDULER_STOPPED())
255228424Savg		return (1);
256228424Savg
257177843Sattilio	KASSERT(rw->rw_lock != RW_DESTROYED,
258177843Sattilio	    ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
259177843Sattilio
260193307Sattilio	if (rw_wlocked(rw) &&
261193307Sattilio	    (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
262177843Sattilio		rw->rw_recurse++;
263177843Sattilio		rval = 1;
264177843Sattilio	} else
265177843Sattilio		rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
266177843Sattilio		    (uintptr_t)curthread);
267177843Sattilio
268177843Sattilio	LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
269177843Sattilio	if (rval) {
270177843Sattilio		WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
271177843Sattilio		    file, line);
272177843Sattilio		curthread->td_locks++;
273177843Sattilio	}
274177843Sattilio	return (rval);
275177843Sattilio}
276177843Sattilio
277154941Sjhbvoid
278154941Sjhb_rw_wunlock(struct rwlock *rw, const char *file, int line)
279154941Sjhb{
280154941Sjhb
281228424Savg	if (SCHEDULER_STOPPED())
282228424Savg		return;
283154941Sjhb	MPASS(curthread != NULL);
284169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
285169394Sjhb	    ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
286154941Sjhb	_rw_assert(rw, RA_WLOCKED, file, line);
287160771Sjhb	curthread->td_locks--;
288167787Sjhb	WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
289171052Sattilio	LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
290171052Sattilio	    line);
291171052Sattilio	if (!rw_recursed(rw))
292192853Ssson		LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_WUNLOCK_RELEASE, rw);
293154941Sjhb	__rw_wunlock(rw, curthread, file, line);
294154941Sjhb}
295176017Sjeff/*
296176017Sjeff * Determines whether a new reader can acquire a lock.  Succeeds if the
297176017Sjeff * reader already owns a read lock and the lock is locked for read to
298176017Sjeff * prevent deadlock from reader recursion.  Also succeeds if the lock
299176017Sjeff * is unlocked and has no writer waiters or spinners.  Failing otherwise
300176017Sjeff * prioritizes writers before readers.
301176017Sjeff */
302176017Sjeff#define	RW_CAN_READ(_rw)						\
303176017Sjeff    ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) &	\
304176017Sjeff    (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) ==	\
305176017Sjeff    RW_LOCK_READ)
306154941Sjhb
307154941Sjhbvoid
308154941Sjhb_rw_rlock(struct rwlock *rw, const char *file, int line)
309154941Sjhb{
310170295Sjeff	struct turnstile *ts;
311167801Sjhb#ifdef ADAPTIVE_RWLOCKS
312157846Sjhb	volatile struct thread *owner;
313177912Sjeff	int spintries = 0;
314177912Sjeff	int i;
315157851Swkoszek#endif
316189846Sjeff#ifdef LOCK_PROFILING
317167307Sjhb	uint64_t waittime = 0;
318167054Skmacy	int contested = 0;
319189846Sjeff#endif
320176017Sjeff	uintptr_t v;
321192853Ssson#ifdef KDTRACE_HOOKS
322192853Ssson	uint64_t spin_cnt = 0;
323192853Ssson	uint64_t sleep_cnt = 0;
324192853Ssson	int64_t sleep_time = 0;
325192853Ssson#endif
326154941Sjhb
327228424Savg	if (SCHEDULER_STOPPED())
328228424Savg		return;
329228424Savg
330169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
331169394Sjhb	    ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
332157826Sjhb	KASSERT(rw_wowner(rw) != curthread,
333154941Sjhb	    ("%s (%s): wlock already held @ %s:%d", __func__,
334167787Sjhb	    rw->lock_object.lo_name, file, line));
335182914Sjhb	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
336154941Sjhb
337154941Sjhb	for (;;) {
338192853Ssson#ifdef KDTRACE_HOOKS
339192853Ssson		spin_cnt++;
340192853Ssson#endif
341154941Sjhb		/*
342154941Sjhb		 * Handle the easy case.  If no other thread has a write
343154941Sjhb		 * lock, then try to bump up the count of read locks.  Note
344154941Sjhb		 * that we have to preserve the current state of the
345154941Sjhb		 * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
346154941Sjhb		 * read lock, then rw_lock must have changed, so restart
347154941Sjhb		 * the loop.  Note that this handles the case of a
348154941Sjhb		 * completely unlocked rwlock since such a lock is encoded
349154941Sjhb		 * as a read lock with no waiters.
350154941Sjhb		 */
351176017Sjeff		v = rw->rw_lock;
352176017Sjeff		if (RW_CAN_READ(v)) {
353154941Sjhb			/*
354154941Sjhb			 * The RW_LOCK_READ_WAITERS flag should only be set
355176017Sjeff			 * if the lock has been unlocked and write waiters
356176017Sjeff			 * were present.
357154941Sjhb			 */
358176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
359176017Sjeff			    v + RW_ONE_READER)) {
360167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
361154941Sjhb					CTR4(KTR_LOCK,
362154941Sjhb					    "%s: %p succeed %p -> %p", __func__,
363176017Sjeff					    rw, (void *)v,
364176017Sjeff					    (void *)(v + RW_ONE_READER));
365154941Sjhb				break;
366154941Sjhb			}
367154941Sjhb			continue;
368154941Sjhb		}
369174629Sjeff		lock_profile_obtain_lock_failed(&rw->lock_object,
370174629Sjeff		    &contested, &waittime);
371154941Sjhb
372173960Sattilio#ifdef ADAPTIVE_RWLOCKS
373154941Sjhb		/*
374173960Sattilio		 * If the owner is running on another CPU, spin until
375173960Sattilio		 * the owner stops running or the state of the lock
376173960Sattilio		 * changes.
377173960Sattilio		 */
378176017Sjeff		if ((v & RW_LOCK_READ) == 0) {
379176017Sjeff			owner = (struct thread *)RW_OWNER(v);
380176017Sjeff			if (TD_IS_RUNNING(owner)) {
381176017Sjeff				if (LOCK_LOG_TEST(&rw->lock_object, 0))
382176017Sjeff					CTR3(KTR_LOCK,
383176017Sjeff					    "%s: spinning on %p held by %p",
384176017Sjeff					    __func__, rw, owner);
385176017Sjeff				while ((struct thread*)RW_OWNER(rw->rw_lock) ==
386192853Ssson				    owner && TD_IS_RUNNING(owner)) {
387176017Sjeff					cpu_spinwait();
388192853Ssson#ifdef KDTRACE_HOOKS
389192853Ssson					spin_cnt++;
390192853Ssson#endif
391192853Ssson				}
392176017Sjeff				continue;
393176017Sjeff			}
394177912Sjeff		} else if (spintries < rowner_retries) {
395177912Sjeff			spintries++;
396177912Sjeff			for (i = 0; i < rowner_loops; i++) {
397177912Sjeff				v = rw->rw_lock;
398177912Sjeff				if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
399177912Sjeff					break;
400177912Sjeff				cpu_spinwait();
401177912Sjeff			}
402177912Sjeff			if (i != rowner_loops)
403177912Sjeff				continue;
404173960Sattilio		}
405173960Sattilio#endif
406173960Sattilio
407173960Sattilio		/*
408154941Sjhb		 * Okay, now it's the hard case.  Some other thread already
409176017Sjeff		 * has a write lock or there are write waiters present,
410176017Sjeff		 * acquire the turnstile lock so we can begin the process
411176017Sjeff		 * of blocking.
412154941Sjhb		 */
413170295Sjeff		ts = turnstile_trywait(&rw->lock_object);
414154941Sjhb
415154941Sjhb		/*
416154941Sjhb		 * The lock might have been released while we spun, so
417176017Sjeff		 * recheck its state and restart the loop if needed.
418154941Sjhb		 */
419176017Sjeff		v = rw->rw_lock;
420176017Sjeff		if (RW_CAN_READ(v)) {
421170295Sjeff			turnstile_cancel(ts);
422154941Sjhb			continue;
423154941Sjhb		}
424154941Sjhb
425173960Sattilio#ifdef ADAPTIVE_RWLOCKS
426154941Sjhb		/*
427193035Sjhb		 * The current lock owner might have started executing
428193035Sjhb		 * on another CPU (or the lock could have changed
429193035Sjhb		 * owners) while we were waiting on the turnstile
430193035Sjhb		 * chain lock.  If so, drop the turnstile lock and try
431193035Sjhb		 * again.
432173960Sattilio		 */
433176017Sjeff		if ((v & RW_LOCK_READ) == 0) {
434176017Sjeff			owner = (struct thread *)RW_OWNER(v);
435176017Sjeff			if (TD_IS_RUNNING(owner)) {
436176017Sjeff				turnstile_cancel(ts);
437176017Sjeff				continue;
438176017Sjeff			}
439173960Sattilio		}
440173960Sattilio#endif
441173960Sattilio
442173960Sattilio		/*
443176017Sjeff		 * The lock is held in write mode or it already has waiters.
444154941Sjhb		 */
445176017Sjeff		MPASS(!RW_CAN_READ(v));
446176017Sjeff
447176017Sjeff		/*
448176017Sjeff		 * If the RW_LOCK_READ_WAITERS flag is already set, then
449176017Sjeff		 * we can go ahead and block.  If it is not set then try
450176017Sjeff		 * to set it.  If we fail to set it drop the turnstile
451176017Sjeff		 * lock and restart the loop.
452176017Sjeff		 */
453176017Sjeff		if (!(v & RW_LOCK_READ_WAITERS)) {
454176017Sjeff			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
455176017Sjeff			    v | RW_LOCK_READ_WAITERS)) {
456170295Sjeff				turnstile_cancel(ts);
457157826Sjhb				continue;
458157826Sjhb			}
459167787Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
460157826Sjhb				CTR2(KTR_LOCK, "%s: %p set read waiters flag",
461157826Sjhb				    __func__, rw);
462154941Sjhb		}
463154941Sjhb
464154941Sjhb		/*
465154941Sjhb		 * We were unable to acquire the lock and the read waiters
466154941Sjhb		 * flag is set, so we must block on the turnstile.
467154941Sjhb		 */
468167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
469154941Sjhb			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
470154941Sjhb			    rw);
471192853Ssson#ifdef KDTRACE_HOOKS
472192853Ssson		sleep_time -= lockstat_nsecs();
473192853Ssson#endif
474170295Sjeff		turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
475192853Ssson#ifdef KDTRACE_HOOKS
476192853Ssson		sleep_time += lockstat_nsecs();
477192853Ssson		sleep_cnt++;
478192853Ssson#endif
479167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
480154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
481154941Sjhb			    __func__, rw);
482154941Sjhb	}
483154941Sjhb
484154941Sjhb	/*
485154941Sjhb	 * TODO: acquire "owner of record" here.  Here be turnstile dragons
486154941Sjhb	 * however.  turnstiles don't like owners changing between calls to
487154941Sjhb	 * turnstile_wait() currently.
488154941Sjhb	 */
489192853Ssson	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
490174629Sjeff	    waittime, file, line);
491167787Sjhb	LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
492167787Sjhb	WITNESS_LOCK(&rw->lock_object, 0, file, line);
493160771Sjhb	curthread->td_locks++;
494176017Sjeff	curthread->td_rw_rlocks++;
495192853Ssson#ifdef KDTRACE_HOOKS
496192853Ssson	if (sleep_time)
497192853Ssson		LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
498192853Ssson
499192853Ssson	/*
500192853Ssson	 * Record only the loops spinning and not sleeping.
501192853Ssson	 */
502192853Ssson	if (spin_cnt > sleep_cnt)
503192853Ssson		LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
504192853Ssson#endif
505154941Sjhb}
506154941Sjhb
507177843Sattilioint
508177843Sattilio_rw_try_rlock(struct rwlock *rw, const char *file, int line)
509177843Sattilio{
510177843Sattilio	uintptr_t x;
511177843Sattilio
512228424Savg	if (SCHEDULER_STOPPED())
513228424Savg		return (1);
514228424Savg
515177843Sattilio	for (;;) {
516177843Sattilio		x = rw->rw_lock;
517177843Sattilio		KASSERT(rw->rw_lock != RW_DESTROYED,
518177843Sattilio		    ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
519177843Sattilio		if (!(x & RW_LOCK_READ))
520177843Sattilio			break;
521177843Sattilio		if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
522177843Sattilio			LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
523177843Sattilio			    line);
524177843Sattilio			WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
525177843Sattilio			curthread->td_locks++;
526177843Sattilio			curthread->td_rw_rlocks++;
527177843Sattilio			return (1);
528177843Sattilio		}
529177843Sattilio	}
530177843Sattilio
531177843Sattilio	LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
532177843Sattilio	return (0);
533177843Sattilio}
534177843Sattilio
535154941Sjhbvoid
536154941Sjhb_rw_runlock(struct rwlock *rw, const char *file, int line)
537154941Sjhb{
538154941Sjhb	struct turnstile *ts;
539176017Sjeff	uintptr_t x, v, queue;
540154941Sjhb
541228424Savg	if (SCHEDULER_STOPPED())
542228424Savg		return;
543228424Savg
544169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
545169394Sjhb	    ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
546154941Sjhb	_rw_assert(rw, RA_RLOCKED, file, line);
547160771Sjhb	curthread->td_locks--;
548176017Sjeff	curthread->td_rw_rlocks--;
549167787Sjhb	WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
550167787Sjhb	LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
551154941Sjhb
552154941Sjhb	/* TODO: drop "owner of record" here. */
553154941Sjhb
554154941Sjhb	for (;;) {
555154941Sjhb		/*
556154941Sjhb		 * See if there is more than one read lock held.  If so,
557154941Sjhb		 * just drop one and return.
558154941Sjhb		 */
559154941Sjhb		x = rw->rw_lock;
560154941Sjhb		if (RW_READERS(x) > 1) {
561197643Sattilio			if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
562154941Sjhb			    x - RW_ONE_READER)) {
563167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
564154941Sjhb					CTR4(KTR_LOCK,
565154941Sjhb					    "%s: %p succeeded %p -> %p",
566154941Sjhb					    __func__, rw, (void *)x,
567154941Sjhb					    (void *)(x - RW_ONE_READER));
568154941Sjhb				break;
569154941Sjhb			}
570154941Sjhb			continue;
571167307Sjhb		}
572154941Sjhb		/*
573154941Sjhb		 * If there aren't any waiters for a write lock, then try
574154941Sjhb		 * to drop it quickly.
575154941Sjhb		 */
576176017Sjeff		if (!(x & RW_LOCK_WAITERS)) {
577176017Sjeff			MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
578176017Sjeff			    RW_READERS_LOCK(1));
579197643Sattilio			if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
580197643Sattilio			    RW_UNLOCKED)) {
581167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
582154941Sjhb					CTR2(KTR_LOCK, "%s: %p last succeeded",
583154941Sjhb					    __func__, rw);
584154941Sjhb				break;
585154941Sjhb			}
586154941Sjhb			continue;
587154941Sjhb		}
588154941Sjhb		/*
589176017Sjeff		 * Ok, we know we have waiters and we think we are the
590176017Sjeff		 * last reader, so grab the turnstile lock.
591154941Sjhb		 */
592170295Sjeff		turnstile_chain_lock(&rw->lock_object);
593176017Sjeff		v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
594176017Sjeff		MPASS(v & RW_LOCK_WAITERS);
595154941Sjhb
596154941Sjhb		/*
597154941Sjhb		 * Try to drop our lock leaving the lock in a unlocked
598154941Sjhb		 * state.
599154941Sjhb		 *
600154941Sjhb		 * If you wanted to do explicit lock handoff you'd have to
601154941Sjhb		 * do it here.  You'd also want to use turnstile_signal()
602154941Sjhb		 * and you'd have to handle the race where a higher
603154941Sjhb		 * priority thread blocks on the write lock before the
604154941Sjhb		 * thread you wakeup actually runs and have the new thread
605154941Sjhb		 * "steal" the lock.  For now it's a lot simpler to just
606154941Sjhb		 * wakeup all of the waiters.
607154941Sjhb		 *
608154941Sjhb		 * As above, if we fail, then another thread might have
609154941Sjhb		 * acquired a read lock, so drop the turnstile lock and
610154941Sjhb		 * restart.
611154941Sjhb		 */
612176017Sjeff		x = RW_UNLOCKED;
613176017Sjeff		if (v & RW_LOCK_WRITE_WAITERS) {
614176017Sjeff			queue = TS_EXCLUSIVE_QUEUE;
615176017Sjeff			x |= (v & RW_LOCK_READ_WAITERS);
616176017Sjeff		} else
617176017Sjeff			queue = TS_SHARED_QUEUE;
618197643Sattilio		if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
619176017Sjeff		    x)) {
620170295Sjeff			turnstile_chain_unlock(&rw->lock_object);
621154941Sjhb			continue;
622154941Sjhb		}
623167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
624154941Sjhb			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
625154941Sjhb			    __func__, rw);
626154941Sjhb
627154941Sjhb		/*
628154941Sjhb		 * Ok.  The lock is released and all that's left is to
629154941Sjhb		 * wake up the waiters.  Note that the lock might not be
630154941Sjhb		 * free anymore, but in that case the writers will just
631154941Sjhb		 * block again if they run before the new lock holder(s)
632154941Sjhb		 * release the lock.
633154941Sjhb		 */
634167787Sjhb		ts = turnstile_lookup(&rw->lock_object);
635157846Sjhb		MPASS(ts != NULL);
636176017Sjeff		turnstile_broadcast(ts, queue);
637154941Sjhb		turnstile_unpend(ts, TS_SHARED_LOCK);
638170295Sjeff		turnstile_chain_unlock(&rw->lock_object);
639154941Sjhb		break;
640154941Sjhb	}
641192853Ssson	LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
642154941Sjhb}
643154941Sjhb
644154941Sjhb/*
645154941Sjhb * This function is called when we are unable to obtain a write lock on the
646154941Sjhb * first try.  This means that at least one other thread holds either a
647154941Sjhb * read or write lock.
648154941Sjhb */
649154941Sjhbvoid
650154941Sjhb_rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
651154941Sjhb{
652170295Sjeff	struct turnstile *ts;
653167801Sjhb#ifdef ADAPTIVE_RWLOCKS
654157846Sjhb	volatile struct thread *owner;
655176017Sjeff	int spintries = 0;
656176017Sjeff	int i;
657157851Swkoszek#endif
658189846Sjeff	uintptr_t v, x;
659189846Sjeff#ifdef LOCK_PROFILING
660171516Sattilio	uint64_t waittime = 0;
661171516Sattilio	int contested = 0;
662189846Sjeff#endif
663192853Ssson#ifdef KDTRACE_HOOKS
664192853Ssson	uint64_t spin_cnt = 0;
665192853Ssson	uint64_t sleep_cnt = 0;
666192853Ssson	int64_t sleep_time = 0;
667192853Ssson#endif
668154941Sjhb
669228424Savg	if (SCHEDULER_STOPPED())
670228424Savg		return;
671228424Savg
672171052Sattilio	if (rw_wlocked(rw)) {
673193307Sattilio		KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
674171052Sattilio		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
675171052Sattilio		    __func__, rw->lock_object.lo_name, file, line));
676171052Sattilio		rw->rw_recurse++;
677171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
678171052Sattilio			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
679171052Sattilio		return;
680171052Sattilio	}
681171052Sattilio
682167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
683154941Sjhb		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
684167787Sjhb		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
685154941Sjhb
686154941Sjhb	while (!_rw_write_lock(rw, tid)) {
687192853Ssson#ifdef KDTRACE_HOOKS
688192853Ssson		spin_cnt++;
689192853Ssson#endif
690174629Sjeff		lock_profile_obtain_lock_failed(&rw->lock_object,
691174629Sjeff		    &contested, &waittime);
692173960Sattilio#ifdef ADAPTIVE_RWLOCKS
693173960Sattilio		/*
694173960Sattilio		 * If the lock is write locked and the owner is
695173960Sattilio		 * running on another CPU, spin until the owner stops
696173960Sattilio		 * running or the state of the lock changes.
697173960Sattilio		 */
698173960Sattilio		v = rw->rw_lock;
699173960Sattilio		owner = (struct thread *)RW_OWNER(v);
700173960Sattilio		if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
701173960Sattilio			if (LOCK_LOG_TEST(&rw->lock_object, 0))
702173960Sattilio				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
703173960Sattilio				    __func__, rw, owner);
704173960Sattilio			while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
705192853Ssson			    TD_IS_RUNNING(owner)) {
706173960Sattilio				cpu_spinwait();
707192853Ssson#ifdef KDTRACE_HOOKS
708192853Ssson				spin_cnt++;
709192853Ssson#endif
710192853Ssson			}
711173960Sattilio			continue;
712173960Sattilio		}
713177912Sjeff		if ((v & RW_LOCK_READ) && RW_READERS(v) &&
714177912Sjeff		    spintries < rowner_retries) {
715176017Sjeff			if (!(v & RW_LOCK_WRITE_SPINNER)) {
716176017Sjeff				if (!atomic_cmpset_ptr(&rw->rw_lock, v,
717176017Sjeff				    v | RW_LOCK_WRITE_SPINNER)) {
718176017Sjeff					continue;
719176017Sjeff				}
720176017Sjeff			}
721176017Sjeff			spintries++;
722177912Sjeff			for (i = 0; i < rowner_loops; i++) {
723176017Sjeff				if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
724176017Sjeff					break;
725176017Sjeff				cpu_spinwait();
726176017Sjeff			}
727192853Ssson#ifdef KDTRACE_HOOKS
728192853Ssson			spin_cnt += rowner_loops - i;
729192853Ssson#endif
730177912Sjeff			if (i != rowner_loops)
731176017Sjeff				continue;
732176017Sjeff		}
733173960Sattilio#endif
734170295Sjeff		ts = turnstile_trywait(&rw->lock_object);
735154941Sjhb		v = rw->rw_lock;
736154941Sjhb
737173960Sattilio#ifdef ADAPTIVE_RWLOCKS
738154941Sjhb		/*
739193035Sjhb		 * The current lock owner might have started executing
740193035Sjhb		 * on another CPU (or the lock could have changed
741193035Sjhb		 * owners) while we were waiting on the turnstile
742193035Sjhb		 * chain lock.  If so, drop the turnstile lock and try
743193035Sjhb		 * again.
744173960Sattilio		 */
745173960Sattilio		if (!(v & RW_LOCK_READ)) {
746173960Sattilio			owner = (struct thread *)RW_OWNER(v);
747173960Sattilio			if (TD_IS_RUNNING(owner)) {
748173960Sattilio				turnstile_cancel(ts);
749173960Sattilio				continue;
750173960Sattilio			}
751173960Sattilio		}
752173960Sattilio#endif
753173960Sattilio		/*
754179334Sattilio		 * Check for the waiters flags about this rwlock.
755179334Sattilio		 * If the lock was released, without maintain any pending
756179334Sattilio		 * waiters queue, simply try to acquire it.
757179334Sattilio		 * If a pending waiters queue is present, claim the lock
758179334Sattilio		 * ownership and maintain the pending queue.
759154941Sjhb		 */
760176017Sjeff		x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
761176017Sjeff		if ((v & ~x) == RW_UNLOCKED) {
762176017Sjeff			x &= ~RW_LOCK_WRITE_SPINNER;
763176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
764176017Sjeff				if (x)
765176017Sjeff					turnstile_claim(ts);
766176017Sjeff				else
767176017Sjeff					turnstile_cancel(ts);
768154941Sjhb				break;
769154941Sjhb			}
770170295Sjeff			turnstile_cancel(ts);
771154941Sjhb			continue;
772154941Sjhb		}
773154941Sjhb		/*
774154941Sjhb		 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
775154941Sjhb		 * set it.  If we fail to set it, then loop back and try
776154941Sjhb		 * again.
777154941Sjhb		 */
778157826Sjhb		if (!(v & RW_LOCK_WRITE_WAITERS)) {
779157826Sjhb			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
780157826Sjhb			    v | RW_LOCK_WRITE_WAITERS)) {
781170295Sjeff				turnstile_cancel(ts);
782157826Sjhb				continue;
783157826Sjhb			}
784167787Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
785157826Sjhb				CTR2(KTR_LOCK, "%s: %p set write waiters flag",
786157826Sjhb				    __func__, rw);
787154941Sjhb		}
788157846Sjhb		/*
789154941Sjhb		 * We were unable to acquire the lock and the write waiters
790154941Sjhb		 * flag is set, so we must block on the turnstile.
791154941Sjhb		 */
792167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
793154941Sjhb			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
794154941Sjhb			    rw);
795192853Ssson#ifdef KDTRACE_HOOKS
796192853Ssson		sleep_time -= lockstat_nsecs();
797192853Ssson#endif
798170295Sjeff		turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
799192853Ssson#ifdef KDTRACE_HOOKS
800192853Ssson		sleep_time += lockstat_nsecs();
801192853Ssson		sleep_cnt++;
802192853Ssson#endif
803167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
804154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
805154941Sjhb			    __func__, rw);
806176017Sjeff#ifdef ADAPTIVE_RWLOCKS
807176017Sjeff		spintries = 0;
808176017Sjeff#endif
809154941Sjhb	}
810192853Ssson	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
811192853Ssson	    waittime, file, line);
812192853Ssson#ifdef KDTRACE_HOOKS
813192853Ssson	if (sleep_time)
814192853Ssson		LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
815192853Ssson
816192853Ssson	/*
817192853Ssson	 * Record only the loops spinning and not sleeping.
818192853Ssson	 */
819192853Ssson	if (spin_cnt > sleep_cnt)
820192853Ssson		LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
821192853Ssson#endif
822154941Sjhb}
823154941Sjhb
824154941Sjhb/*
825154941Sjhb * This function is called if the first try at releasing a write lock failed.
826154941Sjhb * This means that one of the 2 waiter bits must be set indicating that at
827154941Sjhb * least one thread is waiting on this lock.
828154941Sjhb */
829154941Sjhbvoid
830154941Sjhb_rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
831154941Sjhb{
832154941Sjhb	struct turnstile *ts;
833154941Sjhb	uintptr_t v;
834154941Sjhb	int queue;
835154941Sjhb
836228424Savg	if (SCHEDULER_STOPPED())
837228424Savg		return;
838228424Savg
839171052Sattilio	if (rw_wlocked(rw) && rw_recursed(rw)) {
840176017Sjeff		rw->rw_recurse--;
841171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
842171052Sattilio			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
843171052Sattilio		return;
844171052Sattilio	}
845171052Sattilio
846154941Sjhb	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
847154941Sjhb	    ("%s: neither of the waiter flags are set", __func__));
848154941Sjhb
849167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
850154941Sjhb		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
851154941Sjhb
852170295Sjeff	turnstile_chain_lock(&rw->lock_object);
853167787Sjhb	ts = turnstile_lookup(&rw->lock_object);
854154941Sjhb	MPASS(ts != NULL);
855154941Sjhb
856154941Sjhb	/*
857154941Sjhb	 * Use the same algo as sx locks for now.  Prefer waking up shared
858154941Sjhb	 * waiters if we have any over writers.  This is probably not ideal.
859154941Sjhb	 *
860154941Sjhb	 * 'v' is the value we are going to write back to rw_lock.  If we
861154941Sjhb	 * have waiters on both queues, we need to preserve the state of
862154941Sjhb	 * the waiter flag for the queue we don't wake up.  For now this is
863154941Sjhb	 * hardcoded for the algorithm mentioned above.
864154941Sjhb	 *
865154941Sjhb	 * In the case of both readers and writers waiting we wakeup the
866154941Sjhb	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
867154941Sjhb	 * new writer comes in before a reader it will claim the lock up
868154941Sjhb	 * above.  There is probably a potential priority inversion in
869154941Sjhb	 * there that could be worked around either by waking both queues
870154941Sjhb	 * of waiters or doing some complicated lock handoff gymnastics.
871154941Sjhb	 */
872157846Sjhb	v = RW_UNLOCKED;
873176076Sjeff	if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
874176076Sjeff		queue = TS_EXCLUSIVE_QUEUE;
875176076Sjeff		v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
876176076Sjeff	} else
877154941Sjhb		queue = TS_SHARED_QUEUE;
878157846Sjhb
879157846Sjhb	/* Wake up all waiters for the specific queue. */
880167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
881154941Sjhb		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
882154941Sjhb		    queue == TS_SHARED_QUEUE ? "read" : "write");
883154941Sjhb	turnstile_broadcast(ts, queue);
884154941Sjhb	atomic_store_rel_ptr(&rw->rw_lock, v);
885154941Sjhb	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
886170295Sjeff	turnstile_chain_unlock(&rw->lock_object);
887154941Sjhb}
888154941Sjhb
889157882Sjhb/*
890157882Sjhb * Attempt to do a non-blocking upgrade from a read lock to a write
891157882Sjhb * lock.  This will only succeed if this thread holds a single read
892157882Sjhb * lock.  Returns true if the upgrade succeeded and false otherwise.
893157882Sjhb */
894157882Sjhbint
895157882Sjhb_rw_try_upgrade(struct rwlock *rw, const char *file, int line)
896157882Sjhb{
897176017Sjeff	uintptr_t v, x, tid;
898170295Sjeff	struct turnstile *ts;
899157882Sjhb	int success;
900157882Sjhb
901228424Savg	if (SCHEDULER_STOPPED())
902228424Savg		return (1);
903228424Savg
904169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
905169394Sjhb	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
906157882Sjhb	_rw_assert(rw, RA_RLOCKED, file, line);
907157882Sjhb
908157882Sjhb	/*
909157882Sjhb	 * Attempt to switch from one reader to a writer.  If there
910157882Sjhb	 * are any write waiters, then we will have to lock the
911157882Sjhb	 * turnstile first to prevent races with another writer
912157882Sjhb	 * calling turnstile_wait() before we have claimed this
913157882Sjhb	 * turnstile.  So, do the simple case of no waiters first.
914157882Sjhb	 */
915157882Sjhb	tid = (uintptr_t)curthread;
916176017Sjeff	success = 0;
917176017Sjeff	for (;;) {
918176017Sjeff		v = rw->rw_lock;
919176017Sjeff		if (RW_READERS(v) > 1)
920176017Sjeff			break;
921176017Sjeff		if (!(v & RW_LOCK_WAITERS)) {
922176017Sjeff			success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
923176017Sjeff			if (!success)
924176017Sjeff				continue;
925176017Sjeff			break;
926176017Sjeff		}
927157882Sjhb
928176017Sjeff		/*
929176017Sjeff		 * Ok, we think we have waiters, so lock the turnstile.
930176017Sjeff		 */
931176017Sjeff		ts = turnstile_trywait(&rw->lock_object);
932176017Sjeff		v = rw->rw_lock;
933176017Sjeff		if (RW_READERS(v) > 1) {
934176017Sjeff			turnstile_cancel(ts);
935176017Sjeff			break;
936176017Sjeff		}
937176017Sjeff		/*
938176017Sjeff		 * Try to switch from one reader to a writer again.  This time
939176017Sjeff		 * we honor the current state of the waiters flags.
940176017Sjeff		 * If we obtain the lock with the flags set, then claim
941176017Sjeff		 * ownership of the turnstile.
942176017Sjeff		 */
943176017Sjeff		x = rw->rw_lock & RW_LOCK_WAITERS;
944176017Sjeff		success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
945176017Sjeff		if (success) {
946176017Sjeff			if (x)
947176017Sjeff				turnstile_claim(ts);
948176017Sjeff			else
949176017Sjeff				turnstile_cancel(ts);
950176017Sjeff			break;
951176017Sjeff		}
952170295Sjeff		turnstile_cancel(ts);
953176017Sjeff	}
954167787Sjhb	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
955176017Sjeff	if (success) {
956176017Sjeff		curthread->td_rw_rlocks--;
957167787Sjhb		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
958157882Sjhb		    file, line);
959192853Ssson		LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
960176017Sjeff	}
961157882Sjhb	return (success);
962157882Sjhb}
963157882Sjhb
964157882Sjhb/*
965157882Sjhb * Downgrade a write lock into a single read lock.
966157882Sjhb */
967157882Sjhbvoid
968157882Sjhb_rw_downgrade(struct rwlock *rw, const char *file, int line)
969157882Sjhb{
970157882Sjhb	struct turnstile *ts;
971157882Sjhb	uintptr_t tid, v;
972176017Sjeff	int rwait, wwait;
973157882Sjhb
974228424Savg	if (SCHEDULER_STOPPED())
975228424Savg		return;
976228424Savg
977169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
978169394Sjhb	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
979171052Sattilio	_rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
980171052Sattilio#ifndef INVARIANTS
981171052Sattilio	if (rw_recursed(rw))
982171052Sattilio		panic("downgrade of a recursed lock");
983171052Sattilio#endif
984157882Sjhb
985167787Sjhb	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
986157882Sjhb
987157882Sjhb	/*
988157882Sjhb	 * Convert from a writer to a single reader.  First we handle
989157882Sjhb	 * the easy case with no waiters.  If there are any waiters, we
990176017Sjeff	 * lock the turnstile and "disown" the lock.
991157882Sjhb	 */
992157882Sjhb	tid = (uintptr_t)curthread;
993157882Sjhb	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
994157882Sjhb		goto out;
995157882Sjhb
996157882Sjhb	/*
997157882Sjhb	 * Ok, we think we have waiters, so lock the turnstile so we can
998157882Sjhb	 * read the waiter flags without any races.
999157882Sjhb	 */
1000170295Sjeff	turnstile_chain_lock(&rw->lock_object);
1001176017Sjeff	v = rw->rw_lock & RW_LOCK_WAITERS;
1002176017Sjeff	rwait = v & RW_LOCK_READ_WAITERS;
1003176017Sjeff	wwait = v & RW_LOCK_WRITE_WAITERS;
1004176017Sjeff	MPASS(rwait | wwait);
1005157882Sjhb
1006157882Sjhb	/*
1007176017Sjeff	 * Downgrade from a write lock while preserving waiters flag
1008176017Sjeff	 * and give up ownership of the turnstile.
1009157882Sjhb	 */
1010167787Sjhb	ts = turnstile_lookup(&rw->lock_object);
1011157882Sjhb	MPASS(ts != NULL);
1012176017Sjeff	if (!wwait)
1013176017Sjeff		v &= ~RW_LOCK_READ_WAITERS;
1014176017Sjeff	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1015176017Sjeff	/*
1016176017Sjeff	 * Wake other readers if there are no writers pending.  Otherwise they
1017176017Sjeff	 * won't be able to acquire the lock anyway.
1018176017Sjeff	 */
1019176017Sjeff	if (rwait && !wwait) {
1020157882Sjhb		turnstile_broadcast(ts, TS_SHARED_QUEUE);
1021157882Sjhb		turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1022176017Sjeff	} else
1023157882Sjhb		turnstile_disown(ts);
1024170295Sjeff	turnstile_chain_unlock(&rw->lock_object);
1025157882Sjhbout:
1026176017Sjeff	curthread->td_rw_rlocks++;
1027167787Sjhb	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1028192853Ssson	LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
1029157882Sjhb}
1030157882Sjhb
1031154941Sjhb#ifdef INVARIANT_SUPPORT
1032155162Sscottl#ifndef INVARIANTS
1033154941Sjhb#undef _rw_assert
1034154941Sjhb#endif
1035154941Sjhb
1036154941Sjhb/*
1037154941Sjhb * In the non-WITNESS case, rw_assert() can only detect that at least
1038154941Sjhb * *some* thread owns an rlock, but it cannot guarantee that *this*
1039154941Sjhb * thread owns an rlock.
1040154941Sjhb */
1041154941Sjhbvoid
1042227588Spjd_rw_assert(const struct rwlock *rw, int what, const char *file, int line)
1043154941Sjhb{
1044154941Sjhb
1045154941Sjhb	if (panicstr != NULL)
1046154941Sjhb		return;
1047154941Sjhb	switch (what) {
1048154941Sjhb	case RA_LOCKED:
1049171052Sattilio	case RA_LOCKED | RA_RECURSED:
1050171052Sattilio	case RA_LOCKED | RA_NOTRECURSED:
1051154941Sjhb	case RA_RLOCKED:
1052154941Sjhb#ifdef WITNESS
1053167787Sjhb		witness_assert(&rw->lock_object, what, file, line);
1054154941Sjhb#else
1055154941Sjhb		/*
1056154941Sjhb		 * If some other thread has a write lock or we have one
1057154941Sjhb		 * and are asserting a read lock, fail.  Also, if no one
1058154941Sjhb		 * has a lock at all, fail.
1059154941Sjhb		 */
1060155061Sscottl		if (rw->rw_lock == RW_UNLOCKED ||
1061155061Sscottl		    (!(rw->rw_lock & RW_LOCK_READ) && (what == RA_RLOCKED ||
1062157826Sjhb		    rw_wowner(rw) != curthread)))
1063154941Sjhb			panic("Lock %s not %slocked @ %s:%d\n",
1064167787Sjhb			    rw->lock_object.lo_name, (what == RA_RLOCKED) ?
1065154941Sjhb			    "read " : "", file, line);
1066171052Sattilio
1067171052Sattilio		if (!(rw->rw_lock & RW_LOCK_READ)) {
1068171052Sattilio			if (rw_recursed(rw)) {
1069171052Sattilio				if (what & RA_NOTRECURSED)
1070171052Sattilio					panic("Lock %s recursed @ %s:%d\n",
1071171052Sattilio					    rw->lock_object.lo_name, file,
1072171052Sattilio					    line);
1073171052Sattilio			} else if (what & RA_RECURSED)
1074171052Sattilio				panic("Lock %s not recursed @ %s:%d\n",
1075171052Sattilio				    rw->lock_object.lo_name, file, line);
1076171052Sattilio		}
1077154941Sjhb#endif
1078154941Sjhb		break;
1079154941Sjhb	case RA_WLOCKED:
1080171052Sattilio	case RA_WLOCKED | RA_RECURSED:
1081171052Sattilio	case RA_WLOCKED | RA_NOTRECURSED:
1082157826Sjhb		if (rw_wowner(rw) != curthread)
1083154941Sjhb			panic("Lock %s not exclusively locked @ %s:%d\n",
1084167787Sjhb			    rw->lock_object.lo_name, file, line);
1085171052Sattilio		if (rw_recursed(rw)) {
1086171052Sattilio			if (what & RA_NOTRECURSED)
1087171052Sattilio				panic("Lock %s recursed @ %s:%d\n",
1088171052Sattilio				    rw->lock_object.lo_name, file, line);
1089171052Sattilio		} else if (what & RA_RECURSED)
1090171052Sattilio			panic("Lock %s not recursed @ %s:%d\n",
1091171052Sattilio			    rw->lock_object.lo_name, file, line);
1092154941Sjhb		break;
1093154941Sjhb	case RA_UNLOCKED:
1094154941Sjhb#ifdef WITNESS
1095167787Sjhb		witness_assert(&rw->lock_object, what, file, line);
1096154941Sjhb#else
1097154941Sjhb		/*
1098154941Sjhb		 * If we hold a write lock fail.  We can't reliably check
1099154941Sjhb		 * to see if we hold a read lock or not.
1100154941Sjhb		 */
1101157826Sjhb		if (rw_wowner(rw) == curthread)
1102154941Sjhb			panic("Lock %s exclusively locked @ %s:%d\n",
1103167787Sjhb			    rw->lock_object.lo_name, file, line);
1104154941Sjhb#endif
1105154941Sjhb		break;
1106154941Sjhb	default:
1107154941Sjhb		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1108154941Sjhb		    line);
1109154941Sjhb	}
1110154941Sjhb}
1111154941Sjhb#endif /* INVARIANT_SUPPORT */
1112154941Sjhb
1113154941Sjhb#ifdef DDB
1114154941Sjhbvoid
1115227588Spjddb_show_rwlock(const struct lock_object *lock)
1116154941Sjhb{
1117227588Spjd	const struct rwlock *rw;
1118154941Sjhb	struct thread *td;
1119154941Sjhb
1120227588Spjd	rw = (const struct rwlock *)lock;
1121154941Sjhb
1122154941Sjhb	db_printf(" state: ");
1123154941Sjhb	if (rw->rw_lock == RW_UNLOCKED)
1124154941Sjhb		db_printf("UNLOCKED\n");
1125169394Sjhb	else if (rw->rw_lock == RW_DESTROYED) {
1126169394Sjhb		db_printf("DESTROYED\n");
1127169394Sjhb		return;
1128169394Sjhb	} else if (rw->rw_lock & RW_LOCK_READ)
1129167504Sjhb		db_printf("RLOCK: %ju locks\n",
1130167504Sjhb		    (uintmax_t)(RW_READERS(rw->rw_lock)));
1131154941Sjhb	else {
1132157826Sjhb		td = rw_wowner(rw);
1133154941Sjhb		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1134173600Sjulian		    td->td_tid, td->td_proc->p_pid, td->td_name);
1135171052Sattilio		if (rw_recursed(rw))
1136171052Sattilio			db_printf(" recursed: %u\n", rw->rw_recurse);
1137154941Sjhb	}
1138154941Sjhb	db_printf(" waiters: ");
1139154941Sjhb	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1140154941Sjhb	case RW_LOCK_READ_WAITERS:
1141154941Sjhb		db_printf("readers\n");
1142154941Sjhb		break;
1143154941Sjhb	case RW_LOCK_WRITE_WAITERS:
1144154941Sjhb		db_printf("writers\n");
1145154941Sjhb		break;
1146154941Sjhb	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1147167492Sjhb		db_printf("readers and writers\n");
1148154941Sjhb		break;
1149154941Sjhb	default:
1150154941Sjhb		db_printf("none\n");
1151154941Sjhb		break;
1152154941Sjhb	}
1153154941Sjhb}
1154154941Sjhb
1155154941Sjhb#endif
1156