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