kern_rwlock.c revision 171052
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 171052 2007-06-26 21:31:56Z attilio $");
36
37#include "opt_ddb.h"
38#include "opt_no_adaptive_rwlocks.h"
39
40#include <sys/param.h>
41#include <sys/ktr.h>
42#include <sys/lock.h>
43#include <sys/mutex.h>
44#include <sys/proc.h>
45#include <sys/rwlock.h>
46#include <sys/systm.h>
47#include <sys/turnstile.h>
48#include <sys/lock_profile.h>
49#include <machine/cpu.h>
50
51CTASSERT((RW_RECURSE & LO_CLASSFLAGS) == RW_RECURSE);
52
53#if defined(SMP) && !defined(NO_ADAPTIVE_RWLOCKS)
54#define	ADAPTIVE_RWLOCKS
55#endif
56
57#ifdef DDB
58#include <ddb/ddb.h>
59
60static void	db_show_rwlock(struct lock_object *lock);
61#endif
62static void	lock_rw(struct lock_object *lock, int how);
63static int	unlock_rw(struct lock_object *lock);
64
65struct lock_class lock_class_rw = {
66	.lc_name = "rw",
67	.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE,
68#ifdef DDB
69	.lc_ddb_show = db_show_rwlock,
70#endif
71	.lc_lock = lock_rw,
72	.lc_unlock = unlock_rw,
73};
74
75/*
76 * Return a pointer to the owning thread if the lock is write-locked or
77 * NULL if the lock is unlocked or read-locked.
78 */
79#define	rw_wowner(rw)							\
80	((rw)->rw_lock & RW_LOCK_READ ? NULL :				\
81	    (struct thread *)RW_OWNER((rw)->rw_lock))
82
83/*
84 * Returns if a write owner is recursed.  Write ownership is not assured
85 * here and should be previously checked.
86 */
87#define	rw_recursed(rw)		((rw)->rw_recurse != 0)
88
89/*
90 * Return true if curthread helds the lock.
91 */
92#define	rw_wlocked(rw)		(rw_wowner((rw)) == curthread)
93
94/*
95 * Return a pointer to the owning thread for this lock who should receive
96 * any priority lent by threads that block on this lock.  Currently this
97 * is identical to rw_wowner().
98 */
99#define	rw_owner(rw)		rw_wowner(rw)
100
101#ifndef INVARIANTS
102#define	_rw_assert(rw, what, file, line)
103#endif
104
105void
106lock_rw(struct lock_object *lock, int how)
107{
108	struct rwlock *rw;
109
110	rw = (struct rwlock *)lock;
111	if (how)
112		rw_wlock(rw);
113	else
114		rw_rlock(rw);
115}
116
117int
118unlock_rw(struct lock_object *lock)
119{
120	struct rwlock *rw;
121
122	rw = (struct rwlock *)lock;
123	rw_assert(rw, RA_LOCKED | LA_NOTRECURSED);
124	if (rw->rw_lock & RW_LOCK_READ) {
125		rw_runlock(rw);
126		return (0);
127	} else {
128		rw_wunlock(rw);
129		return (1);
130	}
131}
132
133void
134rw_init_flags(struct rwlock *rw, const char *name, int opts)
135{
136	int flags;
137
138	MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET |
139	    RW_RECURSE)) == 0);
140
141	flags = LO_UPGRADABLE | LO_RECURSABLE;
142	if (opts & RW_DUPOK)
143		flags |= LO_DUPOK;
144	if (opts & RW_NOPROFILE)
145		flags |= LO_NOPROFILE;
146	if (!(opts & RW_NOWITNESS))
147		flags |= LO_WITNESS;
148	if (opts & RW_QUIET)
149		flags |= LO_QUIET;
150	flags |= opts & RW_RECURSE;
151
152	rw->rw_lock = RW_UNLOCKED;
153	rw->rw_recurse = 0;
154	lock_init(&rw->lock_object, &lock_class_rw, name, NULL, flags);
155}
156
157void
158rw_destroy(struct rwlock *rw)
159{
160
161	KASSERT(rw->rw_lock == RW_UNLOCKED, ("rw lock not unlocked"));
162	KASSERT(rw->rw_recurse == 0, ("rw lock still recursed"));
163	rw->rw_lock = RW_DESTROYED;
164	lock_destroy(&rw->lock_object);
165}
166
167void
168rw_sysinit(void *arg)
169{
170	struct rw_args *args = arg;
171
172	rw_init(args->ra_rw, args->ra_desc);
173}
174
175int
176rw_wowned(struct rwlock *rw)
177{
178
179	return (rw_wowner(rw) == curthread);
180}
181
182void
183_rw_wlock(struct rwlock *rw, const char *file, int line)
184{
185
186	MPASS(curthread != NULL);
187	KASSERT(rw->rw_lock != RW_DESTROYED,
188	    ("rw_wlock() of destroyed rwlock @ %s:%d", file, line));
189	KASSERT(rw_wowner(rw) != curthread,
190	    ("%s (%s): wlock already held @ %s:%d", __func__,
191	    rw->lock_object.lo_name, file, line));
192	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
193	    line);
194	__rw_wlock(rw, curthread, file, line);
195	LOCK_LOG_LOCK("WLOCK", &rw->lock_object, 0, rw->rw_recurse, file, line);
196	WITNESS_LOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
197	curthread->td_locks++;
198}
199
200void
201_rw_wunlock(struct rwlock *rw, const char *file, int line)
202{
203
204	MPASS(curthread != NULL);
205	KASSERT(rw->rw_lock != RW_DESTROYED,
206	    ("rw_wunlock() of destroyed rwlock @ %s:%d", file, line));
207	_rw_assert(rw, RA_WLOCKED, file, line);
208	curthread->td_locks--;
209	WITNESS_UNLOCK(&rw->lock_object, LOP_EXCLUSIVE, file, line);
210	LOCK_LOG_LOCK("WUNLOCK", &rw->lock_object, 0, rw->rw_recurse, file,
211	    line);
212	if (!rw_recursed(rw))
213		lock_profile_release_lock(&rw->lock_object);
214	__rw_wunlock(rw, curthread, file, line);
215}
216
217void
218_rw_rlock(struct rwlock *rw, const char *file, int line)
219{
220	struct turnstile *ts;
221#ifdef ADAPTIVE_RWLOCKS
222	volatile struct thread *owner;
223#endif
224	uint64_t waittime = 0;
225	int contested = 0;
226	uintptr_t x;
227
228	KASSERT(rw->rw_lock != RW_DESTROYED,
229	    ("rw_rlock() of destroyed rwlock @ %s:%d", file, line));
230	KASSERT(rw_wowner(rw) != curthread,
231	    ("%s (%s): wlock already held @ %s:%d", __func__,
232	    rw->lock_object.lo_name, file, line));
233	WITNESS_CHECKORDER(&rw->lock_object, LOP_NEWORDER, file, line);
234
235	/*
236	 * Note that we don't make any attempt to try to block read
237	 * locks once a writer has blocked on the lock.  The reason is
238	 * that we currently allow for read locks to recurse and we
239	 * don't keep track of all the holders of read locks.  Thus, if
240	 * we were to block readers once a writer blocked and a reader
241	 * tried to recurse on their reader lock after a writer had
242	 * blocked we would end up in a deadlock since the reader would
243	 * be blocked on the writer, and the writer would be blocked
244	 * waiting for the reader to release its original read lock.
245	 */
246	for (;;) {
247		/*
248		 * Handle the easy case.  If no other thread has a write
249		 * lock, then try to bump up the count of read locks.  Note
250		 * that we have to preserve the current state of the
251		 * RW_LOCK_WRITE_WAITERS flag.  If we fail to acquire a
252		 * read lock, then rw_lock must have changed, so restart
253		 * the loop.  Note that this handles the case of a
254		 * completely unlocked rwlock since such a lock is encoded
255		 * as a read lock with no waiters.
256		 */
257		x = rw->rw_lock;
258		if (x & RW_LOCK_READ) {
259
260			/*
261			 * The RW_LOCK_READ_WAITERS flag should only be set
262			 * if another thread currently holds a write lock,
263			 * and in that case RW_LOCK_READ should be clear.
264			 */
265			MPASS((x & RW_LOCK_READ_WAITERS) == 0);
266			if (atomic_cmpset_acq_ptr(&rw->rw_lock, x,
267			    x + RW_ONE_READER)) {
268				if (LOCK_LOG_TEST(&rw->lock_object, 0))
269					CTR4(KTR_LOCK,
270					    "%s: %p succeed %p -> %p", __func__,
271					    rw, (void *)x,
272					    (void *)(x + RW_ONE_READER));
273				if (RW_READERS(x) == 0)
274					lock_profile_obtain_lock_success(
275					    &rw->lock_object, contested, waittime,
276					    file, line);
277				break;
278			}
279			cpu_spinwait();
280			continue;
281		}
282		lock_profile_obtain_lock_failed(&rw->lock_object, &contested,
283		    &waittime);
284
285		/*
286		 * Okay, now it's the hard case.  Some other thread already
287		 * has a write lock, so acquire the turnstile lock so we can
288		 * begin the process of blocking.
289		 */
290		ts = turnstile_trywait(&rw->lock_object);
291
292		/*
293		 * The lock might have been released while we spun, so
294		 * recheck its state and restart the loop if there is no
295		 * longer a write lock.
296		 */
297		x = rw->rw_lock;
298		if (x & RW_LOCK_READ) {
299			turnstile_cancel(ts);
300			cpu_spinwait();
301			continue;
302		}
303
304		/*
305		 * Ok, it's still a write lock.  If the RW_LOCK_READ_WAITERS
306		 * flag is already set, then we can go ahead and block.  If
307		 * it is not set then try to set it.  If we fail to set it
308		 * drop the turnstile lock and restart the loop.
309		 */
310		if (!(x & RW_LOCK_READ_WAITERS)) {
311			if (!atomic_cmpset_ptr(&rw->rw_lock, x,
312			    x | RW_LOCK_READ_WAITERS)) {
313				turnstile_cancel(ts);
314				cpu_spinwait();
315				continue;
316			}
317			if (LOCK_LOG_TEST(&rw->lock_object, 0))
318				CTR2(KTR_LOCK, "%s: %p set read waiters flag",
319				    __func__, rw);
320		}
321
322#ifdef ADAPTIVE_RWLOCKS
323		/*
324		 * If the owner is running on another CPU, spin until
325		 * the owner stops running or the state of the lock
326		 * changes.
327		 */
328		owner = (struct thread *)RW_OWNER(x);
329		if (TD_IS_RUNNING(owner)) {
330			turnstile_cancel(ts);
331			if (LOCK_LOG_TEST(&rw->lock_object, 0))
332				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
333				    __func__, rw, owner);
334			while ((struct thread*)RW_OWNER(rw->rw_lock)== owner &&
335			    TD_IS_RUNNING(owner))
336				cpu_spinwait();
337			continue;
338		}
339#endif
340
341		/*
342		 * We were unable to acquire the lock and the read waiters
343		 * flag is set, so we must block on the turnstile.
344		 */
345		if (LOCK_LOG_TEST(&rw->lock_object, 0))
346			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
347			    rw);
348		turnstile_wait(ts, rw_owner(rw), TS_SHARED_QUEUE);
349		if (LOCK_LOG_TEST(&rw->lock_object, 0))
350			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
351			    __func__, rw);
352	}
353
354	/*
355	 * TODO: acquire "owner of record" here.  Here be turnstile dragons
356	 * however.  turnstiles don't like owners changing between calls to
357	 * turnstile_wait() currently.
358	 */
359
360	LOCK_LOG_LOCK("RLOCK", &rw->lock_object, 0, 0, file, line);
361	WITNESS_LOCK(&rw->lock_object, 0, file, line);
362	curthread->td_locks++;
363}
364
365void
366_rw_runlock(struct rwlock *rw, const char *file, int line)
367{
368	struct turnstile *ts;
369	uintptr_t x;
370
371	KASSERT(rw->rw_lock != RW_DESTROYED,
372	    ("rw_runlock() of destroyed rwlock @ %s:%d", file, line));
373	_rw_assert(rw, RA_RLOCKED, file, line);
374	curthread->td_locks--;
375	WITNESS_UNLOCK(&rw->lock_object, 0, file, line);
376	LOCK_LOG_LOCK("RUNLOCK", &rw->lock_object, 0, 0, file, line);
377
378	/* TODO: drop "owner of record" here. */
379
380	for (;;) {
381		/*
382		 * See if there is more than one read lock held.  If so,
383		 * just drop one and return.
384		 */
385		x = rw->rw_lock;
386		if (RW_READERS(x) > 1) {
387			if (atomic_cmpset_ptr(&rw->rw_lock, x,
388			    x - RW_ONE_READER)) {
389				if (LOCK_LOG_TEST(&rw->lock_object, 0))
390					CTR4(KTR_LOCK,
391					    "%s: %p succeeded %p -> %p",
392					    __func__, rw, (void *)x,
393					    (void *)(x - RW_ONE_READER));
394				break;
395			}
396			continue;
397		}
398
399
400		/*
401		 * We should never have read waiters while at least one
402		 * thread holds a read lock.  (See note above)
403		 */
404		KASSERT(!(x & RW_LOCK_READ_WAITERS),
405		    ("%s: waiting readers", __func__));
406
407		/*
408		 * If there aren't any waiters for a write lock, then try
409		 * to drop it quickly.
410		 */
411		if (!(x & RW_LOCK_WRITE_WAITERS)) {
412
413			/*
414			 * There shouldn't be any flags set and we should
415			 * be the only read lock.  If we fail to release
416			 * the single read lock, then another thread might
417			 * have just acquired a read lock, so go back up
418			 * to the multiple read locks case.
419			 */
420			MPASS(x == RW_READERS_LOCK(1));
421			if (atomic_cmpset_ptr(&rw->rw_lock, RW_READERS_LOCK(1),
422			    RW_UNLOCKED)) {
423				if (LOCK_LOG_TEST(&rw->lock_object, 0))
424					CTR2(KTR_LOCK, "%s: %p last succeeded",
425					    __func__, rw);
426				break;
427			}
428			continue;
429		}
430
431		/*
432		 * There should just be one reader with one or more
433		 * writers waiting.
434		 */
435		MPASS(x == (RW_READERS_LOCK(1) | RW_LOCK_WRITE_WAITERS));
436
437		/*
438		 * Ok, we know we have a waiting writer and we think we
439		 * are the last reader, so grab the turnstile lock.
440		 */
441		turnstile_chain_lock(&rw->lock_object);
442
443		/*
444		 * Try to drop our lock leaving the lock in a unlocked
445		 * state.
446		 *
447		 * If you wanted to do explicit lock handoff you'd have to
448		 * do it here.  You'd also want to use turnstile_signal()
449		 * and you'd have to handle the race where a higher
450		 * priority thread blocks on the write lock before the
451		 * thread you wakeup actually runs and have the new thread
452		 * "steal" the lock.  For now it's a lot simpler to just
453		 * wakeup all of the waiters.
454		 *
455		 * As above, if we fail, then another thread might have
456		 * acquired a read lock, so drop the turnstile lock and
457		 * restart.
458		 */
459		if (!atomic_cmpset_ptr(&rw->rw_lock,
460		    RW_READERS_LOCK(1) | RW_LOCK_WRITE_WAITERS, RW_UNLOCKED)) {
461			turnstile_chain_unlock(&rw->lock_object);
462			continue;
463		}
464		if (LOCK_LOG_TEST(&rw->lock_object, 0))
465			CTR2(KTR_LOCK, "%s: %p last succeeded with waiters",
466			    __func__, rw);
467
468		/*
469		 * Ok.  The lock is released and all that's left is to
470		 * wake up the waiters.  Note that the lock might not be
471		 * free anymore, but in that case the writers will just
472		 * block again if they run before the new lock holder(s)
473		 * release the lock.
474		 */
475		ts = turnstile_lookup(&rw->lock_object);
476		MPASS(ts != NULL);
477		turnstile_broadcast(ts, TS_EXCLUSIVE_QUEUE);
478		turnstile_unpend(ts, TS_SHARED_LOCK);
479		turnstile_chain_unlock(&rw->lock_object);
480		break;
481	}
482	lock_profile_release_lock(&rw->lock_object);
483}
484
485/*
486 * This function is called when we are unable to obtain a write lock on the
487 * first try.  This means that at least one other thread holds either a
488 * read or write lock.
489 */
490void
491_rw_wlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
492{
493	struct turnstile *ts;
494#ifdef ADAPTIVE_RWLOCKS
495	volatile struct thread *owner;
496#endif
497	uintptr_t v;
498
499	if (rw_wlocked(rw)) {
500		KASSERT(rw->lock_object.lo_flags & RW_RECURSE,
501		    ("%s: recursing but non-recursive rw %s @ %s:%d\n",
502		    __func__, rw->lock_object.lo_name, file, line));
503		rw->rw_recurse++;
504		atomic_set_ptr(&rw->rw_lock, RW_LOCK_RECURSED);
505		if (LOCK_LOG_TEST(&rw->lock_object, 0))
506			CTR2(KTR_LOCK, "%s: %p recursing", __func__, rw);
507		return;
508	}
509
510	if (LOCK_LOG_TEST(&rw->lock_object, 0))
511		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
512		    rw->lock_object.lo_name, (void *)rw->rw_lock, file, line);
513
514	while (!_rw_write_lock(rw, tid)) {
515		ts = turnstile_trywait(&rw->lock_object);
516		v = rw->rw_lock;
517
518		/*
519		 * If the lock was released while spinning on the
520		 * turnstile chain lock, try again.
521		 */
522		if (v == RW_UNLOCKED) {
523			turnstile_cancel(ts);
524			cpu_spinwait();
525			continue;
526		}
527
528		/*
529		 * If the lock was released by a writer with both readers
530		 * and writers waiting and a reader hasn't woken up and
531		 * acquired the lock yet, rw_lock will be set to the
532		 * value RW_UNLOCKED | RW_LOCK_WRITE_WAITERS.  If we see
533		 * that value, try to acquire it once.  Note that we have
534		 * to preserve the RW_LOCK_WRITE_WAITERS flag as there are
535		 * other writers waiting still.  If we fail, restart the
536		 * loop.
537		 */
538		if (v == (RW_UNLOCKED | RW_LOCK_WRITE_WAITERS)) {
539			if (atomic_cmpset_acq_ptr(&rw->rw_lock,
540			    RW_UNLOCKED | RW_LOCK_WRITE_WAITERS,
541			    tid | RW_LOCK_WRITE_WAITERS)) {
542				turnstile_claim(ts);
543				CTR2(KTR_LOCK, "%s: %p claimed by new writer",
544				    __func__, rw);
545				break;
546			}
547			turnstile_cancel(ts);
548			cpu_spinwait();
549			continue;
550		}
551
552		/*
553		 * If the RW_LOCK_WRITE_WAITERS flag isn't set, then try to
554		 * set it.  If we fail to set it, then loop back and try
555		 * again.
556		 */
557		if (!(v & RW_LOCK_WRITE_WAITERS)) {
558			if (!atomic_cmpset_ptr(&rw->rw_lock, v,
559			    v | RW_LOCK_WRITE_WAITERS)) {
560				turnstile_cancel(ts);
561				cpu_spinwait();
562				continue;
563			}
564			if (LOCK_LOG_TEST(&rw->lock_object, 0))
565				CTR2(KTR_LOCK, "%s: %p set write waiters flag",
566				    __func__, rw);
567		}
568
569#ifdef ADAPTIVE_RWLOCKS
570		/*
571		 * If the lock is write locked and the owner is
572		 * running on another CPU, spin until the owner stops
573		 * running or the state of the lock changes.
574		 */
575		owner = (struct thread *)RW_OWNER(v);
576		if (!(v & RW_LOCK_READ) && TD_IS_RUNNING(owner)) {
577			turnstile_cancel(ts);
578			if (LOCK_LOG_TEST(&rw->lock_object, 0))
579				CTR3(KTR_LOCK, "%s: spinning on %p held by %p",
580				    __func__, rw, owner);
581			while ((struct thread*)RW_OWNER(rw->rw_lock)== owner &&
582			    TD_IS_RUNNING(owner))
583				cpu_spinwait();
584			continue;
585		}
586#endif
587
588		/*
589		 * We were unable to acquire the lock and the write waiters
590		 * flag is set, so we must block on the turnstile.
591		 */
592		if (LOCK_LOG_TEST(&rw->lock_object, 0))
593			CTR2(KTR_LOCK, "%s: %p blocking on turnstile", __func__,
594			    rw);
595		turnstile_wait(ts, rw_owner(rw), TS_EXCLUSIVE_QUEUE);
596		if (LOCK_LOG_TEST(&rw->lock_object, 0))
597			CTR2(KTR_LOCK, "%s: %p resuming from turnstile",
598			    __func__, rw);
599	}
600}
601
602/*
603 * This function is called if the first try at releasing a write lock failed.
604 * This means that one of the 2 waiter bits must be set indicating that at
605 * least one thread is waiting on this lock.
606 */
607void
608_rw_wunlock_hard(struct rwlock *rw, uintptr_t tid, const char *file, int line)
609{
610	struct turnstile *ts;
611	uintptr_t v;
612	int queue;
613
614	if (rw_wlocked(rw) && rw_recursed(rw)) {
615		if ((--rw->rw_recurse) == 0)
616			atomic_clear_ptr(&rw->rw_lock, RW_LOCK_RECURSED);
617		if (LOCK_LOG_TEST(&rw->lock_object, 0))
618			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, rw);
619		return;
620	}
621
622	KASSERT(rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS),
623	    ("%s: neither of the waiter flags are set", __func__));
624
625	if (LOCK_LOG_TEST(&rw->lock_object, 0))
626		CTR2(KTR_LOCK, "%s: %p contested", __func__, rw);
627
628	turnstile_chain_lock(&rw->lock_object);
629	ts = turnstile_lookup(&rw->lock_object);
630
631#ifdef ADAPTIVE_RWLOCKS
632	/*
633	 * There might not be a turnstile for this lock if all of
634	 * the waiters are adaptively spinning.  In that case, just
635	 * reset the lock to the unlocked state and return.
636	 */
637	if (ts == NULL) {
638		atomic_store_rel_ptr(&rw->rw_lock, RW_UNLOCKED);
639		if (LOCK_LOG_TEST(&rw->lock_object, 0))
640			CTR2(KTR_LOCK, "%s: %p no sleepers", __func__, rw);
641		turnstile_chain_unlock(&rw->lock_object);
642		return;
643	}
644#else
645	MPASS(ts != NULL);
646#endif
647
648	/*
649	 * Use the same algo as sx locks for now.  Prefer waking up shared
650	 * waiters if we have any over writers.  This is probably not ideal.
651	 *
652	 * 'v' is the value we are going to write back to rw_lock.  If we
653	 * have waiters on both queues, we need to preserve the state of
654	 * the waiter flag for the queue we don't wake up.  For now this is
655	 * hardcoded for the algorithm mentioned above.
656	 *
657	 * In the case of both readers and writers waiting we wakeup the
658	 * readers but leave the RW_LOCK_WRITE_WAITERS flag set.  If a
659	 * new writer comes in before a reader it will claim the lock up
660	 * above.  There is probably a potential priority inversion in
661	 * there that could be worked around either by waking both queues
662	 * of waiters or doing some complicated lock handoff gymnastics.
663	 *
664	 * Note that in the ADAPTIVE_RWLOCKS case, if both flags are
665	 * set, there might not be any actual writers on the turnstile
666	 * as they might all be spinning.  In that case, we don't want
667	 * to preserve the RW_LOCK_WRITE_WAITERS flag as the turnstile
668	 * is going to go away once we wakeup all the readers.
669	 */
670	v = RW_UNLOCKED;
671	if (rw->rw_lock & RW_LOCK_READ_WAITERS) {
672		queue = TS_SHARED_QUEUE;
673#ifdef ADAPTIVE_RWLOCKS
674		if (rw->rw_lock & RW_LOCK_WRITE_WAITERS &&
675		    !turnstile_empty(ts, TS_EXCLUSIVE_QUEUE))
676			v |= RW_LOCK_WRITE_WAITERS;
677#else
678		v |= (rw->rw_lock & RW_LOCK_WRITE_WAITERS);
679#endif
680	} else
681		queue = TS_EXCLUSIVE_QUEUE;
682
683#ifdef ADAPTIVE_RWLOCKS
684	/*
685	 * We have to make sure that we actually have waiters to
686	 * wakeup.  If they are all spinning, then we just need to
687	 * disown the turnstile and return.
688	 */
689	if (turnstile_empty(ts, queue)) {
690		if (LOCK_LOG_TEST(&rw->lock_object, 0))
691			CTR2(KTR_LOCK, "%s: %p no sleepers 2", __func__, rw);
692		atomic_store_rel_ptr(&rw->rw_lock, v);
693		turnstile_disown(ts);
694		turnstile_chain_unlock(&rw->lock_object);
695		return;
696	}
697#endif
698
699	/* Wake up all waiters for the specific queue. */
700	if (LOCK_LOG_TEST(&rw->lock_object, 0))
701		CTR3(KTR_LOCK, "%s: %p waking up %s waiters", __func__, rw,
702		    queue == TS_SHARED_QUEUE ? "read" : "write");
703	turnstile_broadcast(ts, queue);
704	atomic_store_rel_ptr(&rw->rw_lock, v);
705	turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
706	turnstile_chain_unlock(&rw->lock_object);
707}
708
709/*
710 * Attempt to do a non-blocking upgrade from a read lock to a write
711 * lock.  This will only succeed if this thread holds a single read
712 * lock.  Returns true if the upgrade succeeded and false otherwise.
713 */
714int
715_rw_try_upgrade(struct rwlock *rw, const char *file, int line)
716{
717	uintptr_t v, tid;
718	struct turnstile *ts;
719	int success;
720
721	KASSERT(rw->rw_lock != RW_DESTROYED,
722	    ("rw_try_upgrade() of destroyed rwlock @ %s:%d", file, line));
723	_rw_assert(rw, RA_RLOCKED, file, line);
724
725	/*
726	 * Attempt to switch from one reader to a writer.  If there
727	 * are any write waiters, then we will have to lock the
728	 * turnstile first to prevent races with another writer
729	 * calling turnstile_wait() before we have claimed this
730	 * turnstile.  So, do the simple case of no waiters first.
731	 */
732	tid = (uintptr_t)curthread;
733	if (!(rw->rw_lock & RW_LOCK_WRITE_WAITERS)) {
734		success = atomic_cmpset_ptr(&rw->rw_lock, RW_READERS_LOCK(1),
735		    tid);
736		goto out;
737	}
738
739	/*
740	 * Ok, we think we have write waiters, so lock the
741	 * turnstile.
742	 */
743	ts = turnstile_trywait(&rw->lock_object);
744
745	/*
746	 * Try to switch from one reader to a writer again.  This time
747	 * we honor the current state of the RW_LOCK_WRITE_WAITERS
748	 * flag.  If we obtain the lock with the flag set, then claim
749	 * ownership of the turnstile.  In the ADAPTIVE_RWLOCKS case
750	 * it is possible for there to not be an associated turnstile
751	 * even though there are waiters if all of the waiters are
752	 * spinning.
753	 */
754	v = rw->rw_lock & RW_LOCK_WRITE_WAITERS;
755	success = atomic_cmpset_ptr(&rw->rw_lock, RW_READERS_LOCK(1) | v,
756	    tid | v);
757#ifdef ADAPTIVE_RWLOCKS
758	if (success && v && turnstile_lookup(&rw->lock_object) != NULL)
759#else
760	if (success && v)
761#endif
762		turnstile_claim(ts);
763	else
764		turnstile_cancel(ts);
765out:
766	LOCK_LOG_TRY("WUPGRADE", &rw->lock_object, 0, success, file, line);
767	if (success)
768		WITNESS_UPGRADE(&rw->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
769		    file, line);
770	return (success);
771}
772
773/*
774 * Downgrade a write lock into a single read lock.
775 */
776void
777_rw_downgrade(struct rwlock *rw, const char *file, int line)
778{
779	struct turnstile *ts;
780	uintptr_t tid, v;
781
782	KASSERT(rw->rw_lock != RW_DESTROYED,
783	    ("rw_downgrade() of destroyed rwlock @ %s:%d", file, line));
784	_rw_assert(rw, RA_WLOCKED | RA_NOTRECURSED, file, line);
785#ifndef INVARIANTS
786	if (rw_recursed(rw))
787		panic("downgrade of a recursed lock");
788#endif
789
790	WITNESS_DOWNGRADE(&rw->lock_object, 0, file, line);
791
792	/*
793	 * Convert from a writer to a single reader.  First we handle
794	 * the easy case with no waiters.  If there are any waiters, we
795	 * lock the turnstile, "disown" the lock, and awaken any read
796	 * waiters.
797	 */
798	tid = (uintptr_t)curthread;
799	if (atomic_cmpset_rel_ptr(&rw->rw_lock, tid, RW_READERS_LOCK(1)))
800		goto out;
801
802	/*
803	 * Ok, we think we have waiters, so lock the turnstile so we can
804	 * read the waiter flags without any races.
805	 */
806	turnstile_chain_lock(&rw->lock_object);
807	v = rw->rw_lock;
808	MPASS(v & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS));
809
810	/*
811	 * Downgrade from a write lock while preserving
812	 * RW_LOCK_WRITE_WAITERS and give up ownership of the
813	 * turnstile.  If there are any read waiters, wake them up.
814	 *
815	 * For ADAPTIVE_RWLOCKS, we have to allow for the fact that
816	 * all of the read waiters might be spinning.  In that case,
817	 * act as if RW_LOCK_READ_WAITERS is not set.  Also, only
818	 * preserve the RW_LOCK_WRITE_WAITERS flag if at least one
819	 * writer is blocked on the turnstile.
820	 */
821	ts = turnstile_lookup(&rw->lock_object);
822#ifdef ADAPTIVE_RWLOCKS
823	if (ts == NULL)
824		v &= ~(RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS);
825	else if (v & RW_LOCK_READ_WAITERS &&
826	    turnstile_empty(ts, TS_SHARED_QUEUE))
827		v &= ~RW_LOCK_READ_WAITERS;
828	else if (v & RW_LOCK_WRITE_WAITERS &&
829	    turnstile_empty(ts, TS_EXCLUSIVE_QUEUE))
830		v &= ~RW_LOCK_WRITE_WAITERS;
831#else
832	MPASS(ts != NULL);
833#endif
834	if (v & RW_LOCK_READ_WAITERS)
835		turnstile_broadcast(ts, TS_SHARED_QUEUE);
836	atomic_store_rel_ptr(&rw->rw_lock, RW_READERS_LOCK(1) |
837	    (v & RW_LOCK_WRITE_WAITERS));
838	if (v & RW_LOCK_READ_WAITERS)
839		turnstile_unpend(ts, TS_EXCLUSIVE_LOCK);
840	else if (ts)
841		turnstile_disown(ts);
842	turnstile_chain_unlock(&rw->lock_object);
843out:
844	LOCK_LOG_LOCK("WDOWNGRADE", &rw->lock_object, 0, 0, file, line);
845}
846
847#ifdef INVARIANT_SUPPORT
848#ifndef INVARIANTS
849#undef _rw_assert
850#endif
851
852/*
853 * In the non-WITNESS case, rw_assert() can only detect that at least
854 * *some* thread owns an rlock, but it cannot guarantee that *this*
855 * thread owns an rlock.
856 */
857void
858_rw_assert(struct rwlock *rw, int what, const char *file, int line)
859{
860
861	if (panicstr != NULL)
862		return;
863	switch (what) {
864	case RA_LOCKED:
865	case RA_LOCKED | RA_RECURSED:
866	case RA_LOCKED | RA_NOTRECURSED:
867	case RA_RLOCKED:
868#ifdef WITNESS
869		witness_assert(&rw->lock_object, what, file, line);
870#else
871		/*
872		 * If some other thread has a write lock or we have one
873		 * and are asserting a read lock, fail.  Also, if no one
874		 * has a lock at all, fail.
875		 */
876		if (rw->rw_lock == RW_UNLOCKED ||
877		    (!(rw->rw_lock & RW_LOCK_READ) && (what == RA_RLOCKED ||
878		    rw_wowner(rw) != curthread)))
879			panic("Lock %s not %slocked @ %s:%d\n",
880			    rw->lock_object.lo_name, (what == RA_RLOCKED) ?
881			    "read " : "", file, line);
882
883		if (!(rw->rw_lock & RW_LOCK_READ)) {
884			if (rw_recursed(rw)) {
885				if (what & RA_NOTRECURSED)
886					panic("Lock %s recursed @ %s:%d\n",
887					    rw->lock_object.lo_name, file,
888					    line);
889			} else if (what & RA_RECURSED)
890				panic("Lock %s not recursed @ %s:%d\n",
891				    rw->lock_object.lo_name, file, line);
892		}
893#endif
894		break;
895	case RA_WLOCKED:
896	case RA_WLOCKED | RA_RECURSED:
897	case RA_WLOCKED | RA_NOTRECURSED:
898		if (rw_wowner(rw) != curthread)
899			panic("Lock %s not exclusively locked @ %s:%d\n",
900			    rw->lock_object.lo_name, file, line);
901		if (rw_recursed(rw)) {
902			if (what & RA_NOTRECURSED)
903				panic("Lock %s recursed @ %s:%d\n",
904				    rw->lock_object.lo_name, file, line);
905		} else if (what & RA_RECURSED)
906			panic("Lock %s not recursed @ %s:%d\n",
907			    rw->lock_object.lo_name, file, line);
908		break;
909	case RA_UNLOCKED:
910#ifdef WITNESS
911		witness_assert(&rw->lock_object, what, file, line);
912#else
913		/*
914		 * If we hold a write lock fail.  We can't reliably check
915		 * to see if we hold a read lock or not.
916		 */
917		if (rw_wowner(rw) == curthread)
918			panic("Lock %s exclusively locked @ %s:%d\n",
919			    rw->lock_object.lo_name, file, line);
920#endif
921		break;
922	default:
923		panic("Unknown rw lock assertion: %d @ %s:%d", what, file,
924		    line);
925	}
926}
927#endif /* INVARIANT_SUPPORT */
928
929#ifdef DDB
930void
931db_show_rwlock(struct lock_object *lock)
932{
933	struct rwlock *rw;
934	struct thread *td;
935
936	rw = (struct rwlock *)lock;
937
938	db_printf(" state: ");
939	if (rw->rw_lock == RW_UNLOCKED)
940		db_printf("UNLOCKED\n");
941	else if (rw->rw_lock == RW_DESTROYED) {
942		db_printf("DESTROYED\n");
943		return;
944	} else if (rw->rw_lock & RW_LOCK_READ)
945		db_printf("RLOCK: %ju locks\n",
946		    (uintmax_t)(RW_READERS(rw->rw_lock)));
947	else {
948		td = rw_wowner(rw);
949		db_printf("WLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
950		    td->td_tid, td->td_proc->p_pid, td->td_proc->p_comm);
951		if (rw_recursed(rw))
952			db_printf(" recursed: %u\n", rw->rw_recurse);
953	}
954	db_printf(" waiters: ");
955	switch (rw->rw_lock & (RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS)) {
956	case RW_LOCK_READ_WAITERS:
957		db_printf("readers\n");
958		break;
959	case RW_LOCK_WRITE_WAITERS:
960		db_printf("writers\n");
961		break;
962	case RW_LOCK_READ_WAITERS | RW_LOCK_WRITE_WAITERS:
963		db_printf("readers and writers\n");
964		break;
965	default:
966		db_printf("none\n");
967		break;
968	}
969}
970
971#endif
972