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