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