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