]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_umtx.c
Revert "vnode read(2)/write(2): acquire rangelock regardless of do_vn_io_fault()"
[FreeBSD/FreeBSD.git] / sys / kern / kern_umtx.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2015, 2016 The FreeBSD Foundation
5  * Copyright (c) 2004, David Xu <davidxu@freebsd.org>
6  * Copyright (c) 2002, Jeffrey Roberson <jeff@freebsd.org>
7  * All rights reserved.
8  *
9  * Portions of this software were developed by Konstantin Belousov
10  * under sponsorship from the FreeBSD Foundation.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice unmodified, this list of conditions, and the following
17  *    disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_umtx_profiling.h"
38
39 #include <sys/param.h>
40 #include <sys/kernel.h>
41 #include <sys/fcntl.h>
42 #include <sys/file.h>
43 #include <sys/filedesc.h>
44 #include <sys/limits.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/mman.h>
48 #include <sys/mutex.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/resource.h>
52 #include <sys/resourcevar.h>
53 #include <sys/rwlock.h>
54 #include <sys/sbuf.h>
55 #include <sys/sched.h>
56 #include <sys/smp.h>
57 #include <sys/sysctl.h>
58 #include <sys/systm.h>
59 #include <sys/sysproto.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/taskqueue.h>
62 #include <sys/time.h>
63 #include <sys/eventhandler.h>
64 #include <sys/umtx.h>
65 #include <sys/umtxvar.h>
66
67 #include <security/mac/mac_framework.h>
68
69 #include <vm/vm.h>
70 #include <vm/vm_param.h>
71 #include <vm/pmap.h>
72 #include <vm/vm_map.h>
73 #include <vm/vm_object.h>
74
75 #include <machine/atomic.h>
76 #include <machine/cpu.h>
77
78 #include <compat/freebsd32/freebsd32.h>
79 #ifdef COMPAT_FREEBSD32
80 #include <compat/freebsd32/freebsd32_proto.h>
81 #endif
82
83 #define _UMUTEX_TRY             1
84 #define _UMUTEX_WAIT            2
85
86 #ifdef UMTX_PROFILING
87 #define UPROF_PERC_BIGGER(w, f, sw, sf)                                 \
88         (((w) > (sw)) || ((w) == (sw) && (f) > (sf)))
89 #endif
90
91 #define UMTXQ_LOCKED_ASSERT(uc)         mtx_assert(&(uc)->uc_lock, MA_OWNED)
92 #ifdef INVARIANTS
93 #define UMTXQ_ASSERT_LOCKED_BUSY(key) do {                              \
94         struct umtxq_chain *uc;                                         \
95                                                                         \
96         uc = umtxq_getchain(key);                                       \
97         mtx_assert(&uc->uc_lock, MA_OWNED);                             \
98         KASSERT(uc->uc_busy != 0, ("umtx chain is not busy"));          \
99 } while (0)
100 #else
101 #define UMTXQ_ASSERT_LOCKED_BUSY(key) do {} while (0)
102 #endif
103
104 /*
105  * Don't propagate time-sharing priority, there is a security reason,
106  * a user can simply introduce PI-mutex, let thread A lock the mutex,
107  * and let another thread B block on the mutex, because B is
108  * sleeping, its priority will be boosted, this causes A's priority to
109  * be boosted via priority propagating too and will never be lowered even
110  * if it is using 100%CPU, this is unfair to other processes.
111  */
112
113 #define UPRI(td)        (((td)->td_user_pri >= PRI_MIN_TIMESHARE &&\
114                           (td)->td_user_pri <= PRI_MAX_TIMESHARE) ?\
115                          PRI_MAX_TIMESHARE : (td)->td_user_pri)
116
117 #define GOLDEN_RATIO_PRIME      2654404609U
118 #ifndef UMTX_CHAINS
119 #define UMTX_CHAINS             512
120 #endif
121 #define UMTX_SHIFTS             (__WORD_BIT - 9)
122
123 #define GET_SHARE(flags)        \
124     (((flags) & USYNC_PROCESS_SHARED) == 0 ? THREAD_SHARE : PROCESS_SHARE)
125
126 #define BUSY_SPINS              200
127
128 struct umtx_copyops {
129         int     (*copyin_timeout)(const void *uaddr, struct timespec *tsp);
130         int     (*copyin_umtx_time)(const void *uaddr, size_t size,
131             struct _umtx_time *tp);
132         int     (*copyin_robust_lists)(const void *uaddr, size_t size,
133             struct umtx_robust_lists_params *rbp);
134         int     (*copyout_timeout)(void *uaddr, size_t size,
135             struct timespec *tsp);
136         const size_t    timespec_sz;
137         const size_t    umtx_time_sz;
138         const bool      compat32;
139 };
140
141 _Static_assert(sizeof(struct umutex) == sizeof(struct umutex32), "umutex32");
142 _Static_assert(__offsetof(struct umutex, m_spare[0]) ==
143     __offsetof(struct umutex32, m_spare[0]), "m_spare32");
144
145 int umtx_shm_vnobj_persistent = 0;
146 SYSCTL_INT(_kern_ipc, OID_AUTO, umtx_vnode_persistent, CTLFLAG_RWTUN,
147     &umtx_shm_vnobj_persistent, 0,
148     "False forces destruction of umtx attached to file, on last close");
149 static int umtx_max_rb = 1000;
150 SYSCTL_INT(_kern_ipc, OID_AUTO, umtx_max_robust, CTLFLAG_RWTUN,
151     &umtx_max_rb, 0,
152     "Maximum number of robust mutexes allowed for each thread");
153
154 static uma_zone_t               umtx_pi_zone;
155 static struct umtxq_chain       umtxq_chains[2][UMTX_CHAINS];
156 static MALLOC_DEFINE(M_UMTX, "umtx", "UMTX queue memory");
157 static int                      umtx_pi_allocated;
158
159 static SYSCTL_NODE(_debug, OID_AUTO, umtx, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
160     "umtx debug");
161 SYSCTL_INT(_debug_umtx, OID_AUTO, umtx_pi_allocated, CTLFLAG_RD,
162     &umtx_pi_allocated, 0, "Allocated umtx_pi");
163 static int umtx_verbose_rb = 1;
164 SYSCTL_INT(_debug_umtx, OID_AUTO, robust_faults_verbose, CTLFLAG_RWTUN,
165     &umtx_verbose_rb, 0,
166     "");
167
168 #ifdef UMTX_PROFILING
169 static long max_length;
170 SYSCTL_LONG(_debug_umtx, OID_AUTO, max_length, CTLFLAG_RD, &max_length, 0, "max_length");
171 static SYSCTL_NODE(_debug_umtx, OID_AUTO, chains, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
172     "umtx chain stats");
173 #endif
174
175 static inline void umtx_abs_timeout_init2(struct umtx_abs_timeout *timo,
176     const struct _umtx_time *umtxtime);
177
178 static void umtx_shm_init(void);
179 static void umtxq_sysinit(void *);
180 static void umtxq_hash(struct umtx_key *key);
181 static int do_unlock_pp(struct thread *td, struct umutex *m, uint32_t flags,
182     bool rb);
183 static void umtx_thread_cleanup(struct thread *td);
184 SYSINIT(umtx, SI_SUB_EVENTHANDLER+1, SI_ORDER_MIDDLE, umtxq_sysinit, NULL);
185
186 #define umtxq_signal(key, nwake)        umtxq_signal_queue((key), (nwake), UMTX_SHARED_QUEUE)
187
188 static struct mtx umtx_lock;
189
190 #ifdef UMTX_PROFILING
191 static void
192 umtx_init_profiling(void)
193 {
194         struct sysctl_oid *chain_oid;
195         char chain_name[10];
196         int i;
197
198         for (i = 0; i < UMTX_CHAINS; ++i) {
199                 snprintf(chain_name, sizeof(chain_name), "%d", i);
200                 chain_oid = SYSCTL_ADD_NODE(NULL,
201                     SYSCTL_STATIC_CHILDREN(_debug_umtx_chains), OID_AUTO,
202                     chain_name, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
203                     "umtx hash stats");
204                 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(chain_oid), OID_AUTO,
205                     "max_length0", CTLFLAG_RD, &umtxq_chains[0][i].max_length, 0, NULL);
206                 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(chain_oid), OID_AUTO,
207                     "max_length1", CTLFLAG_RD, &umtxq_chains[1][i].max_length, 0, NULL);
208         }
209 }
210
211 static int
212 sysctl_debug_umtx_chains_peaks(SYSCTL_HANDLER_ARGS)
213 {
214         char buf[512];
215         struct sbuf sb;
216         struct umtxq_chain *uc;
217         u_int fract, i, j, tot, whole;
218         u_int sf0, sf1, sf2, sf3, sf4;
219         u_int si0, si1, si2, si3, si4;
220         u_int sw0, sw1, sw2, sw3, sw4;
221
222         sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
223         for (i = 0; i < 2; i++) {
224                 tot = 0;
225                 for (j = 0; j < UMTX_CHAINS; ++j) {
226                         uc = &umtxq_chains[i][j];
227                         mtx_lock(&uc->uc_lock);
228                         tot += uc->max_length;
229                         mtx_unlock(&uc->uc_lock);
230                 }
231                 if (tot == 0)
232                         sbuf_printf(&sb, "%u) Empty ", i);
233                 else {
234                         sf0 = sf1 = sf2 = sf3 = sf4 = 0;
235                         si0 = si1 = si2 = si3 = si4 = 0;
236                         sw0 = sw1 = sw2 = sw3 = sw4 = 0;
237                         for (j = 0; j < UMTX_CHAINS; j++) {
238                                 uc = &umtxq_chains[i][j];
239                                 mtx_lock(&uc->uc_lock);
240                                 whole = uc->max_length * 100;
241                                 mtx_unlock(&uc->uc_lock);
242                                 fract = (whole % tot) * 100;
243                                 if (UPROF_PERC_BIGGER(whole, fract, sw0, sf0)) {
244                                         sf0 = fract;
245                                         si0 = j;
246                                         sw0 = whole;
247                                 } else if (UPROF_PERC_BIGGER(whole, fract, sw1,
248                                     sf1)) {
249                                         sf1 = fract;
250                                         si1 = j;
251                                         sw1 = whole;
252                                 } else if (UPROF_PERC_BIGGER(whole, fract, sw2,
253                                     sf2)) {
254                                         sf2 = fract;
255                                         si2 = j;
256                                         sw2 = whole;
257                                 } else if (UPROF_PERC_BIGGER(whole, fract, sw3,
258                                     sf3)) {
259                                         sf3 = fract;
260                                         si3 = j;
261                                         sw3 = whole;
262                                 } else if (UPROF_PERC_BIGGER(whole, fract, sw4,
263                                     sf4)) {
264                                         sf4 = fract;
265                                         si4 = j;
266                                         sw4 = whole;
267                                 }
268                         }
269                         sbuf_printf(&sb, "queue %u:\n", i);
270                         sbuf_printf(&sb, "1st: %u.%u%% idx: %u\n", sw0 / tot,
271                             sf0 / tot, si0);
272                         sbuf_printf(&sb, "2nd: %u.%u%% idx: %u\n", sw1 / tot,
273                             sf1 / tot, si1);
274                         sbuf_printf(&sb, "3rd: %u.%u%% idx: %u\n", sw2 / tot,
275                             sf2 / tot, si2);
276                         sbuf_printf(&sb, "4th: %u.%u%% idx: %u\n", sw3 / tot,
277                             sf3 / tot, si3);
278                         sbuf_printf(&sb, "5th: %u.%u%% idx: %u\n", sw4 / tot,
279                             sf4 / tot, si4);
280                 }
281         }
282         sbuf_trim(&sb);
283         sbuf_finish(&sb);
284         sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
285         sbuf_delete(&sb);
286         return (0);
287 }
288
289 static int
290 sysctl_debug_umtx_chains_clear(SYSCTL_HANDLER_ARGS)
291 {
292         struct umtxq_chain *uc;
293         u_int i, j;
294         int clear, error;
295
296         clear = 0;
297         error = sysctl_handle_int(oidp, &clear, 0, req);
298         if (error != 0 || req->newptr == NULL)
299                 return (error);
300
301         if (clear != 0) {
302                 for (i = 0; i < 2; ++i) {
303                         for (j = 0; j < UMTX_CHAINS; ++j) {
304                                 uc = &umtxq_chains[i][j];
305                                 mtx_lock(&uc->uc_lock);
306                                 uc->length = 0;
307                                 uc->max_length = 0;
308                                 mtx_unlock(&uc->uc_lock);
309                         }
310                 }
311         }
312         return (0);
313 }
314
315 SYSCTL_PROC(_debug_umtx_chains, OID_AUTO, clear,
316     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
317     sysctl_debug_umtx_chains_clear, "I",
318     "Clear umtx chains statistics");
319 SYSCTL_PROC(_debug_umtx_chains, OID_AUTO, peaks,
320     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, 0, 0,
321     sysctl_debug_umtx_chains_peaks, "A",
322     "Highest peaks in chains max length");
323 #endif
324
325 static void
326 umtxq_sysinit(void *arg __unused)
327 {
328         int i, j;
329
330         umtx_pi_zone = uma_zcreate("umtx pi", sizeof(struct umtx_pi),
331                 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
332         for (i = 0; i < 2; ++i) {
333                 for (j = 0; j < UMTX_CHAINS; ++j) {
334                         mtx_init(&umtxq_chains[i][j].uc_lock, "umtxql", NULL,
335                                  MTX_DEF | MTX_DUPOK);
336                         LIST_INIT(&umtxq_chains[i][j].uc_queue[0]);
337                         LIST_INIT(&umtxq_chains[i][j].uc_queue[1]);
338                         LIST_INIT(&umtxq_chains[i][j].uc_spare_queue);
339                         TAILQ_INIT(&umtxq_chains[i][j].uc_pi_list);
340                         umtxq_chains[i][j].uc_busy = 0;
341                         umtxq_chains[i][j].uc_waiters = 0;
342 #ifdef UMTX_PROFILING
343                         umtxq_chains[i][j].length = 0;
344                         umtxq_chains[i][j].max_length = 0;
345 #endif
346                 }
347         }
348 #ifdef UMTX_PROFILING
349         umtx_init_profiling();
350 #endif
351         mtx_init(&umtx_lock, "umtx lock", NULL, MTX_DEF);
352         umtx_shm_init();
353 }
354
355 struct umtx_q *
356 umtxq_alloc(void)
357 {
358         struct umtx_q *uq;
359
360         uq = malloc(sizeof(struct umtx_q), M_UMTX, M_WAITOK | M_ZERO);
361         uq->uq_spare_queue = malloc(sizeof(struct umtxq_queue), M_UMTX,
362             M_WAITOK | M_ZERO);
363         TAILQ_INIT(&uq->uq_spare_queue->head);
364         TAILQ_INIT(&uq->uq_pi_contested);
365         uq->uq_inherited_pri = PRI_MAX;
366         return (uq);
367 }
368
369 void
370 umtxq_free(struct umtx_q *uq)
371 {
372
373         MPASS(uq->uq_spare_queue != NULL);
374         free(uq->uq_spare_queue, M_UMTX);
375         free(uq, M_UMTX);
376 }
377
378 static inline void
379 umtxq_hash(struct umtx_key *key)
380 {
381         unsigned n;
382
383         n = (uintptr_t)key->info.both.a + key->info.both.b;
384         key->hash = ((n * GOLDEN_RATIO_PRIME) >> UMTX_SHIFTS) % UMTX_CHAINS;
385 }
386
387 struct umtxq_chain *
388 umtxq_getchain(struct umtx_key *key)
389 {
390
391         if (key->type <= TYPE_SEM)
392                 return (&umtxq_chains[1][key->hash]);
393         return (&umtxq_chains[0][key->hash]);
394 }
395
396 /*
397  * Set chain to busy state when following operation
398  * may be blocked (kernel mutex can not be used).
399  */
400 void
401 umtxq_busy(struct umtx_key *key)
402 {
403         struct umtxq_chain *uc;
404
405         uc = umtxq_getchain(key);
406         mtx_assert(&uc->uc_lock, MA_OWNED);
407         if (uc->uc_busy) {
408 #ifdef SMP
409                 if (smp_cpus > 1) {
410                         int count = BUSY_SPINS;
411                         if (count > 0) {
412                                 umtxq_unlock(key);
413                                 while (uc->uc_busy && --count > 0)
414                                         cpu_spinwait();
415                                 umtxq_lock(key);
416                         }
417                 }
418 #endif
419                 while (uc->uc_busy) {
420                         uc->uc_waiters++;
421                         msleep(uc, &uc->uc_lock, 0, "umtxqb", 0);
422                         uc->uc_waiters--;
423                 }
424         }
425         uc->uc_busy = 1;
426 }
427
428 /*
429  * Unbusy a chain.
430  */
431 void
432 umtxq_unbusy(struct umtx_key *key)
433 {
434         struct umtxq_chain *uc;
435
436         uc = umtxq_getchain(key);
437         mtx_assert(&uc->uc_lock, MA_OWNED);
438         KASSERT(uc->uc_busy != 0, ("not busy"));
439         uc->uc_busy = 0;
440         if (uc->uc_waiters)
441                 wakeup_one(uc);
442 }
443
444 void
445 umtxq_unbusy_unlocked(struct umtx_key *key)
446 {
447
448         umtxq_lock(key);
449         umtxq_unbusy(key);
450         umtxq_unlock(key);
451 }
452
453 static struct umtxq_queue *
454 umtxq_queue_lookup(struct umtx_key *key, int q)
455 {
456         struct umtxq_queue *uh;
457         struct umtxq_chain *uc;
458
459         uc = umtxq_getchain(key);
460         UMTXQ_LOCKED_ASSERT(uc);
461         LIST_FOREACH(uh, &uc->uc_queue[q], link) {
462                 if (umtx_key_match(&uh->key, key))
463                         return (uh);
464         }
465
466         return (NULL);
467 }
468
469 void
470 umtxq_insert_queue(struct umtx_q *uq, int q)
471 {
472         struct umtxq_queue *uh;
473         struct umtxq_chain *uc;
474
475         uc = umtxq_getchain(&uq->uq_key);
476         UMTXQ_LOCKED_ASSERT(uc);
477         KASSERT((uq->uq_flags & UQF_UMTXQ) == 0, ("umtx_q is already on queue"));
478         uh = umtxq_queue_lookup(&uq->uq_key, q);
479         if (uh != NULL) {
480                 LIST_INSERT_HEAD(&uc->uc_spare_queue, uq->uq_spare_queue, link);
481         } else {
482                 uh = uq->uq_spare_queue;
483                 uh->key = uq->uq_key;
484                 LIST_INSERT_HEAD(&uc->uc_queue[q], uh, link);
485 #ifdef UMTX_PROFILING
486                 uc->length++;
487                 if (uc->length > uc->max_length) {
488                         uc->max_length = uc->length;
489                         if (uc->max_length > max_length)
490                                 max_length = uc->max_length;
491                 }
492 #endif
493         }
494         uq->uq_spare_queue = NULL;
495
496         TAILQ_INSERT_TAIL(&uh->head, uq, uq_link);
497         uh->length++;
498         uq->uq_flags |= UQF_UMTXQ;
499         uq->uq_cur_queue = uh;
500         return;
501 }
502
503 void
504 umtxq_remove_queue(struct umtx_q *uq, int q)
505 {
506         struct umtxq_chain *uc;
507         struct umtxq_queue *uh;
508
509         uc = umtxq_getchain(&uq->uq_key);
510         UMTXQ_LOCKED_ASSERT(uc);
511         if (uq->uq_flags & UQF_UMTXQ) {
512                 uh = uq->uq_cur_queue;
513                 TAILQ_REMOVE(&uh->head, uq, uq_link);
514                 uh->length--;
515                 uq->uq_flags &= ~UQF_UMTXQ;
516                 if (TAILQ_EMPTY(&uh->head)) {
517                         KASSERT(uh->length == 0,
518                             ("inconsistent umtxq_queue length"));
519 #ifdef UMTX_PROFILING
520                         uc->length--;
521 #endif
522                         LIST_REMOVE(uh, link);
523                 } else {
524                         uh = LIST_FIRST(&uc->uc_spare_queue);
525                         KASSERT(uh != NULL, ("uc_spare_queue is empty"));
526                         LIST_REMOVE(uh, link);
527                 }
528                 uq->uq_spare_queue = uh;
529                 uq->uq_cur_queue = NULL;
530         }
531 }
532
533 /*
534  * Check if there are multiple waiters
535  */
536 int
537 umtxq_count(struct umtx_key *key)
538 {
539         struct umtxq_queue *uh;
540
541         UMTXQ_LOCKED_ASSERT(umtxq_getchain(key));
542         uh = umtxq_queue_lookup(key, UMTX_SHARED_QUEUE);
543         if (uh != NULL)
544                 return (uh->length);
545         return (0);
546 }
547
548 /*
549  * Check if there are multiple PI waiters and returns first
550  * waiter.
551  */
552 static int
553 umtxq_count_pi(struct umtx_key *key, struct umtx_q **first)
554 {
555         struct umtxq_queue *uh;
556
557         *first = NULL;
558         UMTXQ_LOCKED_ASSERT(umtxq_getchain(key));
559         uh = umtxq_queue_lookup(key, UMTX_SHARED_QUEUE);
560         if (uh != NULL) {
561                 *first = TAILQ_FIRST(&uh->head);
562                 return (uh->length);
563         }
564         return (0);
565 }
566
567 /*
568  * Wake up threads waiting on an userland object by a bit mask.
569  */
570 int
571 umtxq_signal_mask(struct umtx_key *key, int n_wake, u_int bitset)
572 {
573         struct umtxq_queue *uh;
574         struct umtx_q *uq, *uq_temp;
575         int ret;
576
577         ret = 0;
578         UMTXQ_LOCKED_ASSERT(umtxq_getchain(key));
579         uh = umtxq_queue_lookup(key, UMTX_SHARED_QUEUE);
580         if (uh == NULL)
581                 return (0);
582         TAILQ_FOREACH_SAFE(uq, &uh->head, uq_link, uq_temp) {
583                 if ((uq->uq_bitset & bitset) == 0)
584                         continue;
585                 umtxq_remove_queue(uq, UMTX_SHARED_QUEUE);
586                 wakeup_one(uq);
587                 if (++ret >= n_wake)
588                         break;
589         }
590         return (ret);
591 }
592
593 /*
594  * Wake up threads waiting on an userland object.
595  */
596
597 static int
598 umtxq_signal_queue(struct umtx_key *key, int n_wake, int q)
599 {
600         struct umtxq_queue *uh;
601         struct umtx_q *uq;
602         int ret;
603
604         ret = 0;
605         UMTXQ_LOCKED_ASSERT(umtxq_getchain(key));
606         uh = umtxq_queue_lookup(key, q);
607         if (uh != NULL) {
608                 while ((uq = TAILQ_FIRST(&uh->head)) != NULL) {
609                         umtxq_remove_queue(uq, q);
610                         wakeup(uq);
611                         if (++ret >= n_wake)
612                                 return (ret);
613                 }
614         }
615         return (ret);
616 }
617
618 /*
619  * Wake up specified thread.
620  */
621 static inline void
622 umtxq_signal_thread(struct umtx_q *uq)
623 {
624
625         UMTXQ_LOCKED_ASSERT(umtxq_getchain(&uq->uq_key));
626         umtxq_remove(uq);
627         wakeup(uq);
628 }
629
630 /*
631  * Wake up a maximum of n_wake threads that are waiting on an userland
632  * object identified by key. The remaining threads are removed from queue
633  * identified by key and added to the queue identified by key2 (requeued).
634  * The n_requeue specifies an upper limit on the number of threads that
635  * are requeued to the second queue.
636  */
637 int
638 umtxq_requeue(struct umtx_key *key, int n_wake, struct umtx_key *key2,
639     int n_requeue)
640 {
641         struct umtxq_queue *uh, *uh2;
642         struct umtx_q *uq, *uq_temp;
643         int ret;
644
645         ret = 0;
646         UMTXQ_LOCKED_ASSERT(umtxq_getchain(key));
647         UMTXQ_LOCKED_ASSERT(umtxq_getchain(key2));
648         uh = umtxq_queue_lookup(key, UMTX_SHARED_QUEUE);
649         uh2 = umtxq_queue_lookup(key2, UMTX_SHARED_QUEUE);
650         if (uh == NULL)
651                 return (0);
652         TAILQ_FOREACH_SAFE(uq, &uh->head, uq_link, uq_temp) {
653                 if (++ret <= n_wake) {
654                         umtxq_remove(uq);
655                         wakeup_one(uq);
656                 } else {
657                         umtxq_remove(uq);
658                         uq->uq_key = *key2;
659                         umtxq_insert(uq);
660                         if (ret - n_wake == n_requeue)
661                                 break;
662                 }
663         }
664         return (ret);
665 }
666
667 static inline int
668 tstohz(const struct timespec *tsp)
669 {
670         struct timeval tv;
671
672         TIMESPEC_TO_TIMEVAL(&tv, tsp);
673         return tvtohz(&tv);
674 }
675
676 void
677 umtx_abs_timeout_init(struct umtx_abs_timeout *timo, int clockid,
678     int absolute, const struct timespec *timeout)
679 {
680
681         timo->clockid = clockid;
682         if (!absolute) {
683                 timo->is_abs_real = false;
684                 kern_clock_gettime(curthread, timo->clockid, &timo->cur);
685                 timespecadd(&timo->cur, timeout, &timo->end);
686         } else {
687                 timo->end = *timeout;
688                 timo->is_abs_real = clockid == CLOCK_REALTIME ||
689                     clockid == CLOCK_REALTIME_FAST ||
690                     clockid == CLOCK_REALTIME_PRECISE ||
691                     clockid == CLOCK_SECOND;
692         }
693 }
694
695 static void
696 umtx_abs_timeout_init2(struct umtx_abs_timeout *timo,
697     const struct _umtx_time *umtxtime)
698 {
699
700         umtx_abs_timeout_init(timo, umtxtime->_clockid,
701             (umtxtime->_flags & UMTX_ABSTIME) != 0, &umtxtime->_timeout);
702 }
703
704 static void
705 umtx_abs_timeout_enforce_min(sbintime_t *sbt)
706 {
707         sbintime_t when, mint;
708
709         mint = curproc->p_umtx_min_timeout;
710         if (__predict_false(mint != 0)) {
711                 when = sbinuptime() + mint;
712                 if (*sbt < when)
713                         *sbt = when;
714         }
715 }
716
717 static int
718 umtx_abs_timeout_getsbt(struct umtx_abs_timeout *timo, sbintime_t *sbt,
719     int *flags)
720 {
721         struct bintime bt, bbt;
722         struct timespec tts;
723         sbintime_t rem;
724
725         switch (timo->clockid) {
726
727         /* Clocks that can be converted into absolute time. */
728         case CLOCK_REALTIME:
729         case CLOCK_REALTIME_PRECISE:
730         case CLOCK_REALTIME_FAST:
731         case CLOCK_MONOTONIC:
732         case CLOCK_MONOTONIC_PRECISE:
733         case CLOCK_MONOTONIC_FAST:
734         case CLOCK_UPTIME:
735         case CLOCK_UPTIME_PRECISE:
736         case CLOCK_UPTIME_FAST:
737         case CLOCK_SECOND:
738                 timespec2bintime(&timo->end, &bt);
739                 switch (timo->clockid) {
740                 case CLOCK_REALTIME:
741                 case CLOCK_REALTIME_PRECISE:
742                 case CLOCK_REALTIME_FAST:
743                 case CLOCK_SECOND:
744                         getboottimebin(&bbt);
745                         bintime_sub(&bt, &bbt);
746                         break;
747                 }
748                 if (bt.sec < 0)
749                         return (ETIMEDOUT);
750                 if (bt.sec >= (SBT_MAX >> 32)) {
751                         *sbt = 0;
752                         *flags = 0;
753                         return (0);
754                 }
755                 *sbt = bttosbt(bt);
756                 umtx_abs_timeout_enforce_min(sbt);
757
758                 /*
759                  * Check if the absolute time should be aligned to
760                  * avoid firing multiple timer events in non-periodic
761                  * timer mode.
762                  */
763                 switch (timo->clockid) {
764                 case CLOCK_REALTIME_FAST:
765                 case CLOCK_MONOTONIC_FAST:
766                 case CLOCK_UPTIME_FAST:
767                         rem = *sbt % tc_tick_sbt;
768                         if (__predict_true(rem != 0))
769                                 *sbt += tc_tick_sbt - rem;
770                         break;
771                 case CLOCK_SECOND:
772                         rem = *sbt % SBT_1S;
773                         if (__predict_true(rem != 0))
774                                 *sbt += SBT_1S - rem;
775                         break;
776                 }
777                 *flags = C_ABSOLUTE;
778                 return (0);
779
780         /* Clocks that has to be periodically polled. */
781         case CLOCK_VIRTUAL:
782         case CLOCK_PROF:
783         case CLOCK_THREAD_CPUTIME_ID:
784         case CLOCK_PROCESS_CPUTIME_ID:
785         default:
786                 kern_clock_gettime(curthread, timo->clockid, &timo->cur);
787                 if (timespeccmp(&timo->end, &timo->cur, <=))
788                         return (ETIMEDOUT);
789                 timespecsub(&timo->end, &timo->cur, &tts);
790                 *sbt = tick_sbt * tstohz(&tts);
791                 *flags = C_HARDCLOCK;
792                 return (0);
793         }
794 }
795
796 static uint32_t
797 umtx_unlock_val(uint32_t flags, bool rb)
798 {
799
800         if (rb)
801                 return (UMUTEX_RB_OWNERDEAD);
802         else if ((flags & UMUTEX_NONCONSISTENT) != 0)
803                 return (UMUTEX_RB_NOTRECOV);
804         else
805                 return (UMUTEX_UNOWNED);
806
807 }
808
809 /*
810  * Put thread into sleep state, before sleeping, check if
811  * thread was removed from umtx queue.
812  */
813 int
814 umtxq_sleep(struct umtx_q *uq, const char *wmesg,
815     struct umtx_abs_timeout *timo)
816 {
817         struct umtxq_chain *uc;
818         sbintime_t sbt = 0;
819         int error, flags = 0;
820
821         uc = umtxq_getchain(&uq->uq_key);
822         UMTXQ_LOCKED_ASSERT(uc);
823         for (;;) {
824                 if (!(uq->uq_flags & UQF_UMTXQ)) {
825                         error = 0;
826                         break;
827                 }
828                 if (timo != NULL) {
829                         if (timo->is_abs_real)
830                                 curthread->td_rtcgen =
831                                     atomic_load_acq_int(&rtc_generation);
832                         error = umtx_abs_timeout_getsbt(timo, &sbt, &flags);
833                         if (error != 0)
834                                 break;
835                 }
836                 error = msleep_sbt(uq, &uc->uc_lock, PCATCH | PDROP, wmesg,
837                     sbt, 0, flags);
838                 uc = umtxq_getchain(&uq->uq_key);
839                 mtx_lock(&uc->uc_lock);
840                 if (error == EINTR || error == ERESTART)
841                         break;
842                 if (error == EWOULDBLOCK && (flags & C_ABSOLUTE) != 0) {
843                         error = ETIMEDOUT;
844                         break;
845                 }
846         }
847
848         curthread->td_rtcgen = 0;
849         return (error);
850 }
851
852 /*
853  * Convert userspace address into unique logical address.
854  */
855 int
856 umtx_key_get(const void *addr, int type, int share, struct umtx_key *key)
857 {
858         struct thread *td = curthread;
859         vm_map_t map;
860         vm_map_entry_t entry;
861         vm_pindex_t pindex;
862         vm_prot_t prot;
863         boolean_t wired;
864
865         key->type = type;
866         if (share == THREAD_SHARE) {
867                 key->shared = 0;
868                 key->info.private.vs = td->td_proc->p_vmspace;
869                 key->info.private.addr = (uintptr_t)addr;
870         } else {
871                 MPASS(share == PROCESS_SHARE || share == AUTO_SHARE);
872                 map = &td->td_proc->p_vmspace->vm_map;
873                 if (vm_map_lookup(&map, (vm_offset_t)addr, VM_PROT_WRITE,
874                     &entry, &key->info.shared.object, &pindex, &prot,
875                     &wired) != KERN_SUCCESS) {
876                         return (EFAULT);
877                 }
878
879                 if ((share == PROCESS_SHARE) ||
880                     (share == AUTO_SHARE &&
881                      VM_INHERIT_SHARE == entry->inheritance)) {
882                         key->shared = 1;
883                         key->info.shared.offset = (vm_offset_t)addr -
884                             entry->start + entry->offset;
885                         vm_object_reference(key->info.shared.object);
886                 } else {
887                         key->shared = 0;
888                         key->info.private.vs = td->td_proc->p_vmspace;
889                         key->info.private.addr = (uintptr_t)addr;
890                 }
891                 vm_map_lookup_done(map, entry);
892         }
893
894         umtxq_hash(key);
895         return (0);
896 }
897
898 /*
899  * Release key.
900  */
901 void
902 umtx_key_release(struct umtx_key *key)
903 {
904         if (key->shared)
905                 vm_object_deallocate(key->info.shared.object);
906 }
907
908 #ifdef COMPAT_FREEBSD10
909 /*
910  * Lock a umtx object.
911  */
912 static int
913 do_lock_umtx(struct thread *td, struct umtx *umtx, u_long id,
914     const struct timespec *timeout)
915 {
916         struct umtx_abs_timeout timo;
917         struct umtx_q *uq;
918         u_long owner;
919         u_long old;
920         int error = 0;
921
922         uq = td->td_umtxq;
923         if (timeout != NULL)
924                 umtx_abs_timeout_init(&timo, CLOCK_REALTIME, 0, timeout);
925
926         /*
927          * Care must be exercised when dealing with umtx structure. It
928          * can fault on any access.
929          */
930         for (;;) {
931                 /*
932                  * Try the uncontested case.  This should be done in userland.
933                  */
934                 owner = casuword(&umtx->u_owner, UMTX_UNOWNED, id);
935
936                 /* The acquire succeeded. */
937                 if (owner == UMTX_UNOWNED)
938                         return (0);
939
940                 /* The address was invalid. */
941                 if (owner == -1)
942                         return (EFAULT);
943
944                 /* If no one owns it but it is contested try to acquire it. */
945                 if (owner == UMTX_CONTESTED) {
946                         owner = casuword(&umtx->u_owner,
947                             UMTX_CONTESTED, id | UMTX_CONTESTED);
948
949                         if (owner == UMTX_CONTESTED)
950                                 return (0);
951
952                         /* The address was invalid. */
953                         if (owner == -1)
954                                 return (EFAULT);
955
956                         error = thread_check_susp(td, false);
957                         if (error != 0)
958                                 break;
959
960                         /* If this failed the lock has changed, restart. */
961                         continue;
962                 }
963
964                 /*
965                  * If we caught a signal, we have retried and now
966                  * exit immediately.
967                  */
968                 if (error != 0)
969                         break;
970
971                 if ((error = umtx_key_get(umtx, TYPE_SIMPLE_LOCK,
972                         AUTO_SHARE, &uq->uq_key)) != 0)
973                         return (error);
974
975                 umtxq_lock(&uq->uq_key);
976                 umtxq_busy(&uq->uq_key);
977                 umtxq_insert(uq);
978                 umtxq_unbusy(&uq->uq_key);
979                 umtxq_unlock(&uq->uq_key);
980
981                 /*
982                  * Set the contested bit so that a release in user space
983                  * knows to use the system call for unlock.  If this fails
984                  * either some one else has acquired the lock or it has been
985                  * released.
986                  */
987                 old = casuword(&umtx->u_owner, owner, owner | UMTX_CONTESTED);
988
989                 /* The address was invalid. */
990                 if (old == -1) {
991                         umtxq_lock(&uq->uq_key);
992                         umtxq_remove(uq);
993                         umtxq_unlock(&uq->uq_key);
994                         umtx_key_release(&uq->uq_key);
995                         return (EFAULT);
996                 }
997
998                 /*
999                  * We set the contested bit, sleep. Otherwise the lock changed
1000                  * and we need to retry or we lost a race to the thread
1001                  * unlocking the umtx.
1002                  */
1003                 umtxq_lock(&uq->uq_key);
1004                 if (old == owner)
1005                         error = umtxq_sleep(uq, "umtx", timeout == NULL ? NULL :
1006                             &timo);
1007                 umtxq_remove(uq);
1008                 umtxq_unlock(&uq->uq_key);
1009                 umtx_key_release(&uq->uq_key);
1010
1011                 if (error == 0)
1012                         error = thread_check_susp(td, false);
1013         }
1014
1015         if (timeout == NULL) {
1016                 /* Mutex locking is restarted if it is interrupted. */
1017                 if (error == EINTR)
1018                         error = ERESTART;
1019         } else {
1020                 /* Timed-locking is not restarted. */
1021                 if (error == ERESTART)
1022                         error = EINTR;
1023         }
1024         return (error);
1025 }
1026
1027 /*
1028  * Unlock a umtx object.
1029  */
1030 static int
1031 do_unlock_umtx(struct thread *td, struct umtx *umtx, u_long id)
1032 {
1033         struct umtx_key key;
1034         u_long owner;
1035         u_long old;
1036         int error;
1037         int count;
1038
1039         /*
1040          * Make sure we own this mtx.
1041          */
1042         owner = fuword(__DEVOLATILE(u_long *, &umtx->u_owner));
1043         if (owner == -1)
1044                 return (EFAULT);
1045
1046         if ((owner & ~UMTX_CONTESTED) != id)
1047                 return (EPERM);
1048
1049         /* This should be done in userland */
1050         if ((owner & UMTX_CONTESTED) == 0) {
1051                 old = casuword(&umtx->u_owner, owner, UMTX_UNOWNED);
1052                 if (old == -1)
1053                         return (EFAULT);
1054                 if (old == owner)
1055                         return (0);
1056                 owner = old;
1057         }
1058
1059         /* We should only ever be in here for contested locks */
1060         if ((error = umtx_key_get(umtx, TYPE_SIMPLE_LOCK, AUTO_SHARE,
1061             &key)) != 0)
1062                 return (error);
1063
1064         umtxq_lock(&key);
1065         umtxq_busy(&key);
1066         count = umtxq_count(&key);
1067         umtxq_unlock(&key);
1068
1069         /*
1070          * When unlocking the umtx, it must be marked as unowned if
1071          * there is zero or one thread only waiting for it.
1072          * Otherwise, it must be marked as contested.
1073          */
1074         old = casuword(&umtx->u_owner, owner,
1075             count <= 1 ? UMTX_UNOWNED : UMTX_CONTESTED);
1076         umtxq_lock(&key);
1077         umtxq_signal(&key,1);
1078         umtxq_unbusy(&key);
1079         umtxq_unlock(&key);
1080         umtx_key_release(&key);
1081         if (old == -1)
1082                 return (EFAULT);
1083         if (old != owner)
1084                 return (EINVAL);
1085         return (0);
1086 }
1087
1088 #ifdef COMPAT_FREEBSD32
1089
1090 /*
1091  * Lock a umtx object.
1092  */
1093 static int
1094 do_lock_umtx32(struct thread *td, uint32_t *m, uint32_t id,
1095         const struct timespec *timeout)
1096 {
1097         struct umtx_abs_timeout timo;
1098         struct umtx_q *uq;
1099         uint32_t owner;
1100         uint32_t old;
1101         int error = 0;
1102
1103         uq = td->td_umtxq;
1104
1105         if (timeout != NULL)
1106                 umtx_abs_timeout_init(&timo, CLOCK_REALTIME, 0, timeout);
1107
1108         /*
1109          * Care must be exercised when dealing with umtx structure. It
1110          * can fault on any access.
1111          */
1112         for (;;) {
1113                 /*
1114                  * Try the uncontested case.  This should be done in userland.
1115                  */
1116                 owner = casuword32(m, UMUTEX_UNOWNED, id);
1117
1118                 /* The acquire succeeded. */
1119                 if (owner == UMUTEX_UNOWNED)
1120                         return (0);
1121
1122                 /* The address was invalid. */
1123                 if (owner == -1)
1124                         return (EFAULT);
1125
1126                 /* If no one owns it but it is contested try to acquire it. */
1127                 if (owner == UMUTEX_CONTESTED) {
1128                         owner = casuword32(m,
1129                             UMUTEX_CONTESTED, id | UMUTEX_CONTESTED);
1130                         if (owner == UMUTEX_CONTESTED)
1131                                 return (0);
1132
1133                         /* The address was invalid. */
1134                         if (owner == -1)
1135                                 return (EFAULT);
1136
1137                         error = thread_check_susp(td, false);
1138                         if (error != 0)
1139                                 break;
1140
1141                         /* If this failed the lock has changed, restart. */
1142                         continue;
1143                 }
1144
1145                 /*
1146                  * If we caught a signal, we have retried and now
1147                  * exit immediately.
1148                  */
1149                 if (error != 0)
1150                         return (error);
1151
1152                 if ((error = umtx_key_get(m, TYPE_SIMPLE_LOCK,
1153                         AUTO_SHARE, &uq->uq_key)) != 0)
1154                         return (error);
1155
1156                 umtxq_lock(&uq->uq_key);
1157                 umtxq_busy(&uq->uq_key);
1158                 umtxq_insert(uq);
1159                 umtxq_unbusy(&uq->uq_key);
1160                 umtxq_unlock(&uq->uq_key);
1161
1162                 /*
1163                  * Set the contested bit so that a release in user space
1164                  * knows to use the system call for unlock.  If this fails
1165                  * either some one else has acquired the lock or it has been
1166                  * released.
1167                  */
1168                 old = casuword32(m, owner, owner | UMUTEX_CONTESTED);
1169
1170                 /* The address was invalid. */
1171                 if (old == -1) {
1172                         umtxq_lock(&uq->uq_key);
1173                         umtxq_remove(uq);
1174                         umtxq_unlock(&uq->uq_key);
1175                         umtx_key_release(&uq->uq_key);
1176                         return (EFAULT);
1177                 }
1178
1179                 /*
1180                  * We set the contested bit, sleep. Otherwise the lock changed
1181                  * and we need to retry or we lost a race to the thread
1182                  * unlocking the umtx.
1183                  */
1184                 umtxq_lock(&uq->uq_key);
1185                 if (old == owner)
1186                         error = umtxq_sleep(uq, "umtx", timeout == NULL ?
1187                             NULL : &timo);
1188                 umtxq_remove(uq);
1189                 umtxq_unlock(&uq->uq_key);
1190                 umtx_key_release(&uq->uq_key);
1191
1192                 if (error == 0)
1193                         error = thread_check_susp(td, false);
1194         }
1195
1196         if (timeout == NULL) {
1197                 /* Mutex locking is restarted if it is interrupted. */
1198                 if (error == EINTR)
1199                         error = ERESTART;
1200         } else {
1201                 /* Timed-locking is not restarted. */
1202                 if (error == ERESTART)
1203                         error = EINTR;
1204         }
1205         return (error);
1206 }
1207
1208 /*
1209  * Unlock a umtx object.
1210  */
1211 static int
1212 do_unlock_umtx32(struct thread *td, uint32_t *m, uint32_t id)
1213 {
1214         struct umtx_key key;
1215         uint32_t owner;
1216         uint32_t old;
1217         int error;
1218         int count;
1219
1220         /*
1221          * Make sure we own this mtx.
1222          */
1223         owner = fuword32(m);
1224         if (owner == -1)
1225                 return (EFAULT);
1226
1227         if ((owner & ~UMUTEX_CONTESTED) != id)
1228                 return (EPERM);
1229
1230         /* This should be done in userland */
1231         if ((owner & UMUTEX_CONTESTED) == 0) {
1232                 old = casuword32(m, owner, UMUTEX_UNOWNED);
1233                 if (old == -1)
1234                         return (EFAULT);
1235                 if (old == owner)
1236                         return (0);
1237                 owner = old;
1238         }
1239
1240         /* We should only ever be in here for contested locks */
1241         if ((error = umtx_key_get(m, TYPE_SIMPLE_LOCK, AUTO_SHARE,
1242                 &key)) != 0)
1243                 return (error);
1244
1245         umtxq_lock(&key);
1246         umtxq_busy(&key);
1247         count = umtxq_count(&key);
1248         umtxq_unlock(&key);
1249
1250         /*
1251          * When unlocking the umtx, it must be marked as unowned if
1252          * there is zero or one thread only waiting for it.
1253          * Otherwise, it must be marked as contested.
1254          */
1255         old = casuword32(m, owner,
1256                 count <= 1 ? UMUTEX_UNOWNED : UMUTEX_CONTESTED);
1257         umtxq_lock(&key);
1258         umtxq_signal(&key,1);
1259         umtxq_unbusy(&key);
1260         umtxq_unlock(&key);
1261         umtx_key_release(&key);
1262         if (old == -1)
1263                 return (EFAULT);
1264         if (old != owner)
1265                 return (EINVAL);
1266         return (0);
1267 }
1268 #endif  /* COMPAT_FREEBSD32 */
1269 #endif  /* COMPAT_FREEBSD10 */
1270
1271 /*
1272  * Fetch and compare value, sleep on the address if value is not changed.
1273  */
1274 static int
1275 do_wait(struct thread *td, void *addr, u_long id,
1276     struct _umtx_time *timeout, int compat32, int is_private)
1277 {
1278         struct umtx_abs_timeout timo;
1279         struct umtx_q *uq;
1280         u_long tmp;
1281         uint32_t tmp32;
1282         int error = 0;
1283
1284         uq = td->td_umtxq;
1285         if ((error = umtx_key_get(addr, TYPE_SIMPLE_WAIT,
1286             is_private ? THREAD_SHARE : AUTO_SHARE, &uq->uq_key)) != 0)
1287                 return (error);
1288
1289         if (timeout != NULL)
1290                 umtx_abs_timeout_init2(&timo, timeout);
1291
1292         umtxq_lock(&uq->uq_key);
1293         umtxq_insert(uq);
1294         umtxq_unlock(&uq->uq_key);
1295         if (compat32 == 0) {
1296                 error = fueword(addr, &tmp);
1297                 if (error != 0)
1298                         error = EFAULT;
1299         } else {
1300                 error = fueword32(addr, &tmp32);
1301                 if (error == 0)
1302                         tmp = tmp32;
1303                 else
1304                         error = EFAULT;
1305         }
1306         umtxq_lock(&uq->uq_key);
1307         if (error == 0) {
1308                 if (tmp == id)
1309                         error = umtxq_sleep(uq, "uwait", timeout == NULL ?
1310                             NULL : &timo);
1311                 if ((uq->uq_flags & UQF_UMTXQ) == 0)
1312                         error = 0;
1313                 else
1314                         umtxq_remove(uq);
1315         } else if ((uq->uq_flags & UQF_UMTXQ) != 0) {
1316                 umtxq_remove(uq);
1317         }
1318         umtxq_unlock(&uq->uq_key);
1319         umtx_key_release(&uq->uq_key);
1320         if (error == ERESTART)
1321                 error = EINTR;
1322         return (error);
1323 }
1324
1325 /*
1326  * Wake up threads sleeping on the specified address.
1327  */
1328 int
1329 kern_umtx_wake(struct thread *td, void *uaddr, int n_wake, int is_private)
1330 {
1331         struct umtx_key key;
1332         int ret;
1333
1334         if ((ret = umtx_key_get(uaddr, TYPE_SIMPLE_WAIT,
1335             is_private ? THREAD_SHARE : AUTO_SHARE, &key)) != 0)
1336                 return (ret);
1337         umtxq_lock(&key);
1338         umtxq_signal(&key, n_wake);
1339         umtxq_unlock(&key);
1340         umtx_key_release(&key);
1341         return (0);
1342 }
1343
1344 /*
1345  * Lock PTHREAD_PRIO_NONE protocol POSIX mutex.
1346  */
1347 static int
1348 do_lock_normal(struct thread *td, struct umutex *m, uint32_t flags,
1349     struct _umtx_time *timeout, int mode)
1350 {
1351         struct umtx_abs_timeout timo;
1352         struct umtx_q *uq;
1353         uint32_t owner, old, id;
1354         int error, rv;
1355
1356         id = td->td_tid;
1357         uq = td->td_umtxq;
1358         error = 0;
1359         if (timeout != NULL)
1360                 umtx_abs_timeout_init2(&timo, timeout);
1361
1362         /*
1363          * Care must be exercised when dealing with umtx structure. It
1364          * can fault on any access.
1365          */
1366         for (;;) {
1367                 rv = fueword32(&m->m_owner, &owner);
1368                 if (rv == -1)
1369                         return (EFAULT);
1370                 if (mode == _UMUTEX_WAIT) {
1371                         if (owner == UMUTEX_UNOWNED ||
1372                             owner == UMUTEX_CONTESTED ||
1373                             owner == UMUTEX_RB_OWNERDEAD ||
1374                             owner == UMUTEX_RB_NOTRECOV)
1375                                 return (0);
1376                 } else {
1377                         /*
1378                          * Robust mutex terminated.  Kernel duty is to
1379                          * return EOWNERDEAD to the userspace.  The
1380                          * umutex.m_flags UMUTEX_NONCONSISTENT is set
1381                          * by the common userspace code.
1382                          */
1383                         if (owner == UMUTEX_RB_OWNERDEAD) {
1384                                 rv = casueword32(&m->m_owner,
1385                                     UMUTEX_RB_OWNERDEAD, &owner,
1386                                     id | UMUTEX_CONTESTED);
1387                                 if (rv == -1)
1388                                         return (EFAULT);
1389                                 if (rv == 0) {
1390                                         MPASS(owner == UMUTEX_RB_OWNERDEAD);
1391                                         return (EOWNERDEAD); /* success */
1392                                 }
1393                                 MPASS(rv == 1);
1394                                 rv = thread_check_susp(td, false);
1395                                 if (rv != 0)
1396                                         return (rv);
1397                                 continue;
1398                         }
1399                         if (owner == UMUTEX_RB_NOTRECOV)
1400                                 return (ENOTRECOVERABLE);
1401
1402                         /*
1403                          * Try the uncontested case.  This should be
1404                          * done in userland.
1405                          */
1406                         rv = casueword32(&m->m_owner, UMUTEX_UNOWNED,
1407                             &owner, id);
1408                         /* The address was invalid. */
1409                         if (rv == -1)
1410                                 return (EFAULT);
1411
1412                         /* The acquire succeeded. */
1413                         if (rv == 0) {
1414                                 MPASS(owner == UMUTEX_UNOWNED);
1415                                 return (0);
1416                         }
1417
1418                         /*
1419                          * If no one owns it but it is contested try
1420                          * to acquire it.
1421                          */
1422                         MPASS(rv == 1);
1423                         if (owner == UMUTEX_CONTESTED) {
1424                                 rv = casueword32(&m->m_owner,
1425                                     UMUTEX_CONTESTED, &owner,
1426                                     id | UMUTEX_CONTESTED);
1427                                 /* The address was invalid. */
1428                                 if (rv == -1)
1429                                         return (EFAULT);
1430                                 if (rv == 0) {
1431                                         MPASS(owner == UMUTEX_CONTESTED);
1432                                         return (0);
1433                                 }
1434                                 if (rv == 1) {
1435                                         rv = thread_check_susp(td, false);
1436                                         if (rv != 0)
1437                                                 return (rv);
1438                                 }
1439
1440                                 /*
1441                                  * If this failed the lock has
1442                                  * changed, restart.
1443                                  */
1444                                 continue;
1445                         }
1446
1447                         /* rv == 1 but not contested, likely store failure */
1448                         rv = thread_check_susp(td, false);
1449                         if (rv != 0)
1450                                 return (rv);
1451                 }
1452
1453                 if (mode == _UMUTEX_TRY)
1454                         return (EBUSY);
1455
1456                 /*
1457                  * If we caught a signal, we have retried and now
1458                  * exit immediately.
1459                  */
1460                 if (error != 0)
1461                         return (error);
1462
1463                 if ((error = umtx_key_get(m, TYPE_NORMAL_UMUTEX,
1464                     GET_SHARE(flags), &uq->uq_key)) != 0)
1465                         return (error);
1466
1467                 umtxq_lock(&uq->uq_key);
1468                 umtxq_busy(&uq->uq_key);
1469                 umtxq_insert(uq);
1470                 umtxq_unlock(&uq->uq_key);
1471
1472                 /*
1473                  * Set the contested bit so that a release in user space
1474                  * knows to use the system call for unlock.  If this fails
1475                  * either some one else has acquired the lock or it has been
1476                  * released.
1477                  */
1478                 rv = casueword32(&m->m_owner, owner, &old,
1479                     owner | UMUTEX_CONTESTED);
1480
1481                 /* The address was invalid or casueword failed to store. */
1482                 if (rv == -1 || rv == 1) {
1483                         umtxq_lock(&uq->uq_key);
1484                         umtxq_remove(uq);
1485                         umtxq_unbusy(&uq->uq_key);
1486                         umtxq_unlock(&uq->uq_key);
1487                         umtx_key_release(&uq->uq_key);
1488                         if (rv == -1)
1489                                 return (EFAULT);
1490                         if (rv == 1) {
1491                                 rv = thread_check_susp(td, false);
1492                                 if (rv != 0)
1493                                         return (rv);
1494                         }
1495                         continue;
1496                 }
1497
1498                 /*
1499                  * We set the contested bit, sleep. Otherwise the lock changed
1500                  * and we need to retry or we lost a race to the thread
1501                  * unlocking the umtx.
1502                  */
1503                 umtxq_lock(&uq->uq_key);
1504                 umtxq_unbusy(&uq->uq_key);
1505                 MPASS(old == owner);
1506                 error = umtxq_sleep(uq, "umtxn", timeout == NULL ?
1507                     NULL : &timo);
1508                 umtxq_remove(uq);
1509                 umtxq_unlock(&uq->uq_key);
1510                 umtx_key_release(&uq->uq_key);
1511
1512                 if (error == 0)
1513                         error = thread_check_susp(td, false);
1514         }
1515
1516         return (0);
1517 }
1518
1519 /*
1520  * Unlock PTHREAD_PRIO_NONE protocol POSIX mutex.
1521  */
1522 static int
1523 do_unlock_normal(struct thread *td, struct umutex *m, uint32_t flags, bool rb)
1524 {
1525         struct umtx_key key;
1526         uint32_t owner, old, id, newlock;
1527         int error, count;
1528
1529         id = td->td_tid;
1530
1531 again:
1532         /*
1533          * Make sure we own this mtx.
1534          */
1535         error = fueword32(&m->m_owner, &owner);
1536         if (error == -1)
1537                 return (EFAULT);
1538
1539         if ((owner & ~UMUTEX_CONTESTED) != id)
1540                 return (EPERM);
1541
1542         newlock = umtx_unlock_val(flags, rb);
1543         if ((owner & UMUTEX_CONTESTED) == 0) {
1544                 error = casueword32(&m->m_owner, owner, &old, newlock);
1545                 if (error == -1)
1546                         return (EFAULT);
1547                 if (error == 1) {
1548                         error = thread_check_susp(td, false);
1549                         if (error != 0)
1550                                 return (error);
1551                         goto again;
1552                 }
1553                 MPASS(old == owner);
1554                 return (0);
1555         }
1556
1557         /* We should only ever be in here for contested locks */
1558         if ((error = umtx_key_get(m, TYPE_NORMAL_UMUTEX, GET_SHARE(flags),
1559             &key)) != 0)
1560                 return (error);
1561
1562         umtxq_lock(&key);
1563         umtxq_busy(&key);
1564         count = umtxq_count(&key);
1565         umtxq_unlock(&key);
1566
1567         /*
1568          * When unlocking the umtx, it must be marked as unowned if
1569          * there is zero or one thread only waiting for it.
1570          * Otherwise, it must be marked as contested.
1571          */
1572         if (count > 1)
1573                 newlock |= UMUTEX_CONTESTED;
1574         error = casueword32(&m->m_owner, owner, &old, newlock);
1575         umtxq_lock(&key);
1576         umtxq_signal(&key, 1);
1577         umtxq_unbusy(&key);
1578         umtxq_unlock(&key);
1579         umtx_key_release(&key);
1580         if (error == -1)
1581                 return (EFAULT);
1582         if (error == 1) {
1583                 if (old != owner)
1584                         return (EINVAL);
1585                 error = thread_check_susp(td, false);
1586                 if (error != 0)
1587                         return (error);
1588                 goto again;
1589         }
1590         return (0);
1591 }
1592
1593 /*
1594  * Check if the mutex is available and wake up a waiter,
1595  * only for simple mutex.
1596  */
1597 static int
1598 do_wake_umutex(struct thread *td, struct umutex *m)
1599 {
1600         struct umtx_key key;
1601         uint32_t owner;
1602         uint32_t flags;
1603         int error;
1604         int count;
1605
1606 again:
1607         error = fueword32(&m->m_owner, &owner);
1608         if (error == -1)
1609                 return (EFAULT);
1610
1611         if ((owner & ~UMUTEX_CONTESTED) != 0 && owner != UMUTEX_RB_OWNERDEAD &&
1612             owner != UMUTEX_RB_NOTRECOV)
1613                 return (0);
1614
1615         error = fueword32(&m->m_flags, &flags);
1616         if (error == -1)
1617                 return (EFAULT);
1618
1619         /* We should only ever be in here for contested locks */
1620         if ((error = umtx_key_get(m, TYPE_NORMAL_UMUTEX, GET_SHARE(flags),
1621             &key)) != 0)
1622                 return (error);
1623
1624         umtxq_lock(&key);
1625         umtxq_busy(&key);
1626         count = umtxq_count(&key);
1627         umtxq_unlock(&key);
1628
1629         if (count <= 1 && owner != UMUTEX_RB_OWNERDEAD &&
1630             owner != UMUTEX_RB_NOTRECOV) {
1631                 error = casueword32(&m->m_owner, UMUTEX_CONTESTED, &owner,
1632                     UMUTEX_UNOWNED);
1633                 if (error == -1) {
1634                         error = EFAULT;
1635                 } else if (error == 1) {
1636                         umtxq_lock(&key);
1637                         umtxq_unbusy(&key);
1638                         umtxq_unlock(&key);
1639                         umtx_key_release(&key);
1640                         error = thread_check_susp(td, false);
1641                         if (error != 0)
1642                                 return (error);
1643                         goto again;
1644                 }
1645         }
1646
1647         umtxq_lock(&key);
1648         if (error == 0 && count != 0) {
1649                 MPASS((owner & ~UMUTEX_CONTESTED) == 0 ||
1650                     owner == UMUTEX_RB_OWNERDEAD ||
1651                     owner == UMUTEX_RB_NOTRECOV);
1652                 umtxq_signal(&key, 1);
1653         }
1654         umtxq_unbusy(&key);
1655         umtxq_unlock(&key);
1656         umtx_key_release(&key);
1657         return (error);
1658 }
1659
1660 /*
1661  * Check if the mutex has waiters and tries to fix contention bit.
1662  */
1663 static int
1664 do_wake2_umutex(struct thread *td, struct umutex *m, uint32_t flags)
1665 {
1666         struct umtx_key key;
1667         uint32_t owner, old;
1668         int type;
1669         int error;
1670         int count;
1671
1672         switch (flags & (UMUTEX_PRIO_INHERIT | UMUTEX_PRIO_PROTECT |
1673             UMUTEX_ROBUST)) {
1674         case 0:
1675         case UMUTEX_ROBUST:
1676                 type = TYPE_NORMAL_UMUTEX;
1677                 break;
1678         case UMUTEX_PRIO_INHERIT:
1679                 type = TYPE_PI_UMUTEX;
1680                 break;
1681         case (UMUTEX_PRIO_INHERIT | UMUTEX_ROBUST):
1682                 type = TYPE_PI_ROBUST_UMUTEX;
1683                 break;
1684         case UMUTEX_PRIO_PROTECT:
1685                 type = TYPE_PP_UMUTEX;
1686                 break;
1687         case (UMUTEX_PRIO_PROTECT | UMUTEX_ROBUST):
1688                 type = TYPE_PP_ROBUST_UMUTEX;
1689                 break;
1690         default:
1691                 return (EINVAL);
1692         }
1693         if ((error = umtx_key_get(m, type, GET_SHARE(flags), &key)) != 0)
1694                 return (error);
1695
1696         owner = 0;
1697         umtxq_lock(&key);
1698         umtxq_busy(&key);
1699         count = umtxq_count(&key);
1700         umtxq_unlock(&key);
1701
1702         error = fueword32(&m->m_owner, &owner);
1703         if (error == -1)
1704                 error = EFAULT;
1705
1706         /*
1707          * Only repair contention bit if there is a waiter, this means
1708          * the mutex is still being referenced by userland code,
1709          * otherwise don't update any memory.
1710          */
1711         while (error == 0 && (owner & UMUTEX_CONTESTED) == 0 &&
1712             (count > 1 || (count == 1 && (owner & ~UMUTEX_CONTESTED) != 0))) {
1713                 error = casueword32(&m->m_owner, owner, &old,
1714                     owner | UMUTEX_CONTESTED);
1715                 if (error == -1) {
1716                         error = EFAULT;
1717                         break;
1718                 }
1719                 if (error == 0) {
1720                         MPASS(old == owner);
1721                         break;
1722                 }
1723                 owner = old;
1724                 error = thread_check_susp(td, false);
1725         }
1726
1727         umtxq_lock(&key);
1728         if (error == EFAULT) {
1729                 umtxq_signal(&key, INT_MAX);
1730         } else if (count != 0 && ((owner & ~UMUTEX_CONTESTED) == 0 ||
1731             owner == UMUTEX_RB_OWNERDEAD || owner == UMUTEX_RB_NOTRECOV))
1732                 umtxq_signal(&key, 1);
1733         umtxq_unbusy(&key);
1734         umtxq_unlock(&key);
1735         umtx_key_release(&key);
1736         return (error);
1737 }
1738
1739 struct umtx_pi *
1740 umtx_pi_alloc(int flags)
1741 {
1742         struct umtx_pi *pi;
1743
1744         pi = uma_zalloc(umtx_pi_zone, M_ZERO | flags);
1745         TAILQ_INIT(&pi->pi_blocked);
1746         atomic_add_int(&umtx_pi_allocated, 1);
1747         return (pi);
1748 }
1749
1750 void
1751 umtx_pi_free(struct umtx_pi *pi)
1752 {
1753         uma_zfree(umtx_pi_zone, pi);
1754         atomic_add_int(&umtx_pi_allocated, -1);
1755 }
1756
1757 /*
1758  * Adjust the thread's position on a pi_state after its priority has been
1759  * changed.
1760  */
1761 static int
1762 umtx_pi_adjust_thread(struct umtx_pi *pi, struct thread *td)
1763 {
1764         struct umtx_q *uq, *uq1, *uq2;
1765         struct thread *td1;
1766
1767         mtx_assert(&umtx_lock, MA_OWNED);
1768         if (pi == NULL)
1769                 return (0);
1770
1771         uq = td->td_umtxq;
1772
1773         /*
1774          * Check if the thread needs to be moved on the blocked chain.
1775          * It needs to be moved if either its priority is lower than
1776          * the previous thread or higher than the next thread.
1777          */
1778         uq1 = TAILQ_PREV(uq, umtxq_head, uq_lockq);
1779         uq2 = TAILQ_NEXT(uq, uq_lockq);
1780         if ((uq1 != NULL && UPRI(td) < UPRI(uq1->uq_thread)) ||
1781             (uq2 != NULL && UPRI(td) > UPRI(uq2->uq_thread))) {
1782                 /*
1783                  * Remove thread from blocked chain and determine where
1784                  * it should be moved to.
1785                  */
1786                 TAILQ_REMOVE(&pi->pi_blocked, uq, uq_lockq);
1787                 TAILQ_FOREACH(uq1, &pi->pi_blocked, uq_lockq) {
1788                         td1 = uq1->uq_thread;
1789                         MPASS(td1->td_proc->p_magic == P_MAGIC);
1790                         if (UPRI(td1) > UPRI(td))
1791                                 break;
1792                 }
1793
1794                 if (uq1 == NULL)
1795                         TAILQ_INSERT_TAIL(&pi->pi_blocked, uq, uq_lockq);
1796                 else
1797                         TAILQ_INSERT_BEFORE(uq1, uq, uq_lockq);
1798         }
1799         return (1);
1800 }
1801
1802 static struct umtx_pi *
1803 umtx_pi_next(struct umtx_pi *pi)
1804 {
1805         struct umtx_q *uq_owner;
1806
1807         if (pi->pi_owner == NULL)
1808                 return (NULL);
1809         uq_owner = pi->pi_owner->td_umtxq;
1810         if (uq_owner == NULL)
1811                 return (NULL);
1812         return (uq_owner->uq_pi_blocked);
1813 }
1814
1815 /*
1816  * Floyd's Cycle-Finding Algorithm.
1817  */
1818 static bool
1819 umtx_pi_check_loop(struct umtx_pi *pi)
1820 {
1821         struct umtx_pi *pi1;    /* fast iterator */
1822
1823         mtx_assert(&umtx_lock, MA_OWNED);
1824         if (pi == NULL)
1825                 return (false);
1826         pi1 = pi;
1827         for (;;) {
1828                 pi = umtx_pi_next(pi);
1829                 if (pi == NULL)
1830                         break;
1831                 pi1 = umtx_pi_next(pi1);
1832                 if (pi1 == NULL)
1833                         break;
1834                 pi1 = umtx_pi_next(pi1);
1835                 if (pi1 == NULL)
1836                         break;
1837                 if (pi == pi1)
1838                         return (true);
1839         }
1840         return (false);
1841 }
1842
1843 /*
1844  * Propagate priority when a thread is blocked on POSIX
1845  * PI mutex.
1846  */
1847 static void
1848 umtx_propagate_priority(struct thread *td)
1849 {
1850         struct umtx_q *uq;
1851         struct umtx_pi *pi;
1852         int pri;
1853
1854         mtx_assert(&umtx_lock, MA_OWNED);
1855         pri = UPRI(td);
1856         uq = td->td_umtxq;
1857         pi = uq->uq_pi_blocked;
1858         if (pi == NULL)
1859                 return;
1860         if (umtx_pi_check_loop(pi))
1861                 return;
1862
1863         for (;;) {
1864                 td = pi->pi_owner;
1865                 if (td == NULL || td == curthread)
1866                         return;
1867
1868                 MPASS(td->td_proc != NULL);
1869                 MPASS(td->td_proc->p_magic == P_MAGIC);
1870
1871                 thread_lock(td);
1872                 if (td->td_lend_user_pri > pri)
1873                         sched_lend_user_prio(td, pri);
1874                 else {
1875                         thread_unlock(td);
1876                         break;
1877                 }
1878                 thread_unlock(td);
1879
1880                 /*
1881                  * Pick up the lock that td is blocked on.
1882                  */
1883                 uq = td->td_umtxq;
1884                 pi = uq->uq_pi_blocked;
1885                 if (pi == NULL)
1886                         break;
1887                 /* Resort td on the list if needed. */
1888                 umtx_pi_adjust_thread(pi, td);
1889         }
1890 }
1891
1892 /*
1893  * Unpropagate priority for a PI mutex when a thread blocked on
1894  * it is interrupted by signal or resumed by others.
1895  */
1896 static void
1897 umtx_repropagate_priority(struct umtx_pi *pi)
1898 {
1899         struct umtx_q *uq, *uq_owner;
1900         struct umtx_pi *pi2;
1901         int pri;
1902
1903         mtx_assert(&umtx_lock, MA_OWNED);
1904
1905         if (umtx_pi_check_loop(pi))
1906                 return;
1907         while (pi != NULL && pi->pi_owner != NULL) {
1908                 pri = PRI_MAX;
1909                 uq_owner = pi->pi_owner->td_umtxq;
1910
1911                 TAILQ_FOREACH(pi2, &uq_owner->uq_pi_contested, pi_link) {
1912                         uq = TAILQ_FIRST(&pi2->pi_blocked);
1913                         if (uq != NULL) {
1914                                 if (pri > UPRI(uq->uq_thread))
1915                                         pri = UPRI(uq->uq_thread);
1916                         }
1917                 }
1918
1919                 if (pri > uq_owner->uq_inherited_pri)
1920                         pri = uq_owner->uq_inherited_pri;
1921                 thread_lock(pi->pi_owner);
1922                 sched_lend_user_prio(pi->pi_owner, pri);
1923                 thread_unlock(pi->pi_owner);
1924                 if ((pi = uq_owner->uq_pi_blocked) != NULL)
1925                         umtx_pi_adjust_thread(pi, uq_owner->uq_thread);
1926         }
1927 }
1928
1929 /*
1930  * Insert a PI mutex into owned list.
1931  */
1932 static void
1933 umtx_pi_setowner(struct umtx_pi *pi, struct thread *owner)
1934 {
1935         struct umtx_q *uq_owner;
1936
1937         uq_owner = owner->td_umtxq;
1938         mtx_assert(&umtx_lock, MA_OWNED);
1939         MPASS(pi->pi_owner == NULL);
1940         pi->pi_owner = owner;
1941         TAILQ_INSERT_TAIL(&uq_owner->uq_pi_contested, pi, pi_link);
1942 }
1943
1944 /*
1945  * Disown a PI mutex, and remove it from the owned list.
1946  */
1947 static void
1948 umtx_pi_disown(struct umtx_pi *pi)
1949 {
1950
1951         mtx_assert(&umtx_lock, MA_OWNED);
1952         TAILQ_REMOVE(&pi->pi_owner->td_umtxq->uq_pi_contested, pi, pi_link);
1953         pi->pi_owner = NULL;
1954 }
1955
1956 /*
1957  * Claim ownership of a PI mutex.
1958  */
1959 int
1960 umtx_pi_claim(struct umtx_pi *pi, struct thread *owner)
1961 {
1962         struct umtx_q *uq;
1963         int pri;
1964
1965         mtx_lock(&umtx_lock);
1966         if (pi->pi_owner == owner) {
1967                 mtx_unlock(&umtx_lock);
1968                 return (0);
1969         }
1970
1971         if (pi->pi_owner != NULL) {
1972                 /*
1973                  * userland may have already messed the mutex, sigh.
1974                  */
1975                 mtx_unlock(&umtx_lock);
1976                 return (EPERM);
1977         }
1978         umtx_pi_setowner(pi, owner);
1979         uq = TAILQ_FIRST(&pi->pi_blocked);
1980         if (uq != NULL) {
1981                 pri = UPRI(uq->uq_thread);
1982                 thread_lock(owner);
1983                 if (pri < UPRI(owner))
1984                         sched_lend_user_prio(owner, pri);
1985                 thread_unlock(owner);
1986         }
1987         mtx_unlock(&umtx_lock);
1988         return (0);
1989 }
1990
1991 /*
1992  * Adjust a thread's order position in its blocked PI mutex,
1993  * this may result new priority propagating process.
1994  */
1995 void
1996 umtx_pi_adjust(struct thread *td, u_char oldpri)
1997 {
1998         struct umtx_q *uq;
1999         struct umtx_pi *pi;
2000
2001         uq = td->td_umtxq;
2002         mtx_lock(&umtx_lock);
2003         /*
2004          * Pick up the lock that td is blocked on.
2005          */
2006         pi = uq->uq_pi_blocked;
2007         if (pi != NULL) {
2008                 umtx_pi_adjust_thread(pi, td);
2009                 umtx_repropagate_priority(pi);
2010         }
2011         mtx_unlock(&umtx_lock);
2012 }
2013
2014 /*
2015  * Sleep on a PI mutex.
2016  */
2017 int
2018 umtxq_sleep_pi(struct umtx_q *uq, struct umtx_pi *pi, uint32_t owner,
2019     const char *wmesg, struct umtx_abs_timeout *timo, bool shared)
2020 {
2021         struct thread *td, *td1;
2022         struct umtx_q *uq1;
2023         int error, pri;
2024 #ifdef INVARIANTS
2025         struct umtxq_chain *uc;
2026
2027         uc = umtxq_getchain(&pi->pi_key);
2028 #endif
2029         error = 0;
2030         td = uq->uq_thread;
2031         KASSERT(td == curthread, ("inconsistent uq_thread"));
2032         UMTXQ_LOCKED_ASSERT(umtxq_getchain(&uq->uq_key));
2033         KASSERT(uc->uc_busy != 0, ("umtx chain is not busy"));
2034         umtxq_insert(uq);
2035         mtx_lock(&umtx_lock);
2036         if (pi->pi_owner == NULL) {
2037                 mtx_unlock(&umtx_lock);
2038                 td1 = tdfind(owner, shared ? -1 : td->td_proc->p_pid);
2039                 mtx_lock(&umtx_lock);
2040                 if (td1 != NULL) {
2041                         if (pi->pi_owner == NULL)
2042                                 umtx_pi_setowner(pi, td1);
2043                         PROC_UNLOCK(td1->td_proc);
2044                 }
2045         }
2046
2047         TAILQ_FOREACH(uq1, &pi->pi_blocked, uq_lockq) {
2048                 pri = UPRI(uq1->uq_thread);
2049                 if (pri > UPRI(td))
2050                         break;
2051         }
2052
2053         if (uq1 != NULL)
2054                 TAILQ_INSERT_BEFORE(uq1, uq, uq_lockq);
2055         else
2056                 TAILQ_INSERT_TAIL(&pi->pi_blocked, uq, uq_lockq);
2057
2058         uq->uq_pi_blocked = pi;
2059         thread_lock(td);
2060         td->td_flags |= TDF_UPIBLOCKED;
2061         thread_unlock(td);
2062         umtx_propagate_priority(td);
2063         mtx_unlock(&umtx_lock);
2064         umtxq_unbusy(&uq->uq_key);
2065
2066         error = umtxq_sleep(uq, wmesg, timo);
2067         umtxq_remove(uq);
2068
2069         mtx_lock(&umtx_lock);
2070         uq->uq_pi_blocked = NULL;
2071         thread_lock(td);
2072         td->td_flags &= ~TDF_UPIBLOCKED;
2073         thread_unlock(td);
2074         TAILQ_REMOVE(&pi->pi_blocked, uq, uq_lockq);
2075         umtx_repropagate_priority(pi);
2076         mtx_unlock(&umtx_lock);
2077         umtxq_unlock(&uq->uq_key);
2078
2079         return (error);
2080 }
2081
2082 /*
2083  * Add reference count for a PI mutex.
2084  */
2085 void
2086 umtx_pi_ref(struct umtx_pi *pi)
2087 {
2088
2089         UMTXQ_LOCKED_ASSERT(umtxq_getchain(&pi->pi_key));
2090         pi->pi_refcount++;
2091 }
2092
2093 /*
2094  * Decrease reference count for a PI mutex, if the counter
2095  * is decreased to zero, its memory space is freed.
2096  */
2097 void
2098 umtx_pi_unref(struct umtx_pi *pi)
2099 {
2100         struct umtxq_chain *uc;
2101
2102         uc = umtxq_getchain(&pi->pi_key);
2103         UMTXQ_LOCKED_ASSERT(uc);
2104         KASSERT(pi->pi_refcount > 0, ("invalid reference count"));
2105         if (--pi->pi_refcount == 0) {
2106                 mtx_lock(&umtx_lock);
2107                 if (pi->pi_owner != NULL)
2108                         umtx_pi_disown(pi);
2109                 KASSERT(TAILQ_EMPTY(&pi->pi_blocked),
2110                         ("blocked queue not empty"));
2111                 mtx_unlock(&umtx_lock);
2112                 TAILQ_REMOVE(&uc->uc_pi_list, pi, pi_hashlink);
2113                 umtx_pi_free(pi);
2114         }
2115 }
2116
2117 /*
2118  * Find a PI mutex in hash table.
2119  */
2120 struct umtx_pi *
2121 umtx_pi_lookup(struct umtx_key *key)
2122 {
2123         struct umtxq_chain *uc;
2124         struct umtx_pi *pi;
2125
2126         uc = umtxq_getchain(key);
2127         UMTXQ_LOCKED_ASSERT(uc);
2128
2129         TAILQ_FOREACH(pi, &uc->uc_pi_list, pi_hashlink) {
2130                 if (umtx_key_match(&pi->pi_key, key)) {
2131                         return (pi);
2132                 }
2133         }
2134         return (NULL);
2135 }
2136
2137 /*
2138  * Insert a PI mutex into hash table.
2139  */
2140 void
2141 umtx_pi_insert(struct umtx_pi *pi)
2142 {
2143         struct umtxq_chain *uc;
2144
2145         uc = umtxq_getchain(&pi->pi_key);
2146         UMTXQ_LOCKED_ASSERT(uc);
2147         TAILQ_INSERT_TAIL(&uc->uc_pi_list, pi, pi_hashlink);
2148 }
2149
2150 /*
2151  * Drop a PI mutex and wakeup a top waiter.
2152  */
2153 int
2154 umtx_pi_drop(struct thread *td, struct umtx_key *key, bool rb, int *count)
2155 {
2156         struct umtx_q *uq_first, *uq_first2, *uq_me;
2157         struct umtx_pi *pi, *pi2;
2158         int pri;
2159
2160         UMTXQ_ASSERT_LOCKED_BUSY(key);
2161         *count = umtxq_count_pi(key, &uq_first);
2162         if (uq_first != NULL) {
2163                 mtx_lock(&umtx_lock);
2164                 pi = uq_first->uq_pi_blocked;
2165                 KASSERT(pi != NULL, ("pi == NULL?"));
2166                 if (pi->pi_owner != td && !(rb && pi->pi_owner == NULL)) {
2167                         mtx_unlock(&umtx_lock);
2168                         /* userland messed the mutex */
2169                         return (EPERM);
2170                 }
2171                 uq_me = td->td_umtxq;
2172                 if (pi->pi_owner == td)
2173                         umtx_pi_disown(pi);
2174                 /* get highest priority thread which is still sleeping. */
2175                 uq_first = TAILQ_FIRST(&pi->pi_blocked);
2176                 while (uq_first != NULL &&
2177                     (uq_first->uq_flags & UQF_UMTXQ) == 0) {
2178                         uq_first = TAILQ_NEXT(uq_first, uq_lockq);
2179                 }
2180                 pri = PRI_MAX;
2181                 TAILQ_FOREACH(pi2, &uq_me->uq_pi_contested, pi_link) {
2182                         uq_first2 = TAILQ_FIRST(&pi2->pi_blocked);
2183                         if (uq_first2 != NULL) {
2184                                 if (pri > UPRI(uq_first2->uq_thread))
2185                                         pri = UPRI(uq_first2->uq_thread);
2186                         }
2187                 }
2188                 thread_lock(td);
2189                 sched_lend_user_prio(td, pri);
2190                 thread_unlock(td);
2191                 mtx_unlock(&umtx_lock);
2192                 if (uq_first)
2193                         umtxq_signal_thread(uq_first);
2194         } else {
2195                 pi = umtx_pi_lookup(key);
2196                 /*
2197                  * A umtx_pi can exist if a signal or timeout removed the
2198                  * last waiter from the umtxq, but there is still
2199                  * a thread in do_lock_pi() holding the umtx_pi.
2200                  */
2201                 if (pi != NULL) {
2202                         /*
2203                          * The umtx_pi can be unowned, such as when a thread
2204                          * has just entered do_lock_pi(), allocated the
2205                          * umtx_pi, and unlocked the umtxq.
2206                          * If the current thread owns it, it must disown it.
2207                          */
2208                         mtx_lock(&umtx_lock);
2209                         if (pi->pi_owner == td)
2210                                 umtx_pi_disown(pi);
2211                         mtx_unlock(&umtx_lock);
2212                 }
2213         }
2214         return (0);
2215 }
2216
2217 /*
2218  * Lock a PI mutex.
2219  */
2220 static int
2221 do_lock_pi(struct thread *td, struct umutex *m, uint32_t flags,
2222     struct _umtx_time *timeout, int try)
2223 {
2224         struct umtx_abs_timeout timo;
2225         struct umtx_q *uq;
2226         struct umtx_pi *pi, *new_pi;
2227         uint32_t id, old_owner, owner, old;
2228         int error, rv;
2229
2230         id = td->td_tid;
2231         uq = td->td_umtxq;
2232
2233         if ((error = umtx_key_get(m, (flags & UMUTEX_ROBUST) != 0 ?
2234             TYPE_PI_ROBUST_UMUTEX : TYPE_PI_UMUTEX, GET_SHARE(flags),
2235             &uq->uq_key)) != 0)
2236                 return (error);
2237
2238         if (timeout != NULL)
2239                 umtx_abs_timeout_init2(&timo, timeout);
2240
2241         umtxq_lock(&uq->uq_key);
2242         pi = umtx_pi_lookup(&uq->uq_key);
2243         if (pi == NULL) {
2244                 new_pi = umtx_pi_alloc(M_NOWAIT);
2245                 if (new_pi == NULL) {
2246                         umtxq_unlock(&uq->uq_key);
2247                         new_pi = umtx_pi_alloc(M_WAITOK);
2248                         umtxq_lock(&uq->uq_key);
2249                         pi = umtx_pi_lookup(&uq->uq_key);
2250                         if (pi != NULL) {
2251                                 umtx_pi_free(new_pi);
2252                                 new_pi = NULL;
2253                         }
2254                 }
2255                 if (new_pi != NULL) {
2256                         new_pi->pi_key = uq->uq_key;
2257                         umtx_pi_insert(new_pi);
2258                         pi = new_pi;
2259                 }
2260         }
2261         umtx_pi_ref(pi);
2262         umtxq_unlock(&uq->uq_key);
2263
2264         /*
2265          * Care must be exercised when dealing with umtx structure.  It
2266          * can fault on any access.
2267          */
2268         for (;;) {
2269                 /*
2270                  * Try the uncontested case.  This should be done in userland.
2271                  */
2272                 rv = casueword32(&m->m_owner, UMUTEX_UNOWNED, &owner, id);
2273                 /* The address was invalid. */
2274                 if (rv == -1) {
2275                         error = EFAULT;
2276                         break;
2277                 }
2278                 /* The acquire succeeded. */
2279                 if (rv == 0) {
2280                         MPASS(owner == UMUTEX_UNOWNED);
2281                         error = 0;
2282                         break;
2283                 }
2284
2285                 if (owner == UMUTEX_RB_NOTRECOV) {
2286                         error = ENOTRECOVERABLE;
2287                         break;
2288                 }
2289
2290                 /*
2291                  * Nobody owns it, but the acquire failed. This can happen
2292                  * with ll/sc atomics.
2293                  */
2294                 if (owner == UMUTEX_UNOWNED) {
2295                         error = thread_check_susp(td, true);
2296                         if (error != 0)
2297                                 break;
2298                         continue;
2299                 }
2300
2301                 /*
2302                  * Avoid overwriting a possible error from sleep due
2303                  * to the pending signal with suspension check result.
2304                  */
2305                 if (error == 0) {
2306                         error = thread_check_susp(td, true);
2307                         if (error != 0)
2308                                 break;
2309                 }
2310
2311                 /* If no one owns it but it is contested try to acquire it. */
2312                 if (owner == UMUTEX_CONTESTED || owner == UMUTEX_RB_OWNERDEAD) {
2313                         old_owner = owner;
2314                         rv = casueword32(&m->m_owner, owner, &owner,
2315                             id | UMUTEX_CONTESTED);
2316                         /* The address was invalid. */
2317                         if (rv == -1) {
2318                                 error = EFAULT;
2319                                 break;
2320                         }
2321                         if (rv == 1) {
2322                                 if (error == 0) {
2323                                         error = thread_check_susp(td, true);
2324                                         if (error != 0)
2325                                                 break;
2326                                 }
2327
2328                                 /*
2329                                  * If this failed the lock could
2330                                  * changed, restart.
2331                                  */
2332                                 continue;
2333                         }
2334
2335                         MPASS(rv == 0);
2336                         MPASS(owner == old_owner);
2337                         umtxq_lock(&uq->uq_key);
2338                         umtxq_busy(&uq->uq_key);
2339                         error = umtx_pi_claim(pi, td);
2340                         umtxq_unbusy(&uq->uq_key);
2341                         umtxq_unlock(&uq->uq_key);
2342                         if (error != 0) {
2343                                 /*
2344                                  * Since we're going to return an
2345                                  * error, restore the m_owner to its
2346                                  * previous, unowned state to avoid
2347                                  * compounding the problem.
2348                                  */
2349                                 (void)casuword32(&m->m_owner,
2350                                     id | UMUTEX_CONTESTED, old_owner);
2351                         }
2352                         if (error == 0 && old_owner == UMUTEX_RB_OWNERDEAD)
2353                                 error = EOWNERDEAD;
2354                         break;
2355                 }
2356
2357                 if ((owner & ~UMUTEX_CONTESTED) == id) {
2358                         error = EDEADLK;
2359                         break;
2360                 }
2361
2362                 if (try != 0) {
2363                         error = EBUSY;
2364                         break;
2365                 }
2366
2367                 /*
2368                  * If we caught a signal, we have retried and now
2369                  * exit immediately.
2370                  */
2371                 if (error != 0)
2372                         break;
2373
2374                 umtxq_lock(&uq->uq_key);
2375                 umtxq_busy(&uq->uq_key);
2376                 umtxq_unlock(&uq->uq_key);
2377
2378                 /*
2379                  * Set the contested bit so that a release in user space
2380                  * knows to use the system call for unlock.  If this fails
2381                  * either some one else has acquired the lock or it has been
2382                  * released.
2383                  */
2384                 rv = casueword32(&m->m_owner, owner, &old, owner |
2385                     UMUTEX_CONTESTED);
2386
2387                 /* The address was invalid. */
2388                 if (rv == -1) {
2389                         umtxq_unbusy_unlocked(&uq->uq_key);
2390                         error = EFAULT;
2391                         break;
2392                 }
2393                 if (rv == 1) {
2394                         umtxq_unbusy_unlocked(&uq->uq_key);
2395                         error = thread_check_susp(td, true);
2396                         if (error != 0)
2397                                 break;
2398
2399                         /*
2400                          * The lock changed and we need to retry or we
2401                          * lost a race to the thread unlocking the
2402                          * umtx.  Note that the UMUTEX_RB_OWNERDEAD
2403                          * value for owner is impossible there.
2404                          */
2405                         continue;
2406                 }
2407
2408                 umtxq_lock(&uq->uq_key);
2409
2410                 /* We set the contested bit, sleep. */
2411                 MPASS(old == owner);
2412                 error = umtxq_sleep_pi(uq, pi, owner & ~UMUTEX_CONTESTED,
2413                     "umtxpi", timeout == NULL ? NULL : &timo,
2414                     (flags & USYNC_PROCESS_SHARED) != 0);
2415                 if (error != 0)
2416                         continue;
2417
2418                 error = thread_check_susp(td, false);
2419                 if (error != 0)
2420                         break;
2421         }
2422
2423         umtxq_lock(&uq->uq_key);
2424         umtx_pi_unref(pi);
2425         umtxq_unlock(&uq->uq_key);
2426
2427         umtx_key_release(&uq->uq_key);
2428         return (error);
2429 }
2430
2431 /*
2432  * Unlock a PI mutex.
2433  */
2434 static int
2435 do_unlock_pi(struct thread *td, struct umutex *m, uint32_t flags, bool rb)
2436 {
2437         struct umtx_key key;
2438         uint32_t id, new_owner, old, owner;
2439         int count, error;
2440
2441         id = td->td_tid;
2442
2443 usrloop:
2444         /*
2445          * Make sure we own this mtx.
2446          */
2447         error = fueword32(&m->m_owner, &owner);
2448         if (error == -1)
2449                 return (EFAULT);
2450
2451         if ((owner & ~UMUTEX_CONTESTED) != id)
2452                 return (EPERM);
2453
2454         new_owner = umtx_unlock_val(flags, rb);
2455
2456         /* This should be done in userland */
2457         if ((owner & UMUTEX_CONTESTED) == 0) {
2458                 error = casueword32(&m->m_owner, owner, &old, new_owner);
2459                 if (error == -1)
2460                         return (EFAULT);
2461                 if (error == 1) {
2462                         error = thread_check_susp(td, true);
2463                         if (error != 0)
2464                                 return (error);
2465                         goto usrloop;
2466                 }
2467                 if (old == owner)
2468                         return (0);
2469                 owner = old;
2470         }
2471
2472         /* We should only ever be in here for contested locks */
2473         if ((error = umtx_key_get(m, (flags & UMUTEX_ROBUST) != 0 ?
2474             TYPE_PI_ROBUST_UMUTEX : TYPE_PI_UMUTEX, GET_SHARE(flags),
2475             &key)) != 0)
2476                 return (error);
2477
2478         umtxq_lock(&key);
2479         umtxq_busy(&key);
2480         error = umtx_pi_drop(td, &key, rb, &count);
2481         if (error != 0) {
2482                 umtxq_unbusy(&key);
2483                 umtxq_unlock(&key);
2484                 umtx_key_release(&key);
2485                 /* userland messed the mutex */
2486                 return (error);
2487         }
2488         umtxq_unlock(&key);
2489
2490         /*
2491          * When unlocking the umtx, it must be marked as unowned if
2492          * there is zero or one thread only waiting for it.
2493          * Otherwise, it must be marked as contested.
2494          */
2495
2496         if (count > 1)
2497                 new_owner |= UMUTEX_CONTESTED;
2498 again:
2499         error = casueword32(&m->m_owner, owner, &old, new_owner);
2500         if (error == 1) {
2501                 error = thread_check_susp(td, false);
2502                 if (error == 0)
2503                         goto again;
2504         }
2505         umtxq_unbusy_unlocked(&key);
2506         umtx_key_release(&key);
2507         if (error == -1)
2508                 return (EFAULT);
2509         if (error == 0 && old != owner)
2510                 return (EINVAL);
2511         return (error);
2512 }
2513
2514 /*
2515  * Lock a PP mutex.
2516  */
2517 static int
2518 do_lock_pp(struct thread *td, struct umutex *m, uint32_t flags,
2519     struct _umtx_time *timeout, int try)
2520 {
2521         struct umtx_abs_timeout timo;
2522         struct umtx_q *uq, *uq2;
2523         struct umtx_pi *pi;
2524         uint32_t ceiling;
2525         uint32_t owner, id;
2526         int error, pri, old_inherited_pri, su, rv;
2527
2528         id = td->td_tid;
2529         uq = td->td_umtxq;
2530         if ((error = umtx_key_get(m, (flags & UMUTEX_ROBUST) != 0 ?
2531             TYPE_PP_ROBUST_UMUTEX : TYPE_PP_UMUTEX, GET_SHARE(flags),
2532             &uq->uq_key)) != 0)
2533                 return (error);
2534
2535         if (timeout != NULL)
2536                 umtx_abs_timeout_init2(&timo, timeout);
2537
2538         su = (priv_check(td, PRIV_SCHED_RTPRIO) == 0);
2539         for (;;) {
2540                 old_inherited_pri = uq->uq_inherited_pri;
2541                 umtxq_lock(&uq->uq_key);
2542                 umtxq_busy(&uq->uq_key);
2543                 umtxq_unlock(&uq->uq_key);
2544
2545                 rv = fueword32(&m->m_ceilings[0], &ceiling);
2546                 if (rv == -1) {
2547                         error = EFAULT;
2548                         goto out;
2549                 }
2550                 ceiling = RTP_PRIO_MAX - ceiling;
2551                 if (ceiling > RTP_PRIO_MAX) {
2552                         error = EINVAL;
2553                         goto out;
2554                 }
2555
2556                 mtx_lock(&umtx_lock);
2557                 if (UPRI(td) < PRI_MIN_REALTIME + ceiling) {
2558                         mtx_unlock(&umtx_lock);
2559                         error = EINVAL;
2560                         goto out;
2561                 }
2562                 if (su && PRI_MIN_REALTIME + ceiling < uq->uq_inherited_pri) {
2563                         uq->uq_inherited_pri = PRI_MIN_REALTIME + ceiling;
2564                         thread_lock(td);
2565                         if (uq->uq_inherited_pri < UPRI(td))
2566                                 sched_lend_user_prio(td, uq->uq_inherited_pri);
2567                         thread_unlock(td);
2568                 }
2569                 mtx_unlock(&umtx_lock);
2570
2571                 rv = casueword32(&m->m_owner, UMUTEX_CONTESTED, &owner,
2572                     id | UMUTEX_CONTESTED);
2573                 /* The address was invalid. */
2574                 if (rv == -1) {
2575                         error = EFAULT;
2576                         break;
2577                 }
2578                 if (rv == 0) {
2579                         MPASS(owner == UMUTEX_CONTESTED);
2580                         error = 0;
2581                         break;
2582                 }
2583                 /* rv == 1 */
2584                 if (owner == UMUTEX_RB_OWNERDEAD) {
2585                         rv = casueword32(&m->m_owner, UMUTEX_RB_OWNERDEAD,
2586                             &owner, id | UMUTEX_CONTESTED);
2587                         if (rv == -1) {
2588                                 error = EFAULT;
2589                                 break;
2590                         }
2591                         if (rv == 0) {
2592                                 MPASS(owner == UMUTEX_RB_OWNERDEAD);
2593                                 error = EOWNERDEAD; /* success */
2594                                 break;
2595                         }
2596
2597                         /*
2598                          *  rv == 1, only check for suspension if we
2599                          *  did not already catched a signal.  If we
2600                          *  get an error from the check, the same
2601                          *  condition is checked by the umtxq_sleep()
2602                          *  call below, so we should obliterate the
2603                          *  error to not skip the last loop iteration.
2604                          */
2605                         if (error == 0) {
2606                                 error = thread_check_susp(td, false);
2607                                 if (error == 0) {
2608                                         if (try != 0)
2609                                                 error = EBUSY;
2610                                         else
2611                                                 continue;
2612                                 }
2613                                 error = 0;
2614                         }
2615                 } else if (owner == UMUTEX_RB_NOTRECOV) {
2616                         error = ENOTRECOVERABLE;
2617                 }
2618
2619                 if (try != 0)
2620                         error = EBUSY;
2621
2622                 /*
2623                  * If we caught a signal, we have retried and now
2624                  * exit immediately.
2625                  */
2626                 if (error != 0)
2627                         break;
2628
2629                 umtxq_lock(&uq->uq_key);
2630                 umtxq_insert(uq);
2631                 umtxq_unbusy(&uq->uq_key);
2632                 error = umtxq_sleep(uq, "umtxpp", timeout == NULL ?
2633                     NULL : &timo);
2634                 umtxq_remove(uq);
2635                 umtxq_unlock(&uq->uq_key);
2636
2637                 mtx_lock(&umtx_lock);
2638                 uq->uq_inherited_pri = old_inherited_pri;
2639                 pri = PRI_MAX;
2640                 TAILQ_FOREACH(pi, &uq->uq_pi_contested, pi_link) {
2641                         uq2 = TAILQ_FIRST(&pi->pi_blocked);
2642                         if (uq2 != NULL) {
2643                                 if (pri > UPRI(uq2->uq_thread))
2644                                         pri = UPRI(uq2->uq_thread);
2645                         }
2646                 }
2647                 if (pri > uq->uq_inherited_pri)
2648                         pri = uq->uq_inherited_pri;
2649                 thread_lock(td);
2650                 sched_lend_user_prio(td, pri);
2651                 thread_unlock(td);
2652                 mtx_unlock(&umtx_lock);
2653         }
2654
2655         if (error != 0 && error != EOWNERDEAD) {
2656                 mtx_lock(&umtx_lock);
2657                 uq->uq_inherited_pri = old_inherited_pri;
2658                 pri = PRI_MAX;
2659                 TAILQ_FOREACH(pi, &uq->uq_pi_contested, pi_link) {
2660                         uq2 = TAILQ_FIRST(&pi->pi_blocked);
2661                         if (uq2 != NULL) {
2662                                 if (pri > UPRI(uq2->uq_thread))
2663                                         pri = UPRI(uq2->uq_thread);
2664                         }
2665                 }
2666                 if (pri > uq->uq_inherited_pri)
2667                         pri = uq->uq_inherited_pri;
2668                 thread_lock(td);
2669                 sched_lend_user_prio(td, pri);
2670                 thread_unlock(td);
2671                 mtx_unlock(&umtx_lock);
2672         }
2673
2674 out:
2675         umtxq_unbusy_unlocked(&uq->uq_key);
2676         umtx_key_release(&uq->uq_key);
2677         return (error);
2678 }
2679
2680 /*
2681  * Unlock a PP mutex.
2682  */
2683 static int
2684 do_unlock_pp(struct thread *td, struct umutex *m, uint32_t flags, bool rb)
2685 {
2686         struct umtx_key key;
2687         struct umtx_q *uq, *uq2;
2688         struct umtx_pi *pi;
2689         uint32_t id, owner, rceiling;
2690         int error, pri, new_inherited_pri, su;
2691
2692         id = td->td_tid;
2693         uq = td->td_umtxq;
2694         su = (priv_check(td, PRIV_SCHED_RTPRIO) == 0);
2695
2696         /*
2697          * Make sure we own this mtx.
2698          */
2699         error = fueword32(&m->m_owner, &owner);
2700         if (error == -1)
2701                 return (EFAULT);
2702
2703         if ((owner & ~UMUTEX_CONTESTED) != id)
2704                 return (EPERM);
2705
2706         error = copyin(&m->m_ceilings[1], &rceiling, sizeof(uint32_t));
2707         if (error != 0)
2708                 return (error);
2709
2710         if (rceiling == -1)
2711                 new_inherited_pri = PRI_MAX;
2712         else {
2713                 rceiling = RTP_PRIO_MAX - rceiling;
2714                 if (rceiling > RTP_PRIO_MAX)
2715                         return (EINVAL);
2716                 new_inherited_pri = PRI_MIN_REALTIME + rceiling;
2717         }
2718
2719         if ((error = umtx_key_get(m, (flags & UMUTEX_ROBUST) != 0 ?
2720             TYPE_PP_ROBUST_UMUTEX : TYPE_PP_UMUTEX, GET_SHARE(flags),
2721             &key)) != 0)
2722                 return (error);
2723         umtxq_lock(&key);
2724         umtxq_busy(&key);
2725         umtxq_unlock(&key);
2726         /*
2727          * For priority protected mutex, always set unlocked state
2728          * to UMUTEX_CONTESTED, so that userland always enters kernel
2729          * to lock the mutex, it is necessary because thread priority
2730          * has to be adjusted for such mutex.
2731          */
2732         error = suword32(&m->m_owner, umtx_unlock_val(flags, rb) |
2733             UMUTEX_CONTESTED);
2734
2735         umtxq_lock(&key);
2736         if (error == 0)
2737                 umtxq_signal(&key, 1);
2738         umtxq_unbusy(&key);
2739         umtxq_unlock(&key);
2740
2741         if (error == -1)
2742                 error = EFAULT;
2743         else {
2744                 mtx_lock(&umtx_lock);
2745                 if (su != 0)
2746                         uq->uq_inherited_pri = new_inherited_pri;
2747                 pri = PRI_MAX;
2748                 TAILQ_FOREACH(pi, &uq->uq_pi_contested, pi_link) {
2749                         uq2 = TAILQ_FIRST(&pi->pi_blocked);
2750                         if (uq2 != NULL) {
2751                                 if (pri > UPRI(uq2->uq_thread))
2752                                         pri = UPRI(uq2->uq_thread);
2753                         }
2754                 }
2755                 if (pri > uq->uq_inherited_pri)
2756                         pri = uq->uq_inherited_pri;
2757                 thread_lock(td);
2758                 sched_lend_user_prio(td, pri);
2759                 thread_unlock(td);
2760                 mtx_unlock(&umtx_lock);
2761         }
2762         umtx_key_release(&key);
2763         return (error);
2764 }
2765
2766 static int
2767 do_set_ceiling(struct thread *td, struct umutex *m, uint32_t ceiling,
2768     uint32_t *old_ceiling)
2769 {
2770         struct umtx_q *uq;
2771         uint32_t flags, id, owner, save_ceiling;
2772         int error, rv, rv1;
2773
2774         error = fueword32(&m->m_flags, &flags);
2775         if (error == -1)
2776                 return (EFAULT);
2777         if ((flags & UMUTEX_PRIO_PROTECT) == 0)
2778                 return (EINVAL);
2779         if (ceiling > RTP_PRIO_MAX)
2780                 return (EINVAL);
2781         id = td->td_tid;
2782         uq = td->td_umtxq;
2783         if ((error = umtx_key_get(m, (flags & UMUTEX_ROBUST) != 0 ?
2784             TYPE_PP_ROBUST_UMUTEX : TYPE_PP_UMUTEX, GET_SHARE(flags),
2785             &uq->uq_key)) != 0)
2786                 return (error);
2787         for (;;) {
2788                 umtxq_lock(&uq->uq_key);
2789                 umtxq_busy(&uq->uq_key);
2790                 umtxq_unlock(&uq->uq_key);
2791
2792                 rv = fueword32(&m->m_ceilings[0], &save_ceiling);
2793                 if (rv == -1) {
2794                         error = EFAULT;
2795                         break;
2796                 }
2797
2798                 rv = casueword32(&m->m_owner, UMUTEX_CONTESTED, &owner,
2799                     id | UMUTEX_CONTESTED);
2800                 if (rv == -1) {
2801                         error = EFAULT;
2802                         break;
2803                 }
2804
2805                 if (rv == 0) {
2806                         MPASS(owner == UMUTEX_CONTESTED);
2807                         rv = suword32(&m->m_ceilings[0], ceiling);
2808                         rv1 = suword32(&m->m_owner, UMUTEX_CONTESTED);
2809                         error = (rv == 0 && rv1 == 0) ? 0: EFAULT;
2810                         break;
2811                 }
2812
2813                 if ((owner & ~UMUTEX_CONTESTED) == id) {
2814                         rv = suword32(&m->m_ceilings[0], ceiling);
2815                         error = rv == 0 ? 0 : EFAULT;
2816                         break;
2817                 }
2818
2819                 if (owner == UMUTEX_RB_OWNERDEAD) {
2820                         error = EOWNERDEAD;
2821                         break;
2822                 } else if (owner == UMUTEX_RB_NOTRECOV) {
2823                         error = ENOTRECOVERABLE;
2824                         break;
2825                 }
2826
2827                 /*
2828                  * If we caught a signal, we have retried and now
2829                  * exit immediately.
2830                  */
2831                 if (error != 0)
2832                         break;
2833
2834                 /*
2835                  * We set the contested bit, sleep. Otherwise the lock changed
2836                  * and we need to retry or we lost a race to the thread
2837                  * unlocking the umtx.
2838                  */
2839                 umtxq_lock(&uq->uq_key);
2840                 umtxq_insert(uq);
2841                 umtxq_unbusy(&uq->uq_key);
2842                 error = umtxq_sleep(uq, "umtxpp", NULL);
2843                 umtxq_remove(uq);
2844                 umtxq_unlock(&uq->uq_key);
2845         }
2846         umtxq_lock(&uq->uq_key);
2847         if (error == 0)
2848                 umtxq_signal(&uq->uq_key, INT_MAX);
2849         umtxq_unbusy(&uq->uq_key);
2850         umtxq_unlock(&uq->uq_key);
2851         umtx_key_release(&uq->uq_key);
2852         if (error == 0 && old_ceiling != NULL) {
2853                 rv = suword32(old_ceiling, save_ceiling);
2854                 error = rv == 0 ? 0 : EFAULT;
2855         }
2856         return (error);
2857 }
2858
2859 /*
2860  * Lock a userland POSIX mutex.
2861  */
2862 static int
2863 do_lock_umutex(struct thread *td, struct umutex *m,
2864     struct _umtx_time *timeout, int mode)
2865 {
2866         uint32_t flags;
2867         int error;
2868
2869         error = fueword32(&m->m_flags, &flags);
2870         if (error == -1)
2871                 return (EFAULT);
2872
2873         switch (flags & (UMUTEX_PRIO_INHERIT | UMUTEX_PRIO_PROTECT)) {
2874         case 0:
2875                 error = do_lock_normal(td, m, flags, timeout, mode);
2876                 break;
2877         case UMUTEX_PRIO_INHERIT:
2878                 error = do_lock_pi(td, m, flags, timeout, mode);
2879                 break;
2880         case UMUTEX_PRIO_PROTECT:
2881                 error = do_lock_pp(td, m, flags, timeout, mode);
2882                 break;
2883         default:
2884                 return (EINVAL);
2885         }
2886         if (timeout == NULL) {
2887                 if (error == EINTR && mode != _UMUTEX_WAIT)
2888                         error = ERESTART;
2889         } else {
2890                 /* Timed-locking is not restarted. */
2891                 if (error == ERESTART)
2892                         error = EINTR;
2893         }
2894         return (error);
2895 }
2896
2897 /*
2898  * Unlock a userland POSIX mutex.
2899  */
2900 static int
2901 do_unlock_umutex(struct thread *td, struct umutex *m, bool rb)
2902 {
2903         uint32_t flags;
2904         int error;
2905
2906         error = fueword32(&m->m_flags, &flags);
2907         if (error == -1)
2908                 return (EFAULT);
2909
2910         switch (flags & (UMUTEX_PRIO_INHERIT | UMUTEX_PRIO_PROTECT)) {
2911         case 0:
2912                 return (do_unlock_normal(td, m, flags, rb));
2913         case UMUTEX_PRIO_INHERIT:
2914                 return (do_unlock_pi(td, m, flags, rb));
2915         case UMUTEX_PRIO_PROTECT:
2916                 return (do_unlock_pp(td, m, flags, rb));
2917         }
2918
2919         return (EINVAL);
2920 }
2921
2922 static int
2923 do_cv_wait(struct thread *td, struct ucond *cv, struct umutex *m,
2924     struct timespec *timeout, u_long wflags)
2925 {
2926         struct umtx_abs_timeout timo;
2927         struct umtx_q *uq;
2928         uint32_t flags, clockid, hasw;
2929         int error;
2930
2931         uq = td->td_umtxq;
2932         error = fueword32(&cv->c_flags, &flags);
2933         if (error == -1)
2934                 return (EFAULT);
2935         error = umtx_key_get(cv, TYPE_CV, GET_SHARE(flags), &uq->uq_key);
2936         if (error != 0)
2937                 return (error);
2938
2939         if ((wflags & CVWAIT_CLOCKID) != 0) {
2940                 error = fueword32(&cv->c_clockid, &clockid);
2941                 if (error == -1) {
2942                         umtx_key_release(&uq->uq_key);
2943                         return (EFAULT);
2944                 }
2945                 if (clockid < CLOCK_REALTIME ||
2946                     clockid >= CLOCK_THREAD_CPUTIME_ID) {
2947                         /* hmm, only HW clock id will work. */
2948                         umtx_key_release(&uq->uq_key);
2949                         return (EINVAL);
2950                 }
2951         } else {
2952                 clockid = CLOCK_REALTIME;
2953         }
2954
2955         umtxq_lock(&uq->uq_key);
2956         umtxq_busy(&uq->uq_key);
2957         umtxq_insert(uq);
2958         umtxq_unlock(&uq->uq_key);
2959
2960         /*
2961          * Set c_has_waiters to 1 before releasing user mutex, also
2962          * don't modify cache line when unnecessary.
2963          */
2964         error = fueword32(&cv->c_has_waiters, &hasw);
2965         if (error == 0 && hasw == 0)
2966                 suword32(&cv->c_has_waiters, 1);
2967
2968         umtxq_unbusy_unlocked(&uq->uq_key);
2969
2970         error = do_unlock_umutex(td, m, false);
2971
2972         if (timeout != NULL)
2973                 umtx_abs_timeout_init(&timo, clockid,
2974                     (wflags & CVWAIT_ABSTIME) != 0, timeout);
2975
2976         umtxq_lock(&uq->uq_key);
2977         if (error == 0) {
2978                 error = umtxq_sleep(uq, "ucond", timeout == NULL ?
2979                     NULL : &timo);
2980         }
2981
2982         if ((uq->uq_flags & UQF_UMTXQ) == 0)
2983                 error = 0;
2984         else {
2985                 /*
2986                  * This must be timeout,interrupted by signal or
2987                  * surprious wakeup, clear c_has_waiter flag when
2988                  * necessary.
2989                  */
2990                 umtxq_busy(&uq->uq_key);
2991                 if ((uq->uq_flags & UQF_UMTXQ) != 0) {
2992                         int oldlen = uq->uq_cur_queue->length;
2993                         umtxq_remove(uq);
2994                         if (oldlen == 1) {
2995                                 umtxq_unlock(&uq->uq_key);
2996                                 suword32(&cv->c_has_waiters, 0);
2997                                 umtxq_lock(&uq->uq_key);
2998                         }
2999                 }
3000                 umtxq_unbusy(&uq->uq_key);
3001                 if (error == ERESTART)
3002                         error = EINTR;
3003         }
3004
3005         umtxq_unlock(&uq->uq_key);
3006         umtx_key_release(&uq->uq_key);
3007         return (error);
3008 }
3009
3010 /*
3011  * Signal a userland condition variable.
3012  */
3013 static int
3014 do_cv_signal(struct thread *td, struct ucond *cv)
3015 {
3016         struct umtx_key key;
3017         int error, cnt, nwake;
3018         uint32_t flags;
3019
3020         error = fueword32(&cv->c_flags, &flags);
3021         if (error == -1)
3022                 return (EFAULT);
3023         if ((error = umtx_key_get(cv, TYPE_CV, GET_SHARE(flags), &key)) != 0)
3024                 return (error);
3025         umtxq_lock(&key);
3026         umtxq_busy(&key);
3027         cnt = umtxq_count(&key);
3028         nwake = umtxq_signal(&key, 1);
3029         if (cnt <= nwake) {
3030                 umtxq_unlock(&key);
3031                 error = suword32(&cv->c_has_waiters, 0);
3032                 if (error == -1)
3033                         error = EFAULT;
3034                 umtxq_lock(&key);
3035         }
3036         umtxq_unbusy(&key);
3037         umtxq_unlock(&key);
3038         umtx_key_release(&key);
3039         return (error);
3040 }
3041
3042 static int
3043 do_cv_broadcast(struct thread *td, struct ucond *cv)
3044 {
3045         struct umtx_key key;
3046         int error;
3047         uint32_t flags;
3048
3049         error = fueword32(&cv->c_flags, &flags);
3050         if (error == -1)
3051                 return (EFAULT);
3052         if ((error = umtx_key_get(cv, TYPE_CV, GET_SHARE(flags), &key)) != 0)
3053                 return (error);
3054
3055         umtxq_lock(&key);
3056         umtxq_busy(&key);
3057         umtxq_signal(&key, INT_MAX);
3058         umtxq_unlock(&key);
3059
3060         error = suword32(&cv->c_has_waiters, 0);
3061         if (error == -1)
3062                 error = EFAULT;
3063
3064         umtxq_unbusy_unlocked(&key);
3065
3066         umtx_key_release(&key);
3067         return (error);
3068 }
3069
3070 static int
3071 do_rw_rdlock(struct thread *td, struct urwlock *rwlock, long fflag,
3072     struct _umtx_time *timeout)
3073 {
3074         struct umtx_abs_timeout timo;
3075         struct umtx_q *uq;
3076         uint32_t flags, wrflags;
3077         int32_t state, oldstate;
3078         int32_t blocked_readers;
3079         int error, error1, rv;
3080
3081         uq = td->td_umtxq;
3082         error = fueword32(&rwlock->rw_flags, &flags);
3083         if (error == -1)
3084                 return (EFAULT);
3085         error = umtx_key_get(rwlock, TYPE_RWLOCK, GET_SHARE(flags), &uq->uq_key);
3086         if (error != 0)
3087                 return (error);
3088
3089         if (timeout != NULL)
3090                 umtx_abs_timeout_init2(&timo, timeout);
3091
3092         wrflags = URWLOCK_WRITE_OWNER;
3093         if (!(fflag & URWLOCK_PREFER_READER) && !(flags & URWLOCK_PREFER_READER))
3094                 wrflags |= URWLOCK_WRITE_WAITERS;
3095
3096         for (;;) {
3097                 rv = fueword32(&rwlock->rw_state, &state);
3098                 if (rv == -1) {
3099                         umtx_key_release(&uq->uq_key);
3100                         return (EFAULT);
3101                 }
3102
3103                 /* try to lock it */
3104                 while (!(state & wrflags)) {
3105                         if (__predict_false(URWLOCK_READER_COUNT(state) ==
3106                             URWLOCK_MAX_READERS)) {
3107                                 umtx_key_release(&uq->uq_key);
3108                                 return (EAGAIN);
3109                         }
3110                         rv = casueword32(&rwlock->rw_state, state,
3111                             &oldstate, state + 1);
3112                         if (rv == -1) {
3113                                 umtx_key_release(&uq->uq_key);
3114                                 return (EFAULT);
3115                         }
3116                         if (rv == 0) {
3117                                 MPASS(oldstate == state);
3118                                 umtx_key_release(&uq->uq_key);
3119                                 return (0);
3120                         }
3121                         error = thread_check_susp(td, true);
3122                         if (error != 0)
3123                                 break;
3124                         state = oldstate;
3125                 }
3126
3127                 if (error)
3128                         break;
3129
3130                 /* grab monitor lock */
3131                 umtxq_lock(&uq->uq_key);
3132                 umtxq_busy(&uq->uq_key);
3133                 umtxq_unlock(&uq->uq_key);
3134
3135                 /*
3136                  * re-read the state, in case it changed between the try-lock above
3137                  * and the check below
3138                  */
3139                 rv = fueword32(&rwlock->rw_state, &state);
3140                 if (rv == -1)
3141                         error = EFAULT;
3142
3143                 /* set read contention bit */
3144                 while (error == 0 && (state & wrflags) &&
3145                     !(state & URWLOCK_READ_WAITERS)) {
3146                         rv = casueword32(&rwlock->rw_state, state,
3147                             &oldstate, state | URWLOCK_READ_WAITERS);
3148                         if (rv == -1) {
3149                                 error = EFAULT;
3150                                 break;
3151                         }
3152                         if (rv == 0) {
3153                                 MPASS(oldstate == state);
3154                                 goto sleep;
3155                         }
3156                         state = oldstate;
3157                         error = thread_check_susp(td, false);
3158                         if (error != 0)
3159                                 break;
3160                 }
3161                 if (error != 0) {
3162                         umtxq_unbusy_unlocked(&uq->uq_key);
3163                         break;
3164                 }
3165
3166                 /* state is changed while setting flags, restart */
3167                 if (!(state & wrflags)) {
3168                         umtxq_unbusy_unlocked(&uq->uq_key);
3169                         error = thread_check_susp(td, true);
3170                         if (error != 0)
3171                                 break;
3172                         continue;
3173                 }
3174
3175 sleep:
3176                 /*
3177                  * Contention bit is set, before sleeping, increase
3178                  * read waiter count.
3179                  */
3180                 rv = fueword32(&rwlock->rw_blocked_readers,
3181                     &blocked_readers);
3182                 if (rv == -1) {
3183                         umtxq_unbusy_unlocked(&uq->uq_key);
3184                         error = EFAULT;
3185                         break;
3186                 }
3187                 suword32(&rwlock->rw_blocked_readers, blocked_readers+1);
3188
3189                 while (state & wrflags) {
3190                         umtxq_lock(&uq->uq_key);
3191                         umtxq_insert(uq);
3192                         umtxq_unbusy(&uq->uq_key);
3193
3194                         error = umtxq_sleep(uq, "urdlck", timeout == NULL ?
3195                             NULL : &timo);
3196
3197                         umtxq_busy(&uq->uq_key);
3198                         umtxq_remove(uq);
3199                         umtxq_unlock(&uq->uq_key);
3200                         if (error)
3201                                 break;
3202                         rv = fueword32(&rwlock->rw_state, &state);
3203                         if (rv == -1) {
3204                                 error = EFAULT;
3205                                 break;
3206                         }
3207                 }
3208
3209                 /* decrease read waiter count, and may clear read contention bit */
3210                 rv = fueword32(&rwlock->rw_blocked_readers,
3211                     &blocked_readers);
3212                 if (rv == -1) {
3213                         umtxq_unbusy_unlocked(&uq->uq_key);
3214                         error = EFAULT;
3215                         break;
3216                 }
3217                 suword32(&rwlock->rw_blocked_readers, blocked_readers-1);
3218                 if (blocked_readers == 1) {
3219                         rv = fueword32(&rwlock->rw_state, &state);
3220                         if (rv == -1) {
3221                                 umtxq_unbusy_unlocked(&uq->uq_key);
3222                                 error = EFAULT;
3223                                 break;
3224                         }
3225                         for (;;) {
3226                                 rv = casueword32(&rwlock->rw_state, state,
3227                                     &oldstate, state & ~URWLOCK_READ_WAITERS);
3228                                 if (rv == -1) {
3229                                         error = EFAULT;
3230                                         break;
3231                                 }
3232                                 if (rv == 0) {
3233                                         MPASS(oldstate == state);
3234                                         break;
3235                                 }
3236                                 state = oldstate;
3237                                 error1 = thread_check_susp(td, false);
3238                                 if (error1 != 0) {
3239                                         if (error == 0)
3240                                                 error = error1;
3241                                         break;
3242                                 }
3243                         }
3244                 }
3245
3246                 umtxq_unbusy_unlocked(&uq->uq_key);
3247                 if (error != 0)
3248                         break;
3249         }
3250         umtx_key_release(&uq->uq_key);
3251         if (error == ERESTART)
3252                 error = EINTR;
3253         return (error);
3254 }
3255
3256 static int
3257 do_rw_wrlock(struct thread *td, struct urwlock *rwlock, struct _umtx_time *timeout)
3258 {
3259         struct umtx_abs_timeout timo;
3260         struct umtx_q *uq;
3261         uint32_t flags;
3262         int32_t state, oldstate;
3263         int32_t blocked_writers;
3264         int32_t blocked_readers;
3265         int error, error1, rv;
3266
3267         uq = td->td_umtxq;
3268         error = fueword32(&rwlock->rw_flags, &flags);
3269         if (error == -1)
3270                 return (EFAULT);
3271         error = umtx_key_get(rwlock, TYPE_RWLOCK, GET_SHARE(flags), &uq->uq_key);
3272         if (error != 0)
3273                 return (error);
3274
3275         if (timeout != NULL)
3276                 umtx_abs_timeout_init2(&timo, timeout);
3277
3278         blocked_readers = 0;
3279         for (;;) {
3280                 rv = fueword32(&rwlock->rw_state, &state);
3281                 if (rv == -1) {
3282                         umtx_key_release(&uq->uq_key);
3283                         return (EFAULT);
3284                 }
3285                 while ((state & URWLOCK_WRITE_OWNER) == 0 &&
3286                     URWLOCK_READER_COUNT(state) == 0) {
3287                         rv = casueword32(&rwlock->rw_state, state,
3288                             &oldstate, state | URWLOCK_WRITE_OWNER);
3289                         if (rv == -1) {
3290                                 umtx_key_release(&uq->uq_key);
3291                                 return (EFAULT);
3292                         }
3293                         if (rv == 0) {
3294                                 MPASS(oldstate == state);
3295                                 umtx_key_release(&uq->uq_key);
3296                                 return (0);
3297                         }
3298                         state = oldstate;
3299                         error = thread_check_susp(td, true);
3300                         if (error != 0)
3301                                 break;
3302                 }
3303
3304                 if (error) {
3305                         if ((state & (URWLOCK_WRITE_OWNER |
3306                             URWLOCK_WRITE_WAITERS)) == 0 &&
3307                             blocked_readers != 0) {
3308                                 umtxq_lock(&uq->uq_key);
3309                                 umtxq_busy(&uq->uq_key);
3310                                 umtxq_signal_queue(&uq->uq_key, INT_MAX,
3311                                     UMTX_SHARED_QUEUE);
3312                                 umtxq_unbusy(&uq->uq_key);
3313                                 umtxq_unlock(&uq->uq_key);
3314                         }
3315
3316                         break;
3317                 }
3318
3319                 /* grab monitor lock */
3320                 umtxq_lock(&uq->uq_key);
3321                 umtxq_busy(&uq->uq_key);
3322                 umtxq_unlock(&uq->uq_key);
3323
3324                 /*
3325                  * Re-read the state, in case it changed between the
3326                  * try-lock above and the check below.
3327                  */
3328                 rv = fueword32(&rwlock->rw_state, &state);
3329                 if (rv == -1)
3330                         error = EFAULT;
3331
3332                 while (error == 0 && ((state & URWLOCK_WRITE_OWNER) ||
3333                     URWLOCK_READER_COUNT(state) != 0) &&
3334                     (state & URWLOCK_WRITE_WAITERS) == 0) {
3335                         rv = casueword32(&rwlock->rw_state, state,
3336                             &oldstate, state | URWLOCK_WRITE_WAITERS);
3337                         if (rv == -1) {
3338                                 error = EFAULT;
3339                                 break;
3340                         }
3341                         if (rv == 0) {
3342                                 MPASS(oldstate == state);
3343                                 goto sleep;
3344                         }
3345                         state = oldstate;
3346                         error = thread_check_susp(td, false);
3347                         if (error != 0)
3348                                 break;
3349                 }
3350                 if (error != 0) {
3351                         umtxq_unbusy_unlocked(&uq->uq_key);
3352                         break;
3353                 }
3354
3355                 if ((state & URWLOCK_WRITE_OWNER) == 0 &&
3356                     URWLOCK_READER_COUNT(state) == 0) {
3357                         umtxq_unbusy_unlocked(&uq->uq_key);
3358                         error = thread_check_susp(td, false);
3359                         if (error != 0)
3360                                 break;
3361                         continue;
3362                 }
3363 sleep:
3364                 rv = fueword32(&rwlock->rw_blocked_writers,
3365                     &blocked_writers);
3366                 if (rv == -1) {
3367                         umtxq_unbusy_unlocked(&uq->uq_key);
3368                         error = EFAULT;
3369                         break;
3370                 }
3371                 suword32(&rwlock->rw_blocked_writers, blocked_writers + 1);
3372
3373                 while ((state & URWLOCK_WRITE_OWNER) ||
3374                     URWLOCK_READER_COUNT(state) != 0) {
3375                         umtxq_lock(&uq->uq_key);
3376                         umtxq_insert_queue(uq, UMTX_EXCLUSIVE_QUEUE);
3377                         umtxq_unbusy(&uq->uq_key);
3378
3379                         error = umtxq_sleep(uq, "uwrlck", timeout == NULL ?
3380                             NULL : &timo);
3381
3382                         umtxq_busy(&uq->uq_key);
3383                         umtxq_remove_queue(uq, UMTX_EXCLUSIVE_QUEUE);
3384                         umtxq_unlock(&uq->uq_key);
3385                         if (error)
3386                                 break;
3387                         rv = fueword32(&rwlock->rw_state, &state);
3388                         if (rv == -1) {
3389                                 error = EFAULT;
3390                                 break;
3391                         }
3392                 }
3393
3394                 rv = fueword32(&rwlock->rw_blocked_writers,
3395                     &blocked_writers);
3396                 if (rv == -1) {
3397                         umtxq_unbusy_unlocked(&uq->uq_key);
3398                         error = EFAULT;
3399                         break;
3400                 }
3401                 suword32(&rwlock->rw_blocked_writers, blocked_writers-1);
3402                 if (blocked_writers == 1) {
3403                         rv = fueword32(&rwlock->rw_state, &state);
3404                         if (rv == -1) {
3405                                 umtxq_unbusy_unlocked(&uq->uq_key);
3406                                 error = EFAULT;
3407                                 break;
3408                         }
3409                         for (;;) {
3410                                 rv = casueword32(&rwlock->rw_state, state,
3411                                     &oldstate, state & ~URWLOCK_WRITE_WAITERS);
3412                                 if (rv == -1) {
3413                                         error = EFAULT;
3414                                         break;
3415                                 }
3416                                 if (rv == 0) {
3417                                         MPASS(oldstate == state);
3418                                         break;
3419                                 }
3420                                 state = oldstate;
3421                                 error1 = thread_check_susp(td, false);
3422                                 /*
3423                                  * We are leaving the URWLOCK_WRITE_WAITERS
3424                                  * behind, but this should not harm the
3425                                  * correctness.
3426                                  */
3427                                 if (error1 != 0) {
3428                                         if (error == 0)
3429                                                 error = error1;
3430                                         break;
3431                                 }
3432                         }
3433                         rv = fueword32(&rwlock->rw_blocked_readers,
3434                             &blocked_readers);
3435                         if (rv == -1) {
3436                                 umtxq_unbusy_unlocked(&uq->uq_key);
3437                                 error = EFAULT;
3438                                 break;
3439                         }
3440                 } else
3441                         blocked_readers = 0;
3442
3443                 umtxq_unbusy_unlocked(&uq->uq_key);
3444         }
3445
3446         umtx_key_release(&uq->uq_key);
3447         if (error == ERESTART)
3448                 error = EINTR;
3449         return (error);
3450 }
3451
3452 static int
3453 do_rw_unlock(struct thread *td, struct urwlock *rwlock)
3454 {
3455         struct umtx_q *uq;
3456         uint32_t flags;
3457         int32_t state, oldstate;
3458         int error, rv, q, count;
3459
3460         uq = td->td_umtxq;
3461         error = fueword32(&rwlock->rw_flags, &flags);
3462         if (error == -1)
3463                 return (EFAULT);
3464         error = umtx_key_get(rwlock, TYPE_RWLOCK, GET_SHARE(flags), &uq->uq_key);
3465         if (error != 0)
3466                 return (error);
3467
3468         error = fueword32(&rwlock->rw_state, &state);
3469         if (error == -1) {
3470                 error = EFAULT;
3471                 goto out;
3472         }
3473         if (state & URWLOCK_WRITE_OWNER) {
3474                 for (;;) {
3475                         rv = casueword32(&rwlock->rw_state, state,
3476                             &oldstate, state & ~URWLOCK_WRITE_OWNER);
3477                         if (rv == -1) {
3478                                 error = EFAULT;
3479                                 goto out;
3480                         }
3481                         if (rv == 1) {
3482                                 state = oldstate;
3483                                 if (!(oldstate & URWLOCK_WRITE_OWNER)) {
3484                                         error = EPERM;
3485                                         goto out;
3486                                 }
3487                                 error = thread_check_susp(td, true);
3488                                 if (error != 0)
3489                                         goto out;
3490                         } else
3491                                 break;
3492                 }
3493         } else if (URWLOCK_READER_COUNT(state) != 0) {
3494                 for (;;) {
3495                         rv = casueword32(&rwlock->rw_state, state,
3496                             &oldstate, state - 1);
3497                         if (rv == -1) {
3498                                 error = EFAULT;
3499                                 goto out;
3500                         }
3501                         if (rv == 1) {
3502                                 state = oldstate;
3503                                 if (URWLOCK_READER_COUNT(oldstate) == 0) {
3504                                         error = EPERM;
3505                                         goto out;
3506                                 }
3507                                 error = thread_check_susp(td, true);
3508                                 if (error != 0)
3509                                         goto out;
3510                         } else
3511                                 break;
3512                 }
3513         } else {
3514                 error = EPERM;
3515                 goto out;
3516         }
3517
3518         count = 0;
3519
3520         if (!(flags & URWLOCK_PREFER_READER)) {
3521                 if (state & URWLOCK_WRITE_WAITERS) {
3522                         count = 1;
3523                         q = UMTX_EXCLUSIVE_QUEUE;
3524                 } else if (state & URWLOCK_READ_WAITERS) {
3525                         count = INT_MAX;
3526                         q = UMTX_SHARED_QUEUE;
3527                 }
3528         } else {
3529                 if (state & URWLOCK_READ_WAITERS) {
3530                         count = INT_MAX;
3531                         q = UMTX_SHARED_QUEUE;
3532                 } else if (state & URWLOCK_WRITE_WAITERS) {
3533                         count = 1;
3534                         q = UMTX_EXCLUSIVE_QUEUE;
3535                 }
3536         }
3537
3538         if (count) {
3539                 umtxq_lock(&uq->uq_key);
3540                 umtxq_busy(&uq->uq_key);
3541                 umtxq_signal_queue(&uq->uq_key, count, q);
3542                 umtxq_unbusy(&uq->uq_key);
3543                 umtxq_unlock(&uq->uq_key);
3544         }
3545 out:
3546         umtx_key_release(&uq->uq_key);
3547         return (error);
3548 }
3549
3550 #if defined(COMPAT_FREEBSD9) || defined(COMPAT_FREEBSD10)
3551 static int
3552 do_sem_wait(struct thread *td, struct _usem *sem, struct _umtx_time *timeout)
3553 {
3554         struct umtx_abs_timeout timo;
3555         struct umtx_q *uq;
3556         uint32_t flags, count, count1;
3557         int error, rv, rv1;
3558
3559         uq = td->td_umtxq;
3560         error = fueword32(&sem->_flags, &flags);
3561         if (error == -1)
3562                 return (EFAULT);
3563         error = umtx_key_get(sem, TYPE_SEM, GET_SHARE(flags), &uq->uq_key);
3564         if (error != 0)
3565                 return (error);
3566
3567         if (timeout != NULL)
3568                 umtx_abs_timeout_init2(&timo, timeout);
3569
3570 again:
3571         umtxq_lock(&uq->uq_key);
3572         umtxq_busy(&uq->uq_key);
3573         umtxq_insert(uq);
3574         umtxq_unlock(&uq->uq_key);
3575         rv = casueword32(&sem->_has_waiters, 0, &count1, 1);
3576         if (rv != -1)
3577                 rv1 = fueword32(&sem->_count, &count);
3578         if (rv == -1 || rv1 == -1 || count != 0 || (rv == 1 && count1 == 0)) {
3579                 if (rv == 0)
3580                         suword32(&sem->_has_waiters, 0);
3581                 umtxq_lock(&uq->uq_key);
3582                 umtxq_unbusy(&uq->uq_key);
3583                 umtxq_remove(uq);
3584                 umtxq_unlock(&uq->uq_key);
3585                 if (rv == -1 || rv1 == -1) {
3586                         error = EFAULT;
3587                         goto out;
3588                 }
3589                 if (count != 0) {
3590                         error = 0;
3591                         goto out;
3592                 }
3593                 MPASS(rv == 1 && count1 == 0);
3594                 rv = thread_check_susp(td, true);
3595                 if (rv == 0)
3596                         goto again;
3597                 error = rv;
3598                 goto out;
3599         }
3600         umtxq_lock(&uq->uq_key);
3601         umtxq_unbusy(&uq->uq_key);
3602
3603         error = umtxq_sleep(uq, "usem", timeout == NULL ? NULL : &timo);
3604
3605         if ((uq->uq_flags & UQF_UMTXQ) == 0)
3606                 error = 0;
3607         else {
3608                 umtxq_remove(uq);
3609                 /* A relative timeout cannot be restarted. */
3610                 if (error == ERESTART && timeout != NULL &&
3611                     (timeout->_flags & UMTX_ABSTIME) == 0)
3612                         error = EINTR;
3613         }
3614         umtxq_unlock(&uq->uq_key);
3615 out:
3616         umtx_key_release(&uq->uq_key);
3617         return (error);
3618 }
3619
3620 /*
3621  * Signal a userland semaphore.
3622  */
3623 static int
3624 do_sem_wake(struct thread *td, struct _usem *sem)
3625 {
3626         struct umtx_key key;
3627         int error, cnt;
3628         uint32_t flags;
3629
3630         error = fueword32(&sem->_flags, &flags);
3631         if (error == -1)
3632                 return (EFAULT);
3633         if ((error = umtx_key_get(sem, TYPE_SEM, GET_SHARE(flags), &key)) != 0)
3634                 return (error);
3635         umtxq_lock(&key);
3636         umtxq_busy(&key);
3637         cnt = umtxq_count(&key);
3638         if (cnt > 0) {
3639                 /*
3640                  * Check if count is greater than 0, this means the memory is
3641                  * still being referenced by user code, so we can safely
3642                  * update _has_waiters flag.
3643                  */
3644                 if (cnt == 1) {
3645                         umtxq_unlock(&key);
3646                         error = suword32(&sem->_has_waiters, 0);
3647                         umtxq_lock(&key);
3648                         if (error == -1)
3649                                 error = EFAULT;
3650                 }
3651                 umtxq_signal(&key, 1);
3652         }
3653         umtxq_unbusy(&key);
3654         umtxq_unlock(&key);
3655         umtx_key_release(&key);
3656         return (error);
3657 }
3658 #endif
3659
3660 static int
3661 do_sem2_wait(struct thread *td, struct _usem2 *sem, struct _umtx_time *timeout)
3662 {
3663         struct umtx_abs_timeout timo;
3664         struct umtx_q *uq;
3665         uint32_t count, flags;
3666         int error, rv;
3667
3668         uq = td->td_umtxq;
3669         flags = fuword32(&sem->_flags);
3670         if (timeout != NULL)
3671                 umtx_abs_timeout_init2(&timo, timeout);
3672
3673 again:
3674         error = umtx_key_get(sem, TYPE_SEM, GET_SHARE(flags), &uq->uq_key);
3675         if (error != 0)
3676                 return (error);
3677         umtxq_lock(&uq->uq_key);
3678         umtxq_busy(&uq->uq_key);
3679         umtxq_insert(uq);
3680         umtxq_unlock(&uq->uq_key);
3681         rv = fueword32(&sem->_count, &count);
3682         if (rv == -1) {
3683                 umtxq_lock(&uq->uq_key);
3684                 umtxq_unbusy(&uq->uq_key);
3685                 umtxq_remove(uq);
3686                 umtxq_unlock(&uq->uq_key);
3687                 umtx_key_release(&uq->uq_key);
3688                 return (EFAULT);
3689         }
3690         for (;;) {
3691                 if (USEM_COUNT(count) != 0) {
3692                         umtxq_lock(&uq->uq_key);
3693                         umtxq_unbusy(&uq->uq_key);
3694                         umtxq_remove(uq);
3695                         umtxq_unlock(&uq->uq_key);
3696                         umtx_key_release(&uq->uq_key);
3697                         return (0);
3698                 }
3699                 if (count == USEM_HAS_WAITERS)
3700                         break;
3701                 rv = casueword32(&sem->_count, 0, &count, USEM_HAS_WAITERS);
3702                 if (rv == 0)
3703                         break;
3704                 umtxq_lock(&uq->uq_key);
3705                 umtxq_unbusy(&uq->uq_key);
3706                 umtxq_remove(uq);
3707                 umtxq_unlock(&uq->uq_key);
3708                 umtx_key_release(&uq->uq_key);
3709                 if (rv == -1)
3710                         return (EFAULT);
3711                 rv = thread_check_susp(td, true);
3712                 if (rv != 0)
3713                         return (rv);
3714                 goto again;
3715         }
3716         umtxq_lock(&uq->uq_key);
3717         umtxq_unbusy(&uq->uq_key);
3718
3719         error = umtxq_sleep(uq, "usem", timeout == NULL ? NULL : &timo);
3720
3721         if ((uq->uq_flags & UQF_UMTXQ) == 0)
3722                 error = 0;
3723         else {
3724                 umtxq_remove(uq);
3725                 if (timeout != NULL && (timeout->_flags & UMTX_ABSTIME) == 0) {
3726                         /* A relative timeout cannot be restarted. */
3727                         if (error == ERESTART)
3728                                 error = EINTR;
3729                         if (error == EINTR) {
3730                                 kern_clock_gettime(curthread, timo.clockid,
3731                                     &timo.cur);
3732                                 timespecsub(&timo.end, &timo.cur,
3733                                     &timeout->_timeout);
3734                         }
3735                 }
3736         }
3737         umtxq_unlock(&uq->uq_key);
3738         umtx_key_release(&uq->uq_key);
3739         return (error);
3740 }
3741
3742 /*
3743  * Signal a userland semaphore.
3744  */
3745 static int
3746 do_sem2_wake(struct thread *td, struct _usem2 *sem)
3747 {
3748         struct umtx_key key;
3749         int error, cnt, rv;
3750         uint32_t count, flags;
3751
3752         rv = fueword32(&sem->_flags, &flags);
3753         if (rv == -1)
3754                 return (EFAULT);
3755         if ((error = umtx_key_get(sem, TYPE_SEM, GET_SHARE(flags), &key)) != 0)
3756                 return (error);
3757         umtxq_lock(&key);
3758         umtxq_busy(&key);
3759         cnt = umtxq_count(&key);
3760         if (cnt > 0) {
3761                 /*
3762                  * If this was the last sleeping thread, clear the waiters
3763                  * flag in _count.
3764                  */
3765                 if (cnt == 1) {
3766                         umtxq_unlock(&key);
3767                         rv = fueword32(&sem->_count, &count);
3768                         while (rv != -1 && count & USEM_HAS_WAITERS) {
3769                                 rv = casueword32(&sem->_count, count, &count,
3770                                     count & ~USEM_HAS_WAITERS);
3771                                 if (rv == 1) {
3772                                         rv = thread_check_susp(td, true);
3773                                         if (rv != 0)
3774                                                 break;
3775                                 }
3776                         }
3777                         if (rv == -1)
3778                                 error = EFAULT;
3779                         else if (rv > 0) {
3780                                 error = rv;
3781                         }
3782                         umtxq_lock(&key);
3783                 }
3784
3785                 umtxq_signal(&key, 1);
3786         }
3787         umtxq_unbusy(&key);
3788         umtxq_unlock(&key);
3789         umtx_key_release(&key);
3790         return (error);
3791 }
3792
3793 #ifdef COMPAT_FREEBSD10
3794 int
3795 freebsd10__umtx_lock(struct thread *td, struct freebsd10__umtx_lock_args *uap)
3796 {
3797         return (do_lock_umtx(td, uap->umtx, td->td_tid, 0));
3798 }
3799
3800 int
3801 freebsd10__umtx_unlock(struct thread *td,
3802     struct freebsd10__umtx_unlock_args *uap)
3803 {
3804         return (do_unlock_umtx(td, uap->umtx, td->td_tid));
3805 }
3806 #endif
3807
3808 inline int
3809 umtx_copyin_timeout(const void *uaddr, struct timespec *tsp)
3810 {
3811         int error;
3812
3813         error = copyin(uaddr, tsp, sizeof(*tsp));
3814         if (error == 0) {
3815                 if (!timespecvalid_interval(tsp))
3816                         error = EINVAL;
3817         }
3818         return (error);
3819 }
3820
3821 static inline int
3822 umtx_copyin_umtx_time(const void *uaddr, size_t size, struct _umtx_time *tp)
3823 {
3824         int error;
3825
3826         if (size <= sizeof(tp->_timeout)) {
3827                 tp->_clockid = CLOCK_REALTIME;
3828                 tp->_flags = 0;
3829                 error = copyin(uaddr, &tp->_timeout, sizeof(tp->_timeout));
3830         } else
3831                 error = copyin(uaddr, tp, sizeof(*tp));
3832         if (error != 0)
3833                 return (error);
3834         if (!timespecvalid_interval(&tp->_timeout))
3835                 return (EINVAL);
3836         return (0);
3837 }
3838
3839 static int
3840 umtx_copyin_robust_lists(const void *uaddr, size_t size,
3841     struct umtx_robust_lists_params *rb)
3842 {
3843
3844         if (size > sizeof(*rb))
3845                 return (EINVAL);
3846         return (copyin(uaddr, rb, size));
3847 }
3848
3849 static int
3850 umtx_copyout_timeout(void *uaddr, size_t sz, struct timespec *tsp)
3851 {
3852
3853         /*
3854          * Should be guaranteed by the caller, sz == uaddr1 - sizeof(_umtx_time)
3855          * and we're only called if sz >= sizeof(timespec) as supplied in the
3856          * copyops.
3857          */
3858         KASSERT(sz >= sizeof(*tsp),
3859             ("umtx_copyops specifies incorrect sizes"));
3860
3861         return (copyout(tsp, uaddr, sizeof(*tsp)));
3862 }
3863
3864 #ifdef COMPAT_FREEBSD10
3865 static int
3866 __umtx_op_lock_umtx(struct thread *td, struct _umtx_op_args *uap,
3867     const struct umtx_copyops *ops)
3868 {
3869         struct timespec *ts, timeout;
3870         int error;
3871
3872         /* Allow a null timespec (wait forever). */
3873         if (uap->uaddr2 == NULL)
3874                 ts = NULL;
3875         else {
3876                 error = ops->copyin_timeout(uap->uaddr2, &timeout);
3877                 if (error != 0)
3878                         return (error);
3879                 ts = &timeout;
3880         }
3881 #ifdef COMPAT_FREEBSD32
3882         if (ops->compat32)
3883                 return (do_lock_umtx32(td, uap->obj, uap->val, ts));
3884 #endif
3885         return (do_lock_umtx(td, uap->obj, uap->val, ts));
3886 }
3887
3888 static int
3889 __umtx_op_unlock_umtx(struct thread *td, struct _umtx_op_args *uap,
3890     const struct umtx_copyops *ops)
3891 {
3892 #ifdef COMPAT_FREEBSD32
3893         if (ops->compat32)
3894                 return (do_unlock_umtx32(td, uap->obj, uap->val));
3895 #endif
3896         return (do_unlock_umtx(td, uap->obj, uap->val));
3897 }
3898 #endif  /* COMPAT_FREEBSD10 */
3899
3900 #if !defined(COMPAT_FREEBSD10)
3901 static int
3902 __umtx_op_unimpl(struct thread *td __unused, struct _umtx_op_args *uap __unused,
3903     const struct umtx_copyops *ops __unused)
3904 {
3905         return (EOPNOTSUPP);
3906 }
3907 #endif  /* COMPAT_FREEBSD10 */
3908
3909 static int
3910 __umtx_op_wait(struct thread *td, struct _umtx_op_args *uap,
3911     const struct umtx_copyops *ops)
3912 {
3913         struct _umtx_time timeout, *tm_p;
3914         int error;
3915
3916         if (uap->uaddr2 == NULL)
3917                 tm_p = NULL;
3918         else {
3919                 error = ops->copyin_umtx_time(
3920                     uap->uaddr2, (size_t)uap->uaddr1, &timeout);
3921                 if (error != 0)
3922                         return (error);
3923                 tm_p = &timeout;
3924         }
3925         return (do_wait(td, uap->obj, uap->val, tm_p, ops->compat32, 0));
3926 }
3927
3928 static int
3929 __umtx_op_wait_uint(struct thread *td, struct _umtx_op_args *uap,
3930     const struct umtx_copyops *ops)
3931 {
3932         struct _umtx_time timeout, *tm_p;
3933         int error;
3934
3935         if (uap->uaddr2 == NULL)
3936                 tm_p = NULL;
3937         else {
3938                 error = ops->copyin_umtx_time(
3939                     uap->uaddr2, (size_t)uap->uaddr1, &timeout);
3940                 if (error != 0)
3941                         return (error);
3942                 tm_p = &timeout;
3943         }
3944         return (do_wait(td, uap->obj, uap->val, tm_p, 1, 0));
3945 }
3946
3947 static int
3948 __umtx_op_wait_uint_private(struct thread *td, struct _umtx_op_args *uap,
3949     const struct umtx_copyops *ops)
3950 {
3951         struct _umtx_time *tm_p, timeout;
3952         int error;
3953
3954         if (uap->uaddr2 == NULL)
3955                 tm_p = NULL;
3956         else {
3957                 error = ops->copyin_umtx_time(
3958                     uap->uaddr2, (size_t)uap->uaddr1, &timeout);
3959                 if (error != 0)
3960                         return (error);
3961                 tm_p = &timeout;
3962         }
3963         return (do_wait(td, uap->obj, uap->val, tm_p, 1, 1));
3964 }
3965
3966 static int
3967 __umtx_op_wake(struct thread *td, struct _umtx_op_args *uap,
3968     const struct umtx_copyops *ops __unused)
3969 {
3970
3971         return (kern_umtx_wake(td, uap->obj, uap->val, 0));
3972 }
3973
3974 #define BATCH_SIZE      128
3975 static int
3976 __umtx_op_nwake_private_native(struct thread *td, struct _umtx_op_args *uap)
3977 {
3978         char *uaddrs[BATCH_SIZE], **upp;
3979         int count, error, i, pos, tocopy;
3980
3981         upp = (char **)uap->obj;
3982         error = 0;
3983         for (count = uap->val, pos = 0; count > 0; count -= tocopy,
3984             pos += tocopy) {
3985                 tocopy = MIN(count, BATCH_SIZE);
3986                 error = copyin(upp + pos, uaddrs, tocopy * sizeof(char *));
3987                 if (error != 0)
3988                         break;
3989                 for (i = 0; i < tocopy; ++i) {
3990                         kern_umtx_wake(td, uaddrs[i], INT_MAX, 1);
3991                 }
3992                 maybe_yield();
3993         }
3994         return (error);
3995 }
3996
3997 static int
3998 __umtx_op_nwake_private_compat32(struct thread *td, struct _umtx_op_args *uap)
3999 {
4000         uint32_t uaddrs[BATCH_SIZE], *upp;
4001         int count, error, i, pos, tocopy;
4002
4003         upp = (uint32_t *)uap->obj;
4004         error = 0;
4005         for (count = uap->val, pos = 0; count > 0; count -= tocopy,
4006             pos += tocopy) {
4007                 tocopy = MIN(count, BATCH_SIZE);
4008                 error = copyin(upp + pos, uaddrs, tocopy * sizeof(uint32_t));
4009                 if (error != 0)
4010                         break;
4011                 for (i = 0; i < tocopy; ++i) {
4012                         kern_umtx_wake(td, (void *)(uintptr_t)uaddrs[i],
4013                             INT_MAX, 1);
4014                 }
4015                 maybe_yield();
4016         }
4017         return (error);
4018 }
4019
4020 static int
4021 __umtx_op_nwake_private(struct thread *td, struct _umtx_op_args *uap,
4022     const struct umtx_copyops *ops)
4023 {
4024
4025         if (ops->compat32)
4026                 return (__umtx_op_nwake_private_compat32(td, uap));
4027         return (__umtx_op_nwake_private_native(td, uap));
4028 }
4029
4030 static int
4031 __umtx_op_wake_private(struct thread *td, struct _umtx_op_args *uap,
4032     const struct umtx_copyops *ops __unused)
4033 {
4034
4035         return (kern_umtx_wake(td, uap->obj, uap->val, 1));
4036 }
4037
4038 static int
4039 __umtx_op_lock_umutex(struct thread *td, struct _umtx_op_args *uap,
4040    const struct umtx_copyops *ops)
4041 {
4042         struct _umtx_time *tm_p, timeout;
4043         int error;
4044
4045         /* Allow a null timespec (wait forever). */
4046         if (uap->uaddr2 == NULL)
4047                 tm_p = NULL;
4048         else {
4049                 error = ops->copyin_umtx_time(
4050                     uap->uaddr2, (size_t)uap->uaddr1, &timeout);
4051                 if (error != 0)
4052                         return (error);
4053                 tm_p = &timeout;
4054         }
4055         return (do_lock_umutex(td, uap->obj, tm_p, 0));
4056 }
4057
4058 static int
4059 __umtx_op_trylock_umutex(struct thread *td, struct _umtx_op_args *uap,
4060     const struct umtx_copyops *ops __unused)
4061 {
4062
4063         return (do_lock_umutex(td, uap->obj, NULL, _UMUTEX_TRY));
4064 }
4065
4066 static int
4067 __umtx_op_wait_umutex(struct thread *td, struct _umtx_op_args *uap,
4068     const struct umtx_copyops *ops)
4069 {
4070         struct _umtx_time *tm_p, timeout;
4071         int error;
4072
4073         /* Allow a null timespec (wait forever). */
4074         if (uap->uaddr2 == NULL)
4075                 tm_p = NULL;
4076         else {
4077                 error = ops->copyin_umtx_time(
4078                     uap->uaddr2, (size_t)uap->uaddr1, &timeout);
4079                 if (error != 0)
4080                         return (error);
4081                 tm_p = &timeout;
4082         }
4083         return (do_lock_umutex(td, uap->obj, tm_p, _UMUTEX_WAIT));
4084 }
4085
4086 static int
4087 __umtx_op_wake_umutex(struct thread *td, struct _umtx_op_args *uap,
4088     const struct umtx_copyops *ops __unused)
4089 {
4090
4091         return (do_wake_umutex(td, uap->obj));
4092 }
4093
4094 static int
4095 __umtx_op_unlock_umutex(struct thread *td, struct _umtx_op_args *uap,
4096     const struct umtx_copyops *ops __unused)
4097 {
4098
4099         return (do_unlock_umutex(td, uap->obj, false));
4100 }
4101
4102 static int
4103 __umtx_op_set_ceiling(struct thread *td, struct _umtx_op_args *uap,
4104     const struct umtx_copyops *ops __unused)
4105 {
4106
4107         return (do_set_ceiling(td, uap->obj, uap->val, uap->uaddr1));
4108 }
4109
4110 static int
4111 __umtx_op_cv_wait(struct thread *td, struct _umtx_op_args *uap,
4112     const struct umtx_copyops *ops)
4113 {
4114         struct timespec *ts, timeout;
4115         int error;
4116
4117         /* Allow a null timespec (wait forever). */
4118         if (uap->uaddr2 == NULL)
4119                 ts = NULL;
4120         else {
4121                 error = ops->copyin_timeout(uap->uaddr2, &timeout);
4122                 if (error != 0)
4123                         return (error);
4124                 ts = &timeout;
4125         }
4126         return (do_cv_wait(td, uap->obj, uap->uaddr1, ts, uap->val));
4127 }
4128
4129 static int
4130 __umtx_op_cv_signal(struct thread *td, struct _umtx_op_args *uap,
4131     const struct umtx_copyops *ops __unused)
4132 {
4133
4134         return (do_cv_signal(td, uap->obj));
4135 }
4136
4137 static int
4138 __umtx_op_cv_broadcast(struct thread *td, struct _umtx_op_args *uap,
4139     const struct umtx_copyops *ops __unused)
4140 {
4141
4142         return (do_cv_broadcast(td, uap->obj));
4143 }
4144
4145 static int
4146 __umtx_op_rw_rdlock(struct thread *td, struct _umtx_op_args *uap,
4147     const struct umtx_copyops *ops)
4148 {
4149         struct _umtx_time timeout;
4150         int error;
4151
4152         /* Allow a null timespec (wait forever). */
4153         if (uap->uaddr2 == NULL) {
4154                 error = do_rw_rdlock(td, uap->obj, uap->val, 0);
4155         } else {
4156                 error = ops->copyin_umtx_time(uap->uaddr2,
4157                    (size_t)uap->uaddr1, &timeout);
4158                 if (error != 0)
4159                         return (error);
4160                 error = do_rw_rdlock(td, uap->obj, uap->val, &timeout);
4161         }
4162         return (error);
4163 }
4164
4165 static int
4166 __umtx_op_rw_wrlock(struct thread *td, struct _umtx_op_args *uap,
4167     const struct umtx_copyops *ops)
4168 {
4169         struct _umtx_time timeout;
4170         int error;
4171
4172         /* Allow a null timespec (wait forever). */
4173         if (uap->uaddr2 == NULL) {
4174                 error = do_rw_wrlock(td, uap->obj, 0);
4175         } else {
4176                 error = ops->copyin_umtx_time(uap->uaddr2,
4177                    (size_t)uap->uaddr1, &timeout);
4178                 if (error != 0)
4179                         return (error);
4180
4181                 error = do_rw_wrlock(td, uap->obj, &timeout);
4182         }
4183         return (error);
4184 }
4185
4186 static int
4187 __umtx_op_rw_unlock(struct thread *td, struct _umtx_op_args *uap,
4188     const struct umtx_copyops *ops __unused)
4189 {
4190
4191         return (do_rw_unlock(td, uap->obj));
4192 }
4193
4194 #if defined(COMPAT_FREEBSD9) || defined(COMPAT_FREEBSD10)
4195 static int
4196 __umtx_op_sem_wait(struct thread *td, struct _umtx_op_args *uap,
4197     const struct umtx_copyops *ops)
4198 {
4199         struct _umtx_time *tm_p, timeout;
4200         int error;
4201
4202         /* Allow a null timespec (wait forever). */
4203         if (uap->uaddr2 == NULL)
4204                 tm_p = NULL;
4205         else {
4206                 error = ops->copyin_umtx_time(
4207                     uap->uaddr2, (size_t)uap->uaddr1, &timeout);
4208                 if (error != 0)
4209                         return (error);
4210                 tm_p = &timeout;
4211         }
4212         return (do_sem_wait(td, uap->obj, tm_p));
4213 }
4214
4215 static int
4216 __umtx_op_sem_wake(struct thread *td, struct _umtx_op_args *uap,
4217     const struct umtx_copyops *ops __unused)
4218 {
4219
4220         return (do_sem_wake(td, uap->obj));
4221 }
4222 #endif
4223
4224 static int
4225 __umtx_op_wake2_umutex(struct thread *td, struct _umtx_op_args *uap,
4226     const struct umtx_copyops *ops __unused)
4227 {
4228
4229         return (do_wake2_umutex(td, uap->obj, uap->val));
4230 }
4231
4232 static int
4233 __umtx_op_sem2_wait(struct thread *td, struct _umtx_op_args *uap,
4234     const struct umtx_copyops *ops)
4235 {
4236         struct _umtx_time *tm_p, timeout;
4237         size_t uasize;
4238         int error;
4239
4240         /* Allow a null timespec (wait forever). */
4241         if (uap->uaddr2 == NULL) {
4242                 uasize = 0;
4243                 tm_p = NULL;
4244         } else {
4245                 uasize = (size_t)uap->uaddr1;
4246                 error = ops->copyin_umtx_time(uap->uaddr2, uasize, &timeout);
4247                 if (error != 0)
4248                         return (error);
4249                 tm_p = &timeout;
4250         }
4251         error = do_sem2_wait(td, uap->obj, tm_p);
4252         if (error == EINTR && uap->uaddr2 != NULL &&
4253             (timeout._flags & UMTX_ABSTIME) == 0 &&
4254             uasize >= ops->umtx_time_sz + ops->timespec_sz) {
4255                 error = ops->copyout_timeout(
4256                     (void *)((uintptr_t)uap->uaddr2 + ops->umtx_time_sz),
4257                     uasize - ops->umtx_time_sz, &timeout._timeout);
4258                 if (error == 0) {
4259                         error = EINTR;
4260                 }
4261         }
4262
4263         return (error);
4264 }
4265
4266 static int
4267 __umtx_op_sem2_wake(struct thread *td, struct _umtx_op_args *uap,
4268     const struct umtx_copyops *ops __unused)
4269 {
4270
4271         return (do_sem2_wake(td, uap->obj));
4272 }
4273
4274 #define USHM_OBJ_UMTX(o)                                                \
4275     ((struct umtx_shm_obj_list *)(&(o)->umtx_data))
4276
4277 #define USHMF_REG_LINKED        0x0001
4278 #define USHMF_OBJ_LINKED        0x0002
4279 struct umtx_shm_reg {
4280         TAILQ_ENTRY(umtx_shm_reg) ushm_reg_link;
4281         LIST_ENTRY(umtx_shm_reg) ushm_obj_link;
4282         struct umtx_key         ushm_key;
4283         struct ucred            *ushm_cred;
4284         struct shmfd            *ushm_obj;
4285         u_int                   ushm_refcnt;
4286         u_int                   ushm_flags;
4287 };
4288
4289 LIST_HEAD(umtx_shm_obj_list, umtx_shm_reg);
4290 TAILQ_HEAD(umtx_shm_reg_head, umtx_shm_reg);
4291
4292 static uma_zone_t umtx_shm_reg_zone;
4293 static struct umtx_shm_reg_head umtx_shm_registry[UMTX_CHAINS];
4294 static struct mtx umtx_shm_lock;
4295 static struct umtx_shm_reg_head umtx_shm_reg_delfree =
4296     TAILQ_HEAD_INITIALIZER(umtx_shm_reg_delfree);
4297
4298 static void umtx_shm_free_reg(struct umtx_shm_reg *reg);
4299
4300 static void
4301 umtx_shm_reg_delfree_tq(void *context __unused, int pending __unused)
4302 {
4303         struct umtx_shm_reg_head d;
4304         struct umtx_shm_reg *reg, *reg1;
4305
4306         TAILQ_INIT(&d);
4307         mtx_lock(&umtx_shm_lock);
4308         TAILQ_CONCAT(&d, &umtx_shm_reg_delfree, ushm_reg_link);
4309         mtx_unlock(&umtx_shm_lock);
4310         TAILQ_FOREACH_SAFE(reg, &d, ushm_reg_link, reg1) {
4311                 TAILQ_REMOVE(&d, reg, ushm_reg_link);
4312                 umtx_shm_free_reg(reg);
4313         }
4314 }
4315
4316 static struct task umtx_shm_reg_delfree_task =
4317     TASK_INITIALIZER(0, umtx_shm_reg_delfree_tq, NULL);
4318
4319 static struct umtx_shm_reg *
4320 umtx_shm_find_reg_locked(const struct umtx_key *key)
4321 {
4322         struct umtx_shm_reg *reg;
4323         struct umtx_shm_reg_head *reg_head;
4324
4325         KASSERT(key->shared, ("umtx_p_find_rg: private key"));
4326         mtx_assert(&umtx_shm_lock, MA_OWNED);
4327         reg_head = &umtx_shm_registry[key->hash];
4328         TAILQ_FOREACH(reg, reg_head, ushm_reg_link) {
4329                 KASSERT(reg->ushm_key.shared,
4330                     ("non-shared key on reg %p %d", reg, reg->ushm_key.shared));
4331                 if (reg->ushm_key.info.shared.object ==
4332                     key->info.shared.object &&
4333                     reg->ushm_key.info.shared.offset ==
4334                     key->info.shared.offset) {
4335                         KASSERT(reg->ushm_key.type == TYPE_SHM, ("TYPE_USHM"));
4336                         KASSERT(reg->ushm_refcnt > 0,
4337                             ("reg %p refcnt 0 onlist", reg));
4338                         KASSERT((reg->ushm_flags & USHMF_REG_LINKED) != 0,
4339                             ("reg %p not linked", reg));
4340                         reg->ushm_refcnt++;
4341                         return (reg);
4342                 }
4343         }
4344         return (NULL);
4345 }
4346
4347 static struct umtx_shm_reg *
4348 umtx_shm_find_reg(const struct umtx_key *key)
4349 {
4350         struct umtx_shm_reg *reg;
4351
4352         mtx_lock(&umtx_shm_lock);
4353         reg = umtx_shm_find_reg_locked(key);
4354         mtx_unlock(&umtx_shm_lock);
4355         return (reg);
4356 }
4357
4358 static void
4359 umtx_shm_free_reg(struct umtx_shm_reg *reg)
4360 {
4361
4362         chgumtxcnt(reg->ushm_cred->cr_ruidinfo, -1, 0);
4363         crfree(reg->ushm_cred);
4364         shm_drop(reg->ushm_obj);
4365         uma_zfree(umtx_shm_reg_zone, reg);
4366 }
4367
4368 static bool
4369 umtx_shm_unref_reg_locked(struct umtx_shm_reg *reg, bool force)
4370 {
4371         bool res;
4372
4373         mtx_assert(&umtx_shm_lock, MA_OWNED);
4374         KASSERT(reg->ushm_refcnt > 0, ("ushm_reg %p refcnt 0", reg));
4375         reg->ushm_refcnt--;
4376         res = reg->ushm_refcnt == 0;
4377         if (res || force) {
4378                 if ((reg->ushm_flags & USHMF_REG_LINKED) != 0) {
4379                         TAILQ_REMOVE(&umtx_shm_registry[reg->ushm_key.hash],
4380                             reg, ushm_reg_link);
4381                         reg->ushm_flags &= ~USHMF_REG_LINKED;
4382                 }
4383                 if ((reg->ushm_flags & USHMF_OBJ_LINKED) != 0) {
4384                         LIST_REMOVE(reg, ushm_obj_link);
4385                         reg->ushm_flags &= ~USHMF_OBJ_LINKED;
4386                 }
4387         }
4388         return (res);
4389 }
4390
4391 static void
4392 umtx_shm_unref_reg(struct umtx_shm_reg *reg, bool force)
4393 {
4394         vm_object_t object;
4395         bool dofree;
4396
4397         if (force) {
4398                 object = reg->ushm_obj->shm_object;
4399                 VM_OBJECT_WLOCK(object);
4400                 vm_object_set_flag(object, OBJ_UMTXDEAD);
4401                 VM_OBJECT_WUNLOCK(object);
4402         }
4403         mtx_lock(&umtx_shm_lock);
4404         dofree = umtx_shm_unref_reg_locked(reg, force);
4405         mtx_unlock(&umtx_shm_lock);
4406         if (dofree)
4407                 umtx_shm_free_reg(reg);
4408 }
4409
4410 void
4411 umtx_shm_object_init(vm_object_t object)
4412 {
4413
4414         LIST_INIT(USHM_OBJ_UMTX(object));
4415 }
4416
4417 void
4418 umtx_shm_object_terminated(vm_object_t object)
4419 {
4420         struct umtx_shm_reg *reg, *reg1;
4421         bool dofree;
4422
4423         if (LIST_EMPTY(USHM_OBJ_UMTX(object)))
4424                 return;
4425
4426         dofree = false;
4427         mtx_lock(&umtx_shm_lock);
4428         LIST_FOREACH_SAFE(reg, USHM_OBJ_UMTX(object), ushm_obj_link, reg1) {
4429                 if (umtx_shm_unref_reg_locked(reg, true)) {
4430                         TAILQ_INSERT_TAIL(&umtx_shm_reg_delfree, reg,
4431                             ushm_reg_link);
4432                         dofree = true;
4433                 }
4434         }
4435         mtx_unlock(&umtx_shm_lock);
4436         if (dofree)
4437                 taskqueue_enqueue(taskqueue_thread, &umtx_shm_reg_delfree_task);
4438 }
4439
4440 static int
4441 umtx_shm_create_reg(struct thread *td, const struct umtx_key *key,
4442     struct umtx_shm_reg **res)
4443 {
4444         struct umtx_shm_reg *reg, *reg1;
4445         struct ucred *cred;
4446         int error;
4447
4448         reg = umtx_shm_find_reg(key);
4449         if (reg != NULL) {
4450                 *res = reg;
4451                 return (0);
4452         }
4453         cred = td->td_ucred;
4454         if (!chgumtxcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_UMTXP)))
4455                 return (ENOMEM);
4456         reg = uma_zalloc(umtx_shm_reg_zone, M_WAITOK | M_ZERO);
4457         reg->ushm_refcnt = 1;
4458         bcopy(key, &reg->ushm_key, sizeof(*key));
4459         reg->ushm_obj = shm_alloc(td->td_ucred, O_RDWR, false);
4460         reg->ushm_cred = crhold(cred);
4461         error = shm_dotruncate(reg->ushm_obj, PAGE_SIZE);
4462         if (error != 0) {
4463                 umtx_shm_free_reg(reg);
4464                 return (error);
4465         }
4466         mtx_lock(&umtx_shm_lock);
4467         reg1 = umtx_shm_find_reg_locked(key);
4468         if (reg1 != NULL) {
4469                 mtx_unlock(&umtx_shm_lock);
4470                 umtx_shm_free_reg(reg);
4471                 *res = reg1;
4472                 return (0);
4473         }
4474         reg->ushm_refcnt++;
4475         TAILQ_INSERT_TAIL(&umtx_shm_registry[key->hash], reg, ushm_reg_link);
4476         LIST_INSERT_HEAD(USHM_OBJ_UMTX(key->info.shared.object), reg,
4477             ushm_obj_link);
4478         reg->ushm_flags = USHMF_REG_LINKED | USHMF_OBJ_LINKED;
4479         mtx_unlock(&umtx_shm_lock);
4480         *res = reg;
4481         return (0);
4482 }
4483
4484 static int
4485 umtx_shm_alive(struct thread *td, void *addr)
4486 {
4487         vm_map_t map;
4488         vm_map_entry_t entry;
4489         vm_object_t object;
4490         vm_pindex_t pindex;
4491         vm_prot_t prot;
4492         int res, ret;
4493         boolean_t wired;
4494
4495         map = &td->td_proc->p_vmspace->vm_map;
4496         res = vm_map_lookup(&map, (uintptr_t)addr, VM_PROT_READ, &entry,
4497             &object, &pindex, &prot, &wired);
4498         if (res != KERN_SUCCESS)
4499                 return (EFAULT);
4500         if (object == NULL)
4501                 ret = EINVAL;
4502         else
4503                 ret = (object->flags & OBJ_UMTXDEAD) != 0 ? ENOTTY : 0;
4504         vm_map_lookup_done(map, entry);
4505         return (ret);
4506 }
4507
4508 static void
4509 umtx_shm_init(void)
4510 {
4511         int i;
4512
4513         umtx_shm_reg_zone = uma_zcreate("umtx_shm", sizeof(struct umtx_shm_reg),
4514             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
4515         mtx_init(&umtx_shm_lock, "umtxshm", NULL, MTX_DEF);
4516         for (i = 0; i < nitems(umtx_shm_registry); i++)
4517                 TAILQ_INIT(&umtx_shm_registry[i]);
4518 }
4519
4520 static int
4521 umtx_shm(struct thread *td, void *addr, u_int flags)
4522 {
4523         struct umtx_key key;
4524         struct umtx_shm_reg *reg;
4525         struct file *fp;
4526         int error, fd;
4527
4528         if (__bitcount(flags & (UMTX_SHM_CREAT | UMTX_SHM_LOOKUP |
4529             UMTX_SHM_DESTROY| UMTX_SHM_ALIVE)) != 1)
4530                 return (EINVAL);
4531         if ((flags & UMTX_SHM_ALIVE) != 0)
4532                 return (umtx_shm_alive(td, addr));
4533         error = umtx_key_get(addr, TYPE_SHM, PROCESS_SHARE, &key);
4534         if (error != 0)
4535                 return (error);
4536         KASSERT(key.shared == 1, ("non-shared key"));
4537         if ((flags & UMTX_SHM_CREAT) != 0) {
4538                 error = umtx_shm_create_reg(td, &key, &reg);
4539         } else {
4540                 reg = umtx_shm_find_reg(&key);
4541                 if (reg == NULL)
4542                         error = ESRCH;
4543         }
4544         umtx_key_release(&key);
4545         if (error != 0)
4546                 return (error);
4547         KASSERT(reg != NULL, ("no reg"));
4548         if ((flags & UMTX_SHM_DESTROY) != 0) {
4549                 umtx_shm_unref_reg(reg, true);
4550         } else {
4551 #if 0
4552 #ifdef MAC
4553                 error = mac_posixshm_check_open(td->td_ucred,
4554                     reg->ushm_obj, FFLAGS(O_RDWR));
4555                 if (error == 0)
4556 #endif
4557                         error = shm_access(reg->ushm_obj, td->td_ucred,
4558                             FFLAGS(O_RDWR));
4559                 if (error == 0)
4560 #endif
4561                         error = falloc_caps(td, &fp, &fd, O_CLOEXEC, NULL);
4562                 if (error == 0) {
4563                         shm_hold(reg->ushm_obj);
4564                         finit(fp, FFLAGS(O_RDWR), DTYPE_SHM, reg->ushm_obj,
4565                             &shm_ops);
4566                         td->td_retval[0] = fd;
4567                         fdrop(fp, td);
4568                 }
4569         }
4570         umtx_shm_unref_reg(reg, false);
4571         return (error);
4572 }
4573
4574 static int
4575 __umtx_op_shm(struct thread *td, struct _umtx_op_args *uap,
4576     const struct umtx_copyops *ops __unused)
4577 {
4578
4579         return (umtx_shm(td, uap->uaddr1, uap->val));
4580 }
4581
4582 static int
4583 __umtx_op_robust_lists(struct thread *td, struct _umtx_op_args *uap,
4584     const struct umtx_copyops *ops)
4585 {
4586         struct umtx_robust_lists_params rb;
4587         int error;
4588
4589         if (ops->compat32) {
4590                 if ((td->td_pflags2 & TDP2_COMPAT32RB) == 0 &&
4591                     (td->td_rb_list != 0 || td->td_rbp_list != 0 ||
4592                     td->td_rb_inact != 0))
4593                         return (EBUSY);
4594         } else if ((td->td_pflags2 & TDP2_COMPAT32RB) != 0) {
4595                 return (EBUSY);
4596         }
4597
4598         bzero(&rb, sizeof(rb));
4599         error = ops->copyin_robust_lists(uap->uaddr1, uap->val, &rb);
4600         if (error != 0)
4601                 return (error);
4602
4603         if (ops->compat32)
4604                 td->td_pflags2 |= TDP2_COMPAT32RB;
4605
4606         td->td_rb_list = rb.robust_list_offset;
4607         td->td_rbp_list = rb.robust_priv_list_offset;
4608         td->td_rb_inact = rb.robust_inact_offset;
4609         return (0);
4610 }
4611
4612 static int
4613 __umtx_op_get_min_timeout(struct thread *td, struct _umtx_op_args *uap,
4614     const struct umtx_copyops *ops)
4615 {
4616         long val;
4617         int error, val1;
4618
4619         val = sbttons(td->td_proc->p_umtx_min_timeout);
4620         if (ops->compat32) {
4621                 val1 = (int)val;
4622                 error = copyout(&val1, uap->uaddr1, sizeof(val1));
4623         } else {
4624                 error = copyout(&val, uap->uaddr1, sizeof(val));
4625         }
4626         return (error);
4627 }
4628
4629 static int
4630 __umtx_op_set_min_timeout(struct thread *td, struct _umtx_op_args *uap,
4631     const struct umtx_copyops *ops)
4632 {
4633         if (uap->val < 0)
4634                 return (EINVAL);
4635         td->td_proc->p_umtx_min_timeout = nstosbt(uap->val);
4636         return (0);
4637 }
4638
4639 #if defined(__i386__) || defined(__amd64__)
4640 /*
4641  * Provide the standard 32-bit definitions for x86, since native/compat32 use a
4642  * 32-bit time_t there.  Other architectures just need the i386 definitions
4643  * along with their standard compat32.
4644  */
4645 struct timespecx32 {
4646         int64_t                 tv_sec;
4647         int32_t                 tv_nsec;
4648 };
4649
4650 struct umtx_timex32 {
4651         struct  timespecx32     _timeout;
4652         uint32_t                _flags;
4653         uint32_t                _clockid;
4654 };
4655
4656 #ifndef __i386__
4657 #define timespeci386    timespec32
4658 #define umtx_timei386   umtx_time32
4659 #endif
4660 #else /* !__i386__ && !__amd64__ */
4661 /* 32-bit architectures can emulate i386, so define these almost everywhere. */
4662 struct timespeci386 {
4663         int32_t                 tv_sec;
4664         int32_t                 tv_nsec;
4665 };
4666
4667 struct umtx_timei386 {
4668         struct  timespeci386    _timeout;
4669         uint32_t                _flags;
4670         uint32_t                _clockid;
4671 };
4672
4673 #if defined(__LP64__)
4674 #define timespecx32     timespec32
4675 #define umtx_timex32    umtx_time32
4676 #endif
4677 #endif
4678
4679 static int
4680 umtx_copyin_robust_lists32(const void *uaddr, size_t size,
4681     struct umtx_robust_lists_params *rbp)
4682 {
4683         struct umtx_robust_lists_params_compat32 rb32;
4684         int error;
4685
4686         if (size > sizeof(rb32))
4687                 return (EINVAL);
4688         bzero(&rb32, sizeof(rb32));
4689         error = copyin(uaddr, &rb32, size);
4690         if (error != 0)
4691                 return (error);
4692         CP(rb32, *rbp, robust_list_offset);
4693         CP(rb32, *rbp, robust_priv_list_offset);
4694         CP(rb32, *rbp, robust_inact_offset);
4695         return (0);
4696 }
4697
4698 #ifndef __i386__
4699 static inline int
4700 umtx_copyin_timeouti386(const void *uaddr, struct timespec *tsp)
4701 {
4702         struct timespeci386 ts32;
4703         int error;
4704
4705         error = copyin(uaddr, &ts32, sizeof(ts32));
4706         if (error == 0) {
4707                 if (!timespecvalid_interval(&ts32))
4708                         error = EINVAL;
4709                 else {
4710                         CP(ts32, *tsp, tv_sec);
4711                         CP(ts32, *tsp, tv_nsec);
4712                 }
4713         }
4714         return (error);
4715 }
4716
4717 static inline int
4718 umtx_copyin_umtx_timei386(const void *uaddr, size_t size, struct _umtx_time *tp)
4719 {
4720         struct umtx_timei386 t32;
4721         int error;
4722
4723         t32._clockid = CLOCK_REALTIME;
4724         t32._flags   = 0;
4725         if (size <= sizeof(t32._timeout))
4726                 error = copyin(uaddr, &t32._timeout, sizeof(t32._timeout));
4727         else
4728                 error = copyin(uaddr, &t32, sizeof(t32));
4729         if (error != 0)
4730                 return (error);
4731         if (!timespecvalid_interval(&t32._timeout))
4732                 return (EINVAL);
4733         TS_CP(t32, *tp, _timeout);
4734         CP(t32, *tp, _flags);
4735         CP(t32, *tp, _clockid);
4736         return (0);
4737 }
4738
4739 static int
4740 umtx_copyout_timeouti386(void *uaddr, size_t sz, struct timespec *tsp)
4741 {
4742         struct timespeci386 remain32 = {
4743                 .tv_sec = tsp->tv_sec,
4744                 .tv_nsec = tsp->tv_nsec,
4745         };
4746
4747         /*
4748          * Should be guaranteed by the caller, sz == uaddr1 - sizeof(_umtx_time)
4749          * and we're only called if sz >= sizeof(timespec) as supplied in the
4750          * copyops.
4751          */
4752         KASSERT(sz >= sizeof(remain32),
4753             ("umtx_copyops specifies incorrect sizes"));
4754
4755         return (copyout(&remain32, uaddr, sizeof(remain32)));
4756 }
4757 #endif /* !__i386__ */
4758
4759 #if defined(__i386__) || defined(__LP64__)
4760 static inline int
4761 umtx_copyin_timeoutx32(const void *uaddr, struct timespec *tsp)
4762 {
4763         struct timespecx32 ts32;
4764         int error;
4765
4766         error = copyin(uaddr, &ts32, sizeof(ts32));
4767         if (error == 0) {
4768                 if (!timespecvalid_interval(&ts32))
4769                         error = EINVAL;
4770                 else {
4771                         CP(ts32, *tsp, tv_sec);
4772                         CP(ts32, *tsp, tv_nsec);
4773                 }
4774         }
4775         return (error);
4776 }
4777
4778 static inline int
4779 umtx_copyin_umtx_timex32(const void *uaddr, size_t size, struct _umtx_time *tp)
4780 {
4781         struct umtx_timex32 t32;
4782         int error;
4783
4784         t32._clockid = CLOCK_REALTIME;
4785         t32._flags   = 0;
4786         if (size <= sizeof(t32._timeout))
4787                 error = copyin(uaddr, &t32._timeout, sizeof(t32._timeout));
4788         else
4789                 error = copyin(uaddr, &t32, sizeof(t32));
4790         if (error != 0)
4791                 return (error);
4792         if (!timespecvalid_interval(&t32._timeout))
4793                 return (EINVAL);
4794         TS_CP(t32, *tp, _timeout);
4795         CP(t32, *tp, _flags);
4796         CP(t32, *tp, _clockid);
4797         return (0);
4798 }
4799
4800 static int
4801 umtx_copyout_timeoutx32(void *uaddr, size_t sz, struct timespec *tsp)
4802 {
4803         struct timespecx32 remain32 = {
4804                 .tv_sec = tsp->tv_sec,
4805                 .tv_nsec = tsp->tv_nsec,
4806         };
4807
4808         /*
4809          * Should be guaranteed by the caller, sz == uaddr1 - sizeof(_umtx_time)
4810          * and we're only called if sz >= sizeof(timespec) as supplied in the
4811          * copyops.
4812          */
4813         KASSERT(sz >= sizeof(remain32),
4814             ("umtx_copyops specifies incorrect sizes"));
4815
4816         return (copyout(&remain32, uaddr, sizeof(remain32)));
4817 }
4818 #endif /* __i386__ || __LP64__ */
4819
4820 typedef int (*_umtx_op_func)(struct thread *td, struct _umtx_op_args *uap,
4821     const struct umtx_copyops *umtx_ops);
4822
4823 static const _umtx_op_func op_table[] = {
4824 #ifdef COMPAT_FREEBSD10
4825         [UMTX_OP_LOCK]          = __umtx_op_lock_umtx,
4826         [UMTX_OP_UNLOCK]        = __umtx_op_unlock_umtx,
4827 #else
4828         [UMTX_OP_LOCK]          = __umtx_op_unimpl,
4829         [UMTX_OP_UNLOCK]        = __umtx_op_unimpl,
4830 #endif
4831         [UMTX_OP_WAIT]          = __umtx_op_wait,
4832         [UMTX_OP_WAKE]          = __umtx_op_wake,
4833         [UMTX_OP_MUTEX_TRYLOCK] = __umtx_op_trylock_umutex,
4834         [UMTX_OP_MUTEX_LOCK]    = __umtx_op_lock_umutex,
4835         [UMTX_OP_MUTEX_UNLOCK]  = __umtx_op_unlock_umutex,
4836         [UMTX_OP_SET_CEILING]   = __umtx_op_set_ceiling,
4837         [UMTX_OP_CV_WAIT]       = __umtx_op_cv_wait,
4838         [UMTX_OP_CV_SIGNAL]     = __umtx_op_cv_signal,
4839         [UMTX_OP_CV_BROADCAST]  = __umtx_op_cv_broadcast,
4840         [UMTX_OP_WAIT_UINT]     = __umtx_op_wait_uint,
4841         [UMTX_OP_RW_RDLOCK]     = __umtx_op_rw_rdlock,
4842         [UMTX_OP_RW_WRLOCK]     = __umtx_op_rw_wrlock,
4843         [UMTX_OP_RW_UNLOCK]     = __umtx_op_rw_unlock,
4844         [UMTX_OP_WAIT_UINT_PRIVATE] = __umtx_op_wait_uint_private,
4845         [UMTX_OP_WAKE_PRIVATE]  = __umtx_op_wake_private,
4846         [UMTX_OP_MUTEX_WAIT]    = __umtx_op_wait_umutex,
4847         [UMTX_OP_MUTEX_WAKE]    = __umtx_op_wake_umutex,
4848 #if defined(COMPAT_FREEBSD9) || defined(COMPAT_FREEBSD10)
4849         [UMTX_OP_SEM_WAIT]      = __umtx_op_sem_wait,
4850         [UMTX_OP_SEM_WAKE]      = __umtx_op_sem_wake,
4851 #else
4852         [UMTX_OP_SEM_WAIT]      = __umtx_op_unimpl,
4853         [UMTX_OP_SEM_WAKE]      = __umtx_op_unimpl,
4854 #endif
4855         [UMTX_OP_NWAKE_PRIVATE] = __umtx_op_nwake_private,
4856         [UMTX_OP_MUTEX_WAKE2]   = __umtx_op_wake2_umutex,
4857         [UMTX_OP_SEM2_WAIT]     = __umtx_op_sem2_wait,
4858         [UMTX_OP_SEM2_WAKE]     = __umtx_op_sem2_wake,
4859         [UMTX_OP_SHM]           = __umtx_op_shm,
4860         [UMTX_OP_ROBUST_LISTS]  = __umtx_op_robust_lists,
4861         [UMTX_OP_GET_MIN_TIMEOUT] = __umtx_op_get_min_timeout,
4862         [UMTX_OP_SET_MIN_TIMEOUT] = __umtx_op_set_min_timeout,
4863 };
4864
4865 static const struct umtx_copyops umtx_native_ops = {
4866         .copyin_timeout = umtx_copyin_timeout,
4867         .copyin_umtx_time = umtx_copyin_umtx_time,
4868         .copyin_robust_lists = umtx_copyin_robust_lists,
4869         .copyout_timeout = umtx_copyout_timeout,
4870         .timespec_sz = sizeof(struct timespec),
4871         .umtx_time_sz = sizeof(struct _umtx_time),
4872 };
4873
4874 #ifndef __i386__
4875 static const struct umtx_copyops umtx_native_opsi386 = {
4876         .copyin_timeout = umtx_copyin_timeouti386,
4877         .copyin_umtx_time = umtx_copyin_umtx_timei386,
4878         .copyin_robust_lists = umtx_copyin_robust_lists32,
4879         .copyout_timeout = umtx_copyout_timeouti386,
4880         .timespec_sz = sizeof(struct timespeci386),
4881         .umtx_time_sz = sizeof(struct umtx_timei386),
4882         .compat32 = true,
4883 };
4884 #endif
4885
4886 #if defined(__i386__) || defined(__LP64__)
4887 /* i386 can emulate other 32-bit archs, too! */
4888 static const struct umtx_copyops umtx_native_opsx32 = {
4889         .copyin_timeout = umtx_copyin_timeoutx32,
4890         .copyin_umtx_time = umtx_copyin_umtx_timex32,
4891         .copyin_robust_lists = umtx_copyin_robust_lists32,
4892         .copyout_timeout = umtx_copyout_timeoutx32,
4893         .timespec_sz = sizeof(struct timespecx32),
4894         .umtx_time_sz = sizeof(struct umtx_timex32),
4895         .compat32 = true,
4896 };
4897
4898 #ifdef COMPAT_FREEBSD32
4899 #ifdef __amd64__
4900 #define umtx_native_ops32       umtx_native_opsi386
4901 #else
4902 #define umtx_native_ops32       umtx_native_opsx32
4903 #endif
4904 #endif /* COMPAT_FREEBSD32 */
4905 #endif /* __i386__ || __LP64__ */
4906
4907 #define UMTX_OP__FLAGS  (UMTX_OP__32BIT | UMTX_OP__I386)
4908
4909 static int
4910 kern__umtx_op(struct thread *td, void *obj, int op, unsigned long val,
4911     void *uaddr1, void *uaddr2, const struct umtx_copyops *ops)
4912 {
4913         struct _umtx_op_args uap = {
4914                 .obj = obj,
4915                 .op = op & ~UMTX_OP__FLAGS,
4916                 .val = val,
4917                 .uaddr1 = uaddr1,
4918                 .uaddr2 = uaddr2
4919         };
4920
4921         if ((uap.op >= nitems(op_table)))
4922                 return (EINVAL);
4923         return ((*op_table[uap.op])(td, &uap, ops));
4924 }
4925
4926 int
4927 sys__umtx_op(struct thread *td, struct _umtx_op_args *uap)
4928 {
4929         static const struct umtx_copyops *umtx_ops;
4930
4931         umtx_ops = &umtx_native_ops;
4932 #ifdef __LP64__
4933         if ((uap->op & (UMTX_OP__32BIT | UMTX_OP__I386)) != 0) {
4934                 if ((uap->op & UMTX_OP__I386) != 0)
4935                         umtx_ops = &umtx_native_opsi386;
4936                 else
4937                         umtx_ops = &umtx_native_opsx32;
4938         }
4939 #elif !defined(__i386__)
4940         /* We consider UMTX_OP__32BIT a nop on !i386 ILP32. */
4941         if ((uap->op & UMTX_OP__I386) != 0)
4942                 umtx_ops = &umtx_native_opsi386;
4943 #else
4944         /* Likewise, UMTX_OP__I386 is a nop on i386. */
4945         if ((uap->op & UMTX_OP__32BIT) != 0)
4946                 umtx_ops = &umtx_native_opsx32;
4947 #endif
4948         return (kern__umtx_op(td, uap->obj, uap->op, uap->val, uap->uaddr1,
4949             uap->uaddr2, umtx_ops));
4950 }
4951
4952 #ifdef COMPAT_FREEBSD32
4953 #ifdef COMPAT_FREEBSD10
4954 int
4955 freebsd10_freebsd32_umtx_lock(struct thread *td,
4956     struct freebsd10_freebsd32_umtx_lock_args *uap)
4957 {
4958         return (do_lock_umtx32(td, (uint32_t *)uap->umtx, td->td_tid, NULL));
4959 }
4960
4961 int
4962 freebsd10_freebsd32_umtx_unlock(struct thread *td,
4963     struct freebsd10_freebsd32_umtx_unlock_args *uap)
4964 {
4965         return (do_unlock_umtx32(td, (uint32_t *)uap->umtx, td->td_tid));
4966 }
4967 #endif /* COMPAT_FREEBSD10 */
4968
4969 int
4970 freebsd32__umtx_op(struct thread *td, struct freebsd32__umtx_op_args *uap)
4971 {
4972
4973         return (kern__umtx_op(td, uap->obj, uap->op, uap->val, uap->uaddr,
4974             uap->uaddr2, &umtx_native_ops32));
4975 }
4976 #endif /* COMPAT_FREEBSD32 */
4977
4978 void
4979 umtx_thread_init(struct thread *td)
4980 {
4981
4982         td->td_umtxq = umtxq_alloc();
4983         td->td_umtxq->uq_thread = td;
4984 }
4985
4986 void
4987 umtx_thread_fini(struct thread *td)
4988 {
4989
4990         umtxq_free(td->td_umtxq);
4991 }
4992
4993 /*
4994  * It will be called when new thread is created, e.g fork().
4995  */
4996 void
4997 umtx_thread_alloc(struct thread *td)
4998 {
4999         struct umtx_q *uq;
5000
5001         uq = td->td_umtxq;
5002         uq->uq_inherited_pri = PRI_MAX;
5003
5004         KASSERT(uq->uq_flags == 0, ("uq_flags != 0"));
5005         KASSERT(uq->uq_thread == td, ("uq_thread != td"));
5006         KASSERT(uq->uq_pi_blocked == NULL, ("uq_pi_blocked != NULL"));
5007         KASSERT(TAILQ_EMPTY(&uq->uq_pi_contested), ("uq_pi_contested is not empty"));
5008 }
5009
5010 /*
5011  * exec() hook.
5012  *
5013  * Clear robust lists for all process' threads, not delaying the
5014  * cleanup to thread exit, since the relevant address space is
5015  * destroyed right now.
5016  */
5017 void
5018 umtx_exec(struct proc *p)
5019 {
5020         struct thread *td;
5021
5022         KASSERT(p == curproc, ("need curproc"));
5023         KASSERT((p->p_flag & P_HADTHREADS) == 0 ||
5024             (p->p_flag & P_STOPPED_SINGLE) != 0,
5025             ("curproc must be single-threaded"));
5026         /*
5027          * There is no need to lock the list as only this thread can be
5028          * running.
5029          */
5030         FOREACH_THREAD_IN_PROC(p, td) {
5031                 KASSERT(td == curthread ||
5032                     ((td->td_flags & TDF_BOUNDARY) != 0 && TD_IS_SUSPENDED(td)),
5033                     ("running thread %p %p", p, td));
5034                 umtx_thread_cleanup(td);
5035                 td->td_rb_list = td->td_rbp_list = td->td_rb_inact = 0;
5036         }
5037
5038         p->p_umtx_min_timeout = 0;
5039 }
5040
5041 /*
5042  * thread exit hook.
5043  */
5044 void
5045 umtx_thread_exit(struct thread *td)
5046 {
5047
5048         umtx_thread_cleanup(td);
5049 }
5050
5051 static int
5052 umtx_read_uptr(struct thread *td, uintptr_t ptr, uintptr_t *res, bool compat32)
5053 {
5054         u_long res1;
5055         uint32_t res32;
5056         int error;
5057
5058         if (compat32) {
5059                 error = fueword32((void *)ptr, &res32);
5060                 if (error == 0)
5061                         res1 = res32;
5062         } else {
5063                 error = fueword((void *)ptr, &res1);
5064         }
5065         if (error == 0)
5066                 *res = res1;
5067         else
5068                 error = EFAULT;
5069         return (error);
5070 }
5071
5072 static void
5073 umtx_read_rb_list(struct thread *td, struct umutex *m, uintptr_t *rb_list,
5074     bool compat32)
5075 {
5076         struct umutex32 m32;
5077
5078         if (compat32) {
5079                 memcpy(&m32, m, sizeof(m32));
5080                 *rb_list = m32.m_rb_lnk;
5081         } else {
5082                 *rb_list = m->m_rb_lnk;
5083         }
5084 }
5085
5086 static int
5087 umtx_handle_rb(struct thread *td, uintptr_t rbp, uintptr_t *rb_list, bool inact,
5088     bool compat32)
5089 {
5090         struct umutex m;
5091         int error;
5092
5093         KASSERT(td->td_proc == curproc, ("need current vmspace"));
5094         error = copyin((void *)rbp, &m, sizeof(m));
5095         if (error != 0)
5096                 return (error);
5097         if (rb_list != NULL)
5098                 umtx_read_rb_list(td, &m, rb_list, compat32);
5099         if ((m.m_flags & UMUTEX_ROBUST) == 0)
5100                 return (EINVAL);
5101         if ((m.m_owner & ~UMUTEX_CONTESTED) != td->td_tid)
5102                 /* inact is cleared after unlock, allow the inconsistency */
5103                 return (inact ? 0 : EINVAL);
5104         return (do_unlock_umutex(td, (struct umutex *)rbp, true));
5105 }
5106
5107 static void
5108 umtx_cleanup_rb_list(struct thread *td, uintptr_t rb_list, uintptr_t *rb_inact,
5109     const char *name, bool compat32)
5110 {
5111         int error, i;
5112         uintptr_t rbp;
5113         bool inact;
5114
5115         if (rb_list == 0)
5116                 return;
5117         error = umtx_read_uptr(td, rb_list, &rbp, compat32);
5118         for (i = 0; error == 0 && rbp != 0 && i < umtx_max_rb; i++) {
5119                 if (rbp == *rb_inact) {
5120                         inact = true;
5121                         *rb_inact = 0;
5122                 } else
5123                         inact = false;
5124                 error = umtx_handle_rb(td, rbp, &rbp, inact, compat32);
5125         }
5126         if (i == umtx_max_rb && umtx_verbose_rb) {
5127                 uprintf("comm %s pid %d: reached umtx %smax rb %d\n",
5128                     td->td_proc->p_comm, td->td_proc->p_pid, name, umtx_max_rb);
5129         }
5130         if (error != 0 && umtx_verbose_rb) {
5131                 uprintf("comm %s pid %d: handling %srb error %d\n",
5132                     td->td_proc->p_comm, td->td_proc->p_pid, name, error);
5133         }
5134 }
5135
5136 /*
5137  * Clean up umtx data.
5138  */
5139 static void
5140 umtx_thread_cleanup(struct thread *td)
5141 {
5142         struct umtx_q *uq;
5143         struct umtx_pi *pi;
5144         uintptr_t rb_inact;
5145         bool compat32;
5146
5147         /*
5148          * Disown pi mutexes.
5149          */
5150         uq = td->td_umtxq;
5151         if (uq != NULL) {
5152                 if (uq->uq_inherited_pri != PRI_MAX ||
5153                     !TAILQ_EMPTY(&uq->uq_pi_contested)) {
5154                         mtx_lock(&umtx_lock);
5155                         uq->uq_inherited_pri = PRI_MAX;
5156                         while ((pi = TAILQ_FIRST(&uq->uq_pi_contested)) != NULL) {
5157                                 pi->pi_owner = NULL;
5158                                 TAILQ_REMOVE(&uq->uq_pi_contested, pi, pi_link);
5159                         }
5160                         mtx_unlock(&umtx_lock);
5161                 }
5162                 sched_lend_user_prio_cond(td, PRI_MAX);
5163         }
5164
5165         compat32 = (td->td_pflags2 & TDP2_COMPAT32RB) != 0;
5166         td->td_pflags2 &= ~TDP2_COMPAT32RB;
5167
5168         if (td->td_rb_inact == 0 && td->td_rb_list == 0 && td->td_rbp_list == 0)
5169                 return;
5170
5171         /*
5172          * Handle terminated robust mutexes.  Must be done after
5173          * robust pi disown, otherwise unlock could see unowned
5174          * entries.
5175          */
5176         rb_inact = td->td_rb_inact;
5177         if (rb_inact != 0)
5178                 (void)umtx_read_uptr(td, rb_inact, &rb_inact, compat32);
5179         umtx_cleanup_rb_list(td, td->td_rb_list, &rb_inact, "", compat32);
5180         umtx_cleanup_rb_list(td, td->td_rbp_list, &rb_inact, "priv ", compat32);
5181         if (rb_inact != 0)
5182                 (void)umtx_handle_rb(td, rb_inact, NULL, true, compat32);
5183 }