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