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