Home | History | Annotate | Line # | Download | only in kern
kern_rwlock.c revision 1.59.2.4
      1 /*	$NetBSD: kern_rwlock.c,v 1.59.2.4 2020/01/22 11:40:17 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2002, 2006, 2007, 2008, 2009, 2019, 2020
      5  *     The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Jason R. Thorpe and Andrew Doran.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Kernel reader/writer lock implementation, modeled after those
     35  * found in Solaris, a description of which can be found in:
     36  *
     37  *	Solaris Internals: Core Kernel Architecture, Jim Mauro and
     38  *	    Richard McDougall.
     39  */
     40 
     41 #include <sys/cdefs.h>
     42 __KERNEL_RCSID(0, "$NetBSD: kern_rwlock.c,v 1.59.2.4 2020/01/22 11:40:17 ad Exp $");
     43 
     44 #include "opt_lockdebug.h"
     45 
     46 #define	__RWLOCK_PRIVATE
     47 
     48 #include <sys/param.h>
     49 #include <sys/proc.h>
     50 #include <sys/rwlock.h>
     51 #include <sys/sched.h>
     52 #include <sys/sleepq.h>
     53 #include <sys/systm.h>
     54 #include <sys/lockdebug.h>
     55 #include <sys/cpu.h>
     56 #include <sys/atomic.h>
     57 #include <sys/lock.h>
     58 #include <sys/pserialize.h>
     59 
     60 #include <dev/lockstat.h>
     61 
     62 #include <machine/rwlock.h>
     63 
     64 /*
     65  * LOCKDEBUG
     66  */
     67 
     68 #define	RW_DEBUG_P(rw)		(((rw)->rw_owner & RW_NODEBUG) == 0)
     69 
     70 #define	RW_WANTLOCK(rw, op) \
     71     LOCKDEBUG_WANTLOCK(RW_DEBUG_P(rw), (rw), \
     72         (uintptr_t)__builtin_return_address(0), op == RW_READER);
     73 #define	RW_LOCKED(rw, op) \
     74     LOCKDEBUG_LOCKED(RW_DEBUG_P(rw), (rw), NULL, \
     75         (uintptr_t)__builtin_return_address(0), op == RW_READER);
     76 #define	RW_UNLOCKED(rw, op) \
     77     LOCKDEBUG_UNLOCKED(RW_DEBUG_P(rw), (rw), \
     78         (uintptr_t)__builtin_return_address(0), op == RW_READER);
     79 
     80 /*
     81  * DIAGNOSTIC
     82  */
     83 
     84 #if defined(DIAGNOSTIC)
     85 #define	RW_ASSERT(rw, cond) \
     86 do { \
     87 	if (__predict_false(!(cond))) \
     88 		rw_abort(__func__, __LINE__, rw, "assertion failed: " #cond);\
     89 } while (/* CONSTCOND */ 0)
     90 #else
     91 #define	RW_ASSERT(rw, cond)	/* nothing */
     92 #endif	/* DIAGNOSTIC */
     93 
     94 /*
     95  * Memory barriers.
     96  */
     97 #ifdef __HAVE_ATOMIC_AS_MEMBAR
     98 #define	RW_MEMBAR_ENTER()
     99 #define	RW_MEMBAR_EXIT()
    100 #define	RW_MEMBAR_PRODUCER()
    101 #else
    102 #define	RW_MEMBAR_ENTER()		membar_enter()
    103 #define	RW_MEMBAR_EXIT()		membar_exit()
    104 #define	RW_MEMBAR_PRODUCER()		membar_producer()
    105 #endif
    106 
    107 /*
    108  * For platforms that do not provide stubs, or for the LOCKDEBUG case.
    109  */
    110 #ifdef LOCKDEBUG
    111 #undef	__HAVE_RW_STUBS
    112 #endif
    113 
    114 #ifndef __HAVE_RW_STUBS
    115 __strong_alias(rw_enter,rw_vector_enter);
    116 __strong_alias(rw_exit,rw_vector_exit);
    117 __strong_alias(rw_tryenter,rw_vector_tryenter);
    118 #endif
    119 
    120 static void	rw_abort(const char *, size_t, krwlock_t *, const char *);
    121 static void	rw_dump(const volatile void *, lockop_printer_t);
    122 static lwp_t	*rw_owner(wchan_t);
    123 
    124 lockops_t rwlock_lockops = {
    125 	.lo_name = "Reader / writer lock",
    126 	.lo_type = LOCKOPS_SLEEP,
    127 	.lo_dump = rw_dump,
    128 };
    129 
    130 syncobj_t rw_syncobj = {
    131 	.sobj_flag	= SOBJ_SLEEPQ_SORTED,
    132 	.sobj_unsleep	= turnstile_unsleep,
    133 	.sobj_changepri	= turnstile_changepri,
    134 	.sobj_lendpri	= sleepq_lendpri,
    135 	.sobj_owner	= rw_owner,
    136 };
    137 
    138 /*
    139  * rw_cas:
    140  *
    141  *	Do an atomic compare-and-swap on the lock word.
    142  */
    143 static inline uintptr_t
    144 rw_cas(krwlock_t *rw, uintptr_t o, uintptr_t n)
    145 {
    146 
    147 	return (uintptr_t)atomic_cas_ptr((volatile void *)&rw->rw_owner,
    148 	    (void *)o, (void *)n);
    149 }
    150 
    151 /*
    152  * rw_swap:
    153  *
    154  *	Do an atomic swap of the lock word.  This is used only when it's
    155  *	known that the lock word is set up such that it can't be changed
    156  *	behind us (assert this), so there's no point considering the result.
    157  */
    158 static inline void
    159 rw_swap(krwlock_t *rw, uintptr_t o, uintptr_t n)
    160 {
    161 
    162 	n = (uintptr_t)atomic_swap_ptr((volatile void *)&rw->rw_owner,
    163 	    (void *)n);
    164 
    165 	RW_ASSERT(rw, n == o);
    166 	RW_ASSERT(rw, (o & RW_HAS_WAITERS) != 0);
    167 }
    168 
    169 /*
    170  * rw_dump:
    171  *
    172  *	Dump the contents of a rwlock structure.
    173  */
    174 static void
    175 rw_dump(const volatile void *cookie, lockop_printer_t pr)
    176 {
    177 	const volatile krwlock_t *rw = cookie;
    178 
    179 	pr("owner/count  : %#018lx flags    : %#018x\n",
    180 	    (long)RW_OWNER(rw), (int)RW_FLAGS(rw));
    181 }
    182 
    183 /*
    184  * rw_abort:
    185  *
    186  *	Dump information about an error and panic the system.  This
    187  *	generates a lot of machine code in the DIAGNOSTIC case, so
    188  *	we ask the compiler to not inline it.
    189  */
    190 static void __noinline
    191 rw_abort(const char *func, size_t line, krwlock_t *rw, const char *msg)
    192 {
    193 
    194 	if (panicstr != NULL)
    195 		return;
    196 
    197 	LOCKDEBUG_ABORT(func, line, rw, &rwlock_lockops, msg);
    198 }
    199 
    200 /*
    201  * rw_init:
    202  *
    203  *	Initialize a rwlock for use.
    204  */
    205 void
    206 _rw_init(krwlock_t *rw, uintptr_t return_address)
    207 {
    208 
    209 #ifdef LOCKDEBUG
    210 	/* XXX only because the assembly stubs can't handle RW_NODEBUG */
    211 	if (LOCKDEBUG_ALLOC(rw, &rwlock_lockops, return_address))
    212 		rw->rw_owner = 0;
    213 	else
    214 		rw->rw_owner = RW_NODEBUG;
    215 #else
    216 	rw->rw_owner = 0;
    217 #endif
    218 }
    219 
    220 void
    221 rw_init(krwlock_t *rw)
    222 {
    223 
    224 	_rw_init(rw, (uintptr_t)__builtin_return_address(0));
    225 }
    226 
    227 /*
    228  * rw_destroy:
    229  *
    230  *	Tear down a rwlock.
    231  */
    232 void
    233 rw_destroy(krwlock_t *rw)
    234 {
    235 
    236 	RW_ASSERT(rw, (rw->rw_owner & ~RW_NODEBUG) == 0);
    237 	LOCKDEBUG_FREE((rw->rw_owner & RW_NODEBUG) == 0, rw);
    238 }
    239 
    240 /*
    241  * rw_oncpu:
    242  *
    243  *	Return true if an rwlock owner is running on a CPU in the system.
    244  *	If the target is waiting on the kernel big lock, then we must
    245  *	release it.  This is necessary to avoid deadlock.
    246  */
    247 static bool
    248 rw_oncpu(uintptr_t owner)
    249 {
    250 #ifdef MULTIPROCESSOR
    251 	struct cpu_info *ci;
    252 	lwp_t *l;
    253 
    254 	KASSERT(kpreempt_disabled());
    255 
    256 	if ((owner & (RW_WRITE_LOCKED|RW_HAS_WAITERS)) != RW_WRITE_LOCKED) {
    257 		return false;
    258 	}
    259 
    260 	/*
    261 	 * See lwp_dtor() why dereference of the LWP pointer is safe.
    262 	 * We must have kernel preemption disabled for that.
    263 	 */
    264 	l = (lwp_t *)(owner & RW_THREAD);
    265 	ci = l->l_cpu;
    266 
    267 	if (ci && ci->ci_curlwp == l) {
    268 		/* Target is running; do we need to block? */
    269 		return (ci->ci_biglock_wanted != l);
    270 	}
    271 #endif
    272 	/* Not running.  It may be safe to block now. */
    273 	return false;
    274 }
    275 
    276 /*
    277  * rw_vector_enter:
    278  *
    279  *	Acquire a rwlock.
    280  */
    281 void
    282 rw_vector_enter(krwlock_t *rw, const krw_t op)
    283 {
    284 	uintptr_t owner, incr, need_wait, set_wait, curthread, next;
    285 	turnstile_t *ts;
    286 	int queue;
    287 	lwp_t *l;
    288 	LOCKSTAT_TIMER(slptime);
    289 	LOCKSTAT_TIMER(slpcnt);
    290 	LOCKSTAT_TIMER(spintime);
    291 	LOCKSTAT_COUNTER(spincnt);
    292 	LOCKSTAT_FLAG(lsflag);
    293 
    294 	l = curlwp;
    295 	curthread = (uintptr_t)l;
    296 
    297 	RW_ASSERT(rw, !cpu_intr_p());
    298 	RW_ASSERT(rw, curthread != 0);
    299 	RW_WANTLOCK(rw, op);
    300 
    301 	if (panicstr == NULL) {
    302 		KDASSERT(pserialize_not_in_read_section());
    303 		LOCKDEBUG_BARRIER(&kernel_lock, 1);
    304 	}
    305 
    306 	/*
    307 	 * We play a slight trick here.  If we're a reader, we want
    308 	 * increment the read count.  If we're a writer, we want to
    309 	 * set the owner field and the WRITE_LOCKED bit.
    310 	 *
    311 	 * In the latter case, we expect those bits to be zero,
    312 	 * therefore we can use an add operation to set them, which
    313 	 * means an add operation for both cases.
    314 	 */
    315 	if (__predict_true(op == RW_READER)) {
    316 		incr = RW_READ_INCR;
    317 		set_wait = RW_HAS_WAITERS;
    318 		need_wait = RW_WRITE_LOCKED | RW_WRITE_WANTED;
    319 		queue = TS_READER_Q;
    320 	} else {
    321 		RW_ASSERT(rw, op == RW_WRITER);
    322 		incr = curthread | RW_WRITE_LOCKED;
    323 		set_wait = RW_HAS_WAITERS | RW_WRITE_WANTED;
    324 		need_wait = RW_WRITE_LOCKED | RW_THREAD;
    325 		queue = TS_WRITER_Q;
    326 	}
    327 
    328 	LOCKSTAT_ENTER(lsflag);
    329 
    330 	KPREEMPT_DISABLE(curlwp);
    331 	for (owner = rw->rw_owner;;) {
    332 		/*
    333 		 * Read the lock owner field.  If the need-to-wait
    334 		 * indicator is clear, then try to acquire the lock.
    335 		 */
    336 		if ((owner & need_wait) == 0) {
    337 			next = rw_cas(rw, owner, (owner + incr) &
    338 			    ~RW_WRITE_WANTED);
    339 			if (__predict_true(next == owner)) {
    340 				/* Got it! */
    341 				RW_MEMBAR_ENTER();
    342 				break;
    343 			}
    344 
    345 			/*
    346 			 * Didn't get it -- spin around again (we'll
    347 			 * probably sleep on the next iteration).
    348 			 */
    349 			owner = next;
    350 			continue;
    351 		}
    352 		if (__predict_false(RW_OWNER(rw) == curthread)) {
    353 			rw_abort(__func__, __LINE__, rw,
    354 			    "locking against myself");
    355 		}
    356 		/*
    357 		 * If the lock owner is running on another CPU, and
    358 		 * there are no existing waiters, then spin.
    359 		 */
    360 		if (rw_oncpu(owner)) {
    361 			LOCKSTAT_START_TIMER(lsflag, spintime);
    362 			u_int count = SPINLOCK_BACKOFF_MIN;
    363 			do {
    364 				KPREEMPT_ENABLE(curlwp);
    365 				SPINLOCK_BACKOFF(count);
    366 				KPREEMPT_DISABLE(curlwp);
    367 				owner = rw->rw_owner;
    368 			} while (rw_oncpu(owner));
    369 			LOCKSTAT_STOP_TIMER(lsflag, spintime);
    370 			LOCKSTAT_COUNT(spincnt, 1);
    371 			if ((owner & need_wait) == 0)
    372 				continue;
    373 		}
    374 
    375 		/*
    376 		 * Grab the turnstile chain lock.  Once we have that, we
    377 		 * can adjust the waiter bits and sleep queue.
    378 		 */
    379 		ts = turnstile_lookup(rw);
    380 
    381 		/*
    382 		 * Mark the rwlock as having waiters.  If the set fails,
    383 		 * then we may not need to sleep and should spin again.
    384 		 * Reload rw_owner because turnstile_lookup() may have
    385 		 * spun on the turnstile chain lock.
    386 		 */
    387 		owner = rw->rw_owner;
    388 		if ((owner & need_wait) == 0 || rw_oncpu(owner)) {
    389 			turnstile_exit(rw);
    390 			continue;
    391 		}
    392 		next = rw_cas(rw, owner, owner | set_wait);
    393 		if (__predict_false(next != owner)) {
    394 			turnstile_exit(rw);
    395 			owner = next;
    396 			continue;
    397 		}
    398 
    399 		LOCKSTAT_START_TIMER(lsflag, slptime);
    400 		turnstile_block(ts, queue, rw, &rw_syncobj);
    401 		LOCKSTAT_STOP_TIMER(lsflag, slptime);
    402 		LOCKSTAT_COUNT(slpcnt, 1);
    403 
    404 		/*
    405 		 * No need for a memory barrier because of context switch.
    406 		 * If not handed the lock, then spin again.
    407 		 */
    408 		if (op == RW_READER || (rw->rw_owner & RW_THREAD) == curthread)
    409 			break;
    410 
    411 		owner = rw->rw_owner;
    412 	}
    413 	KPREEMPT_ENABLE(curlwp);
    414 
    415 	LOCKSTAT_EVENT_RA(lsflag, rw, LB_RWLOCK |
    416 	    (op == RW_WRITER ? LB_SLEEP1 : LB_SLEEP2), slpcnt, slptime,
    417 	    (l->l_rwcallsite != 0 ? l->l_rwcallsite :
    418 	      (uintptr_t)__builtin_return_address(0)));
    419 	LOCKSTAT_EVENT_RA(lsflag, rw, LB_RWLOCK | LB_SPIN, spincnt, spintime,
    420 	    (l->l_rwcallsite != 0 ? l->l_rwcallsite :
    421 	      (uintptr_t)__builtin_return_address(0)));
    422 	LOCKSTAT_EXIT(lsflag);
    423 
    424 	RW_ASSERT(rw, (op != RW_READER && RW_OWNER(rw) == curthread) ||
    425 	    (op == RW_READER && RW_COUNT(rw) != 0));
    426 	RW_LOCKED(rw, op);
    427 }
    428 
    429 /*
    430  * rw_vector_exit:
    431  *
    432  *	Release a rwlock.
    433  */
    434 void
    435 rw_vector_exit(krwlock_t *rw)
    436 {
    437 	uintptr_t curthread, owner, decr, newown, next;
    438 	turnstile_t *ts;
    439 	int rcnt, wcnt;
    440 	lwp_t *l;
    441 
    442 	l = curlwp;
    443 	curthread = (uintptr_t)l;
    444 	RW_ASSERT(rw, curthread != 0);
    445 
    446 	/*
    447 	 * Again, we use a trick.  Since we used an add operation to
    448 	 * set the required lock bits, we can use a subtract to clear
    449 	 * them, which makes the read-release and write-release path
    450 	 * the same.
    451 	 */
    452 	owner = rw->rw_owner;
    453 	if (__predict_false((owner & RW_WRITE_LOCKED) != 0)) {
    454 		RW_UNLOCKED(rw, RW_WRITER);
    455 		RW_ASSERT(rw, RW_OWNER(rw) == curthread);
    456 		decr = curthread | RW_WRITE_LOCKED;
    457 	} else {
    458 		RW_UNLOCKED(rw, RW_READER);
    459 		RW_ASSERT(rw, RW_COUNT(rw) != 0);
    460 		decr = RW_READ_INCR;
    461 	}
    462 
    463 	/*
    464 	 * Compute what we expect the new value of the lock to be. Only
    465 	 * proceed to do direct handoff if there are waiters, and if the
    466 	 * lock would become unowned.
    467 	 */
    468 	RW_MEMBAR_EXIT();
    469 	for (;;) {
    470 		newown = (owner - decr);
    471 		if ((newown & (RW_THREAD | RW_HAS_WAITERS)) == RW_HAS_WAITERS)
    472 			break;
    473 		next = rw_cas(rw, owner, newown);
    474 		if (__predict_true(next == owner))
    475 			return;
    476 		owner = next;
    477 	}
    478 
    479 	/*
    480 	 * Grab the turnstile chain lock.  This gets the interlock
    481 	 * on the sleep queue.  Once we have that, we can adjust the
    482 	 * waiter bits.
    483 	 */
    484 	ts = turnstile_lookup(rw);
    485 	owner = rw->rw_owner;
    486 	RW_ASSERT(rw, ts != NULL);
    487 	RW_ASSERT(rw, (owner & RW_HAS_WAITERS) != 0);
    488 
    489 	wcnt = TS_WAITERS(ts, TS_WRITER_Q);
    490 	rcnt = TS_WAITERS(ts, TS_READER_Q);
    491 
    492 	/*
    493 	 * Give the lock away.
    494 	 *
    495 	 * If we are releasing a write lock, then prefer to wake all
    496 	 * outstanding readers.  Otherwise, wake one writer if there
    497 	 * are outstanding readers, or all writers if there are no
    498 	 * pending readers.  If waking one specific writer, the writer
    499 	 * is handed the lock here.  If waking multiple writers, we
    500 	 * set WRITE_WANTED to block out new readers, and let them
    501 	 * do the work of acquiring the lock in rw_vector_enter().
    502 	 */
    503 	if (rcnt == 0 || decr == RW_READ_INCR) {
    504 		RW_ASSERT(rw, wcnt != 0);
    505 		RW_ASSERT(rw, (owner & RW_WRITE_WANTED) != 0);
    506 
    507 		if (rcnt != 0) {
    508 			/* Give the lock to the longest waiting writer. */
    509 			l = TS_FIRST(ts, TS_WRITER_Q);
    510 			newown = (uintptr_t)l | (owner & RW_NODEBUG);
    511 			newown |= RW_WRITE_LOCKED | RW_HAS_WAITERS;
    512 			if (wcnt > 1)
    513 				newown |= RW_WRITE_WANTED;
    514 			rw_swap(rw, owner, newown);
    515 			turnstile_wakeup(ts, TS_WRITER_Q, 1, l);
    516 		} else {
    517 			/* Wake all writers and let them fight it out. */
    518 			newown = owner & RW_NODEBUG;
    519 			newown |= RW_WRITE_WANTED;
    520 			rw_swap(rw, owner, newown);
    521 			turnstile_wakeup(ts, TS_WRITER_Q, wcnt, NULL);
    522 		}
    523 	} else {
    524 		RW_ASSERT(rw, rcnt != 0);
    525 
    526 		/*
    527 		 * Give the lock to all blocked readers.  If there
    528 		 * is a writer waiting, new readers that arrive
    529 		 * after the release will be blocked out.
    530 		 */
    531 		newown = owner & RW_NODEBUG;
    532 		newown += rcnt << RW_READ_COUNT_SHIFT;
    533 		if (wcnt != 0)
    534 			newown |= RW_HAS_WAITERS | RW_WRITE_WANTED;
    535 
    536 		/* Wake up all sleeping readers. */
    537 		rw_swap(rw, owner, newown);
    538 		turnstile_wakeup(ts, TS_READER_Q, rcnt, NULL);
    539 	}
    540 }
    541 
    542 /*
    543  * rw_vector_tryenter:
    544  *
    545  *	Try to acquire a rwlock.
    546  */
    547 int
    548 rw_vector_tryenter(krwlock_t *rw, const krw_t op)
    549 {
    550 	uintptr_t curthread, owner, incr, need_wait, next;
    551 	lwp_t *l;
    552 
    553 	l = curlwp;
    554 	curthread = (uintptr_t)l;
    555 
    556 	RW_ASSERT(rw, curthread != 0);
    557 
    558 	if (op == RW_READER) {
    559 		incr = RW_READ_INCR;
    560 		need_wait = RW_WRITE_LOCKED | RW_WRITE_WANTED;
    561 	} else {
    562 		RW_ASSERT(rw, op == RW_WRITER);
    563 		incr = curthread | RW_WRITE_LOCKED;
    564 		need_wait = RW_WRITE_LOCKED | RW_THREAD;
    565 	}
    566 
    567 	for (owner = rw->rw_owner;; owner = next) {
    568 		if (__predict_false((owner & need_wait) != 0))
    569 			return 0;
    570 		next = rw_cas(rw, owner, owner + incr);
    571 		if (__predict_true(next == owner)) {
    572 			/* Got it! */
    573 			break;
    574 		}
    575 	}
    576 
    577 	RW_WANTLOCK(rw, op);
    578 	RW_LOCKED(rw, op);
    579 	RW_ASSERT(rw, (op != RW_READER && RW_OWNER(rw) == curthread) ||
    580 	    (op == RW_READER && RW_COUNT(rw) != 0));
    581 
    582 	RW_MEMBAR_ENTER();
    583 	return 1;
    584 }
    585 
    586 /*
    587  * rw_downgrade:
    588  *
    589  *	Downgrade a write lock to a read lock.
    590  */
    591 void
    592 rw_downgrade(krwlock_t *rw)
    593 {
    594 	uintptr_t owner, curthread, newown, next;
    595 	turnstile_t *ts;
    596 	int rcnt, wcnt;
    597 	lwp_t *l;
    598 
    599 	l = curlwp;
    600 	curthread = (uintptr_t)l;
    601 	RW_ASSERT(rw, curthread != 0);
    602 	RW_ASSERT(rw, (rw->rw_owner & RW_WRITE_LOCKED) != 0);
    603 	RW_ASSERT(rw, RW_OWNER(rw) == curthread);
    604 	RW_UNLOCKED(rw, RW_WRITER);
    605 #if !defined(DIAGNOSTIC)
    606 	__USE(curthread);
    607 #endif
    608 
    609 	RW_MEMBAR_PRODUCER();
    610 
    611 	for (owner = rw->rw_owner;; owner = next) {
    612 		/*
    613 		 * If there are no waiters we can do this the easy way.  Try
    614 		 * swapping us down to one read hold.  If it fails, the lock
    615 		 * condition has changed and we most likely now have
    616 		 * waiters.
    617 		 */
    618 		if ((owner & RW_HAS_WAITERS) == 0) {
    619 			newown = (owner & RW_NODEBUG);
    620 			next = rw_cas(rw, owner, newown + RW_READ_INCR);
    621 			if (__predict_true(next == owner)) {
    622 				RW_LOCKED(rw, RW_READER);
    623 				RW_ASSERT(rw,
    624 				    (rw->rw_owner & RW_WRITE_LOCKED) == 0);
    625 				RW_ASSERT(rw, RW_COUNT(rw) != 0);
    626 				return;
    627 			}
    628 			continue;
    629 		}
    630 
    631 		/*
    632 		 * Grab the turnstile chain lock.  This gets the interlock
    633 		 * on the sleep queue.  Once we have that, we can adjust the
    634 		 * waiter bits.
    635 		 */
    636 		ts = turnstile_lookup(rw);
    637 		RW_ASSERT(rw, ts != NULL);
    638 
    639 		rcnt = TS_WAITERS(ts, TS_READER_Q);
    640 		wcnt = TS_WAITERS(ts, TS_WRITER_Q);
    641 
    642 		if (rcnt == 0) {
    643 			/*
    644 			 * If there are no readers, just preserve the
    645 			 * waiters bits, swap us down to one read hold and
    646 			 * return.
    647 			 */
    648 			RW_ASSERT(rw, wcnt != 0);
    649 			RW_ASSERT(rw, (rw->rw_owner & RW_WRITE_WANTED) != 0);
    650 			RW_ASSERT(rw, (rw->rw_owner & RW_HAS_WAITERS) != 0);
    651 
    652 			newown = owner & RW_NODEBUG;
    653 			newown |= RW_READ_INCR | RW_HAS_WAITERS |
    654 			    RW_WRITE_WANTED;
    655 			next = rw_cas(rw, owner, newown);
    656 			turnstile_exit(rw);
    657 			if (__predict_true(next == owner))
    658 				break;
    659 		} else {
    660 			/*
    661 			 * Give the lock to all blocked readers.  We may
    662 			 * retain one read hold if downgrading.  If there is
    663 			 * a writer waiting, new readers will be blocked
    664 			 * out.
    665 			 */
    666 			newown = owner & RW_NODEBUG;
    667 			newown += (rcnt << RW_READ_COUNT_SHIFT) + RW_READ_INCR;
    668 			if (wcnt != 0)
    669 				newown |= RW_HAS_WAITERS | RW_WRITE_WANTED;
    670 
    671 			next = rw_cas(rw, owner, newown);
    672 			if (__predict_true(next == owner)) {
    673 				/* Wake up all sleeping readers. */
    674 				turnstile_wakeup(ts, TS_READER_Q, rcnt, NULL);
    675 				break;
    676 			}
    677 			turnstile_exit(rw);
    678 		}
    679 	}
    680 
    681 	RW_WANTLOCK(rw, RW_READER);
    682 	RW_LOCKED(rw, RW_READER);
    683 	RW_ASSERT(rw, (rw->rw_owner & RW_WRITE_LOCKED) == 0);
    684 	RW_ASSERT(rw, RW_COUNT(rw) != 0);
    685 }
    686 
    687 /*
    688  * rw_tryupgrade:
    689  *
    690  *	Try to upgrade a read lock to a write lock.  We must be the only
    691  *	reader.
    692  */
    693 int
    694 rw_tryupgrade(krwlock_t *rw)
    695 {
    696 	uintptr_t owner, curthread, newown, next;
    697 	struct lwp *l;
    698 
    699 	l = curlwp;
    700 	curthread = (uintptr_t)l;
    701 	RW_ASSERT(rw, curthread != 0);
    702 	RW_ASSERT(rw, rw_read_held(rw));
    703 
    704 	for (owner = RW_READ_INCR;; owner = next) {
    705 		newown = curthread | RW_WRITE_LOCKED | (owner & ~RW_THREAD);
    706 		next = rw_cas(rw, owner, newown);
    707 		if (__predict_true(next == owner)) {
    708 			RW_MEMBAR_PRODUCER();
    709 			break;
    710 		}
    711 		RW_ASSERT(rw, (next & RW_WRITE_LOCKED) == 0);
    712 		if (__predict_false((next & RW_THREAD) != RW_READ_INCR)) {
    713 			RW_ASSERT(rw, (next & RW_THREAD) != 0);
    714 			return 0;
    715 		}
    716 	}
    717 
    718 	RW_UNLOCKED(rw, RW_READER);
    719 	RW_WANTLOCK(rw, RW_WRITER);
    720 	RW_LOCKED(rw, RW_WRITER);
    721 	RW_ASSERT(rw, rw->rw_owner & RW_WRITE_LOCKED);
    722 	RW_ASSERT(rw, RW_OWNER(rw) == curthread);
    723 
    724 	return 1;
    725 }
    726 
    727 /*
    728  * rw_read_held:
    729  *
    730  *	Returns true if the rwlock is held for reading.  Must only be
    731  *	used for diagnostic assertions, and never be used to make
    732  * 	decisions about how to use a rwlock.
    733  */
    734 int
    735 rw_read_held(krwlock_t *rw)
    736 {
    737 	uintptr_t owner;
    738 
    739 	if (rw == NULL)
    740 		return 0;
    741 	owner = rw->rw_owner;
    742 	return (owner & RW_WRITE_LOCKED) == 0 && (owner & RW_THREAD) != 0;
    743 }
    744 
    745 /*
    746  * rw_write_held:
    747  *
    748  *	Returns true if the rwlock is held for writing.  Must only be
    749  *	used for diagnostic assertions, and never be used to make
    750  *	decisions about how to use a rwlock.
    751  */
    752 int
    753 rw_write_held(krwlock_t *rw)
    754 {
    755 
    756 	if (rw == NULL)
    757 		return 0;
    758 	return (rw->rw_owner & (RW_WRITE_LOCKED | RW_THREAD)) ==
    759 	    (RW_WRITE_LOCKED | (uintptr_t)curlwp);
    760 }
    761 
    762 /*
    763  * rw_lock_held:
    764  *
    765  *	Returns true if the rwlock is held for reading or writing.  Must
    766  *	only be used for diagnostic assertions, and never be used to make
    767  *	decisions about how to use a rwlock.
    768  */
    769 int
    770 rw_lock_held(krwlock_t *rw)
    771 {
    772 
    773 	if (rw == NULL)
    774 		return 0;
    775 	return (rw->rw_owner & RW_THREAD) != 0;
    776 }
    777 
    778 /*
    779  * rw_owner:
    780  *
    781  *	Return the current owner of an RW lock, but only if it is write
    782  *	held.  Used for priority inheritance.
    783  */
    784 static lwp_t *
    785 rw_owner(wchan_t obj)
    786 {
    787 	krwlock_t *rw = (void *)(uintptr_t)obj; /* discard qualifiers */
    788 	uintptr_t owner = rw->rw_owner;
    789 
    790 	if ((owner & RW_WRITE_LOCKED) == 0)
    791 		return NULL;
    792 
    793 	return (void *)(owner & RW_THREAD);
    794 }
    795 
    796 /*
    797  * rw_owner_running:
    798  *
    799  *	Return true if a RW lock is unheld, or write held and the owner is
    800  *	running on a CPU.  For the pagedaemon.
    801  */
    802 bool
    803 rw_owner_running(const krwlock_t *rw)
    804 {
    805 #ifdef MULTIPROCESSOR
    806 	uintptr_t owner;
    807 	bool rv;
    808 
    809 	kpreempt_disable();
    810 	owner = rw->rw_owner;
    811 	rv = (owner & RW_THREAD) == 0 || rw_oncpu(owner);
    812 	kpreempt_enable();
    813 	return rv;
    814 #else
    815 	return rw_owner(rw) == curlwp;
    816 #endif
    817 }
    818