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