Home | History | Annotate | Line # | Download | only in kern
sys_futex.c revision 1.24
      1 /*	$NetBSD: sys_futex.c,v 1.24 2025/03/05 14:01:20 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2018, 2019, 2020 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Taylor R. Campbell and Jason R. Thorpe.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 __KERNEL_RCSID(0, "$NetBSD: sys_futex.c,v 1.24 2025/03/05 14:01:20 riastradh Exp $");
     34 
     35 /*
     36  * Futexes
     37  *
     38  *	The futex system call coordinates notifying threads waiting for
     39  *	changes on a 32-bit word of memory.  The word can be managed by
     40  *	CPU atomic operations in userland, without system calls, as long
     41  *	as there is no contention.
     42  *
     43  *	The simplest use case demonstrating the utility is:
     44  *
     45  *		// 32-bit word of memory shared among threads or
     46  *		// processes in userland.  lock & 1 means owned;
     47  *		// lock & 2 means there are waiters waiting.
     48  *		volatile int lock = 0;
     49  *
     50  *		int v;
     51  *
     52  *		// Acquire a lock.
     53  *		do {
     54  *			v = lock;
     55  *			if (v & 1) {
     56  *				// Lock is held.  Set a bit to say that
     57  *				// there are waiters, and wait for lock
     58  *				// to change to anything other than v;
     59  *				// then retry.
     60  *				if (atomic_cas_uint(&lock, v, v | 2) != v)
     61  *					continue;
     62  *				futex(&lock, FUTEX_WAIT, v | 2, NULL, NULL, 0,
     63  *				    0);
     64  *				continue;
     65  *			}
     66  *		} while (atomic_cas_uint(&lock, v, v | 1) != v);
     67  *		membar_acquire();
     68  *
     69  *		...
     70  *
     71  *		// Release the lock.  Optimistically assume there are
     72  *		// no waiters first until demonstrated otherwise.
     73  *		membar_release();
     74  *		if (atomic_cas_uint(&lock, 1, 0) != 1) {
     75  *			// There may be waiters.
     76  *			v = atomic_swap_uint(&lock, 0);
     77  *			// If there are still waiters, wake one.
     78  *			if (v & 2)
     79  *				futex(&lock, FUTEX_WAKE, 1, NULL, NULL, 0, 0);
     80  *		}
     81  *
     82  *	The goal is to avoid the futex system call unless there is
     83  *	contention; then if there is contention, to guarantee no missed
     84  *	wakeups.
     85  *
     86  *	For a simple implementation, futex(FUTEX_WAIT) could queue
     87  *	itself to be woken, double-check the lock word, and then sleep;
     88  *	spurious wakeups are generally a fact of life, so any
     89  *	FUTEX_WAKE could just wake every FUTEX_WAIT in the system.
     90  *
     91  *	If this were all there is to it, we could then increase
     92  *	parallelism by refining the approximation: partition the
     93  *	waiters into buckets by hashing the lock addresses to reduce
     94  *	the incidence of spurious wakeups.  But this is not all.
     95  *
     96  *	The futex(&lock, FUTEX_CMP_REQUEUE, n, timeout, &lock2, m, val)
     97  *	operation not only wakes n waiters on lock if lock == val, but
     98  *	also _transfers_ m additional waiters to lock2.  Unless wakeups
     99  *	on lock2 also trigger wakeups on lock, we cannot move waiters
    100  *	to lock2 if they merely share the same hash as waiters on lock.
    101  *	Thus, we can't approximately distribute waiters into queues by
    102  *	a hash function; we must distinguish futex queues exactly by
    103  *	lock address.
    104  *
    105  *	For now, we use a global red/black tree to index futexes.  This
    106  *	should be replaced by a lockless radix tree with a thread to
    107  *	free entries no longer in use once all lookups on all CPUs have
    108  *	completed.
    109  *
    110  *	Specifically, we maintain two maps:
    111  *
    112  *	futex_tab.va[vmspace, va] for private futexes
    113  *	futex_tab.oa[uvm_voaddr] for shared futexes
    114  *
    115  *	This implementation does not support priority inheritance.
    116  */
    117 
    118 #include <sys/param.h>
    119 #include <sys/types.h>
    120 #include <sys/atomic.h>
    121 #include <sys/condvar.h>
    122 #include <sys/futex.h>
    123 #include <sys/mutex.h>
    124 #include <sys/rbtree.h>
    125 #include <sys/queue.h>
    126 
    127 #include <sys/syscall.h>
    128 #include <sys/syscallargs.h>
    129 #include <sys/syscallvar.h>
    130 
    131 #include <uvm/uvm_extern.h>
    132 
    133 /*
    134  * Lock order:
    135  *
    136  *	futex_tab.lock
    137  *	futex::fx_qlock			ordered by kva of struct futex
    138  *	 -> futex_wait::fw_lock		only one at a time
    139  *	futex_wait::fw_lock		only one at a time
    140  *	 -> futex::fx_abortlock		only one at a time
    141  */
    142 
    143 /*
    144  * union futex_key
    145  *
    146  *	A futex is addressed either by a vmspace+va (private) or by
    147  *	a uvm_voaddr (shared).
    148  */
    149 union futex_key {
    150 	struct {
    151 		struct vmspace			*vmspace;
    152 		vaddr_t				va;
    153 	}			fk_private;
    154 	struct uvm_voaddr	fk_shared;
    155 };
    156 
    157 /*
    158  * struct futex
    159  *
    160  *	Kernel state for a futex located at a particular address in a
    161  *	particular virtual address space.
    162  *
    163  *	N.B. fx_refcnt is an unsigned long because we need to be able
    164  *	to operate on it atomically on all systems while at the same
    165  *	time rendering practically impossible the chance of it reaching
    166  *	its max value.  In practice, we're limited by the number of LWPs
    167  *	that can be present on the system at any given time, and the
    168  *	assumption is that limit will be good enough on a 32-bit platform.
    169  *	See futex_wake() for why overflow needs to be avoided.
    170  */
    171 struct futex {
    172 	union futex_key		fx_key;
    173 	unsigned long		fx_refcnt;
    174 	bool			fx_shared;
    175 	bool			fx_on_tree;
    176 	struct rb_node		fx_node;
    177 
    178 	kmutex_t			fx_qlock;
    179 	TAILQ_HEAD(, futex_wait)	fx_queue;
    180 
    181 	kmutex_t			fx_abortlock;
    182 	LIST_HEAD(, futex_wait)		fx_abortlist;
    183 	kcondvar_t			fx_abortcv;
    184 };
    185 
    186 /*
    187  * struct futex_wait
    188  *
    189  *	State for a thread to wait on a futex.  Threads wait on fw_cv
    190  *	for fw_bitset to be set to zero.  The thread may transition to
    191  *	a different futex queue at any time under the futex's lock.
    192  */
    193 struct futex_wait {
    194 	kmutex_t		fw_lock;
    195 	kcondvar_t		fw_cv;
    196 	struct futex		*fw_futex;
    197 	TAILQ_ENTRY(futex_wait)	fw_entry;	/* queue lock */
    198 	LIST_ENTRY(futex_wait)	fw_abort;	/* queue abortlock */
    199 	int			fw_bitset;
    200 	bool			fw_aborting;	/* fw_lock */
    201 };
    202 
    203 /*
    204  * futex_tab
    205  *
    206  *	Global trees of futexes by vmspace/va and VM object address.
    207  *
    208  *	XXX This obviously doesn't scale in parallel.  We could use a
    209  *	pserialize-safe data structure, but there may be a high cost to
    210  *	frequent deletion since we don't cache futexes after we're done
    211  *	with them.  We could use hashed locks.  But for now, just make
    212  *	sure userland can't DoS the serial performance, by using a
    213  *	balanced binary tree for lookup.
    214  *
    215  *	XXX We could use a per-process tree for the table indexed by
    216  *	virtual address to reduce contention between processes.
    217  */
    218 static struct {
    219 	kmutex_t	lock;
    220 	struct rb_tree	va;
    221 	struct rb_tree	oa;
    222 } futex_tab __cacheline_aligned;
    223 
    224 static int
    225 compare_futex_key(void *cookie, const void *n, const void *k)
    226 {
    227 	const struct futex *fa = n;
    228 	const union futex_key *fka = &fa->fx_key;
    229 	const union futex_key *fkb = k;
    230 
    231 	if ((uintptr_t)fka->fk_private.vmspace <
    232 	    (uintptr_t)fkb->fk_private.vmspace)
    233 		return -1;
    234 	if ((uintptr_t)fka->fk_private.vmspace >
    235 	    (uintptr_t)fkb->fk_private.vmspace)
    236 		return +1;
    237 	if (fka->fk_private.va < fkb->fk_private.va)
    238 		return -1;
    239 	if (fka->fk_private.va > fkb->fk_private.va)
    240 		return +1;
    241 	return 0;
    242 }
    243 
    244 static int
    245 compare_futex(void *cookie, const void *na, const void *nb)
    246 {
    247 	const struct futex *fa = na;
    248 	const struct futex *fb = nb;
    249 
    250 	return compare_futex_key(cookie, fa, &fb->fx_key);
    251 }
    252 
    253 static const rb_tree_ops_t futex_rb_ops = {
    254 	.rbto_compare_nodes = compare_futex,
    255 	.rbto_compare_key = compare_futex_key,
    256 	.rbto_node_offset = offsetof(struct futex, fx_node),
    257 };
    258 
    259 static int
    260 compare_futex_shared_key(void *cookie, const void *n, const void *k)
    261 {
    262 	const struct futex *fa = n;
    263 	const union futex_key *fka = &fa->fx_key;
    264 	const union futex_key *fkb = k;
    265 
    266 	return uvm_voaddr_compare(&fka->fk_shared, &fkb->fk_shared);
    267 }
    268 
    269 static int
    270 compare_futex_shared(void *cookie, const void *na, const void *nb)
    271 {
    272 	const struct futex *fa = na;
    273 	const struct futex *fb = nb;
    274 
    275 	return compare_futex_shared_key(cookie, fa, &fb->fx_key);
    276 }
    277 
    278 static const rb_tree_ops_t futex_shared_rb_ops = {
    279 	.rbto_compare_nodes = compare_futex_shared,
    280 	.rbto_compare_key = compare_futex_shared_key,
    281 	.rbto_node_offset = offsetof(struct futex, fx_node),
    282 };
    283 
    284 static void	futex_wait_dequeue(struct futex_wait *, struct futex *);
    285 
    286 /*
    287  * futex_load(uaddr, kaddr)
    288  *
    289  *	Perform a single atomic load to read *uaddr, and return the
    290  *	result in *kaddr.  Return 0 on success, EFAULT if uaddr is not
    291  *	mapped.
    292  */
    293 static inline int
    294 futex_load(int *uaddr, int *kaddr)
    295 {
    296 	return ufetch_int((u_int *)uaddr, (u_int *)kaddr);
    297 }
    298 
    299 /*
    300  * futex_test(uaddr, expected)
    301  *
    302  *	True if *uaddr == expected.  False if *uaddr != expected, or if
    303  *	uaddr is not mapped.
    304  */
    305 static bool
    306 futex_test(int *uaddr, int expected)
    307 {
    308 	int val;
    309 	int error;
    310 
    311 	error = futex_load(uaddr, &val);
    312 	if (error)
    313 		return false;
    314 	return val == expected;
    315 }
    316 
    317 /*
    318  * futex_sys_init()
    319  *
    320  *	Initialize the futex subsystem.
    321  */
    322 void
    323 futex_sys_init(void)
    324 {
    325 
    326 	mutex_init(&futex_tab.lock, MUTEX_DEFAULT, IPL_NONE);
    327 	rb_tree_init(&futex_tab.va, &futex_rb_ops);
    328 	rb_tree_init(&futex_tab.oa, &futex_shared_rb_ops);
    329 }
    330 
    331 /*
    332  * futex_sys_fini()
    333  *
    334  *	Finalize the futex subsystem.
    335  */
    336 void
    337 futex_sys_fini(void)
    338 {
    339 
    340 	KASSERT(RB_TREE_MIN(&futex_tab.oa) == NULL);
    341 	KASSERT(RB_TREE_MIN(&futex_tab.va) == NULL);
    342 	mutex_destroy(&futex_tab.lock);
    343 }
    344 
    345 /*
    346  * futex_queue_init(f)
    347  *
    348  *	Initialize the futex queue.  Caller must call futex_queue_fini
    349  *	when done.
    350  *
    351  *	Never sleeps.
    352  */
    353 static void
    354 futex_queue_init(struct futex *f)
    355 {
    356 
    357 	mutex_init(&f->fx_qlock, MUTEX_DEFAULT, IPL_NONE);
    358 	mutex_init(&f->fx_abortlock, MUTEX_DEFAULT, IPL_NONE);
    359 	cv_init(&f->fx_abortcv, "fqabort");
    360 	LIST_INIT(&f->fx_abortlist);
    361 	TAILQ_INIT(&f->fx_queue);
    362 }
    363 
    364 /*
    365  * futex_queue_drain(f)
    366  *
    367  *	Wait for any aborting waiters in f; then empty the queue of
    368  *	any stragglers and wake them.  Caller must guarantee no new
    369  *	references to f.
    370  *
    371  *	May sleep.
    372  */
    373 static void
    374 futex_queue_drain(struct futex *f)
    375 {
    376 	struct futex_wait *fw, *fw_next;
    377 
    378 	mutex_enter(&f->fx_abortlock);
    379 	while (!LIST_EMPTY(&f->fx_abortlist))
    380 		cv_wait(&f->fx_abortcv, &f->fx_abortlock);
    381 	mutex_exit(&f->fx_abortlock);
    382 
    383 	mutex_enter(&f->fx_qlock);
    384 	TAILQ_FOREACH_SAFE(fw, &f->fx_queue, fw_entry, fw_next) {
    385 		mutex_enter(&fw->fw_lock);
    386 		futex_wait_dequeue(fw, f);
    387 		cv_broadcast(&fw->fw_cv);
    388 		mutex_exit(&fw->fw_lock);
    389 	}
    390 	mutex_exit(&f->fx_qlock);
    391 }
    392 
    393 /*
    394  * futex_queue_fini(fq)
    395  *
    396  *	Finalize the futex queue initialized by futex_queue_init.  Queue
    397  *	must be empty.  Caller must not use f again until a subsequent
    398  *	futex_queue_init.
    399  */
    400 static void
    401 futex_queue_fini(struct futex *f)
    402 {
    403 
    404 	KASSERT(TAILQ_EMPTY(&f->fx_queue));
    405 	KASSERT(LIST_EMPTY(&f->fx_abortlist));
    406 	mutex_destroy(&f->fx_qlock);
    407 	mutex_destroy(&f->fx_abortlock);
    408 	cv_destroy(&f->fx_abortcv);
    409 }
    410 
    411 /*
    412  * futex_key_init(key, vm, va, shared)
    413  *
    414  *	Initialize a futex key for lookup, etc.
    415  */
    416 static int
    417 futex_key_init(union futex_key *fk, struct vmspace *vm, vaddr_t va, bool shared)
    418 {
    419 	int error = 0;
    420 
    421 	if (__predict_false(shared)) {
    422 		if (!uvm_voaddr_acquire(&vm->vm_map, va, &fk->fk_shared))
    423 			error = EFAULT;
    424 	} else {
    425 		fk->fk_private.vmspace = vm;
    426 		fk->fk_private.va = va;
    427 	}
    428 
    429 	return error;
    430 }
    431 
    432 /*
    433  * futex_key_fini(key, shared)
    434  *
    435  *	Release a futex key.
    436  */
    437 static void
    438 futex_key_fini(union futex_key *fk, bool shared)
    439 {
    440 	if (__predict_false(shared))
    441 		uvm_voaddr_release(&fk->fk_shared);
    442 	memset(fk, 0, sizeof(*fk));
    443 }
    444 
    445 /*
    446  * futex_create(fk, shared)
    447  *
    448  *	Create a futex.  Initial reference count is 1, representing the
    449  *	caller.  Returns NULL on failure.  Always takes ownership of the
    450  *	key, either transferring it to the newly-created futex, or releasing
    451  *	the key if creation fails.
    452  *
    453  *	Never sleeps for memory, but may sleep to acquire a lock.
    454  */
    455 static struct futex *
    456 futex_create(union futex_key *fk, bool shared)
    457 {
    458 	struct futex *f;
    459 
    460 	f = kmem_alloc(sizeof(*f), KM_NOSLEEP);
    461 	if (f == NULL) {
    462 		futex_key_fini(fk, shared);
    463 		return NULL;
    464 	}
    465 	f->fx_key = *fk;
    466 	f->fx_refcnt = 1;
    467 	f->fx_shared = shared;
    468 	f->fx_on_tree = false;
    469 	futex_queue_init(f);
    470 
    471 	return f;
    472 }
    473 
    474 /*
    475  * futex_destroy(f)
    476  *
    477  *	Destroy a futex created with futex_create.  Reference count
    478  *	must be zero.
    479  *
    480  *	May sleep.
    481  */
    482 static void
    483 futex_destroy(struct futex *f)
    484 {
    485 
    486 	ASSERT_SLEEPABLE();
    487 
    488 	KASSERT(atomic_load_relaxed(&f->fx_refcnt) == 0);
    489 	KASSERT(!f->fx_on_tree);
    490 
    491 	/* Drain and destroy the private queue.  */
    492 	futex_queue_drain(f);
    493 	futex_queue_fini(f);
    494 
    495 	futex_key_fini(&f->fx_key, f->fx_shared);
    496 
    497 	kmem_free(f, sizeof(*f));
    498 }
    499 
    500 /*
    501  * futex_hold(f)
    502  *
    503  *	Attempt to acquire a reference to f.  Return 0 on success,
    504  *	ENFILE on too many references.
    505  *
    506  *	Never sleeps.
    507  */
    508 static int
    509 futex_hold(struct futex *f)
    510 {
    511 	unsigned long refcnt;
    512 
    513 	do {
    514 		refcnt = atomic_load_relaxed(&f->fx_refcnt);
    515 		if (refcnt == ULONG_MAX)
    516 			return ENFILE;
    517 	} while (atomic_cas_ulong(&f->fx_refcnt, refcnt, refcnt + 1) != refcnt);
    518 
    519 	return 0;
    520 }
    521 
    522 /*
    523  * futex_rele(f)
    524  *
    525  *	Release a reference to f acquired with futex_create or
    526  *	futex_hold.
    527  *
    528  *	May sleep to free f.
    529  */
    530 static void
    531 futex_rele(struct futex *f)
    532 {
    533 	unsigned long refcnt;
    534 
    535 	ASSERT_SLEEPABLE();
    536 
    537 	do {
    538 		refcnt = atomic_load_relaxed(&f->fx_refcnt);
    539 		if (refcnt == 1)
    540 			goto trylast;
    541 		membar_release();
    542 	} while (atomic_cas_ulong(&f->fx_refcnt, refcnt, refcnt - 1) != refcnt);
    543 	return;
    544 
    545 trylast:
    546 	mutex_enter(&futex_tab.lock);
    547 	if (atomic_dec_ulong_nv(&f->fx_refcnt) == 0) {
    548 		membar_acquire();
    549 		if (f->fx_on_tree) {
    550 			if (__predict_false(f->fx_shared))
    551 				rb_tree_remove_node(&futex_tab.oa, f);
    552 			else
    553 				rb_tree_remove_node(&futex_tab.va, f);
    554 			f->fx_on_tree = false;
    555 		}
    556 	} else {
    557 		/* References remain -- don't destroy it.  */
    558 		f = NULL;
    559 	}
    560 	mutex_exit(&futex_tab.lock);
    561 	if (f != NULL)
    562 		futex_destroy(f);
    563 }
    564 
    565 /*
    566  * futex_rele_not_last(f)
    567  *
    568  *	Release a reference to f acquired with futex_create or
    569  *	futex_hold.
    570  *
    571  *	This version asserts that we are not dropping the last
    572  *	reference to f.
    573  */
    574 static void
    575 futex_rele_not_last(struct futex *f)
    576 {
    577 	unsigned long refcnt;
    578 
    579 	do {
    580 		refcnt = atomic_load_relaxed(&f->fx_refcnt);
    581 		KASSERT(refcnt > 1);
    582 	} while (atomic_cas_ulong(&f->fx_refcnt, refcnt, refcnt - 1) != refcnt);
    583 }
    584 
    585 /*
    586  * futex_lookup_by_key(key, shared, &f)
    587  *
    588  *	Try to find an existing futex va reference in the specified key
    589  *	On success, return 0, set f to found futex or to NULL if not found,
    590  *	and increment f's reference count if found.
    591  *
    592  *	Return ENFILE if reference count too high.
    593  *
    594  *	Internal lookup routine shared by futex_lookup() and
    595  *	futex_lookup_create().
    596  */
    597 static int
    598 futex_lookup_by_key(union futex_key *fk, bool shared, struct futex **fp)
    599 {
    600 	struct futex *f;
    601 	int error = 0;
    602 
    603 	mutex_enter(&futex_tab.lock);
    604 	if (__predict_false(shared)) {
    605 		f = rb_tree_find_node(&futex_tab.oa, fk);
    606 	} else {
    607 		f = rb_tree_find_node(&futex_tab.va, fk);
    608 	}
    609 	if (f) {
    610 		error = futex_hold(f);
    611 		if (error)
    612 			f = NULL;
    613 	}
    614  	*fp = f;
    615 	mutex_exit(&futex_tab.lock);
    616 
    617 	return error;
    618 }
    619 
    620 /*
    621  * futex_insert(f, fp)
    622  *
    623  *	Try to insert the futex f into the tree by va.  If there
    624  *	already is a futex for its va, acquire a reference to it, and
    625  *	store it in *fp; otherwise store f in *fp.
    626  *
    627  *	Return 0 on success, ENFILE if there already is a futex but its
    628  *	reference count is too high.
    629  */
    630 static int
    631 futex_insert(struct futex *f, struct futex **fp)
    632 {
    633 	struct futex *f0;
    634 	int error;
    635 
    636 	KASSERT(atomic_load_relaxed(&f->fx_refcnt) != 0);
    637 	KASSERT(!f->fx_on_tree);
    638 
    639 	mutex_enter(&futex_tab.lock);
    640 	if (__predict_false(f->fx_shared))
    641 		f0 = rb_tree_insert_node(&futex_tab.oa, f);
    642 	else
    643 		f0 = rb_tree_insert_node(&futex_tab.va, f);
    644 	if (f0 == f) {
    645 		f->fx_on_tree = true;
    646 		error = 0;
    647 	} else {
    648 		KASSERT(atomic_load_relaxed(&f0->fx_refcnt) != 0);
    649 		KASSERT(f0->fx_on_tree);
    650 		error = futex_hold(f0);
    651 		if (error)
    652 			goto out;
    653 	}
    654 	*fp = f0;
    655 out:	mutex_exit(&futex_tab.lock);
    656 
    657 	return error;
    658 }
    659 
    660 /*
    661  * futex_lookup(uaddr, shared, &f)
    662  *
    663  *	Find a futex at the userland pointer uaddr in the current
    664  *	process's VM space.  On success, return the futex in f and
    665  *	increment its reference count.
    666  *
    667  *	Caller must call futex_rele when done.
    668  */
    669 static int
    670 futex_lookup(int *uaddr, bool shared, struct futex **fp)
    671 {
    672 	union futex_key fk;
    673 	struct vmspace *vm = curproc->p_vmspace;
    674 	vaddr_t va = (vaddr_t)uaddr;
    675 	int error;
    676 
    677 	/*
    678 	 * Reject unaligned user pointers so we don't cross page
    679 	 * boundaries and so atomics will work.
    680 	 */
    681 	if ((va & 3) != 0)
    682 		return EINVAL;
    683 
    684 	/* Look it up. */
    685 	error = futex_key_init(&fk, vm, va, shared);
    686 	if (error)
    687 		return error;
    688 
    689 	error = futex_lookup_by_key(&fk, shared, fp);
    690 	futex_key_fini(&fk, shared);
    691 	if (error)
    692 		return error;
    693 
    694 	KASSERT(*fp == NULL || (*fp)->fx_shared == shared);
    695 	KASSERT(*fp == NULL || atomic_load_relaxed(&(*fp)->fx_refcnt) != 0);
    696 
    697 	/*
    698 	 * Success!  (Caller must still check whether we found
    699 	 * anything, but nothing went _wrong_ like trying to use
    700 	 * unmapped memory.)
    701 	 */
    702 	KASSERT(error == 0);
    703 
    704 	return error;
    705 }
    706 
    707 /*
    708  * futex_lookup_create(uaddr, shared, &f)
    709  *
    710  *	Find or create a futex at the userland pointer uaddr in the
    711  *	current process's VM space.  On success, return the futex in f
    712  *	and increment its reference count.
    713  *
    714  *	Caller must call futex_rele when done.
    715  */
    716 static int
    717 futex_lookup_create(int *uaddr, bool shared, struct futex **fp)
    718 {
    719 	union futex_key fk;
    720 	struct vmspace *vm = curproc->p_vmspace;
    721 	struct futex *f = NULL;
    722 	vaddr_t va = (vaddr_t)uaddr;
    723 	int error;
    724 
    725 	/*
    726 	 * Reject unaligned user pointers so we don't cross page
    727 	 * boundaries and so atomics will work.
    728 	 */
    729 	if ((va & 3) != 0)
    730 		return EINVAL;
    731 
    732 	error = futex_key_init(&fk, vm, va, shared);
    733 	if (error)
    734 		return error;
    735 
    736 	/*
    737 	 * Optimistically assume there already is one, and try to find
    738 	 * it.
    739 	 */
    740 	error = futex_lookup_by_key(&fk, shared, fp);
    741 	if (error || *fp != NULL) {
    742 		/*
    743 		 * We either found one, or there was an error.
    744 		 * In either case, we are done with the key.
    745 		 */
    746 		futex_key_fini(&fk, shared);
    747 		goto out;
    748 	}
    749 
    750 	/*
    751 	 * Create a futex record.  This transfers ownership of the key
    752 	 * in all cases.
    753 	 */
    754 	f = futex_create(&fk, shared);
    755 	if (f == NULL) {
    756 		error = ENOMEM;
    757 		goto out;
    758 	}
    759 
    760 	/*
    761 	 * Insert our new futex, or use existing if someone else beat
    762 	 * us to it.
    763 	 */
    764 	error = futex_insert(f, fp);
    765 	if (error)
    766 		goto out;
    767 	if (*fp == f)
    768 		f = NULL;	/* don't release on exit */
    769 
    770 	/* Success!  */
    771 	KASSERT(error == 0);
    772 
    773 out:	if (f != NULL)
    774 		futex_rele(f);
    775 	KASSERT(error || *fp != NULL);
    776 	KASSERT(error || atomic_load_relaxed(&(*fp)->fx_refcnt) != 0);
    777 	return error;
    778 }
    779 
    780 /*
    781  * futex_wait_init(fw, bitset)
    782  *
    783  *	Initialize a record for a thread to wait on a futex matching
    784  *	the specified bit set.  Should be passed to futex_wait_enqueue
    785  *	before futex_wait, and should be passed to futex_wait_fini when
    786  *	done.
    787  */
    788 static void
    789 futex_wait_init(struct futex_wait *fw, int bitset)
    790 {
    791 
    792 	KASSERT(bitset);
    793 
    794 	mutex_init(&fw->fw_lock, MUTEX_DEFAULT, IPL_NONE);
    795 	cv_init(&fw->fw_cv, "futex");
    796 	fw->fw_futex = NULL;
    797 	fw->fw_bitset = bitset;
    798 	fw->fw_aborting = false;
    799 }
    800 
    801 /*
    802  * futex_wait_fini(fw)
    803  *
    804  *	Finalize a record for a futex waiter.  Must not be on any
    805  *	futex's queue.
    806  */
    807 static void
    808 futex_wait_fini(struct futex_wait *fw)
    809 {
    810 
    811 	KASSERT(fw->fw_futex == NULL);
    812 
    813 	cv_destroy(&fw->fw_cv);
    814 	mutex_destroy(&fw->fw_lock);
    815 }
    816 
    817 /*
    818  * futex_wait_enqueue(fw, f)
    819  *
    820  *	Put fw on the futex queue.  Must be done before futex_wait.
    821  *	Caller must hold fw's lock and f's lock, and fw must not be on
    822  *	any existing futex's waiter list.
    823  */
    824 static void
    825 futex_wait_enqueue(struct futex_wait *fw, struct futex *f)
    826 {
    827 
    828 	KASSERT(mutex_owned(&f->fx_qlock));
    829 	KASSERT(mutex_owned(&fw->fw_lock));
    830 	KASSERT(fw->fw_futex == NULL);
    831 	KASSERT(!fw->fw_aborting);
    832 
    833 	fw->fw_futex = f;
    834 	TAILQ_INSERT_TAIL(&f->fx_queue, fw, fw_entry);
    835 }
    836 
    837 /*
    838  * futex_wait_dequeue(fw, f)
    839  *
    840  *	Remove fw from the futex queue.  Precludes subsequent
    841  *	futex_wait until a futex_wait_enqueue.  Caller must hold fw's
    842  *	lock and f's lock, and fw must be on f.
    843  */
    844 static void
    845 futex_wait_dequeue(struct futex_wait *fw, struct futex *f)
    846 {
    847 
    848 	KASSERT(mutex_owned(&f->fx_qlock));
    849 	KASSERT(mutex_owned(&fw->fw_lock));
    850 	KASSERT(fw->fw_futex == f);
    851 
    852 	TAILQ_REMOVE(&f->fx_queue, fw, fw_entry);
    853 	fw->fw_futex = NULL;
    854 }
    855 
    856 /*
    857  * futex_wait_abort(fw)
    858  *
    859  *	Caller is no longer waiting for fw.  Remove it from any queue
    860  *	if it was on one.  Caller must hold fw->fw_lock.
    861  */
    862 static void
    863 futex_wait_abort(struct futex_wait *fw)
    864 {
    865 	struct futex *f;
    866 
    867 	KASSERT(mutex_owned(&fw->fw_lock));
    868 
    869 	/*
    870 	 * Grab the futex queue.  It can't go away as long as we hold
    871 	 * fw_lock.  However, we can't take the queue lock because
    872 	 * that's a lock order reversal.
    873 	 */
    874 	f = fw->fw_futex;
    875 
    876 	/* Put us on the abort list so that fq won't go away.  */
    877 	mutex_enter(&f->fx_abortlock);
    878 	LIST_INSERT_HEAD(&f->fx_abortlist, fw, fw_abort);
    879 	mutex_exit(&f->fx_abortlock);
    880 
    881 	/*
    882 	 * Mark fw as aborting so it won't lose wakeups and won't be
    883 	 * transferred to any other queue.
    884 	 */
    885 	fw->fw_aborting = true;
    886 
    887 	/* f is now stable, so we can release fw_lock.  */
    888 	mutex_exit(&fw->fw_lock);
    889 
    890 	/* Now we can remove fw under the queue lock.  */
    891 	mutex_enter(&f->fx_qlock);
    892 	mutex_enter(&fw->fw_lock);
    893 	futex_wait_dequeue(fw, f);
    894 	mutex_exit(&fw->fw_lock);
    895 	mutex_exit(&f->fx_qlock);
    896 
    897 	/*
    898 	 * Finally, remove us from the abort list and notify anyone
    899 	 * waiting for the abort to complete if we were the last to go.
    900 	 */
    901 	mutex_enter(&f->fx_abortlock);
    902 	LIST_REMOVE(fw, fw_abort);
    903 	if (LIST_EMPTY(&f->fx_abortlist))
    904 		cv_broadcast(&f->fx_abortcv);
    905 	mutex_exit(&f->fx_abortlock);
    906 
    907 	/*
    908 	 * Release our reference to the futex now that we are not
    909 	 * waiting for it.
    910 	 */
    911 	futex_rele(f);
    912 
    913 	/*
    914 	 * Reacquire the fw lock as caller expects.  Verify that we're
    915 	 * aborting and no longer associated with a futex.
    916 	 */
    917 	mutex_enter(&fw->fw_lock);
    918 	KASSERT(fw->fw_aborting);
    919 	KASSERT(fw->fw_futex == NULL);
    920 }
    921 
    922 /*
    923  * futex_wait(fw, deadline, clkid)
    924  *
    925  *	fw must be a waiter on a futex's queue.  Wait until deadline on
    926  *	the clock clkid, or forever if deadline is NULL, for a futex
    927  *	wakeup.  Return 0 on explicit wakeup or destruction of futex,
    928  *	ETIMEDOUT on timeout, EINTR/ERESTART on signal.  Either way, fw
    929  *	will no longer be on a futex queue on return.
    930  */
    931 static int
    932 futex_wait(struct futex_wait *fw, const struct timespec *deadline,
    933     clockid_t clkid)
    934 {
    935 	int error = 0;
    936 
    937 	/* Test and wait under the wait lock.  */
    938 	mutex_enter(&fw->fw_lock);
    939 
    940 	for (;;) {
    941 		/* If we're done yet, stop and report success.  */
    942 		if (fw->fw_bitset == 0 || fw->fw_futex == NULL) {
    943 			error = 0;
    944 			break;
    945 		}
    946 
    947 		/* If anything went wrong in the last iteration, stop.  */
    948 		if (error)
    949 			break;
    950 
    951 		/* Not done yet.  Wait.  */
    952 		if (deadline) {
    953 			struct timespec ts;
    954 
    955 			/* Check our watch.  */
    956 			error = clock_gettime1(clkid, &ts);
    957 			if (error)
    958 				break;
    959 
    960 			/* If we're past the deadline, ETIMEDOUT.  */
    961 			if (timespeccmp(deadline, &ts, <=)) {
    962 				error = ETIMEDOUT;
    963 				break;
    964 			}
    965 
    966 			/* Count how much time is left.  */
    967 			timespecsub(deadline, &ts, &ts);
    968 
    969 			/* Wait for that much time, allowing signals.  */
    970 			error = cv_timedwait_sig(&fw->fw_cv, &fw->fw_lock,
    971 			    tstohz(&ts));
    972 		} else {
    973 			/* Wait indefinitely, allowing signals. */
    974 			error = cv_wait_sig(&fw->fw_cv, &fw->fw_lock);
    975 		}
    976 	}
    977 
    978 	/*
    979 	 * If we were woken up, the waker will have removed fw from the
    980 	 * queue.  But if anything went wrong, we must remove fw from
    981 	 * the queue ourselves.  While here, convert EWOULDBLOCK to
    982 	 * ETIMEDOUT.
    983 	 */
    984 	if (error) {
    985 		futex_wait_abort(fw);
    986 		if (error == EWOULDBLOCK)
    987 			error = ETIMEDOUT;
    988 	}
    989 
    990 	mutex_exit(&fw->fw_lock);
    991 
    992 	return error;
    993 }
    994 
    995 /*
    996  * futex_wake(f, nwake, f2, nrequeue, bitset)
    997  *
    998  *	Wake up to nwake waiters on f matching bitset; then, if f2 is
    999  *	provided, move up to nrequeue remaining waiters on f matching
   1000  *	bitset to f2.  Return the number of waiters actually woken or
   1001  *	requeued.  Caller must hold the locks of f and f2, if provided.
   1002  */
   1003 static unsigned
   1004 futex_wake(struct futex *f, unsigned nwake, struct futex *f2,
   1005     unsigned nrequeue, int bitset)
   1006 {
   1007 	struct futex_wait *fw, *fw_next;
   1008 	unsigned nwoken_or_requeued = 0;
   1009 	int hold_error __diagused;
   1010 
   1011 	KASSERT(mutex_owned(&f->fx_qlock));
   1012 	KASSERT(f2 == NULL || mutex_owned(&f2->fx_qlock));
   1013 
   1014 	/* Wake up to nwake waiters, and count the number woken.  */
   1015 	TAILQ_FOREACH_SAFE(fw, &f->fx_queue, fw_entry, fw_next) {
   1016 		if ((fw->fw_bitset & bitset) == 0)
   1017 			continue;
   1018 		if (nwake > 0) {
   1019 			mutex_enter(&fw->fw_lock);
   1020 			if (__predict_false(fw->fw_aborting)) {
   1021 				mutex_exit(&fw->fw_lock);
   1022 				continue;
   1023 			}
   1024 			futex_wait_dequeue(fw, f);
   1025 			fw->fw_bitset = 0;
   1026 			cv_broadcast(&fw->fw_cv);
   1027 			mutex_exit(&fw->fw_lock);
   1028 			nwake--;
   1029 			nwoken_or_requeued++;
   1030 			/*
   1031 			 * Drop the futex reference on behalf of the
   1032 			 * waiter.  We assert this is not the last
   1033 			 * reference on the futex (our caller should
   1034 			 * also have one).
   1035 			 */
   1036 			futex_rele_not_last(f);
   1037 		} else {
   1038 			break;
   1039 		}
   1040 	}
   1041 
   1042 	if (f2) {
   1043 		/* Move up to nrequeue waiters from f's queue to f2's queue. */
   1044 		TAILQ_FOREACH_SAFE(fw, &f->fx_queue, fw_entry, fw_next) {
   1045 			if ((fw->fw_bitset & bitset) == 0)
   1046 				continue;
   1047 			if (nrequeue > 0) {
   1048 				mutex_enter(&fw->fw_lock);
   1049 				if (__predict_false(fw->fw_aborting)) {
   1050 					mutex_exit(&fw->fw_lock);
   1051 					continue;
   1052 				}
   1053 				futex_wait_dequeue(fw, f);
   1054 				futex_wait_enqueue(fw, f2);
   1055 				mutex_exit(&fw->fw_lock);
   1056 				nrequeue--;
   1057 				/*
   1058 				 * PR kern/59004: Missing constant for upper
   1059 				 * bound on systemwide number of lwps
   1060 				 */
   1061 				KASSERT(nwoken_or_requeued <
   1062 				    MIN(PID_MAX*MAXMAXLWP, FUTEX_TID_MASK));
   1063 				__CTASSERT(UINT_MAX >=
   1064 				    MIN(PID_MAX*MAXMAXLWP, FUTEX_TID_MASK));
   1065 				if (++nwoken_or_requeued == 0) /* paranoia */
   1066 					nwoken_or_requeued = UINT_MAX;
   1067 				/*
   1068 				 * Transfer the reference from f to f2.
   1069 				 * As above, we assert that we are not
   1070 				 * dropping the last reference to f here.
   1071 				 *
   1072 				 * XXX futex_hold() could theoretically
   1073 				 * XXX fail here.
   1074 				 */
   1075 				futex_rele_not_last(f);
   1076 				hold_error = futex_hold(f2);
   1077 				KASSERT(hold_error == 0);
   1078 			} else {
   1079 				break;
   1080 			}
   1081 		}
   1082 	} else {
   1083 		KASSERT(nrequeue == 0);
   1084 	}
   1085 
   1086 	/* Return the number of waiters woken or requeued.  */
   1087 	return nwoken_or_requeued;
   1088 }
   1089 
   1090 /*
   1091  * futex_queue_lock(f)
   1092  *
   1093  *	Acquire the queue lock of f.  Pair with futex_queue_unlock.  Do
   1094  *	not use if caller needs to acquire two locks; use
   1095  *	futex_queue_lock2 instead.
   1096  */
   1097 static void
   1098 futex_queue_lock(struct futex *f)
   1099 {
   1100 	mutex_enter(&f->fx_qlock);
   1101 }
   1102 
   1103 /*
   1104  * futex_queue_unlock(f)
   1105  *
   1106  *	Release the queue lock of f.
   1107  */
   1108 static void
   1109 futex_queue_unlock(struct futex *f)
   1110 {
   1111 	mutex_exit(&f->fx_qlock);
   1112 }
   1113 
   1114 /*
   1115  * futex_queue_lock2(f, f2)
   1116  *
   1117  *	Acquire the queue locks of both f and f2, which may be null, or
   1118  *	which may have the same underlying queue.  If they are
   1119  *	distinct, an arbitrary total order is chosen on the locks.
   1120  *
   1121  *	Callers should only ever acquire multiple queue locks
   1122  *	simultaneously using futex_queue_lock2.
   1123  */
   1124 static void
   1125 futex_queue_lock2(struct futex *f, struct futex *f2)
   1126 {
   1127 
   1128 	/*
   1129 	 * If both are null, do nothing; if one is null and the other
   1130 	 * is not, lock the other and be done with it.
   1131 	 */
   1132 	if (f == NULL && f2 == NULL) {
   1133 		return;
   1134 	} else if (f == NULL) {
   1135 		mutex_enter(&f2->fx_qlock);
   1136 		return;
   1137 	} else if (f2 == NULL) {
   1138 		mutex_enter(&f->fx_qlock);
   1139 		return;
   1140 	}
   1141 
   1142 	/* If both futexes are the same, acquire only one. */
   1143 	if (f == f2) {
   1144 		mutex_enter(&f->fx_qlock);
   1145 		return;
   1146 	}
   1147 
   1148 	/* Otherwise, use the ordering on the kva of the futex pointer.  */
   1149 	if ((uintptr_t)f < (uintptr_t)f2) {
   1150 		mutex_enter(&f->fx_qlock);
   1151 		mutex_enter(&f2->fx_qlock);
   1152 	} else {
   1153 		mutex_enter(&f2->fx_qlock);
   1154 		mutex_enter(&f->fx_qlock);
   1155 	}
   1156 }
   1157 
   1158 /*
   1159  * futex_queue_unlock2(f, f2)
   1160  *
   1161  *	Release the queue locks of both f and f2, which may be null, or
   1162  *	which may have the same underlying queue.
   1163  */
   1164 static void
   1165 futex_queue_unlock2(struct futex *f, struct futex *f2)
   1166 {
   1167 
   1168 	/*
   1169 	 * If both are null, do nothing; if one is null and the other
   1170 	 * is not, unlock the other and be done with it.
   1171 	 */
   1172 	if (f == NULL && f2 == NULL) {
   1173 		return;
   1174 	} else if (f == NULL) {
   1175 		mutex_exit(&f2->fx_qlock);
   1176 		return;
   1177 	} else if (f2 == NULL) {
   1178 		mutex_exit(&f->fx_qlock);
   1179 		return;
   1180 	}
   1181 
   1182 	/* If both futexes are the same, release only one. */
   1183 	if (f == f2) {
   1184 		mutex_exit(&f->fx_qlock);
   1185 		return;
   1186 	}
   1187 
   1188 	/* Otherwise, use the ordering on the kva of the futex pointer.  */
   1189 	if ((uintptr_t)f < (uintptr_t)f2) {
   1190 		mutex_exit(&f2->fx_qlock);
   1191 		mutex_exit(&f->fx_qlock);
   1192 	} else {
   1193 		mutex_exit(&f->fx_qlock);
   1194 		mutex_exit(&f2->fx_qlock);
   1195 	}
   1196 }
   1197 
   1198 /*
   1199  * futex_func_wait(uaddr, val, val3, timeout, clkid, clkflags, retval)
   1200  *
   1201  *	Implement futex(FUTEX_WAIT).
   1202  */
   1203 static int
   1204 futex_func_wait(bool shared, int *uaddr, int val, int val3,
   1205     const struct timespec *timeout, clockid_t clkid, int clkflags,
   1206     register_t *retval)
   1207 {
   1208 	struct futex *f;
   1209 	struct futex_wait wait, *fw = &wait;
   1210 	struct timespec ts;
   1211 	const struct timespec *deadline;
   1212 	int error;
   1213 
   1214 	/*
   1215 	 * If there's nothing to wait for, and nobody will ever wake
   1216 	 * us, then don't set anything up to wait -- just stop here.
   1217 	 */
   1218 	if (val3 == 0)
   1219 		return EINVAL;
   1220 
   1221 	/* Optimistically test before anything else.  */
   1222 	if (!futex_test(uaddr, val))
   1223 		return EAGAIN;
   1224 
   1225 	/* Determine a deadline on the specified clock.  */
   1226 	if (timeout == NULL || (clkflags & TIMER_ABSTIME) == TIMER_ABSTIME) {
   1227 		deadline = timeout;
   1228 	} else {
   1229 		error = clock_gettime1(clkid, &ts);
   1230 		if (error)
   1231 			return error;
   1232 		timespecadd(&ts, timeout, &ts);
   1233 		deadline = &ts;
   1234 	}
   1235 
   1236 	/* Get the futex, creating it if necessary.  */
   1237 	error = futex_lookup_create(uaddr, shared, &f);
   1238 	if (error)
   1239 		return error;
   1240 	KASSERT(f);
   1241 
   1242 	/* Get ready to wait.  */
   1243 	futex_wait_init(fw, val3);
   1244 
   1245 	/*
   1246 	 * Under the queue lock, check the value again: if it has
   1247 	 * already changed, EAGAIN; otherwise enqueue the waiter.
   1248 	 * Since FUTEX_WAKE will use the same lock and be done after
   1249 	 * modifying the value, the order in which we check and enqueue
   1250 	 * is immaterial.
   1251 	 */
   1252 	futex_queue_lock(f);
   1253 	if (!futex_test(uaddr, val)) {
   1254 		futex_queue_unlock(f);
   1255 		error = EAGAIN;
   1256 		goto out;
   1257 	}
   1258 	mutex_enter(&fw->fw_lock);
   1259 	futex_wait_enqueue(fw, f);
   1260 	mutex_exit(&fw->fw_lock);
   1261 	futex_queue_unlock(f);
   1262 
   1263 	/*
   1264 	 * We cannot drop our reference to the futex here, because
   1265 	 * we might be enqueued on a different one when we are awakened.
   1266 	 * The references will be managed on our behalf in the requeue
   1267 	 * and wake cases.
   1268 	 */
   1269 	f = NULL;
   1270 
   1271 	/* Wait. */
   1272 	error = futex_wait(fw, deadline, clkid);
   1273 	if (error)
   1274 		goto out;
   1275 
   1276 	/* Return 0 on success, error on failure. */
   1277 	*retval = 0;
   1278 
   1279 out:	if (f != NULL)
   1280 		futex_rele(f);
   1281 	futex_wait_fini(fw);
   1282 	return error;
   1283 }
   1284 
   1285 /*
   1286  * futex_func_wake(uaddr, val, val3, retval)
   1287  *
   1288  *	Implement futex(FUTEX_WAKE) and futex(FUTEX_WAKE_BITSET).
   1289  */
   1290 static int
   1291 futex_func_wake(bool shared, int *uaddr, int val, int val3, register_t *retval)
   1292 {
   1293 	struct futex *f;
   1294 	unsigned int nwoken = 0;
   1295 	int error = 0;
   1296 
   1297 	/* Reject negative number of wakeups.  */
   1298 	if (val < 0) {
   1299 		error = EINVAL;
   1300 		goto out;
   1301 	}
   1302 
   1303 	/* Look up the futex, if any.  */
   1304 	error = futex_lookup(uaddr, shared, &f);
   1305 	if (error)
   1306 		goto out;
   1307 
   1308 	/* If there's no futex, there are no waiters to wake.  */
   1309 	if (f == NULL)
   1310 		goto out;
   1311 
   1312 	/*
   1313 	 * Under f's queue lock, wake the waiters and remember the
   1314 	 * number woken.
   1315 	 */
   1316 	futex_queue_lock(f);
   1317 	nwoken = futex_wake(f, /*nwake*/val, NULL, /*nrequeue*/0,
   1318 	    /*bitset*/val3);
   1319 	futex_queue_unlock(f);
   1320 
   1321 	/* Release the futex.  */
   1322 	futex_rele(f);
   1323 
   1324 out:
   1325 	/* Return the number of waiters woken.  */
   1326 	*retval = nwoken;
   1327 
   1328 	/* Success!  */
   1329 	return error;
   1330 }
   1331 
   1332 /*
   1333  * futex_func_requeue(op, uaddr, val, uaddr2, val2, val3, retval)
   1334  *
   1335  *	Implement futex(FUTEX_REQUEUE) and futex(FUTEX_CMP_REQUEUE).
   1336  */
   1337 static int
   1338 futex_func_requeue(bool shared, int op, int *uaddr, int val, int *uaddr2,
   1339     int val2, int val3, register_t *retval)
   1340 {
   1341 	struct futex *f = NULL, *f2 = NULL;
   1342 	unsigned nwoken_or_requeued = 0; /* default to zero on early return */
   1343 	int error;
   1344 
   1345 	/* Reject negative number of wakeups or requeues. */
   1346 	if (val < 0 || val2 < 0) {
   1347 		error = EINVAL;
   1348 		goto out;
   1349 	}
   1350 
   1351 	/*
   1352 	 * Look up or create the source futex.  For FUTEX_CMP_REQUEUE,
   1353 	 * we always create it, rather than bail if it has no waiters,
   1354 	 * because FUTEX_CMP_REQUEUE always tests the futex word in
   1355 	 * order to report EAGAIN.
   1356 	 */
   1357 	error = (op == FUTEX_CMP_REQUEUE
   1358 	    ? futex_lookup_create(uaddr, shared, &f)
   1359 	    : futex_lookup(uaddr, shared, &f));
   1360 	if (error)
   1361 		goto out;
   1362 
   1363 	/* If there is none for FUTEX_REQUEUE, nothing to do. */
   1364 	if (f == NULL) {
   1365 		KASSERT(op != FUTEX_CMP_REQUEUE);
   1366 		goto out;
   1367 	}
   1368 
   1369 	/*
   1370 	 * We may need to create the destination futex because it's
   1371 	 * entirely possible it does not currently have any waiters.
   1372 	 */
   1373 	error = futex_lookup_create(uaddr2, shared, &f2);
   1374 	if (error)
   1375 		goto out;
   1376 
   1377 	/*
   1378 	 * Under the futexes' queue locks, check the value; if
   1379 	 * unchanged from val3, wake the waiters.
   1380 	 */
   1381 	futex_queue_lock2(f, f2);
   1382 	if (op == FUTEX_CMP_REQUEUE && !futex_test(uaddr, val3)) {
   1383 		error = EAGAIN;
   1384 	} else {
   1385 		error = 0;
   1386 		nwoken_or_requeued = futex_wake(f, /*nwake*/val,
   1387 		    f2, /*nrequeue*/val2,
   1388 		    FUTEX_BITSET_MATCH_ANY);
   1389 	}
   1390 	futex_queue_unlock2(f, f2);
   1391 
   1392 out:
   1393 	/* Return the number of waiters woken or requeued.  */
   1394 	*retval = nwoken_or_requeued;
   1395 
   1396 	/* Release the futexes if we got them.  */
   1397 	if (f2)
   1398 		futex_rele(f2);
   1399 	if (f)
   1400 		futex_rele(f);
   1401 	return error;
   1402 }
   1403 
   1404 /*
   1405  * futex_opcmp_arg(arg)
   1406  *
   1407  *	arg is either the oparg or cmparg field of a FUTEX_WAKE_OP
   1408  *	operation, a 12-bit string in either case.  Map it to a numeric
   1409  *	argument value by sign-extending it in two's-complement
   1410  *	representation.
   1411  */
   1412 static int
   1413 futex_opcmp_arg(int arg)
   1414 {
   1415 
   1416 	KASSERT(arg == (arg & __BITS(11,0)));
   1417 	return arg - 0x1000*__SHIFTOUT(arg, __BIT(11));
   1418 }
   1419 
   1420 /*
   1421  * futex_validate_op_cmp(val3)
   1422  *
   1423  *	Validate an op/cmp argument for FUTEX_WAKE_OP.
   1424  */
   1425 static int
   1426 futex_validate_op_cmp(int val3)
   1427 {
   1428 	int op = __SHIFTOUT(val3, FUTEX_OP_OP_MASK);
   1429 	int cmp = __SHIFTOUT(val3, FUTEX_OP_CMP_MASK);
   1430 
   1431 	if (op & FUTEX_OP_OPARG_SHIFT) {
   1432 		int oparg =
   1433 		    futex_opcmp_arg(__SHIFTOUT(val3, FUTEX_OP_OPARG_MASK));
   1434 		if (oparg < 0)
   1435 			return EINVAL;
   1436 		if (oparg >= 32)
   1437 			return EINVAL;
   1438 		op &= ~FUTEX_OP_OPARG_SHIFT;
   1439 	}
   1440 
   1441 	switch (op) {
   1442 	case FUTEX_OP_SET:
   1443 	case FUTEX_OP_ADD:
   1444 	case FUTEX_OP_OR:
   1445 	case FUTEX_OP_ANDN:
   1446 	case FUTEX_OP_XOR:
   1447 		break;
   1448 	default:
   1449 		return EINVAL;
   1450 	}
   1451 
   1452 	switch (cmp) {
   1453 	case FUTEX_OP_CMP_EQ:
   1454 	case FUTEX_OP_CMP_NE:
   1455 	case FUTEX_OP_CMP_LT:
   1456 	case FUTEX_OP_CMP_LE:
   1457 	case FUTEX_OP_CMP_GT:
   1458 	case FUTEX_OP_CMP_GE:
   1459 		break;
   1460 	default:
   1461 		return EINVAL;
   1462 	}
   1463 
   1464 	return 0;
   1465 }
   1466 
   1467 /*
   1468  * futex_compute_op(oldval, val3)
   1469  *
   1470  *	Apply a FUTEX_WAKE_OP operation to oldval.
   1471  */
   1472 static int
   1473 futex_compute_op(int oldval, int val3)
   1474 {
   1475 	int op = __SHIFTOUT(val3, FUTEX_OP_OP_MASK);
   1476 	int oparg = futex_opcmp_arg(__SHIFTOUT(val3, FUTEX_OP_OPARG_MASK));
   1477 
   1478 	if (op & FUTEX_OP_OPARG_SHIFT) {
   1479 		KASSERT(oparg >= 0);
   1480 		KASSERT(oparg < 32);
   1481 		oparg = 1u << oparg;
   1482 		op &= ~FUTEX_OP_OPARG_SHIFT;
   1483 	}
   1484 
   1485 	switch (op) {
   1486 	case FUTEX_OP_SET:
   1487 		return oparg;
   1488 
   1489 	case FUTEX_OP_ADD:
   1490 		/*
   1491 		 * Avoid signed arithmetic overflow by doing
   1492 		 * arithmetic unsigned and converting back to signed
   1493 		 * at the end.
   1494 		 */
   1495 		return (int)((unsigned)oldval + (unsigned)oparg);
   1496 
   1497 	case FUTEX_OP_OR:
   1498 		return oldval | oparg;
   1499 
   1500 	case FUTEX_OP_ANDN:
   1501 		return oldval & ~oparg;
   1502 
   1503 	case FUTEX_OP_XOR:
   1504 		return oldval ^ oparg;
   1505 
   1506 	default:
   1507 		panic("invalid futex op");
   1508 	}
   1509 }
   1510 
   1511 /*
   1512  * futex_compute_cmp(oldval, val3)
   1513  *
   1514  *	Apply a FUTEX_WAKE_OP comparison to oldval.
   1515  */
   1516 static bool
   1517 futex_compute_cmp(int oldval, int val3)
   1518 {
   1519 	int cmp = __SHIFTOUT(val3, FUTEX_OP_CMP_MASK);
   1520 	int cmparg = futex_opcmp_arg(__SHIFTOUT(val3, FUTEX_OP_CMPARG_MASK));
   1521 
   1522 	switch (cmp) {
   1523 	case FUTEX_OP_CMP_EQ:
   1524 		return (oldval == cmparg);
   1525 
   1526 	case FUTEX_OP_CMP_NE:
   1527 		return (oldval != cmparg);
   1528 
   1529 	case FUTEX_OP_CMP_LT:
   1530 		return (oldval < cmparg);
   1531 
   1532 	case FUTEX_OP_CMP_LE:
   1533 		return (oldval <= cmparg);
   1534 
   1535 	case FUTEX_OP_CMP_GT:
   1536 		return (oldval > cmparg);
   1537 
   1538 	case FUTEX_OP_CMP_GE:
   1539 		return (oldval >= cmparg);
   1540 
   1541 	default:
   1542 		panic("invalid futex cmp operation");
   1543 	}
   1544 }
   1545 
   1546 /*
   1547  * futex_func_wake_op(uaddr, val, uaddr2, val2, val3, retval)
   1548  *
   1549  *	Implement futex(FUTEX_WAKE_OP).
   1550  */
   1551 static int
   1552 futex_func_wake_op(bool shared, int *uaddr, int val, int *uaddr2, int val2,
   1553     int val3, register_t *retval)
   1554 {
   1555 	struct futex *f = NULL, *f2 = NULL;
   1556 	int oldval, newval, actual;
   1557 	unsigned nwoken = 0;
   1558 	int error;
   1559 
   1560 	/* Reject negative number of wakeups.  */
   1561 	if (val < 0 || val2 < 0) {
   1562 		error = EINVAL;
   1563 		goto out;
   1564 	}
   1565 
   1566 	/* Reject invalid operations before we start doing things.  */
   1567 	if ((error = futex_validate_op_cmp(val3)) != 0)
   1568 		goto out;
   1569 
   1570 	/* Look up the first futex, if any.  */
   1571 	error = futex_lookup(uaddr, shared, &f);
   1572 	if (error)
   1573 		goto out;
   1574 
   1575 	/* Look up the second futex, if any.  */
   1576 	error = futex_lookup(uaddr2, shared, &f2);
   1577 	if (error)
   1578 		goto out;
   1579 
   1580 	/*
   1581 	 * Under the queue locks:
   1582 	 *
   1583 	 * 1. Read/modify/write: *uaddr2 op= oparg.
   1584 	 * 2. Unconditionally wake uaddr.
   1585 	 * 3. Conditionally wake uaddr2, if it previously matched val2.
   1586 	 */
   1587 	futex_queue_lock2(f, f2);
   1588 	do {
   1589 		error = futex_load(uaddr2, &oldval);
   1590 		if (error)
   1591 			goto out_unlock;
   1592 		newval = futex_compute_op(oldval, val3);
   1593 		error = ucas_int(uaddr2, oldval, newval, &actual);
   1594 		if (error)
   1595 			goto out_unlock;
   1596 	} while (actual != oldval);
   1597 	if (f == NULL) {
   1598 		nwoken = 0;
   1599 	} else {
   1600 		nwoken = futex_wake(f, /*nwake*/val, NULL, /*nrequeue*/0,
   1601 		    FUTEX_BITSET_MATCH_ANY);
   1602 	}
   1603 	if (f2 && futex_compute_cmp(oldval, val3)) {
   1604 		nwoken += futex_wake(f2, /*nwake*/val2, NULL, /*nrequeue*/0,
   1605 		    FUTEX_BITSET_MATCH_ANY);
   1606 	}
   1607 
   1608 	/* Success! */
   1609 	error = 0;
   1610 out_unlock:
   1611 	futex_queue_unlock2(f, f2);
   1612 
   1613 out:
   1614 	/* Return the number of waiters woken. */
   1615 	*retval = nwoken;
   1616 
   1617 	/* Release the futexes, if we got them. */
   1618 	if (f2)
   1619 		futex_rele(f2);
   1620 	if (f)
   1621 		futex_rele(f);
   1622 	return error;
   1623 }
   1624 
   1625 /*
   1626  * do_futex(uaddr, op, val, timeout, uaddr2, val2, val3)
   1627  *
   1628  *	Implement the futex system call with all the parameters
   1629  *	parsed out.
   1630  */
   1631 int
   1632 do_futex(int *uaddr, int op, int val, const struct timespec *timeout,
   1633     int *uaddr2, int val2, int val3, register_t *retval)
   1634 {
   1635 	const bool shared = (op & FUTEX_PRIVATE_FLAG) ? false : true;
   1636 	const clockid_t clkid = (op & FUTEX_CLOCK_REALTIME) ? CLOCK_REALTIME
   1637 							    : CLOCK_MONOTONIC;
   1638 
   1639 	op &= FUTEX_CMD_MASK;
   1640 
   1641 	switch (op) {
   1642 	case FUTEX_WAIT:
   1643 		return futex_func_wait(shared, uaddr, val,
   1644 		    FUTEX_BITSET_MATCH_ANY, timeout, clkid, TIMER_RELTIME,
   1645 		    retval);
   1646 
   1647 	case FUTEX_WAKE:
   1648 		val3 = FUTEX_BITSET_MATCH_ANY;
   1649 		/* FALLTHROUGH */
   1650 	case FUTEX_WAKE_BITSET:
   1651 		return futex_func_wake(shared, uaddr, val, val3, retval);
   1652 
   1653 	case FUTEX_REQUEUE:
   1654 	case FUTEX_CMP_REQUEUE:
   1655 		return futex_func_requeue(shared, op, uaddr, val, uaddr2,
   1656 		    val2, val3, retval);
   1657 
   1658 	case FUTEX_WAIT_BITSET:
   1659 		return futex_func_wait(shared, uaddr, val, val3, timeout,
   1660 		    clkid, TIMER_ABSTIME, retval);
   1661 
   1662 	case FUTEX_WAKE_OP:
   1663 		return futex_func_wake_op(shared, uaddr, val, uaddr2, val2,
   1664 		    val3, retval);
   1665 
   1666 	case FUTEX_FD:
   1667 	default:
   1668 		return ENOSYS;
   1669 	}
   1670 }
   1671 
   1672 /*
   1673  * sys___futex(l, uap, retval)
   1674  *
   1675  *	__futex(2) system call: generic futex operations.
   1676  */
   1677 int
   1678 sys___futex(struct lwp *l, const struct sys___futex_args *uap,
   1679     register_t *retval)
   1680 {
   1681 	/* {
   1682 		syscallarg(int *) uaddr;
   1683 		syscallarg(int) op;
   1684 		syscallarg(int) val;
   1685 		syscallarg(const struct timespec *) timeout;
   1686 		syscallarg(int *) uaddr2;
   1687 		syscallarg(int) val2;
   1688 		syscallarg(int) val3;
   1689 	} */
   1690 	struct timespec ts, *tsp;
   1691 	int error;
   1692 
   1693 	/*
   1694 	 * Copy in the timeout argument, if specified.
   1695 	 */
   1696 	if (SCARG(uap, timeout)) {
   1697 		error = copyin(SCARG(uap, timeout), &ts, sizeof(ts));
   1698 		if (error)
   1699 			return error;
   1700 		tsp = &ts;
   1701 	} else {
   1702 		tsp = NULL;
   1703 	}
   1704 
   1705 	return do_futex(SCARG(uap, uaddr), SCARG(uap, op), SCARG(uap, val),
   1706 	    tsp, SCARG(uap, uaddr2), SCARG(uap, val2), SCARG(uap, val3),
   1707 	    retval);
   1708 }
   1709 
   1710 /*
   1711  * sys___futex_set_robust_list(l, uap, retval)
   1712  *
   1713  *	__futex_set_robust_list(2) system call for robust futexes.
   1714  */
   1715 int
   1716 sys___futex_set_robust_list(struct lwp *l,
   1717     const struct sys___futex_set_robust_list_args *uap, register_t *retval)
   1718 {
   1719 	/* {
   1720 		syscallarg(void *) head;
   1721 		syscallarg(size_t) len;
   1722 	} */
   1723 	void *head = SCARG(uap, head);
   1724 
   1725 	if (SCARG(uap, len) != _FUTEX_ROBUST_HEAD_SIZE)
   1726 		return EINVAL;
   1727 	if ((uintptr_t)head % sizeof(u_long))
   1728 		return EINVAL;
   1729 
   1730 	l->l_robust_head = (uintptr_t)head;
   1731 
   1732 	return 0;
   1733 }
   1734 
   1735 /*
   1736  * sys___futex_get_robust_list(l, uap, retval)
   1737  *
   1738  *	__futex_get_robust_list(2) system call for robust futexes.
   1739  */
   1740 int
   1741 sys___futex_get_robust_list(struct lwp *l,
   1742     const struct sys___futex_get_robust_list_args *uap, register_t *retval)
   1743 {
   1744 	/* {
   1745 		syscallarg(lwpid_t) lwpid;
   1746 		syscallarg(void **) headp;
   1747 		syscallarg(size_t *) lenp;
   1748 	} */
   1749 	void *head;
   1750 	const size_t len = _FUTEX_ROBUST_HEAD_SIZE;
   1751 	int error;
   1752 
   1753 	error = futex_robust_head_lookup(l, SCARG(uap, lwpid), &head);
   1754 	if (error)
   1755 		return error;
   1756 
   1757 	/* Copy out the head pointer and the head structure length. */
   1758 	error = copyout(&head, SCARG(uap, headp), sizeof(head));
   1759 	if (__predict_true(error == 0)) {
   1760 		error = copyout(&len, SCARG(uap, lenp), sizeof(len));
   1761 	}
   1762 
   1763 	return error;
   1764 }
   1765 
   1766 /*
   1767  * release_futex(uva, tid)
   1768  *
   1769  *	Try to release the robust futex at uva in the current process
   1770  *	on lwp exit.  If anything goes wrong, silently fail.  It is the
   1771  *	userland program's obligation to arrange correct behaviour.
   1772  */
   1773 static void
   1774 release_futex(uintptr_t const uptr, lwpid_t const tid, bool const is_pi,
   1775     bool const is_pending)
   1776 {
   1777 	int *uaddr;
   1778 	struct futex *f;
   1779 	int oldval, newval, actual;
   1780 	int error;
   1781 
   1782 	/* If it's misaligned, tough.  */
   1783 	if (__predict_false(uptr & 3))
   1784 		return;
   1785 	uaddr = (int *)uptr;
   1786 
   1787 	error = futex_load(uaddr, &oldval);
   1788 	if (__predict_false(error))
   1789 		return;
   1790 
   1791 	/*
   1792 	 * There are two race conditions we need to handle here:
   1793 	 *
   1794 	 * 1. User space cleared the futex word but died before
   1795 	 *    being able to issue the wakeup.  No wakeups will
   1796 	 *    ever be issued, oops!
   1797 	 *
   1798 	 * 2. Awakened waiter died before being able to acquire
   1799 	 *    the futex in user space.  Any other waiters are
   1800 	 *    now stuck, oops!
   1801 	 *
   1802 	 * In both of these cases, the futex word will be 0 (because
   1803 	 * it's updated before the wake is issued).  The best we can
   1804 	 * do is detect this situation if it's the pending futex and
   1805 	 * issue a wake without modifying the futex word.
   1806 	 *
   1807 	 * XXX eventual PI handling?
   1808 	 */
   1809 	if (__predict_false(is_pending && (oldval & ~FUTEX_WAITERS) == 0)) {
   1810 		register_t retval;
   1811 		(void) futex_func_wake(/*shared*/true, uaddr, 1,
   1812 		    FUTEX_BITSET_MATCH_ANY, &retval);
   1813 		return;
   1814 	}
   1815 
   1816 	/* Optimistically test whether we need to do anything at all.  */
   1817 	if ((oldval & FUTEX_TID_MASK) != tid)
   1818 		return;
   1819 
   1820 	/*
   1821 	 * We need to handle the case where this thread owned the futex,
   1822 	 * but it was uncontended.  In this case, there won't be any
   1823 	 * kernel state to look up.  All we can do is mark the futex
   1824 	 * as a zombie to be mopped up the next time another thread
   1825 	 * attempts to acquire it.
   1826 	 *
   1827 	 * N.B. It's important to ensure to set FUTEX_OWNER_DIED in
   1828 	 * this loop, even if waiters appear while we're are doing
   1829 	 * so.  This is beause FUTEX_WAITERS is set by user space
   1830 	 * before calling __futex() to wait, and the futex needs
   1831 	 * to be marked as a zombie when the new waiter gets into
   1832 	 * the kernel.
   1833 	 */
   1834 	if ((oldval & FUTEX_WAITERS) == 0) {
   1835 		do {
   1836 			error = futex_load(uaddr, &oldval);
   1837 			if (error)
   1838 				return;
   1839 			if ((oldval & FUTEX_TID_MASK) != tid)
   1840 				return;
   1841 			newval = oldval | FUTEX_OWNER_DIED;
   1842 			error = ucas_int(uaddr, oldval, newval, &actual);
   1843 			if (error)
   1844 				return;
   1845 		} while (actual != oldval);
   1846 
   1847 		/*
   1848 		 * If where is still no indication of waiters, then there is
   1849 		 * no more work for us to do.
   1850 		 */
   1851 		if ((oldval & FUTEX_WAITERS) == 0)
   1852 			return;
   1853 	}
   1854 
   1855 	/*
   1856 	 * Look for a shared futex since we have no positive indication
   1857 	 * it is private.  If we can't, tough.
   1858 	 */
   1859 	error = futex_lookup(uaddr, /*shared*/true, &f);
   1860 	if (error)
   1861 		return;
   1862 
   1863 	/*
   1864 	 * If there's no kernel state for this futex, there's nothing to
   1865 	 * release.
   1866 	 */
   1867 	if (f == NULL)
   1868 		return;
   1869 
   1870 	/* Work under the futex queue lock.  */
   1871 	futex_queue_lock(f);
   1872 
   1873 	/*
   1874 	 * Fetch the word: if the tid doesn't match ours, skip;
   1875 	 * otherwise, set the owner-died bit, atomically.
   1876 	 */
   1877 	do {
   1878 		error = futex_load(uaddr, &oldval);
   1879 		if (error)
   1880 			goto out;
   1881 		if ((oldval & FUTEX_TID_MASK) != tid)
   1882 			goto out;
   1883 		newval = oldval | FUTEX_OWNER_DIED;
   1884 		error = ucas_int(uaddr, oldval, newval, &actual);
   1885 		if (error)
   1886 			goto out;
   1887 	} while (actual != oldval);
   1888 
   1889 	/*
   1890 	 * If there may be waiters, try to wake one.  If anything goes
   1891 	 * wrong, tough.
   1892 	 *
   1893 	 * XXX eventual PI handling?
   1894 	 */
   1895 	if (oldval & FUTEX_WAITERS) {
   1896 		(void)futex_wake(f, /*nwake*/1, NULL, /*nrequeue*/0,
   1897 		    FUTEX_BITSET_MATCH_ANY);
   1898 	}
   1899 
   1900 	/* Unlock the queue and release the futex.  */
   1901 out:	futex_queue_unlock(f);
   1902 	futex_rele(f);
   1903 }
   1904 
   1905 /*
   1906  * futex_robust_head_lookup(l, lwpid)
   1907  *
   1908  *	Helper function to look up a robust head by LWP ID.
   1909  */
   1910 int
   1911 futex_robust_head_lookup(struct lwp *l, lwpid_t lwpid, void **headp)
   1912 {
   1913 	struct proc *p = l->l_proc;
   1914 
   1915 	/* Find the other lwp, if requested; otherwise use our robust head.  */
   1916 	if (lwpid) {
   1917 		mutex_enter(p->p_lock);
   1918 		l = lwp_find(p, lwpid);
   1919 		if (l == NULL) {
   1920 			mutex_exit(p->p_lock);
   1921 			return ESRCH;
   1922 		}
   1923 		*headp = (void *)l->l_robust_head;
   1924 		mutex_exit(p->p_lock);
   1925 	} else {
   1926 		*headp = (void *)l->l_robust_head;
   1927 	}
   1928 	return 0;
   1929 }
   1930 
   1931 /*
   1932  * futex_fetch_robust_head(uaddr)
   1933  *
   1934  *	Helper routine to fetch the futex robust list head that
   1935  *	handles 32-bit binaries running on 64-bit kernels.
   1936  */
   1937 static int
   1938 futex_fetch_robust_head(uintptr_t uaddr, u_long *rhead)
   1939 {
   1940 #ifdef _LP64
   1941 	if (curproc->p_flag & PK_32) {
   1942 		uint32_t rhead32[_FUTEX_ROBUST_HEAD_NWORDS];
   1943 		int error;
   1944 
   1945 		error = copyin((void *)uaddr, rhead32, sizeof(rhead32));
   1946 		if (__predict_true(error == 0)) {
   1947 			for (int i = 0; i < _FUTEX_ROBUST_HEAD_NWORDS; i++) {
   1948 				if (i == _FUTEX_ROBUST_HEAD_OFFSET) {
   1949 					/*
   1950 					 * Make sure the offset is sign-
   1951 					 * extended.
   1952 					 */
   1953 					rhead[i] = (int32_t)rhead32[i];
   1954 				} else {
   1955 					rhead[i] = rhead32[i];
   1956 				}
   1957 			}
   1958 		}
   1959 		return error;
   1960 	}
   1961 #endif /* _L64 */
   1962 
   1963 	return copyin((void *)uaddr, rhead,
   1964 	    sizeof(*rhead) * _FUTEX_ROBUST_HEAD_NWORDS);
   1965 }
   1966 
   1967 /*
   1968  * futex_decode_robust_word(word)
   1969  *
   1970  *	Decode a robust futex list word into the entry and entry
   1971  *	properties.
   1972  */
   1973 static inline void
   1974 futex_decode_robust_word(uintptr_t const word, uintptr_t * const entry,
   1975     bool * const is_pi)
   1976 {
   1977 	*is_pi = (word & _FUTEX_ROBUST_ENTRY_PI) ? true : false;
   1978 	*entry = word & ~_FUTEX_ROBUST_ENTRY_PI;
   1979 }
   1980 
   1981 /*
   1982  * futex_fetch_robust_entry(uaddr)
   1983  *
   1984  *	Helper routine to fetch and decode a robust futex entry
   1985  *	that handles 32-bit binaries running on 64-bit kernels.
   1986  */
   1987 static int
   1988 futex_fetch_robust_entry(uintptr_t const uaddr, uintptr_t * const valp,
   1989     bool * const is_pi)
   1990 {
   1991 	uintptr_t val = 0;
   1992 	int error = 0;
   1993 
   1994 #ifdef _LP64
   1995 	if (curproc->p_flag & PK_32) {
   1996 		uint32_t val32;
   1997 
   1998 		error = ufetch_32((uint32_t *)uaddr, &val32);
   1999 		if (__predict_true(error == 0))
   2000 			val = val32;
   2001 	} else
   2002 #endif /* _LP64 */
   2003 		error = ufetch_long((u_long *)uaddr, (u_long *)&val);
   2004 	if (__predict_false(error))
   2005 		return error;
   2006 
   2007 	futex_decode_robust_word(val, valp, is_pi);
   2008 	return 0;
   2009 }
   2010 
   2011 /*
   2012  * futex_release_all_lwp(l, tid)
   2013  *
   2014  *	Release all l's robust futexes.  If anything looks funny in
   2015  *	the process, give up -- it's userland's responsibility to dot
   2016  *	the i's and cross the t's.
   2017  */
   2018 void
   2019 futex_release_all_lwp(struct lwp * const l)
   2020 {
   2021 	u_long rhead[_FUTEX_ROBUST_HEAD_NWORDS];
   2022 	int limit = 1000000;
   2023 	int error;
   2024 
   2025 	/* If there's no robust list there's nothing to do. */
   2026 	if (l->l_robust_head == 0)
   2027 		return;
   2028 
   2029 	KASSERT((l->l_lid & FUTEX_TID_MASK) == l->l_lid);
   2030 
   2031 	/* Read the final snapshot of the robust list head. */
   2032 	error = futex_fetch_robust_head(l->l_robust_head, rhead);
   2033 	if (error) {
   2034 		printf("WARNING: pid %jd (%s) lwp %jd:"
   2035 		    " unmapped robust futex list head\n",
   2036 		    (uintmax_t)l->l_proc->p_pid, l->l_proc->p_comm,
   2037 		    (uintmax_t)l->l_lid);
   2038 		return;
   2039 	}
   2040 
   2041 	const long offset = (long)rhead[_FUTEX_ROBUST_HEAD_OFFSET];
   2042 
   2043 	uintptr_t next, pending;
   2044 	bool is_pi, pending_is_pi;
   2045 
   2046 	futex_decode_robust_word(rhead[_FUTEX_ROBUST_HEAD_LIST],
   2047 	    &next, &is_pi);
   2048 	futex_decode_robust_word(rhead[_FUTEX_ROBUST_HEAD_PENDING],
   2049 	    &pending, &pending_is_pi);
   2050 
   2051 	/*
   2052 	 * Walk down the list of locked futexes and release them, up
   2053 	 * to one million of them before we give up.
   2054 	 */
   2055 
   2056 	while (next != l->l_robust_head && limit-- > 0) {
   2057 		/* pending handled below. */
   2058 		if (next != pending)
   2059 			release_futex(next + offset, l->l_lid, is_pi, false);
   2060 		error = futex_fetch_robust_entry(next, &next, &is_pi);
   2061 		if (error)
   2062 			break;
   2063 		preempt_point();
   2064 	}
   2065 	if (limit <= 0) {
   2066 		printf("WARNING: pid %jd (%s) lwp %jd:"
   2067 		    " exhausted robust futex limit\n",
   2068 		    (uintmax_t)l->l_proc->p_pid, l->l_proc->p_comm,
   2069 		    (uintmax_t)l->l_lid);
   2070 	}
   2071 
   2072 	/* If there's a pending futex, it may need to be released too. */
   2073 	if (pending != 0) {
   2074 		release_futex(pending + offset, l->l_lid, pending_is_pi, true);
   2075 	}
   2076 }
   2077