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