kern_rwlock.c revision 285704
1154941Sjhb/*-
2154941Sjhb * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
3154941Sjhb * All rights reserved.
4154941Sjhb *
5154941Sjhb * Redistribution and use in source and binary forms, with or without
6154941Sjhb * modification, are permitted provided that the following conditions
7154941Sjhb * are met:
8154941Sjhb * 1. Redistributions of source code must retain the above copyright
9154941Sjhb *    notice, this list of conditions and the following disclaimer.
10154941Sjhb * 2. Redistributions in binary form must reproduce the above copyright
11154941Sjhb *    notice, this list of conditions and the following disclaimer in the
12154941Sjhb *    documentation and/or other materials provided with the distribution.
13154941Sjhb *
14154941Sjhb * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15154941Sjhb * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16154941Sjhb * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17154941Sjhb * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18154941Sjhb * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19154941Sjhb * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20154941Sjhb * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21154941Sjhb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22154941Sjhb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23154941Sjhb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24154941Sjhb * SUCH DAMAGE.
25154941Sjhb */
26154941Sjhb
27154941Sjhb/*
28154941Sjhb * Machine independent bits of reader/writer lock implementation.
29154941Sjhb */
30154941Sjhb
31154941Sjhb#include <sys/cdefs.h>
32154941Sjhb__FBSDID("$FreeBSD: head/sys/kern/kern_rwlock.c 285704 2015-07-19 22:24:33Z markj $");
33154941Sjhb
34154941Sjhb#include "opt_ddb.h"
35233628Sfabient#include "opt_hwpmc_hooks.h"
36167801Sjhb#include "opt_no_adaptive_rwlocks.h"
37154941Sjhb
38154941Sjhb#include <sys/param.h>
39244582Sattilio#include <sys/kdb.h>
40154941Sjhb#include <sys/ktr.h>
41177912Sjeff#include <sys/kernel.h>
42154941Sjhb#include <sys/lock.h>
43154941Sjhb#include <sys/mutex.h>
44154941Sjhb#include <sys/proc.h>
45154941Sjhb#include <sys/rwlock.h>
46274092Sjhb#include <sys/sched.h>
47177912Sjeff#include <sys/sysctl.h>
48154941Sjhb#include <sys/systm.h>
49154941Sjhb#include <sys/turnstile.h>
50171516Sattilio
51154941Sjhb#include <machine/cpu.h>
52154941Sjhb
53167801Sjhb#if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
54167801Sjhb#define	ADAPTIVE_RWLOCKS
55167801Sjhb#endif
56167801Sjhb
57233628Sfabient#ifdef HWPMC_HOOKS
58233628Sfabient#include <sys/pmckern.h>
59233628SfabientPMC_SOFT_DECLARE( , , lock, failed);
60233628Sfabient#endif
61233628Sfabient
62242515Sattilio/*
63242515Sattilio * Return the rwlock address when the lock cookie address is provided.
64242515Sattilio * This functionality assumes that struct rwlock* have a member named rw_lock.
65242515Sattilio */
66242515Sattilio#define	rwlock2rw(c)	(__containerof(c, struct rwlock, rw_lock))
67242515Sattilio
68177912Sjeff#ifdef ADAPTIVE_RWLOCKS
69177912Sjeffstatic int rowner_retries = 10;
70177912Sjeffstatic int rowner_loops = 10000;
71227309Sedstatic SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL,
72227309Sed    "rwlock debugging");
73177912SjeffSYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
74177912SjeffSYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
75177912Sjeff#endif
76177912Sjeff
77154941Sjhb#ifdef DDB
78154941Sjhb#include <ddb/ddb.h>
79154941Sjhb
80227588Spjdstatic void	db_show_rwlock(const struct lock_object *lock);
81154941Sjhb#endif
82227588Spjdstatic void	assert_rw(const struct lock_object *lock, int what);
83255745Sdavidestatic void	lock_rw(struct lock_object *lock, uintptr_t how);
84192853Ssson#ifdef KDTRACE_HOOKS
85227588Spjdstatic int	owner_rw(const struct lock_object *lock, struct thread **owner);
86192853Ssson#endif
87255745Sdavidestatic uintptr_t unlock_rw(struct lock_object *lock);
88154941Sjhb
89154941Sjhbstruct lock_class lock_class_rw = {
90167365Sjhb	.lc_name = "rw",
91167365Sjhb	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
92173733Sattilio	.lc_assert = assert_rw,
93154941Sjhb#ifdef DDB
94167365Sjhb	.lc_ddb_show = db_show_rwlock,
95154941Sjhb#endif
96167368Sjhb	.lc_lock = lock_rw,
97167368Sjhb	.lc_unlock = unlock_rw,
98192853Ssson#ifdef KDTRACE_HOOKS
99192853Ssson	.lc_owner = owner_rw,
100192853Ssson#endif
101154941Sjhb};
102154941Sjhb
103157826Sjhb/*
104157826Sjhb * Return a pointer to the owning thread if the lock is write-locked or
105157826Sjhb * NULL if the lock is unlocked or read-locked.
106157826Sjhb */
107157826Sjhb#define	rw_wowner(rw)							\
108154941Sjhb	((rw)->rw_lock & RW_LOCK_READ ? NULL :				\
109154941Sjhb	    (struct thread *)RW_OWNER((rw)->rw_lock))
110154941Sjhb
111157826Sjhb/*
112171052Sattilio * Returns if a write owner is recursed.  Write ownership is not assured
113171052Sattilio * here and should be previously checked.
114171052Sattilio */
115171052Sattilio#define	rw_recursed(rw)		((rw)->rw_recurse != 0)
116171052Sattilio
117171052Sattilio/*
118171052Sattilio * Return true if curthread helds the lock.
119171052Sattilio */
120171052Sattilio#define	rw_wlocked(rw)		(rw_wowner((rw)) == curthread)
121171052Sattilio
122171052Sattilio/*
123157826Sjhb * Return a pointer to the owning thread for this lock who should receive
124157826Sjhb * any priority lent by threads that block on this lock.  Currently this
125157826Sjhb * is identical to rw_wowner().
126157826Sjhb */
127157826Sjhb#define	rw_owner(rw)		rw_wowner(rw)
128157826Sjhb
129154941Sjhb#ifndef INVARIANTS
130242515Sattilio#define	__rw_assert(c, what, file, line)
131154941Sjhb#endif
132154941Sjhb
133154941Sjhbvoid
134227588Spjdassert_rw(const struct lock_object *lock, int what)
135173733Sattilio{
136173733Sattilio
137227588Spjd	rw_assert((const struct rwlock *)lock, what);
138173733Sattilio}
139173733Sattilio
140173733Sattiliovoid
141255745Sdavidelock_rw(struct lock_object *lock, uintptr_t how)
142167368Sjhb{
143167368Sjhb	struct rwlock *rw;
144167368Sjhb
145167368Sjhb	rw = (struct rwlock *)lock;
146167368Sjhb	if (how)
147255788Sdavide		rw_rlock(rw);
148255788Sdavide	else
149167368Sjhb		rw_wlock(rw);
150167368Sjhb}
151167368Sjhb
152255745Sdavideuintptr_t
153167368Sjhbunlock_rw(struct lock_object *lock)
154167368Sjhb{
155167368Sjhb	struct rwlock *rw;
156167368Sjhb
157167368Sjhb	rw = (struct rwlock *)lock;
158167368Sjhb	rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
159167368Sjhb	if (rw->rw_lock & RW_LOCK_READ) {
160167368Sjhb		rw_runlock(rw);
161255788Sdavide		return (1);
162167368Sjhb	} else {
163167368Sjhb		rw_wunlock(rw);
164255788Sdavide		return (0);
165167368Sjhb	}
166167368Sjhb}
167167368Sjhb
168192853Ssson#ifdef KDTRACE_HOOKS
169192853Sssonint
170227588Spjdowner_rw(const struct lock_object *lock, struct thread **owner)
171192853Ssson{
172227588Spjd	const struct rwlock *rw = (const struct rwlock *)lock;
173192853Ssson	uintptr_t x = rw->rw_lock;
174192853Ssson
175192853Ssson	*owner = rw_wowner(rw);
176192853Ssson	return ((x & RW_LOCK_READ) != 0 ?  (RW_READERS(x) != 0) :
177192853Ssson	    (*owner != NULL));
178192853Ssson}
179192853Ssson#endif
180192853Ssson
181167368Sjhbvoid
182242515Sattilio_rw_init_flags(volatile uintptr_t *c, const char *name, int opts)
183154941Sjhb{
184242515Sattilio	struct rwlock *rw;
185171052Sattilio	int flags;
186154941Sjhb
187242515Sattilio	rw = rwlock2rw(c);
188242515Sattilio
189171052Sattilio	MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
190275751Sdchagin	    RW_RECURSE | RW_NEW)) == 0);
191196334Sattilio	ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock,
192196334Sattilio	    ("%s: rw_lock not aligned for %s: %p", __func__, name,
193196334Sattilio	    &rw->rw_lock));
194171052Sattilio
195193307Sattilio	flags = LO_UPGRADABLE;
196171052Sattilio	if (opts & RW_DUPOK)
197171052Sattilio		flags |= LO_DUPOK;
198171052Sattilio	if (opts & RW_NOPROFILE)
199171052Sattilio		flags |= LO_NOPROFILE;
200171052Sattilio	if (!(opts & RW_NOWITNESS))
201171052Sattilio		flags |= LO_WITNESS;
202193307Sattilio	if (opts & RW_RECURSE)
203193307Sattilio		flags |= LO_RECURSABLE;
204171052Sattilio	if (opts & RW_QUIET)
205171052Sattilio		flags |= LO_QUIET;
206275751Sdchagin	if (opts & RW_NEW)
207275751Sdchagin		flags |= LO_NEW;
208171052Sattilio
209252212Sjhb	lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
210154941Sjhb	rw->rw_lock = RW_UNLOCKED;
211171052Sattilio	rw->rw_recurse = 0;
212154941Sjhb}
213154941Sjhb
214154941Sjhbvoid
215242515Sattilio_rw_destroy(volatile uintptr_t *c)
216154941Sjhb{
217242515Sattilio	struct rwlock *rw;
218154941Sjhb
219242515Sattilio	rw = rwlock2rw(c);
220242515Sattilio
221205626Sbz	KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock %p not unlocked", rw));
222205626Sbz	KASSERT(rw->rw_recurse == 0, ("rw lock %p still recursed", rw));
223169394Sjhb	rw->rw_lock = RW_DESTROYED;
224167787Sjhb	lock_destroy(&rw->lock_object);
225154941Sjhb}
226154941Sjhb
227154941Sjhbvoid
228154941Sjhbrw_sysinit(void *arg)
229154941Sjhb{
230154941Sjhb	struct rw_args *args = arg;
231154941Sjhb
232242515Sattilio	rw_init((struct rwlock *)args->ra_rw, args->ra_desc);
233154941Sjhb}
234154941Sjhb
235185778Skmacyvoid
236185778Skmacyrw_sysinit_flags(void *arg)
237185778Skmacy{
238185778Skmacy	struct rw_args_flags *args = arg;
239185778Skmacy
240242515Sattilio	rw_init_flags((struct rwlock *)args->ra_rw, args->ra_desc,
241242515Sattilio	    args->ra_flags);
242185778Skmacy}
243185778Skmacy
244167024Srwatsonint
245242515Sattilio_rw_wowned(const volatile uintptr_t *c)
246167024Srwatson{
247167024Srwatson
248242515Sattilio	return (rw_wowner(rwlock2rw(c)) == curthread);
249167024Srwatson}
250167024Srwatson
251154941Sjhbvoid
252242515Sattilio_rw_wlock_cookie(volatile uintptr_t *c, const char *file, int line)
253154941Sjhb{
254242515Sattilio	struct rwlock *rw;
255154941Sjhb
256228424Savg	if (SCHEDULER_STOPPED())
257228424Savg		return;
258242515Sattilio
259242515Sattilio	rw = rwlock2rw(c);
260242515Sattilio
261244582Sattilio	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
262240424Sattilio	    ("rw_wlock() by idle thread %p on rwlock %s @ %s:%d",
263240424Sattilio	    curthread, rw->lock_object.lo_name, file, line));
264169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
265169394Sjhb	    ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
266167787Sjhb	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
267182914Sjhb	    line, NULL);
268154941Sjhb	__rw_wlock(rw, curthread, file, line);
269171052Sattilio	LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
270167787Sjhb	WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
271160771Sjhb	curthread->td_locks++;
272154941Sjhb}
273154941Sjhb
274177843Sattilioint
275242515Sattilio__rw_try_wlock(volatile uintptr_t *c, const char *file, int line)
276177843Sattilio{
277242515Sattilio	struct rwlock *rw;
278177843Sattilio	int rval;
279177843Sattilio
280228424Savg	if (SCHEDULER_STOPPED())
281228424Savg		return (1);
282228424Savg
283242515Sattilio	rw = rwlock2rw(c);
284242515Sattilio
285244582Sattilio	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
286240424Sattilio	    ("rw_try_wlock() by idle thread %p on rwlock %s @ %s:%d",
287240424Sattilio	    curthread, rw->lock_object.lo_name, file, line));
288177843Sattilio	KASSERT(rw->rw_lock != RW_DESTROYED,
289177843Sattilio	    ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
290177843Sattilio
291193307Sattilio	if (rw_wlocked(rw) &&
292193307Sattilio	    (rw->lock_object.lo_flags & LO_RECURSABLE) != 0) {
293177843Sattilio		rw->rw_recurse++;
294177843Sattilio		rval = 1;
295177843Sattilio	} else
296177843Sattilio		rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
297177843Sattilio		    (uintptr_t)curthread);
298177843Sattilio
299177843Sattilio	LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
300177843Sattilio	if (rval) {
301177843Sattilio		WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
302177843Sattilio		    file, line);
303284297Savg		if (!rw_recursed(rw))
304285704Smarkj			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
305285704Smarkj			    rw, 0, 0, file, line, LOCKSTAT_WRITER);
306177843Sattilio		curthread->td_locks++;
307177843Sattilio	}
308177843Sattilio	return (rval);
309177843Sattilio}
310177843Sattilio
311154941Sjhbvoid
312242515Sattilio_rw_wunlock_cookie(volatile uintptr_t *c, const char *file, int line)
313154941Sjhb{
314242515Sattilio	struct rwlock *rw;
315154941Sjhb
316228424Savg	if (SCHEDULER_STOPPED())
317228424Savg		return;
318242515Sattilio
319242515Sattilio	rw = rwlock2rw(c);
320242515Sattilio
321169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
322169394Sjhb	    ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
323242515Sattilio	__rw_assert(c, RA_WLOCKED, file, line);
324167787Sjhb	WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
325171052Sattilio	LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
326171052Sattilio	    line);
327154941Sjhb	__rw_wunlock(rw, curthread, file, line);
328252212Sjhb	curthread->td_locks--;
329154941Sjhb}
330176017Sjeff/*
331176017Sjeff * Determines whether a new reader can acquire a lock.  Succeeds if the
332176017Sjeff * reader already owns a read lock and the lock is locked for read to
333176017Sjeff * prevent deadlock from reader recursion.  Also succeeds if the lock
334176017Sjeff * is unlocked and has no writer waiters or spinners.  Failing otherwise
335176017Sjeff * prioritizes writers before readers.
336176017Sjeff */
337176017Sjeff#define	RW_CAN_READ(_rw)						\
338176017Sjeff    ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) &	\
339176017Sjeff    (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) ==	\
340176017Sjeff    RW_LOCK_READ)
341154941Sjhb
342154941Sjhbvoid
343242515Sattilio__rw_rlock(volatile uintptr_t *c, const char *file, int line)
344154941Sjhb{
345242515Sattilio	struct rwlock *rw;
346170295Sjeff	struct turnstile *ts;
347167801Sjhb#ifdef ADAPTIVE_RWLOCKS
348157846Sjhb	volatile struct thread *owner;
349177912Sjeff	int spintries = 0;
350177912Sjeff	int i;
351157851Swkoszek#endif
352189846Sjeff#ifdef LOCK_PROFILING
353167307Sjhb	uint64_t waittime = 0;
354167054Skmacy	int contested = 0;
355189846Sjeff#endif
356176017Sjeff	uintptr_t v;
357192853Ssson#ifdef KDTRACE_HOOKS
358284297Savg	uintptr_t state;
359192853Ssson	uint64_t spin_cnt = 0;
360192853Ssson	uint64_t sleep_cnt = 0;
361192853Ssson	int64_t sleep_time = 0;
362284297Savg	int64_t all_time = 0;
363192853Ssson#endif
364154941Sjhb
365228424Savg	if (SCHEDULER_STOPPED())
366228424Savg		return;
367228424Savg
368242515Sattilio	rw = rwlock2rw(c);
369242515Sattilio
370244582Sattilio	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
371240424Sattilio	    ("rw_rlock() by idle thread %p on rwlock %s @ %s:%d",
372240424Sattilio	    curthread, rw->lock_object.lo_name, file, line));
373169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
374169394Sjhb	    ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
375157826Sjhb	KASSERT(rw_wowner(rw) != curthread,
376251323Sjhb	    ("rw_rlock: wlock already held for %s @ %s:%d",
377167787Sjhb	    rw->lock_object.lo_name, file, line));
378182914Sjhb	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
379154941Sjhb
380284297Savg#ifdef KDTRACE_HOOKS
381285664Smarkj	all_time -= lockstat_nsecs(&rw->lock_object);
382284297Savg	state = rw->rw_lock;
383284297Savg#endif
384154941Sjhb	for (;;) {
385192853Ssson#ifdef KDTRACE_HOOKS
386192853Ssson		spin_cnt++;
387192853Ssson#endif
388154941Sjhb		/*
389154941Sjhb		 * Handle the easy case.  If no other thread has a write
390154941Sjhb		 * lock, then try to bump up the count of read locks.  Note
391154941Sjhb		 * that we have to preserve the current state of the
392154941Sjhb		 * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
393154941Sjhb		 * read lock, then rw_lock must have changed, so restart
394154941Sjhb		 * the loop.  Note that this handles the case of a
395154941Sjhb		 * completely unlocked rwlock since such a lock is encoded
396154941Sjhb		 * as a read lock with no waiters.
397154941Sjhb		 */
398176017Sjeff		v = rw->rw_lock;
399176017Sjeff		if (RW_CAN_READ(v)) {
400154941Sjhb			/*
401154941Sjhb			 * The RW_LOCK_READ_WAITERS flag should only be set
402176017Sjeff			 * if the lock has been unlocked and write waiters
403176017Sjeff			 * were present.
404154941Sjhb			 */
405176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
406176017Sjeff			    v + RW_ONE_READER)) {
407167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
408154941Sjhb					CTR4(KTR_LOCK,
409154941Sjhb					    "%s: %p succeed %p -> %p", __func__,
410176017Sjeff					    rw, (void *)v,
411176017Sjeff					    (void *)(v + RW_ONE_READER));
412154941Sjhb				break;
413154941Sjhb			}
414154941Sjhb			continue;
415154941Sjhb		}
416233628Sfabient#ifdef HWPMC_HOOKS
417233628Sfabient		PMC_SOFT_CALL( , , lock, failed);
418233628Sfabient#endif
419174629Sjeff		lock_profile_obtain_lock_failed(&rw->lock_object,
420174629Sjeff		    &contested, &waittime);
421154941Sjhb
422173960Sattilio#ifdef ADAPTIVE_RWLOCKS
423154941Sjhb		/*
424173960Sattilio		 * If the owner is running on another CPU, spin until
425173960Sattilio		 * the owner stops running or the state of the lock
426173960Sattilio		 * changes.
427173960Sattilio		 */
428176017Sjeff		if ((v & RW_LOCK_READ) == 0) {
429176017Sjeff			owner = (struct thread *)RW_OWNER(v);
430176017Sjeff			if (TD_IS_RUNNING(owner)) {
431176017Sjeff				if (LOCK_LOG_TEST(&rw->lock_object, 0))
432176017Sjeff					CTR3(KTR_LOCK,
433176017Sjeff					    "%s: spinning on %p held by %p",
434176017Sjeff					    __func__, rw, owner);
435274092Sjhb				KTR_STATE1(KTR_SCHED, "thread",
436274092Sjhb				    sched_tdname(curthread), "spinning",
437274092Sjhb				    "lockname:\"%s\"", rw->lock_object.lo_name);
438176017Sjeff				while ((struct thread*)RW_OWNER(rw->rw_lock) ==
439192853Ssson				    owner && TD_IS_RUNNING(owner)) {
440176017Sjeff					cpu_spinwait();
441192853Ssson#ifdef KDTRACE_HOOKS
442192853Ssson					spin_cnt++;
443192853Ssson#endif
444192853Ssson				}
445274092Sjhb				KTR_STATE0(KTR_SCHED, "thread",
446274092Sjhb				    sched_tdname(curthread), "running");
447176017Sjeff				continue;
448176017Sjeff			}
449177912Sjeff		} else if (spintries < rowner_retries) {
450177912Sjeff			spintries++;
451274092Sjhb			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
452274092Sjhb			    "spinning", "lockname:\"%s\"",
453274092Sjhb			    rw->lock_object.lo_name);
454177912Sjeff			for (i = 0; i < rowner_loops; i++) {
455177912Sjeff				v = rw->rw_lock;
456177912Sjeff				if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
457177912Sjeff					break;
458177912Sjeff				cpu_spinwait();
459177912Sjeff			}
460259509Sattilio#ifdef KDTRACE_HOOKS
461259509Sattilio			spin_cnt += rowner_loops - i;
462259509Sattilio#endif
463274092Sjhb			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
464274092Sjhb			    "running");
465177912Sjeff			if (i != rowner_loops)
466177912Sjeff				continue;
467173960Sattilio		}
468173960Sattilio#endif
469173960Sattilio
470173960Sattilio		/*
471154941Sjhb		 * Okay, now it's the hard case.  Some other thread already
472176017Sjeff		 * has a write lock or there are write waiters present,
473176017Sjeff		 * acquire the turnstile lock so we can begin the process
474176017Sjeff		 * of blocking.
475154941Sjhb		 */
476170295Sjeff		ts = turnstile_trywait(&rw->lock_object);
477154941Sjhb
478154941Sjhb		/*
479154941Sjhb		 * The lock might have been released while we spun, so
480176017Sjeff		 * recheck its state and restart the loop if needed.
481154941Sjhb		 */
482176017Sjeff		v = rw->rw_lock;
483176017Sjeff		if (RW_CAN_READ(v)) {
484170295Sjeff			turnstile_cancel(ts);
485154941Sjhb			continue;
486154941Sjhb		}
487154941Sjhb
488173960Sattilio#ifdef ADAPTIVE_RWLOCKS
489154941Sjhb		/*
490193035Sjhb		 * The current lock owner might have started executing
491193035Sjhb		 * on another CPU (or the lock could have changed
492193035Sjhb		 * owners) while we were waiting on the turnstile
493193035Sjhb		 * chain lock.  If so, drop the turnstile lock and try
494193035Sjhb		 * again.
495173960Sattilio		 */
496176017Sjeff		if ((v & RW_LOCK_READ) == 0) {
497176017Sjeff			owner = (struct thread *)RW_OWNER(v);
498176017Sjeff			if (TD_IS_RUNNING(owner)) {
499176017Sjeff				turnstile_cancel(ts);
500176017Sjeff				continue;
501176017Sjeff			}
502173960Sattilio		}
503173960Sattilio#endif
504173960Sattilio
505173960Sattilio		/*
506176017Sjeff		 * The lock is held in write mode or it already has waiters.
507154941Sjhb		 */
508176017Sjeff		MPASS(!RW_CAN_READ(v));
509176017Sjeff
510176017Sjeff		/*
511176017Sjeff		 * If the RW_LOCK_READ_WAITERS flag is already set, then
512176017Sjeff		 * we can go ahead and block.  If it is not set then try
513176017Sjeff		 * to set it.  If we fail to set it drop the turnstile
514176017Sjeff		 * lock and restart the loop.
515176017Sjeff		 */
516176017Sjeff		if (!(v & RW_LOCK_READ_WAITERS)) {
517176017Sjeff			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
518176017Sjeff			    v | RW_LOCK_READ_WAITERS)) {
519170295Sjeff				turnstile_cancel(ts);
520157826Sjhb				continue;
521157826Sjhb			}
522167787Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
523157826Sjhb				CTR2(KTR_LOCK, "%s: %p set read waiters flag",
524157826Sjhb				    __func__, rw);
525154941Sjhb		}
526154941Sjhb
527154941Sjhb		/*
528154941Sjhb		 * We were unable to acquire the lock and the read waiters
529154941Sjhb		 * flag is set, so we must block on the turnstile.
530154941Sjhb		 */
531167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
532154941Sjhb			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
533154941Sjhb			    rw);
534192853Ssson#ifdef KDTRACE_HOOKS
535285664Smarkj		sleep_time -= lockstat_nsecs(&rw->lock_object);
536192853Ssson#endif
537170295Sjeff		turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
538192853Ssson#ifdef KDTRACE_HOOKS
539285664Smarkj		sleep_time += lockstat_nsecs(&rw->lock_object);
540192853Ssson		sleep_cnt++;
541192853Ssson#endif
542167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
543154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
544154941Sjhb			    __func__, rw);
545154941Sjhb	}
546284297Savg#ifdef KDTRACE_HOOKS
547285664Smarkj	all_time += lockstat_nsecs(&rw->lock_object);
548284297Savg	if (sleep_time)
549285703Smarkj		LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
550284297Savg		    LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
551284297Savg		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
552154941Sjhb
553284297Savg	/* Record only the loops spinning and not sleeping. */
554284297Savg	if (spin_cnt > sleep_cnt)
555285703Smarkj		LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
556284297Savg		    LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
557284297Savg		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
558284297Savg#endif
559154941Sjhb	/*
560154941Sjhb	 * TODO: acquire "owner of record" here.  Here be turnstile dragons
561154941Sjhb	 * however.  turnstiles don't like owners changing between calls to
562154941Sjhb	 * turnstile_wait() currently.
563154941Sjhb	 */
564285704Smarkj	LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
565285704Smarkj	    waittime, file, line, LOCKSTAT_READER);
566167787Sjhb	LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
567167787Sjhb	WITNESS_LOCK(&rw->lock_object, 0, file, line);
568160771Sjhb	curthread->td_locks++;
569176017Sjeff	curthread->td_rw_rlocks++;
570154941Sjhb}
571154941Sjhb
572177843Sattilioint
573242515Sattilio__rw_try_rlock(volatile uintptr_t *c, const char *file, int line)
574177843Sattilio{
575242515Sattilio	struct rwlock *rw;
576177843Sattilio	uintptr_t x;
577177843Sattilio
578228424Savg	if (SCHEDULER_STOPPED())
579228424Savg		return (1);
580228424Savg
581242515Sattilio	rw = rwlock2rw(c);
582242515Sattilio
583244582Sattilio	KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
584240424Sattilio	    ("rw_try_rlock() by idle thread %p on rwlock %s @ %s:%d",
585240424Sattilio	    curthread, rw->lock_object.lo_name, file, line));
586240424Sattilio
587177843Sattilio	for (;;) {
588177843Sattilio		x = rw->rw_lock;
589177843Sattilio		KASSERT(rw->rw_lock != RW_DESTROYED,
590177843Sattilio		    ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
591177843Sattilio		if (!(x & RW_LOCK_READ))
592177843Sattilio			break;
593177843Sattilio		if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
594177843Sattilio			LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
595177843Sattilio			    line);
596177843Sattilio			WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
597285704Smarkj			LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire,
598285704Smarkj			    rw, 0, 0, file, line, LOCKSTAT_READER);
599177843Sattilio			curthread->td_locks++;
600177843Sattilio			curthread->td_rw_rlocks++;
601177843Sattilio			return (1);
602177843Sattilio		}
603177843Sattilio	}
604177843Sattilio
605177843Sattilio	LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
606177843Sattilio	return (0);
607177843Sattilio}
608177843Sattilio
609154941Sjhbvoid
610242515Sattilio_rw_runlock_cookie(volatile uintptr_t *c, const char *file, int line)
611154941Sjhb{
612242515Sattilio	struct rwlock *rw;
613154941Sjhb	struct turnstile *ts;
614176017Sjeff	uintptr_t x, v, queue;
615154941Sjhb
616228424Savg	if (SCHEDULER_STOPPED())
617228424Savg		return;
618228424Savg
619242515Sattilio	rw = rwlock2rw(c);
620242515Sattilio
621169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
622169394Sjhb	    ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
623242515Sattilio	__rw_assert(c, RA_RLOCKED, file, line);
624167787Sjhb	WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
625167787Sjhb	LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
626154941Sjhb
627154941Sjhb	/* TODO: drop "owner of record" here. */
628154941Sjhb
629154941Sjhb	for (;;) {
630154941Sjhb		/*
631154941Sjhb		 * See if there is more than one read lock held.  If so,
632154941Sjhb		 * just drop one and return.
633154941Sjhb		 */
634154941Sjhb		x = rw->rw_lock;
635154941Sjhb		if (RW_READERS(x) > 1) {
636197643Sattilio			if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
637154941Sjhb			    x - RW_ONE_READER)) {
638167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
639154941Sjhb					CTR4(KTR_LOCK,
640154941Sjhb					    "%s: %p succeeded %p -> %p",
641154941Sjhb					    __func__, rw, (void *)x,
642154941Sjhb					    (void *)(x - RW_ONE_READER));
643154941Sjhb				break;
644154941Sjhb			}
645154941Sjhb			continue;
646167307Sjhb		}
647154941Sjhb		/*
648154941Sjhb		 * If there aren't any waiters for a write lock, then try
649154941Sjhb		 * to drop it quickly.
650154941Sjhb		 */
651176017Sjeff		if (!(x & RW_LOCK_WAITERS)) {
652176017Sjeff			MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
653176017Sjeff			    RW_READERS_LOCK(1));
654197643Sattilio			if (atomic_cmpset_rel_ptr(&rw->rw_lock, x,
655197643Sattilio			    RW_UNLOCKED)) {
656167787Sjhb				if (LOCK_LOG_TEST(&rw->lock_object, 0))
657154941Sjhb					CTR2(KTR_LOCK, "%s: %p last succeeded",
658154941Sjhb					    __func__, rw);
659154941Sjhb				break;
660154941Sjhb			}
661154941Sjhb			continue;
662154941Sjhb		}
663154941Sjhb		/*
664176017Sjeff		 * Ok, we know we have waiters and we think we are the
665176017Sjeff		 * last reader, so grab the turnstile lock.
666154941Sjhb		 */
667170295Sjeff		turnstile_chain_lock(&rw->lock_object);
668176017Sjeff		v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
669176017Sjeff		MPASS(v & RW_LOCK_WAITERS);
670154941Sjhb
671154941Sjhb		/*
672154941Sjhb		 * Try to drop our lock leaving the lock in a unlocked
673154941Sjhb		 * state.
674154941Sjhb		 *
675154941Sjhb		 * If you wanted to do explicit lock handoff you'd have to
676154941Sjhb		 * do it here.  You'd also want to use turnstile_signal()
677154941Sjhb		 * and you'd have to handle the race where a higher
678154941Sjhb		 * priority thread blocks on the write lock before the
679154941Sjhb		 * thread you wakeup actually runs and have the new thread
680154941Sjhb		 * "steal" the lock.  For now it's a lot simpler to just
681154941Sjhb		 * wakeup all of the waiters.
682154941Sjhb		 *
683154941Sjhb		 * As above, if we fail, then another thread might have
684154941Sjhb		 * acquired a read lock, so drop the turnstile lock and
685154941Sjhb		 * restart.
686154941Sjhb		 */
687176017Sjeff		x = RW_UNLOCKED;
688176017Sjeff		if (v & RW_LOCK_WRITE_WAITERS) {
689176017Sjeff			queue = TS_EXCLUSIVE_QUEUE;
690176017Sjeff			x |= (v & RW_LOCK_READ_WAITERS);
691176017Sjeff		} else
692176017Sjeff			queue = TS_SHARED_QUEUE;
693197643Sattilio		if (!atomic_cmpset_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
694176017Sjeff		    x)) {
695170295Sjeff			turnstile_chain_unlock(&rw->lock_object);
696154941Sjhb			continue;
697154941Sjhb		}
698167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
699154941Sjhb			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
700154941Sjhb			    __func__, rw);
701154941Sjhb
702154941Sjhb		/*
703154941Sjhb		 * Ok.  The lock is released and all that's left is to
704154941Sjhb		 * wake up the waiters.  Note that the lock might not be
705154941Sjhb		 * free anymore, but in that case the writers will just
706154941Sjhb		 * block again if they run before the new lock holder(s)
707154941Sjhb		 * release the lock.
708154941Sjhb		 */
709167787Sjhb		ts = turnstile_lookup(&rw->lock_object);
710157846Sjhb		MPASS(ts != NULL);
711176017Sjeff		turnstile_broadcast(ts, queue);
712154941Sjhb		turnstile_unpend(ts, TS_SHARED_LOCK);
713170295Sjeff		turnstile_chain_unlock(&rw->lock_object);
714154941Sjhb		break;
715154941Sjhb	}
716285704Smarkj	LOCKSTAT_PROFILE_RELEASE_RWLOCK(rw__release, rw, LOCKSTAT_READER);
717252212Sjhb	curthread->td_locks--;
718252212Sjhb	curthread->td_rw_rlocks--;
719154941Sjhb}
720154941Sjhb
721154941Sjhb/*
722154941Sjhb * This function is called when we are unable to obtain a write lock on the
723154941Sjhb * first try.  This means that at least one other thread holds either a
724154941Sjhb * read or write lock.
725154941Sjhb */
726154941Sjhbvoid
727242515Sattilio__rw_wlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
728242515Sattilio    int line)
729154941Sjhb{
730242515Sattilio	struct rwlock *rw;
731170295Sjeff	struct turnstile *ts;
732167801Sjhb#ifdef ADAPTIVE_RWLOCKS
733157846Sjhb	volatile struct thread *owner;
734176017Sjeff	int spintries = 0;
735176017Sjeff	int i;
736157851Swkoszek#endif
737189846Sjeff	uintptr_t v, x;
738189846Sjeff#ifdef LOCK_PROFILING
739171516Sattilio	uint64_t waittime = 0;
740171516Sattilio	int contested = 0;
741189846Sjeff#endif
742192853Ssson#ifdef KDTRACE_HOOKS
743284297Savg	uintptr_t state;
744192853Ssson	uint64_t spin_cnt = 0;
745192853Ssson	uint64_t sleep_cnt = 0;
746192853Ssson	int64_t sleep_time = 0;
747284297Savg	int64_t all_time = 0;
748192853Ssson#endif
749154941Sjhb
750228424Savg	if (SCHEDULER_STOPPED())
751228424Savg		return;
752228424Savg
753242515Sattilio	rw = rwlock2rw(c);
754242515Sattilio
755171052Sattilio	if (rw_wlocked(rw)) {
756193307Sattilio		KASSERT(rw->lock_object.lo_flags & LO_RECURSABLE,
757171052Sattilio		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
758171052Sattilio		    __func__, rw->lock_object.lo_name, file, line));
759171052Sattilio		rw->rw_recurse++;
760171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
761171052Sattilio			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
762171052Sattilio		return;
763171052Sattilio	}
764171052Sattilio
765167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
766154941Sjhb		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
767167787Sjhb		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
768154941Sjhb
769284297Savg#ifdef KDTRACE_HOOKS
770285664Smarkj	all_time -= lockstat_nsecs(&rw->lock_object);
771284297Savg	state = rw->rw_lock;
772284297Savg#endif
773154941Sjhb	while (!_rw_write_lock(rw, tid)) {
774192853Ssson#ifdef KDTRACE_HOOKS
775192853Ssson		spin_cnt++;
776192853Ssson#endif
777233628Sfabient#ifdef HWPMC_HOOKS
778233628Sfabient		PMC_SOFT_CALL( , , lock, failed);
779233628Sfabient#endif
780174629Sjeff		lock_profile_obtain_lock_failed(&rw->lock_object,
781174629Sjeff		    &contested, &waittime);
782173960Sattilio#ifdef ADAPTIVE_RWLOCKS
783173960Sattilio		/*
784173960Sattilio		 * If the lock is write locked and the owner is
785173960Sattilio		 * running on another CPU, spin until the owner stops
786173960Sattilio		 * running or the state of the lock changes.
787173960Sattilio		 */
788173960Sattilio		v = rw->rw_lock;
789173960Sattilio		owner = (struct thread *)RW_OWNER(v);
790173960Sattilio		if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
791173960Sattilio			if (LOCK_LOG_TEST(&rw->lock_object, 0))
792173960Sattilio				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
793173960Sattilio				    __func__, rw, owner);
794274092Sjhb			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
795274092Sjhb			    "spinning", "lockname:\"%s\"",
796274092Sjhb			    rw->lock_object.lo_name);
797173960Sattilio			while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
798192853Ssson			    TD_IS_RUNNING(owner)) {
799173960Sattilio				cpu_spinwait();
800192853Ssson#ifdef KDTRACE_HOOKS
801192853Ssson				spin_cnt++;
802192853Ssson#endif
803192853Ssson			}
804274092Sjhb			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
805274092Sjhb			    "running");
806173960Sattilio			continue;
807173960Sattilio		}
808177912Sjeff		if ((v & RW_LOCK_READ) && RW_READERS(v) &&
809177912Sjeff		    spintries < rowner_retries) {
810176017Sjeff			if (!(v & RW_LOCK_WRITE_SPINNER)) {
811176017Sjeff				if (!atomic_cmpset_ptr(&rw->rw_lock, v,
812176017Sjeff				    v | RW_LOCK_WRITE_SPINNER)) {
813176017Sjeff					continue;
814176017Sjeff				}
815176017Sjeff			}
816176017Sjeff			spintries++;
817274092Sjhb			KTR_STATE1(KTR_SCHED, "thread", sched_tdname(curthread),
818274092Sjhb			    "spinning", "lockname:\"%s\"",
819274092Sjhb			    rw->lock_object.lo_name);
820177912Sjeff			for (i = 0; i < rowner_loops; i++) {
821176017Sjeff				if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
822176017Sjeff					break;
823176017Sjeff				cpu_spinwait();
824176017Sjeff			}
825274092Sjhb			KTR_STATE0(KTR_SCHED, "thread", sched_tdname(curthread),
826274092Sjhb			    "running");
827192853Ssson#ifdef KDTRACE_HOOKS
828192853Ssson			spin_cnt += rowner_loops - i;
829192853Ssson#endif
830177912Sjeff			if (i != rowner_loops)
831176017Sjeff				continue;
832176017Sjeff		}
833173960Sattilio#endif
834170295Sjeff		ts = turnstile_trywait(&rw->lock_object);
835154941Sjhb		v = rw->rw_lock;
836154941Sjhb
837173960Sattilio#ifdef ADAPTIVE_RWLOCKS
838154941Sjhb		/*
839193035Sjhb		 * The current lock owner might have started executing
840193035Sjhb		 * on another CPU (or the lock could have changed
841193035Sjhb		 * owners) while we were waiting on the turnstile
842193035Sjhb		 * chain lock.  If so, drop the turnstile lock and try
843193035Sjhb		 * again.
844173960Sattilio		 */
845173960Sattilio		if (!(v & RW_LOCK_READ)) {
846173960Sattilio			owner = (struct thread *)RW_OWNER(v);
847173960Sattilio			if (TD_IS_RUNNING(owner)) {
848173960Sattilio				turnstile_cancel(ts);
849173960Sattilio				continue;
850173960Sattilio			}
851173960Sattilio		}
852173960Sattilio#endif
853173960Sattilio		/*
854179334Sattilio		 * Check for the waiters flags about this rwlock.
855179334Sattilio		 * If the lock was released, without maintain any pending
856179334Sattilio		 * waiters queue, simply try to acquire it.
857179334Sattilio		 * If a pending waiters queue is present, claim the lock
858179334Sattilio		 * ownership and maintain the pending queue.
859154941Sjhb		 */
860176017Sjeff		x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
861176017Sjeff		if ((v & ~x) == RW_UNLOCKED) {
862176017Sjeff			x &= ~RW_LOCK_WRITE_SPINNER;
863176017Sjeff			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
864176017Sjeff				if (x)
865176017Sjeff					turnstile_claim(ts);
866176017Sjeff				else
867176017Sjeff					turnstile_cancel(ts);
868154941Sjhb				break;
869154941Sjhb			}
870170295Sjeff			turnstile_cancel(ts);
871154941Sjhb			continue;
872154941Sjhb		}
873154941Sjhb		/*
874154941Sjhb		 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
875154941Sjhb		 * set it.  If we fail to set it, then loop back and try
876154941Sjhb		 * again.
877154941Sjhb		 */
878157826Sjhb		if (!(v & RW_LOCK_WRITE_WAITERS)) {
879157826Sjhb			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
880157826Sjhb			    v | RW_LOCK_WRITE_WAITERS)) {
881170295Sjeff				turnstile_cancel(ts);
882157826Sjhb				continue;
883157826Sjhb			}
884167787Sjhb			if (LOCK_LOG_TEST(&rw->lock_object, 0))
885157826Sjhb				CTR2(KTR_LOCK, "%s: %p set write waiters flag",
886157826Sjhb				    __func__, rw);
887154941Sjhb		}
888157846Sjhb		/*
889154941Sjhb		 * We were unable to acquire the lock and the write waiters
890154941Sjhb		 * flag is set, so we must block on the turnstile.
891154941Sjhb		 */
892167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
893154941Sjhb			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
894154941Sjhb			    rw);
895192853Ssson#ifdef KDTRACE_HOOKS
896285664Smarkj		sleep_time -= lockstat_nsecs(&rw->lock_object);
897192853Ssson#endif
898170295Sjeff		turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
899192853Ssson#ifdef KDTRACE_HOOKS
900285664Smarkj		sleep_time += lockstat_nsecs(&rw->lock_object);
901192853Ssson		sleep_cnt++;
902192853Ssson#endif
903167787Sjhb		if (LOCK_LOG_TEST(&rw->lock_object, 0))
904154941Sjhb			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
905154941Sjhb			    __func__, rw);
906176017Sjeff#ifdef ADAPTIVE_RWLOCKS
907176017Sjeff		spintries = 0;
908176017Sjeff#endif
909154941Sjhb	}
910192853Ssson#ifdef KDTRACE_HOOKS
911285664Smarkj	all_time += lockstat_nsecs(&rw->lock_object);
912192853Ssson	if (sleep_time)
913285703Smarkj		LOCKSTAT_RECORD4(rw__block, rw, sleep_time,
914284297Savg		    LOCKSTAT_WRITER, (state & RW_LOCK_READ) == 0,
915284297Savg		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
916192853Ssson
917284297Savg	/* Record only the loops spinning and not sleeping. */
918192853Ssson	if (spin_cnt > sleep_cnt)
919285703Smarkj		LOCKSTAT_RECORD4(rw__spin, rw, all_time - sleep_time,
920284297Savg		    LOCKSTAT_READER, (state & RW_LOCK_READ) == 0,
921284297Savg		    (state & RW_LOCK_READ) == 0 ? 0 : RW_READERS(state));
922192853Ssson#endif
923285704Smarkj	LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(rw__acquire, rw, contested,
924285704Smarkj	    waittime, file, line, LOCKSTAT_WRITER);
925154941Sjhb}
926154941Sjhb
927154941Sjhb/*
928154941Sjhb * This function is called if the first try at releasing a write lock failed.
929154941Sjhb * This means that one of the 2 waiter bits must be set indicating that at
930154941Sjhb * least one thread is waiting on this lock.
931154941Sjhb */
932154941Sjhbvoid
933242515Sattilio__rw_wunlock_hard(volatile uintptr_t *c, uintptr_t tid, const char *file,
934242515Sattilio    int line)
935154941Sjhb{
936242515Sattilio	struct rwlock *rw;
937154941Sjhb	struct turnstile *ts;
938154941Sjhb	uintptr_t v;
939154941Sjhb	int queue;
940154941Sjhb
941228424Savg	if (SCHEDULER_STOPPED())
942228424Savg		return;
943228424Savg
944242515Sattilio	rw = rwlock2rw(c);
945242515Sattilio
946171052Sattilio	if (rw_wlocked(rw) && rw_recursed(rw)) {
947176017Sjeff		rw->rw_recurse--;
948171052Sattilio		if (LOCK_LOG_TEST(&rw->lock_object, 0))
949171052Sattilio			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
950171052Sattilio		return;
951171052Sattilio	}
952171052Sattilio
953154941Sjhb	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
954154941Sjhb	    ("%s: neither of the waiter flags are set", __func__));
955154941Sjhb
956167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
957154941Sjhb		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
958154941Sjhb
959170295Sjeff	turnstile_chain_lock(&rw->lock_object);
960167787Sjhb	ts = turnstile_lookup(&rw->lock_object);
961154941Sjhb	MPASS(ts != NULL);
962154941Sjhb
963154941Sjhb	/*
964154941Sjhb	 * Use the same algo as sx locks for now.  Prefer waking up shared
965154941Sjhb	 * waiters if we have any over writers.  This is probably not ideal.
966154941Sjhb	 *
967154941Sjhb	 * 'v' is the value we are going to write back to rw_lock.  If we
968154941Sjhb	 * have waiters on both queues, we need to preserve the state of
969154941Sjhb	 * the waiter flag for the queue we don't wake up.  For now this is
970154941Sjhb	 * hardcoded for the algorithm mentioned above.
971154941Sjhb	 *
972154941Sjhb	 * In the case of both readers and writers waiting we wakeup the
973154941Sjhb	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
974154941Sjhb	 * new writer comes in before a reader it will claim the lock up
975154941Sjhb	 * above.  There is probably a potential priority inversion in
976154941Sjhb	 * there that could be worked around either by waking both queues
977154941Sjhb	 * of waiters or doing some complicated lock handoff gymnastics.
978154941Sjhb	 */
979157846Sjhb	v = RW_UNLOCKED;
980176076Sjeff	if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
981176076Sjeff		queue = TS_EXCLUSIVE_QUEUE;
982176076Sjeff		v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
983176076Sjeff	} else
984154941Sjhb		queue = TS_SHARED_QUEUE;
985157846Sjhb
986157846Sjhb	/* Wake up all waiters for the specific queue. */
987167787Sjhb	if (LOCK_LOG_TEST(&rw->lock_object, 0))
988154941Sjhb		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
989154941Sjhb		    queue == TS_SHARED_QUEUE ? "read" : "write");
990154941Sjhb	turnstile_broadcast(ts, queue);
991154941Sjhb	atomic_store_rel_ptr(&rw->rw_lock, v);
992154941Sjhb	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
993170295Sjeff	turnstile_chain_unlock(&rw->lock_object);
994154941Sjhb}
995154941Sjhb
996157882Sjhb/*
997157882Sjhb * Attempt to do a non-blocking upgrade from a read lock to a write
998157882Sjhb * lock.  This will only succeed if this thread holds a single read
999157882Sjhb * lock.  Returns true if the upgrade succeeded and false otherwise.
1000157882Sjhb */
1001157882Sjhbint
1002242515Sattilio__rw_try_upgrade(volatile uintptr_t *c, const char *file, int line)
1003157882Sjhb{
1004242515Sattilio	struct rwlock *rw;
1005176017Sjeff	uintptr_t v, x, tid;
1006170295Sjeff	struct turnstile *ts;
1007157882Sjhb	int success;
1008157882Sjhb
1009228424Savg	if (SCHEDULER_STOPPED())
1010228424Savg		return (1);
1011228424Savg
1012242515Sattilio	rw = rwlock2rw(c);
1013242515Sattilio
1014169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
1015169394Sjhb	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
1016242515Sattilio	__rw_assert(c, RA_RLOCKED, file, line);
1017157882Sjhb
1018157882Sjhb	/*
1019157882Sjhb	 * Attempt to switch from one reader to a writer.  If there
1020157882Sjhb	 * are any write waiters, then we will have to lock the
1021157882Sjhb	 * turnstile first to prevent races with another writer
1022157882Sjhb	 * calling turnstile_wait() before we have claimed this
1023157882Sjhb	 * turnstile.  So, do the simple case of no waiters first.
1024157882Sjhb	 */
1025157882Sjhb	tid = (uintptr_t)curthread;
1026176017Sjeff	success = 0;
1027176017Sjeff	for (;;) {
1028176017Sjeff		v = rw->rw_lock;
1029176017Sjeff		if (RW_READERS(v) > 1)
1030176017Sjeff			break;
1031176017Sjeff		if (!(v & RW_LOCK_WAITERS)) {
1032176017Sjeff			success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
1033176017Sjeff			if (!success)
1034176017Sjeff				continue;
1035176017Sjeff			break;
1036176017Sjeff		}
1037157882Sjhb
1038176017Sjeff		/*
1039176017Sjeff		 * Ok, we think we have waiters, so lock the turnstile.
1040176017Sjeff		 */
1041176017Sjeff		ts = turnstile_trywait(&rw->lock_object);
1042176017Sjeff		v = rw->rw_lock;
1043176017Sjeff		if (RW_READERS(v) > 1) {
1044176017Sjeff			turnstile_cancel(ts);
1045176017Sjeff			break;
1046176017Sjeff		}
1047176017Sjeff		/*
1048176017Sjeff		 * Try to switch from one reader to a writer again.  This time
1049176017Sjeff		 * we honor the current state of the waiters flags.
1050176017Sjeff		 * If we obtain the lock with the flags set, then claim
1051176017Sjeff		 * ownership of the turnstile.
1052176017Sjeff		 */
1053176017Sjeff		x = rw->rw_lock & RW_LOCK_WAITERS;
1054176017Sjeff		success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
1055176017Sjeff		if (success) {
1056176017Sjeff			if (x)
1057176017Sjeff				turnstile_claim(ts);
1058176017Sjeff			else
1059176017Sjeff				turnstile_cancel(ts);
1060176017Sjeff			break;
1061176017Sjeff		}
1062170295Sjeff		turnstile_cancel(ts);
1063176017Sjeff	}
1064167787Sjhb	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
1065176017Sjeff	if (success) {
1066176017Sjeff		curthread->td_rw_rlocks--;
1067167787Sjhb		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
1068157882Sjhb		    file, line);
1069285703Smarkj		LOCKSTAT_RECORD0(rw__upgrade, rw);
1070176017Sjeff	}
1071157882Sjhb	return (success);
1072157882Sjhb}
1073157882Sjhb
1074157882Sjhb/*
1075157882Sjhb * Downgrade a write lock into a single read lock.
1076157882Sjhb */
1077157882Sjhbvoid
1078242515Sattilio__rw_downgrade(volatile uintptr_t *c, const char *file, int line)
1079157882Sjhb{
1080242515Sattilio	struct rwlock *rw;
1081157882Sjhb	struct turnstile *ts;
1082157882Sjhb	uintptr_t tid, v;
1083176017Sjeff	int rwait, wwait;
1084157882Sjhb
1085228424Savg	if (SCHEDULER_STOPPED())
1086228424Savg		return;
1087228424Savg
1088242515Sattilio	rw = rwlock2rw(c);
1089242515Sattilio
1090169394Sjhb	KASSERT(rw->rw_lock != RW_DESTROYED,
1091169394Sjhb	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
1092242515Sattilio	__rw_assert(c, RA_WLOCKED | RA_NOTRECURSED, file, line);
1093171052Sattilio#ifndef INVARIANTS
1094171052Sattilio	if (rw_recursed(rw))
1095171052Sattilio		panic("downgrade of a recursed lock");
1096171052Sattilio#endif
1097157882Sjhb
1098167787Sjhb	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
1099157882Sjhb
1100157882Sjhb	/*
1101157882Sjhb	 * Convert from a writer to a single reader.  First we handle
1102157882Sjhb	 * the easy case with no waiters.  If there are any waiters, we
1103176017Sjeff	 * lock the turnstile and "disown" the lock.
1104157882Sjhb	 */
1105157882Sjhb	tid = (uintptr_t)curthread;
1106157882Sjhb	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
1107157882Sjhb		goto out;
1108157882Sjhb
1109157882Sjhb	/*
1110157882Sjhb	 * Ok, we think we have waiters, so lock the turnstile so we can
1111157882Sjhb	 * read the waiter flags without any races.
1112157882Sjhb	 */
1113170295Sjeff	turnstile_chain_lock(&rw->lock_object);
1114176017Sjeff	v = rw->rw_lock & RW_LOCK_WAITERS;
1115176017Sjeff	rwait = v & RW_LOCK_READ_WAITERS;
1116176017Sjeff	wwait = v & RW_LOCK_WRITE_WAITERS;
1117176017Sjeff	MPASS(rwait | wwait);
1118157882Sjhb
1119157882Sjhb	/*
1120176017Sjeff	 * Downgrade from a write lock while preserving waiters flag
1121176017Sjeff	 * and give up ownership of the turnstile.
1122157882Sjhb	 */
1123167787Sjhb	ts = turnstile_lookup(&rw->lock_object);
1124157882Sjhb	MPASS(ts != NULL);
1125176017Sjeff	if (!wwait)
1126176017Sjeff		v &= ~RW_LOCK_READ_WAITERS;
1127176017Sjeff	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
1128176017Sjeff	/*
1129176017Sjeff	 * Wake other readers if there are no writers pending.  Otherwise they
1130176017Sjeff	 * won't be able to acquire the lock anyway.
1131176017Sjeff	 */
1132176017Sjeff	if (rwait && !wwait) {
1133157882Sjhb		turnstile_broadcast(ts, TS_SHARED_QUEUE);
1134157882Sjhb		turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
1135176017Sjeff	} else
1136157882Sjhb		turnstile_disown(ts);
1137170295Sjeff	turnstile_chain_unlock(&rw->lock_object);
1138157882Sjhbout:
1139176017Sjeff	curthread->td_rw_rlocks++;
1140167787Sjhb	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
1141285703Smarkj	LOCKSTAT_RECORD0(rw__downgrade, rw);
1142157882Sjhb}
1143157882Sjhb
1144154941Sjhb#ifdef INVARIANT_SUPPORT
1145155162Sscottl#ifndef INVARIANTS
1146242515Sattilio#undef __rw_assert
1147154941Sjhb#endif
1148154941Sjhb
1149154941Sjhb/*
1150154941Sjhb * In the non-WITNESS case, rw_assert() can only detect that at least
1151154941Sjhb * *some* thread owns an rlock, but it cannot guarantee that *this*
1152154941Sjhb * thread owns an rlock.
1153154941Sjhb */
1154154941Sjhbvoid
1155242515Sattilio__rw_assert(const volatile uintptr_t *c, int what, const char *file, int line)
1156154941Sjhb{
1157242515Sattilio	const struct rwlock *rw;
1158154941Sjhb
1159154941Sjhb	if (panicstr != NULL)
1160154941Sjhb		return;
1161242515Sattilio
1162242515Sattilio	rw = rwlock2rw(c);
1163242515Sattilio
1164154941Sjhb	switch (what) {
1165154941Sjhb	case RA_LOCKED:
1166171052Sattilio	case RA_LOCKED | RA_RECURSED:
1167171052Sattilio	case RA_LOCKED | RA_NOTRECURSED:
1168154941Sjhb	case RA_RLOCKED:
1169251323Sjhb	case RA_RLOCKED | RA_RECURSED:
1170251323Sjhb	case RA_RLOCKED | RA_NOTRECURSED:
1171154941Sjhb#ifdef WITNESS
1172167787Sjhb		witness_assert(&rw->lock_object, what, file, line);
1173154941Sjhb#else
1174154941Sjhb		/*
1175154941Sjhb		 * If some other thread has a write lock or we have one
1176154941Sjhb		 * and are asserting a read lock, fail.  Also, if no one
1177154941Sjhb		 * has a lock at all, fail.
1178154941Sjhb		 */
1179155061Sscottl		if (rw->rw_lock == RW_UNLOCKED ||
1180251323Sjhb		    (!(rw->rw_lock & RW_LOCK_READ) && (what & RA_RLOCKED ||
1181157826Sjhb		    rw_wowner(rw) != curthread)))
1182154941Sjhb			panic("Lock %s not %slocked @ %s:%d\n",
1183251323Sjhb			    rw->lock_object.lo_name, (what & RA_RLOCKED) ?
1184154941Sjhb			    "read " : "", file, line);
1185171052Sattilio
1186251323Sjhb		if (!(rw->rw_lock & RW_LOCK_READ) && !(what & RA_RLOCKED)) {
1187171052Sattilio			if (rw_recursed(rw)) {
1188171052Sattilio				if (what & RA_NOTRECURSED)
1189171052Sattilio					panic("Lock %s recursed @ %s:%d\n",
1190171052Sattilio					    rw->lock_object.lo_name, file,
1191171052Sattilio					    line);
1192171052Sattilio			} else if (what & RA_RECURSED)
1193171052Sattilio				panic("Lock %s not recursed @ %s:%d\n",
1194171052Sattilio				    rw->lock_object.lo_name, file, line);
1195171052Sattilio		}
1196154941Sjhb#endif
1197154941Sjhb		break;
1198154941Sjhb	case RA_WLOCKED:
1199171052Sattilio	case RA_WLOCKED | RA_RECURSED:
1200171052Sattilio	case RA_WLOCKED | RA_NOTRECURSED:
1201157826Sjhb		if (rw_wowner(rw) != curthread)
1202154941Sjhb			panic("Lock %s not exclusively locked @ %s:%d\n",
1203167787Sjhb			    rw->lock_object.lo_name, file, line);
1204171052Sattilio		if (rw_recursed(rw)) {
1205171052Sattilio			if (what & RA_NOTRECURSED)
1206171052Sattilio				panic("Lock %s recursed @ %s:%d\n",
1207171052Sattilio				    rw->lock_object.lo_name, file, line);
1208171052Sattilio		} else if (what & RA_RECURSED)
1209171052Sattilio			panic("Lock %s not recursed @ %s:%d\n",
1210171052Sattilio			    rw->lock_object.lo_name, file, line);
1211154941Sjhb		break;
1212154941Sjhb	case RA_UNLOCKED:
1213154941Sjhb#ifdef WITNESS
1214167787Sjhb		witness_assert(&rw->lock_object, what, file, line);
1215154941Sjhb#else
1216154941Sjhb		/*
1217154941Sjhb		 * If we hold a write lock fail.  We can't reliably check
1218154941Sjhb		 * to see if we hold a read lock or not.
1219154941Sjhb		 */
1220157826Sjhb		if (rw_wowner(rw) == curthread)
1221154941Sjhb			panic("Lock %s exclusively locked @ %s:%d\n",
1222167787Sjhb			    rw->lock_object.lo_name, file, line);
1223154941Sjhb#endif
1224154941Sjhb		break;
1225154941Sjhb	default:
1226154941Sjhb		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1227154941Sjhb		    line);
1228154941Sjhb	}
1229154941Sjhb}
1230154941Sjhb#endif /* INVARIANT_SUPPORT */
1231154941Sjhb
1232154941Sjhb#ifdef DDB
1233154941Sjhbvoid
1234227588Spjddb_show_rwlock(const struct lock_object *lock)
1235154941Sjhb{
1236227588Spjd	const struct rwlock *rw;
1237154941Sjhb	struct thread *td;
1238154941Sjhb
1239227588Spjd	rw = (const struct rwlock *)lock;
1240154941Sjhb
1241154941Sjhb	db_printf(" state: ");
1242154941Sjhb	if (rw->rw_lock == RW_UNLOCKED)
1243154941Sjhb		db_printf("UNLOCKED\n");
1244169394Sjhb	else if (rw->rw_lock == RW_DESTROYED) {
1245169394Sjhb		db_printf("DESTROYED\n");
1246169394Sjhb		return;
1247169394Sjhb	} else if (rw->rw_lock & RW_LOCK_READ)
1248167504Sjhb		db_printf("RLOCK: %ju locks\n",
1249167504Sjhb		    (uintmax_t)(RW_READERS(rw->rw_lock)));
1250154941Sjhb	else {
1251157826Sjhb		td = rw_wowner(rw);
1252154941Sjhb		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1253173600Sjulian		    td->td_tid, td->td_proc->p_pid, td->td_name);
1254171052Sattilio		if (rw_recursed(rw))
1255171052Sattilio			db_printf(" recursed: %u\n", rw->rw_recurse);
1256154941Sjhb	}
1257154941Sjhb	db_printf(" waiters: ");
1258154941Sjhb	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1259154941Sjhb	case RW_LOCK_READ_WAITERS:
1260154941Sjhb		db_printf("readers\n");
1261154941Sjhb		break;
1262154941Sjhb	case RW_LOCK_WRITE_WAITERS:
1263154941Sjhb		db_printf("writers\n");
1264154941Sjhb		break;
1265154941Sjhb	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1266167492Sjhb		db_printf("readers and writers\n");
1267154941Sjhb		break;
1268154941Sjhb	default:
1269154941Sjhb		db_printf("none\n");
1270154941Sjhb		break;
1271154941Sjhb	}
1272154941Sjhb}
1273154941Sjhb
1274154941Sjhb#endif
1275