kern_rwlock.c revision 192853
1/*-
2 * Copyright (c) 2006 John Baldwin <jhb@FreeBSD.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the author nor the names of any co-contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30/*
31 * Machine independent bits of reader/writer lock implementation.
32 */
33
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD: head/sys/kern/kern_rwlock.c 192853 2009-05-26 20:28:22Z sson $");
36
37#include "opt_ddb.h"
38#include "opt_kdtrace.h"
39#include "opt_no_adaptive_rwlocks.h"
40
41#include <sys/param.h>
42#include <sys/ktr.h>
43#include <sys/kernel.h>
44#include <sys/lock.h>
45#include <sys/mutex.h>
46#include <sys/proc.h>
47#include <sys/rwlock.h>
48#include <sys/sysctl.h>
49#include <sys/systm.h>
50#include <sys/turnstile.h>
51
52#include <machine/cpu.h>
53
54CTASSERT((RW_RECURSE & LO_CLASSFLAGS) == RW_RECURSE);
55
56#if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
57#define	ADAPTIVE_RWLOCKS
58#endif
59
60#ifdef ADAPTIVE_RWLOCKS
61static int rowner_retries = 10;
62static int rowner_loops = 10000;
63SYSCTL_NODE(_debug, OID_AUTO, rwlock, CTLFLAG_RD, NULL, "rwlock debugging");
64SYSCTL_INT(_debug_rwlock, OID_AUTO, retry, CTLFLAG_RW, &rowner_retries, 0, "");
65SYSCTL_INT(_debug_rwlock, OID_AUTO, loops, CTLFLAG_RW, &rowner_loops, 0, "");
66#endif
67
68#ifdef DDB
69#include <ddb/ddb.h>
70
71static void	db_show_rwlock(struct lock_object *lock);
72#endif
73static void	assert_rw(struct lock_object *lock, int what);
74static void	lock_rw(struct lock_object *lock, int how);
75#ifdef KDTRACE_HOOKS
76static int	owner_rw(struct lock_object *lock, struct thread **owner);
77#endif
78static int	unlock_rw(struct lock_object *lock);
79
80struct lock_class lock_class_rw = {
81	.lc_name = "rw",
82	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
83	.lc_assert = assert_rw,
84#ifdef DDB
85	.lc_ddb_show = db_show_rwlock,
86#endif
87	.lc_lock = lock_rw,
88	.lc_unlock = unlock_rw,
89#ifdef KDTRACE_HOOKS
90	.lc_owner = owner_rw,
91#endif
92};
93
94/*
95 * Return a pointer to the owning thread if the lock is write-locked or
96 * NULL if the lock is unlocked or read-locked.
97 */
98#define	rw_wowner(rw)							\
99	((rw)->rw_lock & RW_LOCK_READ ? NULL :				\
100	    (struct thread *)RW_OWNER((rw)->rw_lock))
101
102/*
103 * Returns if a write owner is recursed.  Write ownership is not assured
104 * here and should be previously checked.
105 */
106#define	rw_recursed(rw)		((rw)->rw_recurse != 0)
107
108/*
109 * Return true if curthread helds the lock.
110 */
111#define	rw_wlocked(rw)		(rw_wowner((rw)) == curthread)
112
113/*
114 * Return a pointer to the owning thread for this lock who should receive
115 * any priority lent by threads that block on this lock.  Currently this
116 * is identical to rw_wowner().
117 */
118#define	rw_owner(rw)		rw_wowner(rw)
119
120#ifndef INVARIANTS
121#define	_rw_assert(rw, what, file, line)
122#endif
123
124void
125assert_rw(struct lock_object *lock, int what)
126{
127
128	rw_assert((struct rwlock *)lock, what);
129}
130
131void
132lock_rw(struct lock_object *lock, int how)
133{
134	struct rwlock *rw;
135
136	rw = (struct rwlock *)lock;
137	if (how)
138		rw_wlock(rw);
139	else
140		rw_rlock(rw);
141}
142
143int
144unlock_rw(struct lock_object *lock)
145{
146	struct rwlock *rw;
147
148	rw = (struct rwlock *)lock;
149	rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
150	if (rw->rw_lock & RW_LOCK_READ) {
151		rw_runlock(rw);
152		return (0);
153	} else {
154		rw_wunlock(rw);
155		return (1);
156	}
157}
158
159#ifdef KDTRACE_HOOKS
160int
161owner_rw(struct lock_object *lock, struct thread **owner)
162{
163	struct rwlock *rw = (struct rwlock *)lock;
164	uintptr_t x = rw->rw_lock;
165
166	*owner = rw_wowner(rw);
167	return ((x & RW_LOCK_READ) != 0 ?  (RW_READERS(x) != 0) :
168	    (*owner != NULL));
169}
170#endif
171
172void
173rw_init_flags(struct rwlock *rw, const char *name, int opts)
174{
175	int flags;
176
177	MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
178	    RW_RECURSE)) == 0);
179
180	flags = LO_UPGRADABLE | LO_RECURSABLE;
181	if (opts & RW_DUPOK)
182		flags |= LO_DUPOK;
183	if (opts & RW_NOPROFILE)
184		flags |= LO_NOPROFILE;
185	if (!(opts & RW_NOWITNESS))
186		flags |= LO_WITNESS;
187	if (opts & RW_QUIET)
188		flags |= LO_QUIET;
189	flags |= opts & RW_RECURSE;
190
191	rw->rw_lock = RW_UNLOCKED;
192	rw->rw_recurse = 0;
193	lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
194}
195
196void
197rw_destroy(struct rwlock *rw)
198{
199
200	KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock not unlocked"));
201	KASSERT(rw->rw_recurse == 0, ("rw lock still recursed"));
202	rw->rw_lock = RW_DESTROYED;
203	lock_destroy(&rw->lock_object);
204}
205
206void
207rw_sysinit(void *arg)
208{
209	struct rw_args *args = arg;
210
211	rw_init(args->ra_rw, args->ra_desc);
212}
213
214void
215rw_sysinit_flags(void *arg)
216{
217	struct rw_args_flags *args = arg;
218
219	rw_init_flags(args->ra_rw, args->ra_desc, args->ra_flags);
220}
221
222int
223rw_wowned(struct rwlock *rw)
224{
225
226	return (rw_wowner(rw) == curthread);
227}
228
229void
230_rw_wlock(struct rwlock *rw, const char *file, int line)
231{
232
233	MPASS(curthread != NULL);
234	KASSERT(rw->rw_lock != RW_DESTROYED,
235	    ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
236	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
237	    line, NULL);
238	__rw_wlock(rw, curthread, file, line);
239	LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
240	WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
241	curthread->td_locks++;
242}
243
244int
245_rw_try_wlock(struct rwlock *rw, const char *file, int line)
246{
247	int rval;
248
249	KASSERT(rw->rw_lock != RW_DESTROYED,
250	    ("rw_try_wlock() of destroyed rwlock @ %s:%d", file, line));
251
252	if (rw_wlocked(rw) && (rw->lock_object.lo_flags & RW_RECURSE) != 0) {
253		rw->rw_recurse++;
254		rval = 1;
255	} else
256		rval = atomic_cmpset_acq_ptr(&rw->rw_lock, RW_UNLOCKED,
257		    (uintptr_t)curthread);
258
259	LOCK_LOG_TRY("WLOCK", &rw->lock_object, 0, rval, file, line);
260	if (rval) {
261		WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
262		    file, line);
263		curthread->td_locks++;
264	}
265	return (rval);
266}
267
268void
269_rw_wunlock(struct rwlock *rw, const char *file, int line)
270{
271
272	MPASS(curthread != NULL);
273	KASSERT(rw->rw_lock != RW_DESTROYED,
274	    ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
275	_rw_assert(rw, RA_WLOCKED, file, line);
276	curthread->td_locks--;
277	WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
278	LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
279	    line);
280	if (!rw_recursed(rw))
281		LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_WUNLOCK_RELEASE, rw);
282	__rw_wunlock(rw, curthread, file, line);
283}
284/*
285 * Determines whether a new reader can acquire a lock.  Succeeds if the
286 * reader already owns a read lock and the lock is locked for read to
287 * prevent deadlock from reader recursion.  Also succeeds if the lock
288 * is unlocked and has no writer waiters or spinners.  Failing otherwise
289 * prioritizes writers before readers.
290 */
291#define	RW_CAN_READ(_rw)						\
292    ((curthread->td_rw_rlocks && (_rw) & RW_LOCK_READ) || ((_rw) &	\
293    (RW_LOCK_READ | RW_LOCK_WRITE_WAITERS | RW_LOCK_WRITE_SPINNER)) ==	\
294    RW_LOCK_READ)
295
296void
297_rw_rlock(struct rwlock *rw, const char *file, int line)
298{
299	struct turnstile *ts;
300#ifdef ADAPTIVE_RWLOCKS
301	volatile struct thread *owner;
302	int spintries = 0;
303	int i;
304#endif
305#ifdef LOCK_PROFILING
306	uint64_t waittime = 0;
307	int contested = 0;
308#endif
309	uintptr_t v;
310#ifdef KDTRACE_HOOKS
311	uint64_t spin_cnt = 0;
312	uint64_t sleep_cnt = 0;
313	int64_t sleep_time = 0;
314#endif
315
316	KASSERT(rw->rw_lock != RW_DESTROYED,
317	    ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
318	KASSERT(rw_wowner(rw) != curthread,
319	    ("%s (%s): wlock already held @ %s:%d", __func__,
320	    rw->lock_object.lo_name, file, line));
321	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line, NULL);
322
323	for (;;) {
324#ifdef KDTRACE_HOOKS
325		spin_cnt++;
326#endif
327		/*
328		 * Handle the easy case.  If no other thread has a write
329		 * lock, then try to bump up the count of read locks.  Note
330		 * that we have to preserve the current state of the
331		 * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
332		 * read lock, then rw_lock must have changed, so restart
333		 * the loop.  Note that this handles the case of a
334		 * completely unlocked rwlock since such a lock is encoded
335		 * as a read lock with no waiters.
336		 */
337		v = rw->rw_lock;
338		if (RW_CAN_READ(v)) {
339			/*
340			 * The RW_LOCK_READ_WAITERS flag should only be set
341			 * if the lock has been unlocked and write waiters
342			 * were present.
343			 */
344			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v,
345			    v + RW_ONE_READER)) {
346				if (LOCK_LOG_TEST(&rw->lock_object, 0))
347					CTR4(KTR_LOCK,
348					    "%s: %p succeed %p -> %p", __func__,
349					    rw, (void *)v,
350					    (void *)(v + RW_ONE_READER));
351				break;
352			}
353			cpu_spinwait();
354			continue;
355		}
356		lock_profile_obtain_lock_failed(&rw->lock_object,
357		    &contested, &waittime);
358
359#ifdef ADAPTIVE_RWLOCKS
360		/*
361		 * If the owner is running on another CPU, spin until
362		 * the owner stops running or the state of the lock
363		 * changes.
364		 */
365		if ((v & RW_LOCK_READ) == 0) {
366			owner = (struct thread *)RW_OWNER(v);
367			if (TD_IS_RUNNING(owner)) {
368				if (LOCK_LOG_TEST(&rw->lock_object, 0))
369					CTR3(KTR_LOCK,
370					    "%s: spinning on %p held by %p",
371					    __func__, rw, owner);
372				while ((struct thread*)RW_OWNER(rw->rw_lock) ==
373				    owner && TD_IS_RUNNING(owner)) {
374					cpu_spinwait();
375#ifdef KDTRACE_HOOKS
376					spin_cnt++;
377#endif
378				}
379				continue;
380			}
381		} else if (spintries < rowner_retries) {
382			spintries++;
383			for (i = 0; i < rowner_loops; i++) {
384				v = rw->rw_lock;
385				if ((v & RW_LOCK_READ) == 0 || RW_CAN_READ(v))
386					break;
387				cpu_spinwait();
388			}
389			if (i != rowner_loops)
390				continue;
391		}
392#endif
393
394		/*
395		 * Okay, now it's the hard case.  Some other thread already
396		 * has a write lock or there are write waiters present,
397		 * acquire the turnstile lock so we can begin the process
398		 * of blocking.
399		 */
400		ts = turnstile_trywait(&rw->lock_object);
401
402		/*
403		 * The lock might have been released while we spun, so
404		 * recheck its state and restart the loop if needed.
405		 */
406		v = rw->rw_lock;
407		if (RW_CAN_READ(v)) {
408			turnstile_cancel(ts);
409			cpu_spinwait();
410			continue;
411		}
412
413#ifdef ADAPTIVE_RWLOCKS
414		/*
415		 * If the current owner of the lock is executing on another
416		 * CPU quit the hard path and try to spin.
417		 */
418		if ((v & RW_LOCK_READ) == 0) {
419			owner = (struct thread *)RW_OWNER(v);
420			if (TD_IS_RUNNING(owner)) {
421				turnstile_cancel(ts);
422				cpu_spinwait();
423				continue;
424			}
425		}
426#endif
427
428		/*
429		 * The lock is held in write mode or it already has waiters.
430		 */
431		MPASS(!RW_CAN_READ(v));
432
433		/*
434		 * If the RW_LOCK_READ_WAITERS flag is already set, then
435		 * we can go ahead and block.  If it is not set then try
436		 * to set it.  If we fail to set it drop the turnstile
437		 * lock and restart the loop.
438		 */
439		if (!(v & RW_LOCK_READ_WAITERS)) {
440			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
441			    v | RW_LOCK_READ_WAITERS)) {
442				turnstile_cancel(ts);
443				cpu_spinwait();
444				continue;
445			}
446			if (LOCK_LOG_TEST(&rw->lock_object, 0))
447				CTR2(KTR_LOCK, "%s: %p set read waiters flag",
448				    __func__, rw);
449		}
450
451		/*
452		 * We were unable to acquire the lock and the read waiters
453		 * flag is set, so we must block on the turnstile.
454		 */
455		if (LOCK_LOG_TEST(&rw->lock_object, 0))
456			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
457			    rw);
458#ifdef KDTRACE_HOOKS
459		sleep_time -= lockstat_nsecs();
460#endif
461		turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
462#ifdef KDTRACE_HOOKS
463		sleep_time += lockstat_nsecs();
464		sleep_cnt++;
465#endif
466		if (LOCK_LOG_TEST(&rw->lock_object, 0))
467			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
468			    __func__, rw);
469	}
470
471	/*
472	 * TODO: acquire "owner of record" here.  Here be turnstile dragons
473	 * however.  turnstiles don't like owners changing between calls to
474	 * turnstile_wait() currently.
475	 */
476	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_RLOCK_ACQUIRE, rw, contested,
477	    waittime, file, line);
478	LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
479	WITNESS_LOCK(&rw->lock_object, 0, file, line);
480	curthread->td_locks++;
481	curthread->td_rw_rlocks++;
482#ifdef KDTRACE_HOOKS
483	if (sleep_time)
484		LOCKSTAT_RECORD1(LS_RW_RLOCK_BLOCK, rw, sleep_time);
485
486	/*
487	 * Record only the loops spinning and not sleeping.
488	 */
489	if (spin_cnt > sleep_cnt)
490		LOCKSTAT_RECORD1(LS_RW_RLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
491#endif
492}
493
494int
495_rw_try_rlock(struct rwlock *rw, const char *file, int line)
496{
497	uintptr_t x;
498
499	for (;;) {
500		x = rw->rw_lock;
501		KASSERT(rw->rw_lock != RW_DESTROYED,
502		    ("rw_try_rlock() of destroyed rwlock @ %s:%d", file, line));
503		if (!(x & RW_LOCK_READ))
504			break;
505		if (atomic_cmpset_acq_ptr(&rw->rw_lock, x, x + RW_ONE_READER)) {
506			LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 1, file,
507			    line);
508			WITNESS_LOCK(&rw->lock_object, LOP_TRYLOCK, file, line);
509			curthread->td_locks++;
510			curthread->td_rw_rlocks++;
511			return (1);
512		}
513	}
514
515	LOCK_LOG_TRY("RLOCK", &rw->lock_object, 0, 0, file, line);
516	return (0);
517}
518
519void
520_rw_runlock(struct rwlock *rw, const char *file, int line)
521{
522	struct turnstile *ts;
523	uintptr_t x, v, queue;
524
525	KASSERT(rw->rw_lock != RW_DESTROYED,
526	    ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
527	_rw_assert(rw, RA_RLOCKED, file, line);
528	curthread->td_locks--;
529	curthread->td_rw_rlocks--;
530	WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
531	LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
532
533	/* TODO: drop "owner of record" here. */
534
535	for (;;) {
536		/*
537		 * See if there is more than one read lock held.  If so,
538		 * just drop one and return.
539		 */
540		x = rw->rw_lock;
541		if (RW_READERS(x) > 1) {
542			if (atomic_cmpset_ptr(&rw->rw_lock, x,
543			    x - RW_ONE_READER)) {
544				if (LOCK_LOG_TEST(&rw->lock_object, 0))
545					CTR4(KTR_LOCK,
546					    "%s: %p succeeded %p -> %p",
547					    __func__, rw, (void *)x,
548					    (void *)(x - RW_ONE_READER));
549				break;
550			}
551			continue;
552		}
553		/*
554		 * If there aren't any waiters for a write lock, then try
555		 * to drop it quickly.
556		 */
557		if (!(x & RW_LOCK_WAITERS)) {
558			MPASS((x & ~RW_LOCK_WRITE_SPINNER) ==
559			    RW_READERS_LOCK(1));
560			if (atomic_cmpset_ptr(&rw->rw_lock, x, RW_UNLOCKED)) {
561				if (LOCK_LOG_TEST(&rw->lock_object, 0))
562					CTR2(KTR_LOCK, "%s: %p last succeeded",
563					    __func__, rw);
564				break;
565			}
566			continue;
567		}
568		/*
569		 * Ok, we know we have waiters and we think we are the
570		 * last reader, so grab the turnstile lock.
571		 */
572		turnstile_chain_lock(&rw->lock_object);
573		v = rw->rw_lock & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
574		MPASS(v & RW_LOCK_WAITERS);
575
576		/*
577		 * Try to drop our lock leaving the lock in a unlocked
578		 * state.
579		 *
580		 * If you wanted to do explicit lock handoff you'd have to
581		 * do it here.  You'd also want to use turnstile_signal()
582		 * and you'd have to handle the race where a higher
583		 * priority thread blocks on the write lock before the
584		 * thread you wakeup actually runs and have the new thread
585		 * "steal" the lock.  For now it's a lot simpler to just
586		 * wakeup all of the waiters.
587		 *
588		 * As above, if we fail, then another thread might have
589		 * acquired a read lock, so drop the turnstile lock and
590		 * restart.
591		 */
592		x = RW_UNLOCKED;
593		if (v & RW_LOCK_WRITE_WAITERS) {
594			queue = TS_EXCLUSIVE_QUEUE;
595			x |= (v & RW_LOCK_READ_WAITERS);
596		} else
597			queue = TS_SHARED_QUEUE;
598		if (!atomic_cmpset_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
599		    x)) {
600			turnstile_chain_unlock(&rw->lock_object);
601			continue;
602		}
603		if (LOCK_LOG_TEST(&rw->lock_object, 0))
604			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
605			    __func__, rw);
606
607		/*
608		 * Ok.  The lock is released and all that's left is to
609		 * wake up the waiters.  Note that the lock might not be
610		 * free anymore, but in that case the writers will just
611		 * block again if they run before the new lock holder(s)
612		 * release the lock.
613		 */
614		ts = turnstile_lookup(&rw->lock_object);
615		MPASS(ts != NULL);
616		turnstile_broadcast(ts, queue);
617		turnstile_unpend(ts, TS_SHARED_LOCK);
618		turnstile_chain_unlock(&rw->lock_object);
619		break;
620	}
621	LOCKSTAT_PROFILE_RELEASE_LOCK(LS_RW_RUNLOCK_RELEASE, rw);
622}
623
624/*
625 * This function is called when we are unable to obtain a write lock on the
626 * first try.  This means that at least one other thread holds either a
627 * read or write lock.
628 */
629void
630_rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
631{
632	struct turnstile *ts;
633#ifdef ADAPTIVE_RWLOCKS
634	volatile struct thread *owner;
635	int spintries = 0;
636	int i;
637#endif
638	uintptr_t v, x;
639#ifdef LOCK_PROFILING
640	uint64_t waittime = 0;
641	int contested = 0;
642#endif
643#ifdef KDTRACE_HOOKS
644	uint64_t spin_cnt = 0;
645	uint64_t sleep_cnt = 0;
646	int64_t sleep_time = 0;
647#endif
648
649	if (rw_wlocked(rw)) {
650		KASSERT(rw->lock_object.lo_flags & RW_RECURSE,
651		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
652		    __func__, rw->lock_object.lo_name, file, line));
653		rw->rw_recurse++;
654		if (LOCK_LOG_TEST(&rw->lock_object, 0))
655			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
656		return;
657	}
658
659	if (LOCK_LOG_TEST(&rw->lock_object, 0))
660		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
661		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
662
663	while (!_rw_write_lock(rw, tid)) {
664#ifdef KDTRACE_HOOKS
665		spin_cnt++;
666#endif
667		lock_profile_obtain_lock_failed(&rw->lock_object,
668		    &contested, &waittime);
669#ifdef ADAPTIVE_RWLOCKS
670		/*
671		 * If the lock is write locked and the owner is
672		 * running on another CPU, spin until the owner stops
673		 * running or the state of the lock changes.
674		 */
675		v = rw->rw_lock;
676		owner = (struct thread *)RW_OWNER(v);
677		if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
678			if (LOCK_LOG_TEST(&rw->lock_object, 0))
679				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
680				    __func__, rw, owner);
681			while ((struct thread*)RW_OWNER(rw->rw_lock) == owner &&
682			    TD_IS_RUNNING(owner)) {
683				cpu_spinwait();
684#ifdef KDTRACE_HOOKS
685				spin_cnt++;
686#endif
687			}
688			continue;
689		}
690		if ((v & RW_LOCK_READ) && RW_READERS(v) &&
691		    spintries < rowner_retries) {
692			if (!(v & RW_LOCK_WRITE_SPINNER)) {
693				if (!atomic_cmpset_ptr(&rw->rw_lock, v,
694				    v | RW_LOCK_WRITE_SPINNER)) {
695					cpu_spinwait();
696					continue;
697				}
698			}
699			spintries++;
700			for (i = 0; i < rowner_loops; i++) {
701				if ((rw->rw_lock & RW_LOCK_WRITE_SPINNER) == 0)
702					break;
703				cpu_spinwait();
704			}
705#ifdef KDTRACE_HOOKS
706			spin_cnt += rowner_loops - i;
707#endif
708			if (i != rowner_loops)
709				continue;
710		}
711#endif
712		ts = turnstile_trywait(&rw->lock_object);
713		v = rw->rw_lock;
714
715#ifdef ADAPTIVE_RWLOCKS
716		/*
717		 * If the current owner of the lock is executing on another
718		 * CPU quit the hard path and try to spin.
719		 */
720		if (!(v & RW_LOCK_READ)) {
721			owner = (struct thread *)RW_OWNER(v);
722			if (TD_IS_RUNNING(owner)) {
723				turnstile_cancel(ts);
724				cpu_spinwait();
725				continue;
726			}
727		}
728#endif
729		/*
730		 * Check for the waiters flags about this rwlock.
731		 * If the lock was released, without maintain any pending
732		 * waiters queue, simply try to acquire it.
733		 * If a pending waiters queue is present, claim the lock
734		 * ownership and maintain the pending queue.
735		 */
736		x = v & (RW_LOCK_WAITERS | RW_LOCK_WRITE_SPINNER);
737		if ((v & ~x) == RW_UNLOCKED) {
738			x &= ~RW_LOCK_WRITE_SPINNER;
739			if (atomic_cmpset_acq_ptr(&rw->rw_lock, v, tid | x)) {
740				if (x)
741					turnstile_claim(ts);
742				else
743					turnstile_cancel(ts);
744				break;
745			}
746			turnstile_cancel(ts);
747			cpu_spinwait();
748			continue;
749		}
750		/*
751		 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
752		 * set it.  If we fail to set it, then loop back and try
753		 * again.
754		 */
755		if (!(v & RW_LOCK_WRITE_WAITERS)) {
756			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
757			    v | RW_LOCK_WRITE_WAITERS)) {
758				turnstile_cancel(ts);
759				cpu_spinwait();
760				continue;
761			}
762			if (LOCK_LOG_TEST(&rw->lock_object, 0))
763				CTR2(KTR_LOCK, "%s: %p set write waiters flag",
764				    __func__, rw);
765		}
766		/*
767		 * We were unable to acquire the lock and the write waiters
768		 * flag is set, so we must block on the turnstile.
769		 */
770		if (LOCK_LOG_TEST(&rw->lock_object, 0))
771			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
772			    rw);
773#ifdef KDTRACE_HOOKS
774		sleep_time -= lockstat_nsecs();
775#endif
776		turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
777#ifdef KDTRACE_HOOKS
778		sleep_time += lockstat_nsecs();
779		sleep_cnt++;
780#endif
781		if (LOCK_LOG_TEST(&rw->lock_object, 0))
782			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
783			    __func__, rw);
784#ifdef ADAPTIVE_RWLOCKS
785		spintries = 0;
786#endif
787	}
788	LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(LS_RW_WLOCK_ACQUIRE, rw, contested,
789	    waittime, file, line);
790#ifdef KDTRACE_HOOKS
791	if (sleep_time)
792		LOCKSTAT_RECORD1(LS_RW_WLOCK_BLOCK, rw, sleep_time);
793
794	/*
795	 * Record only the loops spinning and not sleeping.
796	 */
797	if (spin_cnt > sleep_cnt)
798		LOCKSTAT_RECORD1(LS_RW_WLOCK_SPIN, rw, (spin_cnt - sleep_cnt));
799#endif
800}
801
802/*
803 * This function is called if the first try at releasing a write lock failed.
804 * This means that one of the 2 waiter bits must be set indicating that at
805 * least one thread is waiting on this lock.
806 */
807void
808_rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
809{
810	struct turnstile *ts;
811	uintptr_t v;
812	int queue;
813
814	if (rw_wlocked(rw) && rw_recursed(rw)) {
815		rw->rw_recurse--;
816		if (LOCK_LOG_TEST(&rw->lock_object, 0))
817			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
818		return;
819	}
820
821	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
822	    ("%s: neither of the waiter flags are set", __func__));
823
824	if (LOCK_LOG_TEST(&rw->lock_object, 0))
825		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
826
827	turnstile_chain_lock(&rw->lock_object);
828	ts = turnstile_lookup(&rw->lock_object);
829	MPASS(ts != NULL);
830
831	/*
832	 * Use the same algo as sx locks for now.  Prefer waking up shared
833	 * waiters if we have any over writers.  This is probably not ideal.
834	 *
835	 * 'v' is the value we are going to write back to rw_lock.  If we
836	 * have waiters on both queues, we need to preserve the state of
837	 * the waiter flag for the queue we don't wake up.  For now this is
838	 * hardcoded for the algorithm mentioned above.
839	 *
840	 * In the case of both readers and writers waiting we wakeup the
841	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
842	 * new writer comes in before a reader it will claim the lock up
843	 * above.  There is probably a potential priority inversion in
844	 * there that could be worked around either by waking both queues
845	 * of waiters or doing some complicated lock handoff gymnastics.
846	 */
847	v = RW_UNLOCKED;
848	if (rw->rw_lock & RW_LOCK_WRITE_WAITERS) {
849		queue = TS_EXCLUSIVE_QUEUE;
850		v |= (rw->rw_lock & RW_LOCK_READ_WAITERS);
851	} else
852		queue = TS_SHARED_QUEUE;
853
854	/* Wake up all waiters for the specific queue. */
855	if (LOCK_LOG_TEST(&rw->lock_object, 0))
856		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
857		    queue == TS_SHARED_QUEUE ? "read" : "write");
858	turnstile_broadcast(ts, queue);
859	atomic_store_rel_ptr(&rw->rw_lock, v);
860	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
861	turnstile_chain_unlock(&rw->lock_object);
862}
863
864/*
865 * Attempt to do a non-blocking upgrade from a read lock to a write
866 * lock.  This will only succeed if this thread holds a single read
867 * lock.  Returns true if the upgrade succeeded and false otherwise.
868 */
869int
870_rw_try_upgrade(struct rwlock *rw, const char *file, int line)
871{
872	uintptr_t v, x, tid;
873	struct turnstile *ts;
874	int success;
875
876	KASSERT(rw->rw_lock != RW_DESTROYED,
877	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
878	_rw_assert(rw, RA_RLOCKED, file, line);
879
880	/*
881	 * Attempt to switch from one reader to a writer.  If there
882	 * are any write waiters, then we will have to lock the
883	 * turnstile first to prevent races with another writer
884	 * calling turnstile_wait() before we have claimed this
885	 * turnstile.  So, do the simple case of no waiters first.
886	 */
887	tid = (uintptr_t)curthread;
888	success = 0;
889	for (;;) {
890		v = rw->rw_lock;
891		if (RW_READERS(v) > 1)
892			break;
893		if (!(v & RW_LOCK_WAITERS)) {
894			success = atomic_cmpset_ptr(&rw->rw_lock, v, tid);
895			if (!success)
896				continue;
897			break;
898		}
899
900		/*
901		 * Ok, we think we have waiters, so lock the turnstile.
902		 */
903		ts = turnstile_trywait(&rw->lock_object);
904		v = rw->rw_lock;
905		if (RW_READERS(v) > 1) {
906			turnstile_cancel(ts);
907			break;
908		}
909		/*
910		 * Try to switch from one reader to a writer again.  This time
911		 * we honor the current state of the waiters flags.
912		 * If we obtain the lock with the flags set, then claim
913		 * ownership of the turnstile.
914		 */
915		x = rw->rw_lock & RW_LOCK_WAITERS;
916		success = atomic_cmpset_ptr(&rw->rw_lock, v, tid | x);
917		if (success) {
918			if (x)
919				turnstile_claim(ts);
920			else
921				turnstile_cancel(ts);
922			break;
923		}
924		turnstile_cancel(ts);
925	}
926	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
927	if (success) {
928		curthread->td_rw_rlocks--;
929		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
930		    file, line);
931		LOCKSTAT_RECORD0(LS_RW_TRYUPGRADE_UPGRADE, rw);
932	}
933	return (success);
934}
935
936/*
937 * Downgrade a write lock into a single read lock.
938 */
939void
940_rw_downgrade(struct rwlock *rw, const char *file, int line)
941{
942	struct turnstile *ts;
943	uintptr_t tid, v;
944	int rwait, wwait;
945
946	KASSERT(rw->rw_lock != RW_DESTROYED,
947	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
948	_rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
949#ifndef INVARIANTS
950	if (rw_recursed(rw))
951		panic("downgrade of a recursed lock");
952#endif
953
954	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
955
956	/*
957	 * Convert from a writer to a single reader.  First we handle
958	 * the easy case with no waiters.  If there are any waiters, we
959	 * lock the turnstile and "disown" the lock.
960	 */
961	tid = (uintptr_t)curthread;
962	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
963		goto out;
964
965	/*
966	 * Ok, we think we have waiters, so lock the turnstile so we can
967	 * read the waiter flags without any races.
968	 */
969	turnstile_chain_lock(&rw->lock_object);
970	v = rw->rw_lock & RW_LOCK_WAITERS;
971	rwait = v & RW_LOCK_READ_WAITERS;
972	wwait = v & RW_LOCK_WRITE_WAITERS;
973	MPASS(rwait | wwait);
974
975	/*
976	 * Downgrade from a write lock while preserving waiters flag
977	 * and give up ownership of the turnstile.
978	 */
979	ts = turnstile_lookup(&rw->lock_object);
980	MPASS(ts != NULL);
981	if (!wwait)
982		v &= ~RW_LOCK_READ_WAITERS;
983	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v);
984	/*
985	 * Wake other readers if there are no writers pending.  Otherwise they
986	 * won't be able to acquire the lock anyway.
987	 */
988	if (rwait && !wwait) {
989		turnstile_broadcast(ts, TS_SHARED_QUEUE);
990		turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
991	} else
992		turnstile_disown(ts);
993	turnstile_chain_unlock(&rw->lock_object);
994out:
995	curthread->td_rw_rlocks++;
996	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
997	LOCKSTAT_RECORD0(LS_RW_DOWNGRADE_DOWNGRADE, rw);
998}
999
1000#ifdef INVARIANT_SUPPORT
1001#ifndef INVARIANTS
1002#undef _rw_assert
1003#endif
1004
1005/*
1006 * In the non-WITNESS case, rw_assert() can only detect that at least
1007 * *some* thread owns an rlock, but it cannot guarantee that *this*
1008 * thread owns an rlock.
1009 */
1010void
1011_rw_assert(struct rwlock *rw, int what, const char *file, int line)
1012{
1013
1014	if (panicstr != NULL)
1015		return;
1016	switch (what) {
1017	case RA_LOCKED:
1018	case RA_LOCKED | RA_RECURSED:
1019	case RA_LOCKED | RA_NOTRECURSED:
1020	case RA_RLOCKED:
1021#ifdef WITNESS
1022		witness_assert(&rw->lock_object, what, file, line);
1023#else
1024		/*
1025		 * If some other thread has a write lock or we have one
1026		 * and are asserting a read lock, fail.  Also, if no one
1027		 * has a lock at all, fail.
1028		 */
1029		if (rw->rw_lock == RW_UNLOCKED ||
1030		    (!(rw->rw_lock & RW_LOCK_READ) && (what == RA_RLOCKED ||
1031		    rw_wowner(rw) != curthread)))
1032			panic("Lock %s not %slocked @ %s:%d\n",
1033			    rw->lock_object.lo_name, (what == RA_RLOCKED) ?
1034			    "read " : "", file, line);
1035
1036		if (!(rw->rw_lock & RW_LOCK_READ)) {
1037			if (rw_recursed(rw)) {
1038				if (what & RA_NOTRECURSED)
1039					panic("Lock %s recursed @ %s:%d\n",
1040					    rw->lock_object.lo_name, file,
1041					    line);
1042			} else if (what & RA_RECURSED)
1043				panic("Lock %s not recursed @ %s:%d\n",
1044				    rw->lock_object.lo_name, file, line);
1045		}
1046#endif
1047		break;
1048	case RA_WLOCKED:
1049	case RA_WLOCKED | RA_RECURSED:
1050	case RA_WLOCKED | RA_NOTRECURSED:
1051		if (rw_wowner(rw) != curthread)
1052			panic("Lock %s not exclusively locked @ %s:%d\n",
1053			    rw->lock_object.lo_name, file, line);
1054		if (rw_recursed(rw)) {
1055			if (what & RA_NOTRECURSED)
1056				panic("Lock %s recursed @ %s:%d\n",
1057				    rw->lock_object.lo_name, file, line);
1058		} else if (what & RA_RECURSED)
1059			panic("Lock %s not recursed @ %s:%d\n",
1060			    rw->lock_object.lo_name, file, line);
1061		break;
1062	case RA_UNLOCKED:
1063#ifdef WITNESS
1064		witness_assert(&rw->lock_object, what, file, line);
1065#else
1066		/*
1067		 * If we hold a write lock fail.  We can't reliably check
1068		 * to see if we hold a read lock or not.
1069		 */
1070		if (rw_wowner(rw) == curthread)
1071			panic("Lock %s exclusively locked @ %s:%d\n",
1072			    rw->lock_object.lo_name, file, line);
1073#endif
1074		break;
1075	default:
1076		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
1077		    line);
1078	}
1079}
1080#endif /* INVARIANT_SUPPORT */
1081
1082#ifdef DDB
1083void
1084db_show_rwlock(struct lock_object *lock)
1085{
1086	struct rwlock *rw;
1087	struct thread *td;
1088
1089	rw = (struct rwlock *)lock;
1090
1091	db_printf(" state: ");
1092	if (rw->rw_lock == RW_UNLOCKED)
1093		db_printf("UNLOCKED\n");
1094	else if (rw->rw_lock == RW_DESTROYED) {
1095		db_printf("DESTROYED\n");
1096		return;
1097	} else if (rw->rw_lock & RW_LOCK_READ)
1098		db_printf("RLOCK: %ju locks\n",
1099		    (uintmax_t)(RW_READERS(rw->rw_lock)));
1100	else {
1101		td = rw_wowner(rw);
1102		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1103		    td->td_tid, td->td_proc->p_pid, td->td_name);
1104		if (rw_recursed(rw))
1105			db_printf(" recursed: %u\n", rw->rw_recurse);
1106	}
1107	db_printf(" waiters: ");
1108	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
1109	case RW_LOCK_READ_WAITERS:
1110		db_printf("readers\n");
1111		break;
1112	case RW_LOCK_WRITE_WAITERS:
1113		db_printf("writers\n");
1114		break;
1115	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
1116		db_printf("readers and writers\n");
1117		break;
1118	default:
1119		db_printf("none\n");
1120		break;
1121	}
1122}
1123
1124#endif
1125