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