xref: /freebsd/sys/kern/kern_umtx.c (revision 4f1f4356f3012928b463f9ef1710fb908e48b1e2)
1 /*-
2  * Copyright (c) 2004, David Xu <davidxu@freebsd.org>
3  * Copyright (c) 2002, Jeffrey Roberson <jeff@freebsd.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice unmodified, this list of conditions, and the following
11  *    disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_compat.h"
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/limits.h>
35 #include <sys/lock.h>
36 #include <sys/malloc.h>
37 #include <sys/mutex.h>
38 #include <sys/priv.h>
39 #include <sys/proc.h>
40 #include <sys/sched.h>
41 #include <sys/smp.h>
42 #include <sys/sysctl.h>
43 #include <sys/sysent.h>
44 #include <sys/systm.h>
45 #include <sys/sysproto.h>
46 #include <sys/eventhandler.h>
47 #include <sys/umtx.h>
48 
49 #include <vm/vm.h>
50 #include <vm/vm_param.h>
51 #include <vm/pmap.h>
52 #include <vm/vm_map.h>
53 #include <vm/vm_object.h>
54 
55 #include <machine/cpu.h>
56 
57 #ifdef COMPAT_FREEBSD32
58 #include <compat/freebsd32/freebsd32_proto.h>
59 #endif
60 
61 enum {
62 	TYPE_SIMPLE_WAIT,
63 	TYPE_CV,
64 	TYPE_SEM,
65 	TYPE_SIMPLE_LOCK,
66 	TYPE_NORMAL_UMUTEX,
67 	TYPE_PI_UMUTEX,
68 	TYPE_PP_UMUTEX,
69 	TYPE_RWLOCK
70 };
71 
72 #define _UMUTEX_TRY		1
73 #define _UMUTEX_WAIT		2
74 
75 /* Key to represent a unique userland synchronous object */
76 struct umtx_key {
77 	int	hash;
78 	int	type;
79 	int	shared;
80 	union {
81 		struct {
82 			vm_object_t	object;
83 			uintptr_t	offset;
84 		} shared;
85 		struct {
86 			struct vmspace	*vs;
87 			uintptr_t	addr;
88 		} private;
89 		struct {
90 			void		*a;
91 			uintptr_t	b;
92 		} both;
93 	} info;
94 };
95 
96 /* Priority inheritance mutex info. */
97 struct umtx_pi {
98 	/* Owner thread */
99 	struct thread		*pi_owner;
100 
101 	/* Reference count */
102 	int			pi_refcount;
103 
104  	/* List entry to link umtx holding by thread */
105 	TAILQ_ENTRY(umtx_pi)	pi_link;
106 
107 	/* List entry in hash */
108 	TAILQ_ENTRY(umtx_pi)	pi_hashlink;
109 
110 	/* List for waiters */
111 	TAILQ_HEAD(,umtx_q)	pi_blocked;
112 
113 	/* Identify a userland lock object */
114 	struct umtx_key		pi_key;
115 };
116 
117 /* A userland synchronous object user. */
118 struct umtx_q {
119 	/* Linked list for the hash. */
120 	TAILQ_ENTRY(umtx_q)	uq_link;
121 
122 	/* Umtx key. */
123 	struct umtx_key		uq_key;
124 
125 	/* Umtx flags. */
126 	int			uq_flags;
127 #define UQF_UMTXQ	0x0001
128 
129 	/* The thread waits on. */
130 	struct thread		*uq_thread;
131 
132 	/*
133 	 * Blocked on PI mutex. read can use chain lock
134 	 * or umtx_lock, write must have both chain lock and
135 	 * umtx_lock being hold.
136 	 */
137 	struct umtx_pi		*uq_pi_blocked;
138 
139 	/* On blocked list */
140 	TAILQ_ENTRY(umtx_q)	uq_lockq;
141 
142 	/* Thread contending with us */
143 	TAILQ_HEAD(,umtx_pi)	uq_pi_contested;
144 
145 	/* Inherited priority from PP mutex */
146 	u_char			uq_inherited_pri;
147 
148 	/* Spare queue ready to be reused */
149 	struct umtxq_queue	*uq_spare_queue;
150 
151 	/* The queue we on */
152 	struct umtxq_queue	*uq_cur_queue;
153 };
154 
155 TAILQ_HEAD(umtxq_head, umtx_q);
156 
157 /* Per-key wait-queue */
158 struct umtxq_queue {
159 	struct umtxq_head	head;
160 	struct umtx_key		key;
161 	LIST_ENTRY(umtxq_queue)	link;
162 	int			length;
163 };
164 
165 LIST_HEAD(umtxq_list, umtxq_queue);
166 
167 /* Userland lock object's wait-queue chain */
168 struct umtxq_chain {
169 	/* Lock for this chain. */
170 	struct mtx		uc_lock;
171 
172 	/* List of sleep queues. */
173 	struct umtxq_list	uc_queue[2];
174 #define UMTX_SHARED_QUEUE	0
175 #define UMTX_EXCLUSIVE_QUEUE	1
176 
177 	LIST_HEAD(, umtxq_queue) uc_spare_queue;
178 
179 	/* Busy flag */
180 	char			uc_busy;
181 
182 	/* Chain lock waiters */
183 	int			uc_waiters;
184 
185 	/* All PI in the list */
186 	TAILQ_HEAD(,umtx_pi)	uc_pi_list;
187 
188 };
189 
190 #define	UMTXQ_LOCKED_ASSERT(uc)		mtx_assert(&(uc)->uc_lock, MA_OWNED)
191 #define	UMTXQ_BUSY_ASSERT(uc)	KASSERT(&(uc)->uc_busy, ("umtx chain is not busy"))
192 
193 /*
194  * Don't propagate time-sharing priority, there is a security reason,
195  * a user can simply introduce PI-mutex, let thread A lock the mutex,
196  * and let another thread B block on the mutex, because B is
197  * sleeping, its priority will be boosted, this causes A's priority to
198  * be boosted via priority propagating too and will never be lowered even
199  * if it is using 100%CPU, this is unfair to other processes.
200  */
201 
202 #define UPRI(td)	(((td)->td_user_pri >= PRI_MIN_TIMESHARE &&\
203 			  (td)->td_user_pri <= PRI_MAX_TIMESHARE) ?\
204 			 PRI_MAX_TIMESHARE : (td)->td_user_pri)
205 
206 #define	GOLDEN_RATIO_PRIME	2654404609U
207 #define	UMTX_CHAINS		128
208 #define	UMTX_SHIFTS		(__WORD_BIT - 7)
209 
210 #define THREAD_SHARE		0
211 #define PROCESS_SHARE		1
212 #define AUTO_SHARE		2
213 
214 #define	GET_SHARE(flags)	\
215     (((flags) & USYNC_PROCESS_SHARED) == 0 ? THREAD_SHARE : PROCESS_SHARE)
216 
217 #define BUSY_SPINS		200
218 
219 static uma_zone_t		umtx_pi_zone;
220 static struct umtxq_chain	umtxq_chains[2][UMTX_CHAINS];
221 static MALLOC_DEFINE(M_UMTX, "umtx", "UMTX queue memory");
222 static int			umtx_pi_allocated;
223 
224 SYSCTL_NODE(_debug, OID_AUTO, umtx, CTLFLAG_RW, 0, "umtx debug");
225 SYSCTL_INT(_debug_umtx, OID_AUTO, umtx_pi_allocated, CTLFLAG_RD,
226     &umtx_pi_allocated, 0, "Allocated umtx_pi");
227 
228 static void umtxq_sysinit(void *);
229 static void umtxq_hash(struct umtx_key *key);
230 static struct umtxq_chain *umtxq_getchain(struct umtx_key *key);
231 static void umtxq_lock(struct umtx_key *key);
232 static void umtxq_unlock(struct umtx_key *key);
233 static void umtxq_busy(struct umtx_key *key);
234 static void umtxq_unbusy(struct umtx_key *key);
235 static void umtxq_insert_queue(struct umtx_q *uq, int q);
236 static void umtxq_remove_queue(struct umtx_q *uq, int q);
237 static int umtxq_sleep(struct umtx_q *uq, const char *wmesg, int timo);
238 static int umtxq_count(struct umtx_key *key);
239 static int umtx_key_match(const struct umtx_key *k1, const struct umtx_key *k2);
240 static int umtx_key_get(void *addr, int type, int share,
241 	struct umtx_key *key);
242 static void umtx_key_release(struct umtx_key *key);
243 static struct umtx_pi *umtx_pi_alloc(int);
244 static void umtx_pi_free(struct umtx_pi *pi);
245 static void umtx_pi_adjust_locked(struct thread *td, u_char oldpri);
246 static int do_unlock_pp(struct thread *td, struct umutex *m, uint32_t flags);
247 static void umtx_thread_cleanup(struct thread *td);
248 static void umtx_exec_hook(void *arg __unused, struct proc *p __unused,
249 	struct image_params *imgp __unused);
250 SYSINIT(umtx, SI_SUB_EVENTHANDLER+1, SI_ORDER_MIDDLE, umtxq_sysinit, NULL);
251 
252 #define umtxq_signal(key, nwake)	umtxq_signal_queue((key), (nwake), UMTX_SHARED_QUEUE)
253 #define umtxq_insert(uq)	umtxq_insert_queue((uq), UMTX_SHARED_QUEUE)
254 #define umtxq_remove(uq)	umtxq_remove_queue((uq), UMTX_SHARED_QUEUE)
255 
256 static struct mtx umtx_lock;
257 
258 static void
259 umtxq_sysinit(void *arg __unused)
260 {
261 	int i, j;
262 
263 	umtx_pi_zone = uma_zcreate("umtx pi", sizeof(struct umtx_pi),
264 		NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
265 	for (i = 0; i < 2; ++i) {
266 		for (j = 0; j < UMTX_CHAINS; ++j) {
267 			mtx_init(&umtxq_chains[i][j].uc_lock, "umtxql", NULL,
268 				 MTX_DEF | MTX_DUPOK);
269 			LIST_INIT(&umtxq_chains[i][j].uc_queue[0]);
270 			LIST_INIT(&umtxq_chains[i][j].uc_queue[1]);
271 			LIST_INIT(&umtxq_chains[i][j].uc_spare_queue);
272 			TAILQ_INIT(&umtxq_chains[i][j].uc_pi_list);
273 			umtxq_chains[i][j].uc_busy = 0;
274 			umtxq_chains[i][j].uc_waiters = 0;
275 		}
276 	}
277 	mtx_init(&umtx_lock, "umtx lock", NULL, MTX_SPIN);
278 	EVENTHANDLER_REGISTER(process_exec, umtx_exec_hook, NULL,
279 	    EVENTHANDLER_PRI_ANY);
280 }
281 
282 struct umtx_q *
283 umtxq_alloc(void)
284 {
285 	struct umtx_q *uq;
286 
287 	uq = malloc(sizeof(struct umtx_q), M_UMTX, M_WAITOK | M_ZERO);
288 	uq->uq_spare_queue = malloc(sizeof(struct umtxq_queue), M_UMTX, M_WAITOK | M_ZERO);
289 	TAILQ_INIT(&uq->uq_spare_queue->head);
290 	TAILQ_INIT(&uq->uq_pi_contested);
291 	uq->uq_inherited_pri = PRI_MAX;
292 	return (uq);
293 }
294 
295 void
296 umtxq_free(struct umtx_q *uq)
297 {
298 	MPASS(uq->uq_spare_queue != NULL);
299 	free(uq->uq_spare_queue, M_UMTX);
300 	free(uq, M_UMTX);
301 }
302 
303 static inline void
304 umtxq_hash(struct umtx_key *key)
305 {
306 	unsigned n = (uintptr_t)key->info.both.a + key->info.both.b;
307 	key->hash = ((n * GOLDEN_RATIO_PRIME) >> UMTX_SHIFTS) % UMTX_CHAINS;
308 }
309 
310 static inline int
311 umtx_key_match(const struct umtx_key *k1, const struct umtx_key *k2)
312 {
313 	return (k1->type == k2->type &&
314 		k1->info.both.a == k2->info.both.a &&
315 	        k1->info.both.b == k2->info.both.b);
316 }
317 
318 static inline struct umtxq_chain *
319 umtxq_getchain(struct umtx_key *key)
320 {
321 	if (key->type <= TYPE_SEM)
322 		return (&umtxq_chains[1][key->hash]);
323 	return (&umtxq_chains[0][key->hash]);
324 }
325 
326 /*
327  * Lock a chain.
328  */
329 static inline void
330 umtxq_lock(struct umtx_key *key)
331 {
332 	struct umtxq_chain *uc;
333 
334 	uc = umtxq_getchain(key);
335 	mtx_lock(&uc->uc_lock);
336 }
337 
338 /*
339  * Unlock a chain.
340  */
341 static inline void
342 umtxq_unlock(struct umtx_key *key)
343 {
344 	struct umtxq_chain *uc;
345 
346 	uc = umtxq_getchain(key);
347 	mtx_unlock(&uc->uc_lock);
348 }
349 
350 /*
351  * Set chain to busy state when following operation
352  * may be blocked (kernel mutex can not be used).
353  */
354 static inline void
355 umtxq_busy(struct umtx_key *key)
356 {
357 	struct umtxq_chain *uc;
358 
359 	uc = umtxq_getchain(key);
360 	mtx_assert(&uc->uc_lock, MA_OWNED);
361 	if (uc->uc_busy) {
362 #ifdef SMP
363 		if (smp_cpus > 1) {
364 			int count = BUSY_SPINS;
365 			if (count > 0) {
366 				umtxq_unlock(key);
367 				while (uc->uc_busy && --count > 0)
368 					cpu_spinwait();
369 				umtxq_lock(key);
370 			}
371 		}
372 #endif
373 		while (uc->uc_busy) {
374 			uc->uc_waiters++;
375 			msleep(uc, &uc->uc_lock, 0, "umtxqb", 0);
376 			uc->uc_waiters--;
377 		}
378 	}
379 	uc->uc_busy = 1;
380 }
381 
382 /*
383  * Unbusy a chain.
384  */
385 static inline void
386 umtxq_unbusy(struct umtx_key *key)
387 {
388 	struct umtxq_chain *uc;
389 
390 	uc = umtxq_getchain(key);
391 	mtx_assert(&uc->uc_lock, MA_OWNED);
392 	KASSERT(uc->uc_busy != 0, ("not busy"));
393 	uc->uc_busy = 0;
394 	if (uc->uc_waiters)
395 		wakeup_one(uc);
396 }
397 
398 static struct umtxq_queue *
399 umtxq_queue_lookup(struct umtx_key *key, int q)
400 {
401 	struct umtxq_queue *uh;
402 	struct umtxq_chain *uc;
403 
404 	uc = umtxq_getchain(key);
405 	UMTXQ_LOCKED_ASSERT(uc);
406 	LIST_FOREACH(uh, &uc->uc_queue[q], link) {
407 		if (umtx_key_match(&uh->key, key))
408 			return (uh);
409 	}
410 
411 	return (NULL);
412 }
413 
414 static inline void
415 umtxq_insert_queue(struct umtx_q *uq, int q)
416 {
417 	struct umtxq_queue *uh;
418 	struct umtxq_chain *uc;
419 
420 	uc = umtxq_getchain(&uq->uq_key);
421 	UMTXQ_LOCKED_ASSERT(uc);
422 	KASSERT((uq->uq_flags & UQF_UMTXQ) == 0, ("umtx_q is already on queue"));
423 	uh = umtxq_queue_lookup(&uq->uq_key, q);
424 	if (uh != NULL) {
425 		LIST_INSERT_HEAD(&uc->uc_spare_queue, uq->uq_spare_queue, link);
426 	} else {
427 		uh = uq->uq_spare_queue;
428 		uh->key = uq->uq_key;
429 		LIST_INSERT_HEAD(&uc->uc_queue[q], uh, link);
430 	}
431 	uq->uq_spare_queue = NULL;
432 
433 	TAILQ_INSERT_TAIL(&uh->head, uq, uq_link);
434 	uh->length++;
435 	uq->uq_flags |= UQF_UMTXQ;
436 	uq->uq_cur_queue = uh;
437 	return;
438 }
439 
440 static inline void
441 umtxq_remove_queue(struct umtx_q *uq, int q)
442 {
443 	struct umtxq_chain *uc;
444 	struct umtxq_queue *uh;
445 
446 	uc = umtxq_getchain(&uq->uq_key);
447 	UMTXQ_LOCKED_ASSERT(uc);
448 	if (uq->uq_flags & UQF_UMTXQ) {
449 		uh = uq->uq_cur_queue;
450 		TAILQ_REMOVE(&uh->head, uq, uq_link);
451 		uh->length--;
452 		uq->uq_flags &= ~UQF_UMTXQ;
453 		if (TAILQ_EMPTY(&uh->head)) {
454 			KASSERT(uh->length == 0,
455 			    ("inconsistent umtxq_queue length"));
456 			LIST_REMOVE(uh, link);
457 		} else {
458 			uh = LIST_FIRST(&uc->uc_spare_queue);
459 			KASSERT(uh != NULL, ("uc_spare_queue is empty"));
460 			LIST_REMOVE(uh, link);
461 		}
462 		uq->uq_spare_queue = uh;
463 		uq->uq_cur_queue = NULL;
464 	}
465 }
466 
467 /*
468  * Check if there are multiple waiters
469  */
470 static int
471 umtxq_count(struct umtx_key *key)
472 {
473 	struct umtxq_chain *uc;
474 	struct umtxq_queue *uh;
475 
476 	uc = umtxq_getchain(key);
477 	UMTXQ_LOCKED_ASSERT(uc);
478 	uh = umtxq_queue_lookup(key, UMTX_SHARED_QUEUE);
479 	if (uh != NULL)
480 		return (uh->length);
481 	return (0);
482 }
483 
484 /*
485  * Check if there are multiple PI waiters and returns first
486  * waiter.
487  */
488 static int
489 umtxq_count_pi(struct umtx_key *key, struct umtx_q **first)
490 {
491 	struct umtxq_chain *uc;
492 	struct umtxq_queue *uh;
493 
494 	*first = NULL;
495 	uc = umtxq_getchain(key);
496 	UMTXQ_LOCKED_ASSERT(uc);
497 	uh = umtxq_queue_lookup(key, UMTX_SHARED_QUEUE);
498 	if (uh != NULL) {
499 		*first = TAILQ_FIRST(&uh->head);
500 		return (uh->length);
501 	}
502 	return (0);
503 }
504 
505 /*
506  * Wake up threads waiting on an userland object.
507  */
508 
509 static int
510 umtxq_signal_queue(struct umtx_key *key, int n_wake, int q)
511 {
512 	struct umtxq_chain *uc;
513 	struct umtxq_queue *uh;
514 	struct umtx_q *uq;
515 	int ret;
516 
517 	ret = 0;
518 	uc = umtxq_getchain(key);
519 	UMTXQ_LOCKED_ASSERT(uc);
520 	uh = umtxq_queue_lookup(key, q);
521 	if (uh != NULL) {
522 		while ((uq = TAILQ_FIRST(&uh->head)) != NULL) {
523 			umtxq_remove_queue(uq, q);
524 			wakeup(uq);
525 			if (++ret >= n_wake)
526 				return (ret);
527 		}
528 	}
529 	return (ret);
530 }
531 
532 
533 /*
534  * Wake up specified thread.
535  */
536 static inline void
537 umtxq_signal_thread(struct umtx_q *uq)
538 {
539 	struct umtxq_chain *uc;
540 
541 	uc = umtxq_getchain(&uq->uq_key);
542 	UMTXQ_LOCKED_ASSERT(uc);
543 	umtxq_remove(uq);
544 	wakeup(uq);
545 }
546 
547 /*
548  * Put thread into sleep state, before sleeping, check if
549  * thread was removed from umtx queue.
550  */
551 static inline int
552 umtxq_sleep(struct umtx_q *uq, const char *wmesg, int timo)
553 {
554 	struct umtxq_chain *uc;
555 	int error;
556 
557 	uc = umtxq_getchain(&uq->uq_key);
558 	UMTXQ_LOCKED_ASSERT(uc);
559 	if (!(uq->uq_flags & UQF_UMTXQ))
560 		return (0);
561 	error = msleep(uq, &uc->uc_lock, PCATCH, wmesg, timo);
562 	if (error == EWOULDBLOCK)
563 		error = ETIMEDOUT;
564 	return (error);
565 }
566 
567 /*
568  * Convert userspace address into unique logical address.
569  */
570 static int
571 umtx_key_get(void *addr, int type, int share, struct umtx_key *key)
572 {
573 	struct thread *td = curthread;
574 	vm_map_t map;
575 	vm_map_entry_t entry;
576 	vm_pindex_t pindex;
577 	vm_prot_t prot;
578 	boolean_t wired;
579 
580 	key->type = type;
581 	if (share == THREAD_SHARE) {
582 		key->shared = 0;
583 		key->info.private.vs = td->td_proc->p_vmspace;
584 		key->info.private.addr = (uintptr_t)addr;
585 	} else {
586 		MPASS(share == PROCESS_SHARE || share == AUTO_SHARE);
587 		map = &td->td_proc->p_vmspace->vm_map;
588 		if (vm_map_lookup(&map, (vm_offset_t)addr, VM_PROT_WRITE,
589 		    &entry, &key->info.shared.object, &pindex, &prot,
590 		    &wired) != KERN_SUCCESS) {
591 			return EFAULT;
592 		}
593 
594 		if ((share == PROCESS_SHARE) ||
595 		    (share == AUTO_SHARE &&
596 		     VM_INHERIT_SHARE == entry->inheritance)) {
597 			key->shared = 1;
598 			key->info.shared.offset = entry->offset + entry->start -
599 				(vm_offset_t)addr;
600 			vm_object_reference(key->info.shared.object);
601 		} else {
602 			key->shared = 0;
603 			key->info.private.vs = td->td_proc->p_vmspace;
604 			key->info.private.addr = (uintptr_t)addr;
605 		}
606 		vm_map_lookup_done(map, entry);
607 	}
608 
609 	umtxq_hash(key);
610 	return (0);
611 }
612 
613 /*
614  * Release key.
615  */
616 static inline void
617 umtx_key_release(struct umtx_key *key)
618 {
619 	if (key->shared)
620 		vm_object_deallocate(key->info.shared.object);
621 }
622 
623 /*
624  * Lock a umtx object.
625  */
626 static int
627 _do_lock_umtx(struct thread *td, struct umtx *umtx, u_long id, int timo)
628 {
629 	struct umtx_q *uq;
630 	u_long owner;
631 	u_long old;
632 	int error = 0;
633 
634 	uq = td->td_umtxq;
635 
636 	/*
637 	 * Care must be exercised when dealing with umtx structure. It
638 	 * can fault on any access.
639 	 */
640 	for (;;) {
641 		/*
642 		 * Try the uncontested case.  This should be done in userland.
643 		 */
644 		owner = casuword(&umtx->u_owner, UMTX_UNOWNED, id);
645 
646 		/* The acquire succeeded. */
647 		if (owner == UMTX_UNOWNED)
648 			return (0);
649 
650 		/* The address was invalid. */
651 		if (owner == -1)
652 			return (EFAULT);
653 
654 		/* If no one owns it but it is contested try to acquire it. */
655 		if (owner == UMTX_CONTESTED) {
656 			owner = casuword(&umtx->u_owner,
657 			    UMTX_CONTESTED, id | UMTX_CONTESTED);
658 
659 			if (owner == UMTX_CONTESTED)
660 				return (0);
661 
662 			/* The address was invalid. */
663 			if (owner == -1)
664 				return (EFAULT);
665 
666 			/* If this failed the lock has changed, restart. */
667 			continue;
668 		}
669 
670 		/*
671 		 * If we caught a signal, we have retried and now
672 		 * exit immediately.
673 		 */
674 		if (error != 0)
675 			return (error);
676 
677 		if ((error = umtx_key_get(umtx, TYPE_SIMPLE_LOCK,
678 			AUTO_SHARE, &uq->uq_key)) != 0)
679 			return (error);
680 
681 		umtxq_lock(&uq->uq_key);
682 		umtxq_busy(&uq->uq_key);
683 		umtxq_insert(uq);
684 		umtxq_unbusy(&uq->uq_key);
685 		umtxq_unlock(&uq->uq_key);
686 
687 		/*
688 		 * Set the contested bit so that a release in user space
689 		 * knows to use the system call for unlock.  If this fails
690 		 * either some one else has acquired the lock or it has been
691 		 * released.
692 		 */
693 		old = casuword(&umtx->u_owner, owner, owner | UMTX_CONTESTED);
694 
695 		/* The address was invalid. */
696 		if (old == -1) {
697 			umtxq_lock(&uq->uq_key);
698 			umtxq_remove(uq);
699 			umtxq_unlock(&uq->uq_key);
700 			umtx_key_release(&uq->uq_key);
701 			return (EFAULT);
702 		}
703 
704 		/*
705 		 * We set the contested bit, sleep. Otherwise the lock changed
706 		 * and we need to retry or we lost a race to the thread
707 		 * unlocking the umtx.
708 		 */
709 		umtxq_lock(&uq->uq_key);
710 		if (old == owner)
711 			error = umtxq_sleep(uq, "umtx", timo);
712 		umtxq_remove(uq);
713 		umtxq_unlock(&uq->uq_key);
714 		umtx_key_release(&uq->uq_key);
715 	}
716 
717 	return (0);
718 }
719 
720 /*
721  * Lock a umtx object.
722  */
723 static int
724 do_lock_umtx(struct thread *td, struct umtx *umtx, u_long id,
725 	struct timespec *timeout)
726 {
727 	struct timespec ts, ts2, ts3;
728 	struct timeval tv;
729 	int error;
730 
731 	if (timeout == NULL) {
732 		error = _do_lock_umtx(td, umtx, id, 0);
733 		/* Mutex locking is restarted if it is interrupted. */
734 		if (error == EINTR)
735 			error = ERESTART;
736 	} else {
737 		getnanouptime(&ts);
738 		timespecadd(&ts, timeout);
739 		TIMESPEC_TO_TIMEVAL(&tv, timeout);
740 		for (;;) {
741 			error = _do_lock_umtx(td, umtx, id, tvtohz(&tv));
742 			if (error != ETIMEDOUT)
743 				break;
744 			getnanouptime(&ts2);
745 			if (timespeccmp(&ts2, &ts, >=)) {
746 				error = ETIMEDOUT;
747 				break;
748 			}
749 			ts3 = ts;
750 			timespecsub(&ts3, &ts2);
751 			TIMESPEC_TO_TIMEVAL(&tv, &ts3);
752 		}
753 		/* Timed-locking is not restarted. */
754 		if (error == ERESTART)
755 			error = EINTR;
756 	}
757 	return (error);
758 }
759 
760 /*
761  * Unlock a umtx object.
762  */
763 static int
764 do_unlock_umtx(struct thread *td, struct umtx *umtx, u_long id)
765 {
766 	struct umtx_key key;
767 	u_long owner;
768 	u_long old;
769 	int error;
770 	int count;
771 
772 	/*
773 	 * Make sure we own this mtx.
774 	 */
775 	owner = fuword(__DEVOLATILE(u_long *, &umtx->u_owner));
776 	if (owner == -1)
777 		return (EFAULT);
778 
779 	if ((owner & ~UMTX_CONTESTED) != id)
780 		return (EPERM);
781 
782 	/* This should be done in userland */
783 	if ((owner & UMTX_CONTESTED) == 0) {
784 		old = casuword(&umtx->u_owner, owner, UMTX_UNOWNED);
785 		if (old == -1)
786 			return (EFAULT);
787 		if (old == owner)
788 			return (0);
789 		owner = old;
790 	}
791 
792 	/* We should only ever be in here for contested locks */
793 	if ((error = umtx_key_get(umtx, TYPE_SIMPLE_LOCK, AUTO_SHARE,
794 		&key)) != 0)
795 		return (error);
796 
797 	umtxq_lock(&key);
798 	umtxq_busy(&key);
799 	count = umtxq_count(&key);
800 	umtxq_unlock(&key);
801 
802 	/*
803 	 * When unlocking the umtx, it must be marked as unowned if
804 	 * there is zero or one thread only waiting for it.
805 	 * Otherwise, it must be marked as contested.
806 	 */
807 	old = casuword(&umtx->u_owner, owner,
808 		count <= 1 ? UMTX_UNOWNED : UMTX_CONTESTED);
809 	umtxq_lock(&key);
810 	umtxq_signal(&key,1);
811 	umtxq_unbusy(&key);
812 	umtxq_unlock(&key);
813 	umtx_key_release(&key);
814 	if (old == -1)
815 		return (EFAULT);
816 	if (old != owner)
817 		return (EINVAL);
818 	return (0);
819 }
820 
821 #ifdef COMPAT_FREEBSD32
822 
823 /*
824  * Lock a umtx object.
825  */
826 static int
827 _do_lock_umtx32(struct thread *td, uint32_t *m, uint32_t id, int timo)
828 {
829 	struct umtx_q *uq;
830 	uint32_t owner;
831 	uint32_t old;
832 	int error = 0;
833 
834 	uq = td->td_umtxq;
835 
836 	/*
837 	 * Care must be exercised when dealing with umtx structure. It
838 	 * can fault on any access.
839 	 */
840 	for (;;) {
841 		/*
842 		 * Try the uncontested case.  This should be done in userland.
843 		 */
844 		owner = casuword32(m, UMUTEX_UNOWNED, id);
845 
846 		/* The acquire succeeded. */
847 		if (owner == UMUTEX_UNOWNED)
848 			return (0);
849 
850 		/* The address was invalid. */
851 		if (owner == -1)
852 			return (EFAULT);
853 
854 		/* If no one owns it but it is contested try to acquire it. */
855 		if (owner == UMUTEX_CONTESTED) {
856 			owner = casuword32(m,
857 			    UMUTEX_CONTESTED, id | UMUTEX_CONTESTED);
858 			if (owner == UMUTEX_CONTESTED)
859 				return (0);
860 
861 			/* The address was invalid. */
862 			if (owner == -1)
863 				return (EFAULT);
864 
865 			/* If this failed the lock has changed, restart. */
866 			continue;
867 		}
868 
869 		/*
870 		 * If we caught a signal, we have retried and now
871 		 * exit immediately.
872 		 */
873 		if (error != 0)
874 			return (error);
875 
876 		if ((error = umtx_key_get(m, TYPE_SIMPLE_LOCK,
877 			AUTO_SHARE, &uq->uq_key)) != 0)
878 			return (error);
879 
880 		umtxq_lock(&uq->uq_key);
881 		umtxq_busy(&uq->uq_key);
882 		umtxq_insert(uq);
883 		umtxq_unbusy(&uq->uq_key);
884 		umtxq_unlock(&uq->uq_key);
885 
886 		/*
887 		 * Set the contested bit so that a release in user space
888 		 * knows to use the system call for unlock.  If this fails
889 		 * either some one else has acquired the lock or it has been
890 		 * released.
891 		 */
892 		old = casuword32(m, owner, owner | UMUTEX_CONTESTED);
893 
894 		/* The address was invalid. */
895 		if (old == -1) {
896 			umtxq_lock(&uq->uq_key);
897 			umtxq_remove(uq);
898 			umtxq_unlock(&uq->uq_key);
899 			umtx_key_release(&uq->uq_key);
900 			return (EFAULT);
901 		}
902 
903 		/*
904 		 * We set the contested bit, sleep. Otherwise the lock changed
905 		 * and we need to retry or we lost a race to the thread
906 		 * unlocking the umtx.
907 		 */
908 		umtxq_lock(&uq->uq_key);
909 		if (old == owner)
910 			error = umtxq_sleep(uq, "umtx", timo);
911 		umtxq_remove(uq);
912 		umtxq_unlock(&uq->uq_key);
913 		umtx_key_release(&uq->uq_key);
914 	}
915 
916 	return (0);
917 }
918 
919 /*
920  * Lock a umtx object.
921  */
922 static int
923 do_lock_umtx32(struct thread *td, void *m, uint32_t id,
924 	struct timespec *timeout)
925 {
926 	struct timespec ts, ts2, ts3;
927 	struct timeval tv;
928 	int error;
929 
930 	if (timeout == NULL) {
931 		error = _do_lock_umtx32(td, m, id, 0);
932 		/* Mutex locking is restarted if it is interrupted. */
933 		if (error == EINTR)
934 			error = ERESTART;
935 	} else {
936 		getnanouptime(&ts);
937 		timespecadd(&ts, timeout);
938 		TIMESPEC_TO_TIMEVAL(&tv, timeout);
939 		for (;;) {
940 			error = _do_lock_umtx32(td, m, id, tvtohz(&tv));
941 			if (error != ETIMEDOUT)
942 				break;
943 			getnanouptime(&ts2);
944 			if (timespeccmp(&ts2, &ts, >=)) {
945 				error = ETIMEDOUT;
946 				break;
947 			}
948 			ts3 = ts;
949 			timespecsub(&ts3, &ts2);
950 			TIMESPEC_TO_TIMEVAL(&tv, &ts3);
951 		}
952 		/* Timed-locking is not restarted. */
953 		if (error == ERESTART)
954 			error = EINTR;
955 	}
956 	return (error);
957 }
958 
959 /*
960  * Unlock a umtx object.
961  */
962 static int
963 do_unlock_umtx32(struct thread *td, uint32_t *m, uint32_t id)
964 {
965 	struct umtx_key key;
966 	uint32_t owner;
967 	uint32_t old;
968 	int error;
969 	int count;
970 
971 	/*
972 	 * Make sure we own this mtx.
973 	 */
974 	owner = fuword32(m);
975 	if (owner == -1)
976 		return (EFAULT);
977 
978 	if ((owner & ~UMUTEX_CONTESTED) != id)
979 		return (EPERM);
980 
981 	/* This should be done in userland */
982 	if ((owner & UMUTEX_CONTESTED) == 0) {
983 		old = casuword32(m, owner, UMUTEX_UNOWNED);
984 		if (old == -1)
985 			return (EFAULT);
986 		if (old == owner)
987 			return (0);
988 		owner = old;
989 	}
990 
991 	/* We should only ever be in here for contested locks */
992 	if ((error = umtx_key_get(m, TYPE_SIMPLE_LOCK, AUTO_SHARE,
993 		&key)) != 0)
994 		return (error);
995 
996 	umtxq_lock(&key);
997 	umtxq_busy(&key);
998 	count = umtxq_count(&key);
999 	umtxq_unlock(&key);
1000 
1001 	/*
1002 	 * When unlocking the umtx, it must be marked as unowned if
1003 	 * there is zero or one thread only waiting for it.
1004 	 * Otherwise, it must be marked as contested.
1005 	 */
1006 	old = casuword32(m, owner,
1007 		count <= 1 ? UMUTEX_UNOWNED : UMUTEX_CONTESTED);
1008 	umtxq_lock(&key);
1009 	umtxq_signal(&key,1);
1010 	umtxq_unbusy(&key);
1011 	umtxq_unlock(&key);
1012 	umtx_key_release(&key);
1013 	if (old == -1)
1014 		return (EFAULT);
1015 	if (old != owner)
1016 		return (EINVAL);
1017 	return (0);
1018 }
1019 #endif
1020 
1021 /*
1022  * Fetch and compare value, sleep on the address if value is not changed.
1023  */
1024 static int
1025 do_wait(struct thread *td, void *addr, u_long id,
1026 	struct timespec *timeout, int compat32, int is_private)
1027 {
1028 	struct umtx_q *uq;
1029 	struct timespec ts, ts2, ts3;
1030 	struct timeval tv;
1031 	u_long tmp;
1032 	int error = 0;
1033 
1034 	uq = td->td_umtxq;
1035 	if ((error = umtx_key_get(addr, TYPE_SIMPLE_WAIT,
1036 		is_private ? THREAD_SHARE : AUTO_SHARE, &uq->uq_key)) != 0)
1037 		return (error);
1038 
1039 	umtxq_lock(&uq->uq_key);
1040 	umtxq_insert(uq);
1041 	umtxq_unlock(&uq->uq_key);
1042 	if (compat32 == 0)
1043 		tmp = fuword(addr);
1044         else
1045 		tmp = (unsigned int)fuword32(addr);
1046 	if (tmp != id) {
1047 		umtxq_lock(&uq->uq_key);
1048 		umtxq_remove(uq);
1049 		umtxq_unlock(&uq->uq_key);
1050 	} else if (timeout == NULL) {
1051 		umtxq_lock(&uq->uq_key);
1052 		error = umtxq_sleep(uq, "uwait", 0);
1053 		umtxq_remove(uq);
1054 		umtxq_unlock(&uq->uq_key);
1055 	} else {
1056 		getnanouptime(&ts);
1057 		timespecadd(&ts, timeout);
1058 		TIMESPEC_TO_TIMEVAL(&tv, timeout);
1059 		umtxq_lock(&uq->uq_key);
1060 		for (;;) {
1061 			error = umtxq_sleep(uq, "uwait", tvtohz(&tv));
1062 			if (!(uq->uq_flags & UQF_UMTXQ)) {
1063 				error = 0;
1064 				break;
1065 			}
1066 			if (error != ETIMEDOUT)
1067 				break;
1068 			umtxq_unlock(&uq->uq_key);
1069 			getnanouptime(&ts2);
1070 			if (timespeccmp(&ts2, &ts, >=)) {
1071 				error = ETIMEDOUT;
1072 				umtxq_lock(&uq->uq_key);
1073 				break;
1074 			}
1075 			ts3 = ts;
1076 			timespecsub(&ts3, &ts2);
1077 			TIMESPEC_TO_TIMEVAL(&tv, &ts3);
1078 			umtxq_lock(&uq->uq_key);
1079 		}
1080 		umtxq_remove(uq);
1081 		umtxq_unlock(&uq->uq_key);
1082 	}
1083 	umtx_key_release(&uq->uq_key);
1084 	if (error == ERESTART)
1085 		error = EINTR;
1086 	return (error);
1087 }
1088 
1089 /*
1090  * Wake up threads sleeping on the specified address.
1091  */
1092 int
1093 kern_umtx_wake(struct thread *td, void *uaddr, int n_wake, int is_private)
1094 {
1095 	struct umtx_key key;
1096 	int ret;
1097 
1098 	if ((ret = umtx_key_get(uaddr, TYPE_SIMPLE_WAIT,
1099 		is_private ? THREAD_SHARE : AUTO_SHARE, &key)) != 0)
1100 		return (ret);
1101 	umtxq_lock(&key);
1102 	ret = umtxq_signal(&key, n_wake);
1103 	umtxq_unlock(&key);
1104 	umtx_key_release(&key);
1105 	return (0);
1106 }
1107 
1108 /*
1109  * Lock PTHREAD_PRIO_NONE protocol POSIX mutex.
1110  */
1111 static int
1112 _do_lock_normal(struct thread *td, struct umutex *m, uint32_t flags, int timo,
1113 	int mode)
1114 {
1115 	struct umtx_q *uq;
1116 	uint32_t owner, old, id;
1117 	int error = 0;
1118 
1119 	id = td->td_tid;
1120 	uq = td->td_umtxq;
1121 
1122 	/*
1123 	 * Care must be exercised when dealing with umtx structure. It
1124 	 * can fault on any access.
1125 	 */
1126 	for (;;) {
1127 		owner = fuword32(__DEVOLATILE(void *, &m->m_owner));
1128 		if (mode == _UMUTEX_WAIT) {
1129 			if (owner == UMUTEX_UNOWNED || owner == UMUTEX_CONTESTED)
1130 				return (0);
1131 		} else {
1132 			/*
1133 			 * Try the uncontested case.  This should be done in userland.
1134 			 */
1135 			owner = casuword32(&m->m_owner, UMUTEX_UNOWNED, id);
1136 
1137 			/* The acquire succeeded. */
1138 			if (owner == UMUTEX_UNOWNED)
1139 				return (0);
1140 
1141 			/* The address was invalid. */
1142 			if (owner == -1)
1143 				return (EFAULT);
1144 
1145 			/* If no one owns it but it is contested try to acquire it. */
1146 			if (owner == UMUTEX_CONTESTED) {
1147 				owner = casuword32(&m->m_owner,
1148 				    UMUTEX_CONTESTED, id | UMUTEX_CONTESTED);
1149 
1150 				if (owner == UMUTEX_CONTESTED)
1151 					return (0);
1152 
1153 				/* The address was invalid. */
1154 				if (owner == -1)
1155 					return (EFAULT);
1156 
1157 				/* If this failed the lock has changed, restart. */
1158 				continue;
1159 			}
1160 		}
1161 
1162 		if ((flags & UMUTEX_ERROR_CHECK) != 0 &&
1163 		    (owner & ~UMUTEX_CONTESTED) == id)
1164 			return (EDEADLK);
1165 
1166 		if (mode == _UMUTEX_TRY)
1167 			return (EBUSY);
1168 
1169 		/*
1170 		 * If we caught a signal, we have retried and now
1171 		 * exit immediately.
1172 		 */
1173 		if (error != 0)
1174 			return (error);
1175 
1176 		if ((error = umtx_key_get(m, TYPE_NORMAL_UMUTEX,
1177 		    GET_SHARE(flags), &uq->uq_key)) != 0)
1178 			return (error);
1179 
1180 		umtxq_lock(&uq->uq_key);
1181 		umtxq_busy(&uq->uq_key);
1182 		umtxq_insert(uq);
1183 		umtxq_unlock(&uq->uq_key);
1184 
1185 		/*
1186 		 * Set the contested bit so that a release in user space
1187 		 * knows to use the system call for unlock.  If this fails
1188 		 * either some one else has acquired the lock or it has been
1189 		 * released.
1190 		 */
1191 		old = casuword32(&m->m_owner, owner, owner | UMUTEX_CONTESTED);
1192 
1193 		/* The address was invalid. */
1194 		if (old == -1) {
1195 			umtxq_lock(&uq->uq_key);
1196 			umtxq_remove(uq);
1197 			umtxq_unbusy(&uq->uq_key);
1198 			umtxq_unlock(&uq->uq_key);
1199 			umtx_key_release(&uq->uq_key);
1200 			return (EFAULT);
1201 		}
1202 
1203 		/*
1204 		 * We set the contested bit, sleep. Otherwise the lock changed
1205 		 * and we need to retry or we lost a race to the thread
1206 		 * unlocking the umtx.
1207 		 */
1208 		umtxq_lock(&uq->uq_key);
1209 		umtxq_unbusy(&uq->uq_key);
1210 		if (old == owner)
1211 			error = umtxq_sleep(uq, "umtxn", timo);
1212 		umtxq_remove(uq);
1213 		umtxq_unlock(&uq->uq_key);
1214 		umtx_key_release(&uq->uq_key);
1215 	}
1216 
1217 	return (0);
1218 }
1219 
1220 /*
1221  * Lock PTHREAD_PRIO_NONE protocol POSIX mutex.
1222  */
1223 /*
1224  * Unlock PTHREAD_PRIO_NONE protocol POSIX mutex.
1225  */
1226 static int
1227 do_unlock_normal(struct thread *td, struct umutex *m, uint32_t flags)
1228 {
1229 	struct umtx_key key;
1230 	uint32_t owner, old, id;
1231 	int error;
1232 	int count;
1233 
1234 	id = td->td_tid;
1235 	/*
1236 	 * Make sure we own this mtx.
1237 	 */
1238 	owner = fuword32(__DEVOLATILE(uint32_t *, &m->m_owner));
1239 	if (owner == -1)
1240 		return (EFAULT);
1241 
1242 	if ((owner & ~UMUTEX_CONTESTED) != id)
1243 		return (EPERM);
1244 
1245 	if ((owner & UMUTEX_CONTESTED) == 0) {
1246 		old = casuword32(&m->m_owner, owner, UMUTEX_UNOWNED);
1247 		if (old == -1)
1248 			return (EFAULT);
1249 		if (old == owner)
1250 			return (0);
1251 		owner = old;
1252 	}
1253 
1254 	/* We should only ever be in here for contested locks */
1255 	if ((error = umtx_key_get(m, TYPE_NORMAL_UMUTEX, GET_SHARE(flags),
1256 	    &key)) != 0)
1257 		return (error);
1258 
1259 	umtxq_lock(&key);
1260 	umtxq_busy(&key);
1261 	count = umtxq_count(&key);
1262 	umtxq_unlock(&key);
1263 
1264 	/*
1265 	 * When unlocking the umtx, it must be marked as unowned if
1266 	 * there is zero or one thread only waiting for it.
1267 	 * Otherwise, it must be marked as contested.
1268 	 */
1269 	old = casuword32(&m->m_owner, owner,
1270 		count <= 1 ? UMUTEX_UNOWNED : UMUTEX_CONTESTED);
1271 	umtxq_lock(&key);
1272 	umtxq_signal(&key,1);
1273 	umtxq_unbusy(&key);
1274 	umtxq_unlock(&key);
1275 	umtx_key_release(&key);
1276 	if (old == -1)
1277 		return (EFAULT);
1278 	if (old != owner)
1279 		return (EINVAL);
1280 	return (0);
1281 }
1282 
1283 /*
1284  * Check if the mutex is available and wake up a waiter,
1285  * only for simple mutex.
1286  */
1287 static int
1288 do_wake_umutex(struct thread *td, struct umutex *m)
1289 {
1290 	struct umtx_key key;
1291 	uint32_t owner;
1292 	uint32_t flags;
1293 	int error;
1294 	int count;
1295 
1296 	owner = fuword32(__DEVOLATILE(uint32_t *, &m->m_owner));
1297 	if (owner == -1)
1298 		return (EFAULT);
1299 
1300 	if ((owner & ~UMUTEX_CONTESTED) != 0)
1301 		return (0);
1302 
1303 	flags = fuword32(&m->m_flags);
1304 
1305 	/* We should only ever be in here for contested locks */
1306 	if ((error = umtx_key_get(m, TYPE_NORMAL_UMUTEX, GET_SHARE(flags),
1307 	    &key)) != 0)
1308 		return (error);
1309 
1310 	umtxq_lock(&key);
1311 	umtxq_busy(&key);
1312 	count = umtxq_count(&key);
1313 	umtxq_unlock(&key);
1314 
1315 	if (count <= 1)
1316 		owner = casuword32(&m->m_owner, UMUTEX_CONTESTED, UMUTEX_UNOWNED);
1317 
1318 	umtxq_lock(&key);
1319 	if (count != 0 && (owner & ~UMUTEX_CONTESTED) == 0)
1320 		umtxq_signal(&key, 1);
1321 	umtxq_unbusy(&key);
1322 	umtxq_unlock(&key);
1323 	umtx_key_release(&key);
1324 	return (0);
1325 }
1326 
1327 static inline struct umtx_pi *
1328 umtx_pi_alloc(int flags)
1329 {
1330 	struct umtx_pi *pi;
1331 
1332 	pi = uma_zalloc(umtx_pi_zone, M_ZERO | flags);
1333 	TAILQ_INIT(&pi->pi_blocked);
1334 	atomic_add_int(&umtx_pi_allocated, 1);
1335 	return (pi);
1336 }
1337 
1338 static inline void
1339 umtx_pi_free(struct umtx_pi *pi)
1340 {
1341 	uma_zfree(umtx_pi_zone, pi);
1342 	atomic_add_int(&umtx_pi_allocated, -1);
1343 }
1344 
1345 /*
1346  * Adjust the thread's position on a pi_state after its priority has been
1347  * changed.
1348  */
1349 static int
1350 umtx_pi_adjust_thread(struct umtx_pi *pi, struct thread *td)
1351 {
1352 	struct umtx_q *uq, *uq1, *uq2;
1353 	struct thread *td1;
1354 
1355 	mtx_assert(&umtx_lock, MA_OWNED);
1356 	if (pi == NULL)
1357 		return (0);
1358 
1359 	uq = td->td_umtxq;
1360 
1361 	/*
1362 	 * Check if the thread needs to be moved on the blocked chain.
1363 	 * It needs to be moved if either its priority is lower than
1364 	 * the previous thread or higher than the next thread.
1365 	 */
1366 	uq1 = TAILQ_PREV(uq, umtxq_head, uq_lockq);
1367 	uq2 = TAILQ_NEXT(uq, uq_lockq);
1368 	if ((uq1 != NULL && UPRI(td) < UPRI(uq1->uq_thread)) ||
1369 	    (uq2 != NULL && UPRI(td) > UPRI(uq2->uq_thread))) {
1370 		/*
1371 		 * Remove thread from blocked chain and determine where
1372 		 * it should be moved to.
1373 		 */
1374 		TAILQ_REMOVE(&pi->pi_blocked, uq, uq_lockq);
1375 		TAILQ_FOREACH(uq1, &pi->pi_blocked, uq_lockq) {
1376 			td1 = uq1->uq_thread;
1377 			MPASS(td1->td_proc->p_magic == P_MAGIC);
1378 			if (UPRI(td1) > UPRI(td))
1379 				break;
1380 		}
1381 
1382 		if (uq1 == NULL)
1383 			TAILQ_INSERT_TAIL(&pi->pi_blocked, uq, uq_lockq);
1384 		else
1385 			TAILQ_INSERT_BEFORE(uq1, uq, uq_lockq);
1386 	}
1387 	return (1);
1388 }
1389 
1390 /*
1391  * Propagate priority when a thread is blocked on POSIX
1392  * PI mutex.
1393  */
1394 static void
1395 umtx_propagate_priority(struct thread *td)
1396 {
1397 	struct umtx_q *uq;
1398 	struct umtx_pi *pi;
1399 	int pri;
1400 
1401 	mtx_assert(&umtx_lock, MA_OWNED);
1402 	pri = UPRI(td);
1403 	uq = td->td_umtxq;
1404 	pi = uq->uq_pi_blocked;
1405 	if (pi == NULL)
1406 		return;
1407 
1408 	for (;;) {
1409 		td = pi->pi_owner;
1410 		if (td == NULL)
1411 			return;
1412 
1413 		MPASS(td->td_proc != NULL);
1414 		MPASS(td->td_proc->p_magic == P_MAGIC);
1415 
1416 		if (UPRI(td) <= pri)
1417 			return;
1418 
1419 		thread_lock(td);
1420 		sched_lend_user_prio(td, pri);
1421 		thread_unlock(td);
1422 
1423 		/*
1424 		 * Pick up the lock that td is blocked on.
1425 		 */
1426 		uq = td->td_umtxq;
1427 		pi = uq->uq_pi_blocked;
1428 		/* Resort td on the list if needed. */
1429 		if (!umtx_pi_adjust_thread(pi, td))
1430 			break;
1431 	}
1432 }
1433 
1434 /*
1435  * Unpropagate priority for a PI mutex when a thread blocked on
1436  * it is interrupted by signal or resumed by others.
1437  */
1438 static void
1439 umtx_unpropagate_priority(struct umtx_pi *pi)
1440 {
1441 	struct umtx_q *uq, *uq_owner;
1442 	struct umtx_pi *pi2;
1443 	int pri, oldpri;
1444 
1445 	mtx_assert(&umtx_lock, MA_OWNED);
1446 
1447 	while (pi != NULL && pi->pi_owner != NULL) {
1448 		pri = PRI_MAX;
1449 		uq_owner = pi->pi_owner->td_umtxq;
1450 
1451 		TAILQ_FOREACH(pi2, &uq_owner->uq_pi_contested, pi_link) {
1452 			uq = TAILQ_FIRST(&pi2->pi_blocked);
1453 			if (uq != NULL) {
1454 				if (pri > UPRI(uq->uq_thread))
1455 					pri = UPRI(uq->uq_thread);
1456 			}
1457 		}
1458 
1459 		if (pri > uq_owner->uq_inherited_pri)
1460 			pri = uq_owner->uq_inherited_pri;
1461 		thread_lock(pi->pi_owner);
1462 		oldpri = pi->pi_owner->td_user_pri;
1463 		sched_unlend_user_prio(pi->pi_owner, pri);
1464 		thread_unlock(pi->pi_owner);
1465 		if (uq_owner->uq_pi_blocked != NULL)
1466 			umtx_pi_adjust_locked(pi->pi_owner, oldpri);
1467 		pi = uq_owner->uq_pi_blocked;
1468 	}
1469 }
1470 
1471 /*
1472  * Insert a PI mutex into owned list.
1473  */
1474 static void
1475 umtx_pi_setowner(struct umtx_pi *pi, struct thread *owner)
1476 {
1477 	struct umtx_q *uq_owner;
1478 
1479 	uq_owner = owner->td_umtxq;
1480 	mtx_assert(&umtx_lock, MA_OWNED);
1481 	if (pi->pi_owner != NULL)
1482 		panic("pi_ower != NULL");
1483 	pi->pi_owner = owner;
1484 	TAILQ_INSERT_TAIL(&uq_owner->uq_pi_contested, pi, pi_link);
1485 }
1486 
1487 /*
1488  * Claim ownership of a PI mutex.
1489  */
1490 static int
1491 umtx_pi_claim(struct umtx_pi *pi, struct thread *owner)
1492 {
1493 	struct umtx_q *uq, *uq_owner;
1494 
1495 	uq_owner = owner->td_umtxq;
1496 	mtx_lock_spin(&umtx_lock);
1497 	if (pi->pi_owner == owner) {
1498 		mtx_unlock_spin(&umtx_lock);
1499 		return (0);
1500 	}
1501 
1502 	if (pi->pi_owner != NULL) {
1503 		/*
1504 		 * userland may have already messed the mutex, sigh.
1505 		 */
1506 		mtx_unlock_spin(&umtx_lock);
1507 		return (EPERM);
1508 	}
1509 	umtx_pi_setowner(pi, owner);
1510 	uq = TAILQ_FIRST(&pi->pi_blocked);
1511 	if (uq != NULL) {
1512 		int pri;
1513 
1514 		pri = UPRI(uq->uq_thread);
1515 		thread_lock(owner);
1516 		if (pri < UPRI(owner))
1517 			sched_lend_user_prio(owner, pri);
1518 		thread_unlock(owner);
1519 	}
1520 	mtx_unlock_spin(&umtx_lock);
1521 	return (0);
1522 }
1523 
1524 static void
1525 umtx_pi_adjust_locked(struct thread *td, u_char oldpri)
1526 {
1527 	struct umtx_q *uq;
1528 	struct umtx_pi *pi;
1529 
1530 	uq = td->td_umtxq;
1531 	/*
1532 	 * Pick up the lock that td is blocked on.
1533 	 */
1534 	pi = uq->uq_pi_blocked;
1535 	MPASS(pi != NULL);
1536 
1537 	/* Resort the turnstile on the list. */
1538 	if (!umtx_pi_adjust_thread(pi, td))
1539 		return;
1540 
1541 	/*
1542 	 * If our priority was lowered and we are at the head of the
1543 	 * turnstile, then propagate our new priority up the chain.
1544 	 */
1545 	if (uq == TAILQ_FIRST(&pi->pi_blocked) && UPRI(td) < oldpri)
1546 		umtx_propagate_priority(td);
1547 }
1548 
1549 /*
1550  * Adjust a thread's order position in its blocked PI mutex,
1551  * this may result new priority propagating process.
1552  */
1553 void
1554 umtx_pi_adjust(struct thread *td, u_char oldpri)
1555 {
1556 	struct umtx_q *uq;
1557 	struct umtx_pi *pi;
1558 
1559 	uq = td->td_umtxq;
1560 	mtx_lock_spin(&umtx_lock);
1561 	/*
1562 	 * Pick up the lock that td is blocked on.
1563 	 */
1564 	pi = uq->uq_pi_blocked;
1565 	if (pi != NULL)
1566 		umtx_pi_adjust_locked(td, oldpri);
1567 	mtx_unlock_spin(&umtx_lock);
1568 }
1569 
1570 /*
1571  * Sleep on a PI mutex.
1572  */
1573 static int
1574 umtxq_sleep_pi(struct umtx_q *uq, struct umtx_pi *pi,
1575 	uint32_t owner, const char *wmesg, int timo)
1576 {
1577 	struct umtxq_chain *uc;
1578 	struct thread *td, *td1;
1579 	struct umtx_q *uq1;
1580 	int pri;
1581 	int error = 0;
1582 
1583 	td = uq->uq_thread;
1584 	KASSERT(td == curthread, ("inconsistent uq_thread"));
1585 	uc = umtxq_getchain(&uq->uq_key);
1586 	UMTXQ_LOCKED_ASSERT(uc);
1587 	UMTXQ_BUSY_ASSERT(uc);
1588 	umtxq_insert(uq);
1589 	mtx_lock_spin(&umtx_lock);
1590 	if (pi->pi_owner == NULL) {
1591 		/* XXX
1592 		 * Current, We only support process private PI-mutex,
1593 		 * we need a faster way to find an owner thread for
1594 		 * process-shared mutex (not available yet).
1595 		 */
1596 		mtx_unlock_spin(&umtx_lock);
1597 		PROC_LOCK(curproc);
1598 		td1 = thread_find(curproc, owner);
1599 		mtx_lock_spin(&umtx_lock);
1600 		if (td1 != NULL && pi->pi_owner == NULL) {
1601 			uq1 = td1->td_umtxq;
1602 			umtx_pi_setowner(pi, td1);
1603 		}
1604 		PROC_UNLOCK(curproc);
1605 	}
1606 
1607 	TAILQ_FOREACH(uq1, &pi->pi_blocked, uq_lockq) {
1608 		pri = UPRI(uq1->uq_thread);
1609 		if (pri > UPRI(td))
1610 			break;
1611 	}
1612 
1613 	if (uq1 != NULL)
1614 		TAILQ_INSERT_BEFORE(uq1, uq, uq_lockq);
1615 	else
1616 		TAILQ_INSERT_TAIL(&pi->pi_blocked, uq, uq_lockq);
1617 
1618 	uq->uq_pi_blocked = pi;
1619 	thread_lock(td);
1620 	td->td_flags |= TDF_UPIBLOCKED;
1621 	thread_unlock(td);
1622 	umtx_propagate_priority(td);
1623 	mtx_unlock_spin(&umtx_lock);
1624 	umtxq_unbusy(&uq->uq_key);
1625 
1626 	if (uq->uq_flags & UQF_UMTXQ) {
1627 		error = msleep(uq, &uc->uc_lock, PCATCH, wmesg, timo);
1628 		if (error == EWOULDBLOCK)
1629 			error = ETIMEDOUT;
1630 		if (uq->uq_flags & UQF_UMTXQ) {
1631 			umtxq_remove(uq);
1632 		}
1633 	}
1634 	mtx_lock_spin(&umtx_lock);
1635 	uq->uq_pi_blocked = NULL;
1636 	thread_lock(td);
1637 	td->td_flags &= ~TDF_UPIBLOCKED;
1638 	thread_unlock(td);
1639 	TAILQ_REMOVE(&pi->pi_blocked, uq, uq_lockq);
1640 	umtx_unpropagate_priority(pi);
1641 	mtx_unlock_spin(&umtx_lock);
1642 	umtxq_unlock(&uq->uq_key);
1643 
1644 	return (error);
1645 }
1646 
1647 /*
1648  * Add reference count for a PI mutex.
1649  */
1650 static void
1651 umtx_pi_ref(struct umtx_pi *pi)
1652 {
1653 	struct umtxq_chain *uc;
1654 
1655 	uc = umtxq_getchain(&pi->pi_key);
1656 	UMTXQ_LOCKED_ASSERT(uc);
1657 	pi->pi_refcount++;
1658 }
1659 
1660 /*
1661  * Decrease reference count for a PI mutex, if the counter
1662  * is decreased to zero, its memory space is freed.
1663  */
1664 static void
1665 umtx_pi_unref(struct umtx_pi *pi)
1666 {
1667 	struct umtxq_chain *uc;
1668 
1669 	uc = umtxq_getchain(&pi->pi_key);
1670 	UMTXQ_LOCKED_ASSERT(uc);
1671 	KASSERT(pi->pi_refcount > 0, ("invalid reference count"));
1672 	if (--pi->pi_refcount == 0) {
1673 		mtx_lock_spin(&umtx_lock);
1674 		if (pi->pi_owner != NULL) {
1675 			TAILQ_REMOVE(&pi->pi_owner->td_umtxq->uq_pi_contested,
1676 				pi, pi_link);
1677 			pi->pi_owner = NULL;
1678 		}
1679 		KASSERT(TAILQ_EMPTY(&pi->pi_blocked),
1680 			("blocked queue not empty"));
1681 		mtx_unlock_spin(&umtx_lock);
1682 		TAILQ_REMOVE(&uc->uc_pi_list, pi, pi_hashlink);
1683 		umtx_pi_free(pi);
1684 	}
1685 }
1686 
1687 /*
1688  * Find a PI mutex in hash table.
1689  */
1690 static struct umtx_pi *
1691 umtx_pi_lookup(struct umtx_key *key)
1692 {
1693 	struct umtxq_chain *uc;
1694 	struct umtx_pi *pi;
1695 
1696 	uc = umtxq_getchain(key);
1697 	UMTXQ_LOCKED_ASSERT(uc);
1698 
1699 	TAILQ_FOREACH(pi, &uc->uc_pi_list, pi_hashlink) {
1700 		if (umtx_key_match(&pi->pi_key, key)) {
1701 			return (pi);
1702 		}
1703 	}
1704 	return (NULL);
1705 }
1706 
1707 /*
1708  * Insert a PI mutex into hash table.
1709  */
1710 static inline void
1711 umtx_pi_insert(struct umtx_pi *pi)
1712 {
1713 	struct umtxq_chain *uc;
1714 
1715 	uc = umtxq_getchain(&pi->pi_key);
1716 	UMTXQ_LOCKED_ASSERT(uc);
1717 	TAILQ_INSERT_TAIL(&uc->uc_pi_list, pi, pi_hashlink);
1718 }
1719 
1720 /*
1721  * Lock a PI mutex.
1722  */
1723 static int
1724 _do_lock_pi(struct thread *td, struct umutex *m, uint32_t flags, int timo,
1725 	int try)
1726 {
1727 	struct umtx_q *uq;
1728 	struct umtx_pi *pi, *new_pi;
1729 	uint32_t id, owner, old;
1730 	int error;
1731 
1732 	id = td->td_tid;
1733 	uq = td->td_umtxq;
1734 
1735 	if ((error = umtx_key_get(m, TYPE_PI_UMUTEX, GET_SHARE(flags),
1736 	    &uq->uq_key)) != 0)
1737 		return (error);
1738 	umtxq_lock(&uq->uq_key);
1739 	pi = umtx_pi_lookup(&uq->uq_key);
1740 	if (pi == NULL) {
1741 		new_pi = umtx_pi_alloc(M_NOWAIT);
1742 		if (new_pi == NULL) {
1743 			umtxq_unlock(&uq->uq_key);
1744 			new_pi = umtx_pi_alloc(M_WAITOK);
1745 			umtxq_lock(&uq->uq_key);
1746 			pi = umtx_pi_lookup(&uq->uq_key);
1747 			if (pi != NULL) {
1748 				umtx_pi_free(new_pi);
1749 				new_pi = NULL;
1750 			}
1751 		}
1752 		if (new_pi != NULL) {
1753 			new_pi->pi_key = uq->uq_key;
1754 			umtx_pi_insert(new_pi);
1755 			pi = new_pi;
1756 		}
1757 	}
1758 	umtx_pi_ref(pi);
1759 	umtxq_unlock(&uq->uq_key);
1760 
1761 	/*
1762 	 * Care must be exercised when dealing with umtx structure.  It
1763 	 * can fault on any access.
1764 	 */
1765 	for (;;) {
1766 		/*
1767 		 * Try the uncontested case.  This should be done in userland.
1768 		 */
1769 		owner = casuword32(&m->m_owner, UMUTEX_UNOWNED, id);
1770 
1771 		/* The acquire succeeded. */
1772 		if (owner == UMUTEX_UNOWNED) {
1773 			error = 0;
1774 			break;
1775 		}
1776 
1777 		/* The address was invalid. */
1778 		if (owner == -1) {
1779 			error = EFAULT;
1780 			break;
1781 		}
1782 
1783 		/* If no one owns it but it is contested try to acquire it. */
1784 		if (owner == UMUTEX_CONTESTED) {
1785 			owner = casuword32(&m->m_owner,
1786 			    UMUTEX_CONTESTED, id | UMUTEX_CONTESTED);
1787 
1788 			if (owner == UMUTEX_CONTESTED) {
1789 				umtxq_lock(&uq->uq_key);
1790 				umtxq_busy(&uq->uq_key);
1791 				error = umtx_pi_claim(pi, td);
1792 				umtxq_unbusy(&uq->uq_key);
1793 				umtxq_unlock(&uq->uq_key);
1794 				break;
1795 			}
1796 
1797 			/* The address was invalid. */
1798 			if (owner == -1) {
1799 				error = EFAULT;
1800 				break;
1801 			}
1802 
1803 			/* If this failed the lock has changed, restart. */
1804 			continue;
1805 		}
1806 
1807 		if ((flags & UMUTEX_ERROR_CHECK) != 0 &&
1808 		    (owner & ~UMUTEX_CONTESTED) == id) {
1809 			error = EDEADLK;
1810 			break;
1811 		}
1812 
1813 		if (try != 0) {
1814 			error = EBUSY;
1815 			break;
1816 		}
1817 
1818 		/*
1819 		 * If we caught a signal, we have retried and now
1820 		 * exit immediately.
1821 		 */
1822 		if (error != 0)
1823 			break;
1824 
1825 		umtxq_lock(&uq->uq_key);
1826 		umtxq_busy(&uq->uq_key);
1827 		umtxq_unlock(&uq->uq_key);
1828 
1829 		/*
1830 		 * Set the contested bit so that a release in user space
1831 		 * knows to use the system call for unlock.  If this fails
1832 		 * either some one else has acquired the lock or it has been
1833 		 * released.
1834 		 */
1835 		old = casuword32(&m->m_owner, owner, owner | UMUTEX_CONTESTED);
1836 
1837 		/* The address was invalid. */
1838 		if (old == -1) {
1839 			umtxq_lock(&uq->uq_key);
1840 			umtxq_unbusy(&uq->uq_key);
1841 			umtxq_unlock(&uq->uq_key);
1842 			error = EFAULT;
1843 			break;
1844 		}
1845 
1846 		umtxq_lock(&uq->uq_key);
1847 		/*
1848 		 * We set the contested bit, sleep. Otherwise the lock changed
1849 		 * and we need to retry or we lost a race to the thread
1850 		 * unlocking the umtx.
1851 		 */
1852 		if (old == owner)
1853 			error = umtxq_sleep_pi(uq, pi, owner & ~UMUTEX_CONTESTED,
1854 				 "umtxpi", timo);
1855 		else {
1856 			umtxq_unbusy(&uq->uq_key);
1857 			umtxq_unlock(&uq->uq_key);
1858 		}
1859 	}
1860 
1861 	umtxq_lock(&uq->uq_key);
1862 	umtx_pi_unref(pi);
1863 	umtxq_unlock(&uq->uq_key);
1864 
1865 	umtx_key_release(&uq->uq_key);
1866 	return (error);
1867 }
1868 
1869 /*
1870  * Unlock a PI mutex.
1871  */
1872 static int
1873 do_unlock_pi(struct thread *td, struct umutex *m, uint32_t flags)
1874 {
1875 	struct umtx_key key;
1876 	struct umtx_q *uq_first, *uq_first2, *uq_me;
1877 	struct umtx_pi *pi, *pi2;
1878 	uint32_t owner, old, id;
1879 	int error;
1880 	int count;
1881 	int pri;
1882 
1883 	id = td->td_tid;
1884 	/*
1885 	 * Make sure we own this mtx.
1886 	 */
1887 	owner = fuword32(__DEVOLATILE(uint32_t *, &m->m_owner));
1888 	if (owner == -1)
1889 		return (EFAULT);
1890 
1891 	if ((owner & ~UMUTEX_CONTESTED) != id)
1892 		return (EPERM);
1893 
1894 	/* This should be done in userland */
1895 	if ((owner & UMUTEX_CONTESTED) == 0) {
1896 		old = casuword32(&m->m_owner, owner, UMUTEX_UNOWNED);
1897 		if (old == -1)
1898 			return (EFAULT);
1899 		if (old == owner)
1900 			return (0);
1901 		owner = old;
1902 	}
1903 
1904 	/* We should only ever be in here for contested locks */
1905 	if ((error = umtx_key_get(m, TYPE_PI_UMUTEX, GET_SHARE(flags),
1906 	    &key)) != 0)
1907 		return (error);
1908 
1909 	umtxq_lock(&key);
1910 	umtxq_busy(&key);
1911 	count = umtxq_count_pi(&key, &uq_first);
1912 	if (uq_first != NULL) {
1913 		mtx_lock_spin(&umtx_lock);
1914 		pi = uq_first->uq_pi_blocked;
1915 		KASSERT(pi != NULL, ("pi == NULL?"));
1916 		if (pi->pi_owner != curthread) {
1917 			mtx_unlock_spin(&umtx_lock);
1918 			umtxq_unbusy(&key);
1919 			umtxq_unlock(&key);
1920 			umtx_key_release(&key);
1921 			/* userland messed the mutex */
1922 			return (EPERM);
1923 		}
1924 		uq_me = curthread->td_umtxq;
1925 		pi->pi_owner = NULL;
1926 		TAILQ_REMOVE(&uq_me->uq_pi_contested, pi, pi_link);
1927 		/* get highest priority thread which is still sleeping. */
1928 		uq_first = TAILQ_FIRST(&pi->pi_blocked);
1929 		while (uq_first != NULL &&
1930 		       (uq_first->uq_flags & UQF_UMTXQ) == 0) {
1931 			uq_first = TAILQ_NEXT(uq_first, uq_lockq);
1932 		}
1933 		pri = PRI_MAX;
1934 		TAILQ_FOREACH(pi2, &uq_me->uq_pi_contested, pi_link) {
1935 			uq_first2 = TAILQ_FIRST(&pi2->pi_blocked);
1936 			if (uq_first2 != NULL) {
1937 				if (pri > UPRI(uq_first2->uq_thread))
1938 					pri = UPRI(uq_first2->uq_thread);
1939 			}
1940 		}
1941 		thread_lock(curthread);
1942 		sched_unlend_user_prio(curthread, pri);
1943 		thread_unlock(curthread);
1944 		mtx_unlock_spin(&umtx_lock);
1945 		if (uq_first)
1946 			umtxq_signal_thread(uq_first);
1947 	}
1948 	umtxq_unlock(&key);
1949 
1950 	/*
1951 	 * When unlocking the umtx, it must be marked as unowned if
1952 	 * there is zero or one thread only waiting for it.
1953 	 * Otherwise, it must be marked as contested.
1954 	 */
1955 	old = casuword32(&m->m_owner, owner,
1956 		count <= 1 ? UMUTEX_UNOWNED : UMUTEX_CONTESTED);
1957 
1958 	umtxq_lock(&key);
1959 	umtxq_unbusy(&key);
1960 	umtxq_unlock(&key);
1961 	umtx_key_release(&key);
1962 	if (old == -1)
1963 		return (EFAULT);
1964 	if (old != owner)
1965 		return (EINVAL);
1966 	return (0);
1967 }
1968 
1969 /*
1970  * Lock a PP mutex.
1971  */
1972 static int
1973 _do_lock_pp(struct thread *td, struct umutex *m, uint32_t flags, int timo,
1974 	int try)
1975 {
1976 	struct umtx_q *uq, *uq2;
1977 	struct umtx_pi *pi;
1978 	uint32_t ceiling;
1979 	uint32_t owner, id;
1980 	int error, pri, old_inherited_pri, su;
1981 
1982 	id = td->td_tid;
1983 	uq = td->td_umtxq;
1984 	if ((error = umtx_key_get(m, TYPE_PP_UMUTEX, GET_SHARE(flags),
1985 	    &uq->uq_key)) != 0)
1986 		return (error);
1987 	su = (priv_check(td, PRIV_SCHED_RTPRIO) == 0);
1988 	for (;;) {
1989 		old_inherited_pri = uq->uq_inherited_pri;
1990 		umtxq_lock(&uq->uq_key);
1991 		umtxq_busy(&uq->uq_key);
1992 		umtxq_unlock(&uq->uq_key);
1993 
1994 		ceiling = RTP_PRIO_MAX - fuword32(&m->m_ceilings[0]);
1995 		if (ceiling > RTP_PRIO_MAX) {
1996 			error = EINVAL;
1997 			goto out;
1998 		}
1999 
2000 		mtx_lock_spin(&umtx_lock);
2001 		if (UPRI(td) < PRI_MIN_REALTIME + ceiling) {
2002 			mtx_unlock_spin(&umtx_lock);
2003 			error = EINVAL;
2004 			goto out;
2005 		}
2006 		if (su && PRI_MIN_REALTIME + ceiling < uq->uq_inherited_pri) {
2007 			uq->uq_inherited_pri = PRI_MIN_REALTIME + ceiling;
2008 			thread_lock(td);
2009 			if (uq->uq_inherited_pri < UPRI(td))
2010 				sched_lend_user_prio(td, uq->uq_inherited_pri);
2011 			thread_unlock(td);
2012 		}
2013 		mtx_unlock_spin(&umtx_lock);
2014 
2015 		owner = casuword32(&m->m_owner,
2016 		    UMUTEX_CONTESTED, id | UMUTEX_CONTESTED);
2017 
2018 		if (owner == UMUTEX_CONTESTED) {
2019 			error = 0;
2020 			break;
2021 		}
2022 
2023 		/* The address was invalid. */
2024 		if (owner == -1) {
2025 			error = EFAULT;
2026 			break;
2027 		}
2028 
2029 		if ((flags & UMUTEX_ERROR_CHECK) != 0 &&
2030 		    (owner & ~UMUTEX_CONTESTED) == id) {
2031 			error = EDEADLK;
2032 			break;
2033 		}
2034 
2035 		if (try != 0) {
2036 			error = EBUSY;
2037 			break;
2038 		}
2039 
2040 		/*
2041 		 * If we caught a signal, we have retried and now
2042 		 * exit immediately.
2043 		 */
2044 		if (error != 0)
2045 			break;
2046 
2047 		umtxq_lock(&uq->uq_key);
2048 		umtxq_insert(uq);
2049 		umtxq_unbusy(&uq->uq_key);
2050 		error = umtxq_sleep(uq, "umtxpp", timo);
2051 		umtxq_remove(uq);
2052 		umtxq_unlock(&uq->uq_key);
2053 
2054 		mtx_lock_spin(&umtx_lock);
2055 		uq->uq_inherited_pri = old_inherited_pri;
2056 		pri = PRI_MAX;
2057 		TAILQ_FOREACH(pi, &uq->uq_pi_contested, pi_link) {
2058 			uq2 = TAILQ_FIRST(&pi->pi_blocked);
2059 			if (uq2 != NULL) {
2060 				if (pri > UPRI(uq2->uq_thread))
2061 					pri = UPRI(uq2->uq_thread);
2062 			}
2063 		}
2064 		if (pri > uq->uq_inherited_pri)
2065 			pri = uq->uq_inherited_pri;
2066 		thread_lock(td);
2067 		sched_unlend_user_prio(td, pri);
2068 		thread_unlock(td);
2069 		mtx_unlock_spin(&umtx_lock);
2070 	}
2071 
2072 	if (error != 0) {
2073 		mtx_lock_spin(&umtx_lock);
2074 		uq->uq_inherited_pri = old_inherited_pri;
2075 		pri = PRI_MAX;
2076 		TAILQ_FOREACH(pi, &uq->uq_pi_contested, pi_link) {
2077 			uq2 = TAILQ_FIRST(&pi->pi_blocked);
2078 			if (uq2 != NULL) {
2079 				if (pri > UPRI(uq2->uq_thread))
2080 					pri = UPRI(uq2->uq_thread);
2081 			}
2082 		}
2083 		if (pri > uq->uq_inherited_pri)
2084 			pri = uq->uq_inherited_pri;
2085 		thread_lock(td);
2086 		sched_unlend_user_prio(td, pri);
2087 		thread_unlock(td);
2088 		mtx_unlock_spin(&umtx_lock);
2089 	}
2090 
2091 out:
2092 	umtxq_lock(&uq->uq_key);
2093 	umtxq_unbusy(&uq->uq_key);
2094 	umtxq_unlock(&uq->uq_key);
2095 	umtx_key_release(&uq->uq_key);
2096 	return (error);
2097 }
2098 
2099 /*
2100  * Unlock a PP mutex.
2101  */
2102 static int
2103 do_unlock_pp(struct thread *td, struct umutex *m, uint32_t flags)
2104 {
2105 	struct umtx_key key;
2106 	struct umtx_q *uq, *uq2;
2107 	struct umtx_pi *pi;
2108 	uint32_t owner, id;
2109 	uint32_t rceiling;
2110 	int error, pri, new_inherited_pri, su;
2111 
2112 	id = td->td_tid;
2113 	uq = td->td_umtxq;
2114 	su = (priv_check(td, PRIV_SCHED_RTPRIO) == 0);
2115 
2116 	/*
2117 	 * Make sure we own this mtx.
2118 	 */
2119 	owner = fuword32(__DEVOLATILE(uint32_t *, &m->m_owner));
2120 	if (owner == -1)
2121 		return (EFAULT);
2122 
2123 	if ((owner & ~UMUTEX_CONTESTED) != id)
2124 		return (EPERM);
2125 
2126 	error = copyin(&m->m_ceilings[1], &rceiling, sizeof(uint32_t));
2127 	if (error != 0)
2128 		return (error);
2129 
2130 	if (rceiling == -1)
2131 		new_inherited_pri = PRI_MAX;
2132 	else {
2133 		rceiling = RTP_PRIO_MAX - rceiling;
2134 		if (rceiling > RTP_PRIO_MAX)
2135 			return (EINVAL);
2136 		new_inherited_pri = PRI_MIN_REALTIME + rceiling;
2137 	}
2138 
2139 	if ((error = umtx_key_get(m, TYPE_PP_UMUTEX, GET_SHARE(flags),
2140 	    &key)) != 0)
2141 		return (error);
2142 	umtxq_lock(&key);
2143 	umtxq_busy(&key);
2144 	umtxq_unlock(&key);
2145 	/*
2146 	 * For priority protected mutex, always set unlocked state
2147 	 * to UMUTEX_CONTESTED, so that userland always enters kernel
2148 	 * to lock the mutex, it is necessary because thread priority
2149 	 * has to be adjusted for such mutex.
2150 	 */
2151 	error = suword32(__DEVOLATILE(uint32_t *, &m->m_owner),
2152 		UMUTEX_CONTESTED);
2153 
2154 	umtxq_lock(&key);
2155 	if (error == 0)
2156 		umtxq_signal(&key, 1);
2157 	umtxq_unbusy(&key);
2158 	umtxq_unlock(&key);
2159 
2160 	if (error == -1)
2161 		error = EFAULT;
2162 	else {
2163 		mtx_lock_spin(&umtx_lock);
2164 		if (su != 0)
2165 			uq->uq_inherited_pri = new_inherited_pri;
2166 		pri = PRI_MAX;
2167 		TAILQ_FOREACH(pi, &uq->uq_pi_contested, pi_link) {
2168 			uq2 = TAILQ_FIRST(&pi->pi_blocked);
2169 			if (uq2 != NULL) {
2170 				if (pri > UPRI(uq2->uq_thread))
2171 					pri = UPRI(uq2->uq_thread);
2172 			}
2173 		}
2174 		if (pri > uq->uq_inherited_pri)
2175 			pri = uq->uq_inherited_pri;
2176 		thread_lock(td);
2177 		sched_unlend_user_prio(td, pri);
2178 		thread_unlock(td);
2179 		mtx_unlock_spin(&umtx_lock);
2180 	}
2181 	umtx_key_release(&key);
2182 	return (error);
2183 }
2184 
2185 static int
2186 do_set_ceiling(struct thread *td, struct umutex *m, uint32_t ceiling,
2187 	uint32_t *old_ceiling)
2188 {
2189 	struct umtx_q *uq;
2190 	uint32_t save_ceiling;
2191 	uint32_t owner, id;
2192 	uint32_t flags;
2193 	int error;
2194 
2195 	flags = fuword32(&m->m_flags);
2196 	if ((flags & UMUTEX_PRIO_PROTECT) == 0)
2197 		return (EINVAL);
2198 	if (ceiling > RTP_PRIO_MAX)
2199 		return (EINVAL);
2200 	id = td->td_tid;
2201 	uq = td->td_umtxq;
2202 	if ((error = umtx_key_get(m, TYPE_PP_UMUTEX, GET_SHARE(flags),
2203 	   &uq->uq_key)) != 0)
2204 		return (error);
2205 	for (;;) {
2206 		umtxq_lock(&uq->uq_key);
2207 		umtxq_busy(&uq->uq_key);
2208 		umtxq_unlock(&uq->uq_key);
2209 
2210 		save_ceiling = fuword32(&m->m_ceilings[0]);
2211 
2212 		owner = casuword32(&m->m_owner,
2213 		    UMUTEX_CONTESTED, id | UMUTEX_CONTESTED);
2214 
2215 		if (owner == UMUTEX_CONTESTED) {
2216 			suword32(&m->m_ceilings[0], ceiling);
2217 			suword32(__DEVOLATILE(uint32_t *, &m->m_owner),
2218 				UMUTEX_CONTESTED);
2219 			error = 0;
2220 			break;
2221 		}
2222 
2223 		/* The address was invalid. */
2224 		if (owner == -1) {
2225 			error = EFAULT;
2226 			break;
2227 		}
2228 
2229 		if ((owner & ~UMUTEX_CONTESTED) == id) {
2230 			suword32(&m->m_ceilings[0], ceiling);
2231 			error = 0;
2232 			break;
2233 		}
2234 
2235 		/*
2236 		 * If we caught a signal, we have retried and now
2237 		 * exit immediately.
2238 		 */
2239 		if (error != 0)
2240 			break;
2241 
2242 		/*
2243 		 * We set the contested bit, sleep. Otherwise the lock changed
2244 		 * and we need to retry or we lost a race to the thread
2245 		 * unlocking the umtx.
2246 		 */
2247 		umtxq_lock(&uq->uq_key);
2248 		umtxq_insert(uq);
2249 		umtxq_unbusy(&uq->uq_key);
2250 		error = umtxq_sleep(uq, "umtxpp", 0);
2251 		umtxq_remove(uq);
2252 		umtxq_unlock(&uq->uq_key);
2253 	}
2254 	umtxq_lock(&uq->uq_key);
2255 	if (error == 0)
2256 		umtxq_signal(&uq->uq_key, INT_MAX);
2257 	umtxq_unbusy(&uq->uq_key);
2258 	umtxq_unlock(&uq->uq_key);
2259 	umtx_key_release(&uq->uq_key);
2260 	if (error == 0 && old_ceiling != NULL)
2261 		suword32(old_ceiling, save_ceiling);
2262 	return (error);
2263 }
2264 
2265 static int
2266 _do_lock_umutex(struct thread *td, struct umutex *m, int flags, int timo,
2267 	int mode)
2268 {
2269 	switch(flags & (UMUTEX_PRIO_INHERIT | UMUTEX_PRIO_PROTECT)) {
2270 	case 0:
2271 		return (_do_lock_normal(td, m, flags, timo, mode));
2272 	case UMUTEX_PRIO_INHERIT:
2273 		return (_do_lock_pi(td, m, flags, timo, mode));
2274 	case UMUTEX_PRIO_PROTECT:
2275 		return (_do_lock_pp(td, m, flags, timo, mode));
2276 	}
2277 	return (EINVAL);
2278 }
2279 
2280 /*
2281  * Lock a userland POSIX mutex.
2282  */
2283 static int
2284 do_lock_umutex(struct thread *td, struct umutex *m,
2285 	struct timespec *timeout, int mode)
2286 {
2287 	struct timespec ts, ts2, ts3;
2288 	struct timeval tv;
2289 	uint32_t flags;
2290 	int error;
2291 
2292 	flags = fuword32(&m->m_flags);
2293 	if (flags == -1)
2294 		return (EFAULT);
2295 
2296 	if (timeout == NULL) {
2297 		error = _do_lock_umutex(td, m, flags, 0, mode);
2298 		/* Mutex locking is restarted if it is interrupted. */
2299 		if (error == EINTR && mode != _UMUTEX_WAIT)
2300 			error = ERESTART;
2301 	} else {
2302 		getnanouptime(&ts);
2303 		timespecadd(&ts, timeout);
2304 		TIMESPEC_TO_TIMEVAL(&tv, timeout);
2305 		for (;;) {
2306 			error = _do_lock_umutex(td, m, flags, tvtohz(&tv), mode);
2307 			if (error != ETIMEDOUT)
2308 				break;
2309 			getnanouptime(&ts2);
2310 			if (timespeccmp(&ts2, &ts, >=)) {
2311 				error = ETIMEDOUT;
2312 				break;
2313 			}
2314 			ts3 = ts;
2315 			timespecsub(&ts3, &ts2);
2316 			TIMESPEC_TO_TIMEVAL(&tv, &ts3);
2317 		}
2318 		/* Timed-locking is not restarted. */
2319 		if (error == ERESTART)
2320 			error = EINTR;
2321 	}
2322 	return (error);
2323 }
2324 
2325 /*
2326  * Unlock a userland POSIX mutex.
2327  */
2328 static int
2329 do_unlock_umutex(struct thread *td, struct umutex *m)
2330 {
2331 	uint32_t flags;
2332 
2333 	flags = fuword32(&m->m_flags);
2334 	if (flags == -1)
2335 		return (EFAULT);
2336 
2337 	switch(flags & (UMUTEX_PRIO_INHERIT | UMUTEX_PRIO_PROTECT)) {
2338 	case 0:
2339 		return (do_unlock_normal(td, m, flags));
2340 	case UMUTEX_PRIO_INHERIT:
2341 		return (do_unlock_pi(td, m, flags));
2342 	case UMUTEX_PRIO_PROTECT:
2343 		return (do_unlock_pp(td, m, flags));
2344 	}
2345 
2346 	return (EINVAL);
2347 }
2348 
2349 static int
2350 do_cv_wait(struct thread *td, struct ucond *cv, struct umutex *m,
2351 	struct timespec *timeout, u_long wflags)
2352 {
2353 	struct umtx_q *uq;
2354 	struct timeval tv;
2355 	struct timespec cts, ets, tts;
2356 	uint32_t flags;
2357 	int error;
2358 
2359 	uq = td->td_umtxq;
2360 	flags = fuword32(&cv->c_flags);
2361 	error = umtx_key_get(cv, TYPE_CV, GET_SHARE(flags), &uq->uq_key);
2362 	if (error != 0)
2363 		return (error);
2364 	umtxq_lock(&uq->uq_key);
2365 	umtxq_busy(&uq->uq_key);
2366 	umtxq_insert(uq);
2367 	umtxq_unlock(&uq->uq_key);
2368 
2369 	/*
2370 	 * The magic thing is we should set c_has_waiters to 1 before
2371 	 * releasing user mutex.
2372 	 */
2373 	suword32(__DEVOLATILE(uint32_t *, &cv->c_has_waiters), 1);
2374 
2375 	umtxq_lock(&uq->uq_key);
2376 	umtxq_unbusy(&uq->uq_key);
2377 	umtxq_unlock(&uq->uq_key);
2378 
2379 	error = do_unlock_umutex(td, m);
2380 
2381 	umtxq_lock(&uq->uq_key);
2382 	if (error == 0) {
2383 		if ((wflags & UMTX_CHECK_UNPARKING) &&
2384 		    (td->td_pflags & TDP_WAKEUP)) {
2385 			td->td_pflags &= ~TDP_WAKEUP;
2386 			error = EINTR;
2387 		} else if (timeout == NULL) {
2388 			error = umtxq_sleep(uq, "ucond", 0);
2389 		} else {
2390 			getnanouptime(&ets);
2391 			timespecadd(&ets, timeout);
2392 			TIMESPEC_TO_TIMEVAL(&tv, timeout);
2393 			for (;;) {
2394 				error = umtxq_sleep(uq, "ucond", tvtohz(&tv));
2395 				if (error != ETIMEDOUT)
2396 					break;
2397 				getnanouptime(&cts);
2398 				if (timespeccmp(&cts, &ets, >=)) {
2399 					error = ETIMEDOUT;
2400 					break;
2401 				}
2402 				tts = ets;
2403 				timespecsub(&tts, &cts);
2404 				TIMESPEC_TO_TIMEVAL(&tv, &tts);
2405 			}
2406 		}
2407 	}
2408 
2409 	if ((uq->uq_flags & UQF_UMTXQ) == 0)
2410 		error = 0;
2411 	else {
2412 		umtxq_remove(uq);
2413 		if (error == ERESTART)
2414 			error = EINTR;
2415 	}
2416 
2417 	umtxq_unlock(&uq->uq_key);
2418 	umtx_key_release(&uq->uq_key);
2419 	return (error);
2420 }
2421 
2422 /*
2423  * Signal a userland condition variable.
2424  */
2425 static int
2426 do_cv_signal(struct thread *td, struct ucond *cv)
2427 {
2428 	struct umtx_key key;
2429 	int error, cnt, nwake;
2430 	uint32_t flags;
2431 
2432 	flags = fuword32(&cv->c_flags);
2433 	if ((error = umtx_key_get(cv, TYPE_CV, GET_SHARE(flags), &key)) != 0)
2434 		return (error);
2435 	umtxq_lock(&key);
2436 	umtxq_busy(&key);
2437 	cnt = umtxq_count(&key);
2438 	nwake = umtxq_signal(&key, 1);
2439 	if (cnt <= nwake) {
2440 		umtxq_unlock(&key);
2441 		error = suword32(
2442 		    __DEVOLATILE(uint32_t *, &cv->c_has_waiters), 0);
2443 		umtxq_lock(&key);
2444 	}
2445 	umtxq_unbusy(&key);
2446 	umtxq_unlock(&key);
2447 	umtx_key_release(&key);
2448 	return (error);
2449 }
2450 
2451 static int
2452 do_cv_broadcast(struct thread *td, struct ucond *cv)
2453 {
2454 	struct umtx_key key;
2455 	int error;
2456 	uint32_t flags;
2457 
2458 	flags = fuword32(&cv->c_flags);
2459 	if ((error = umtx_key_get(cv, TYPE_CV, GET_SHARE(flags), &key)) != 0)
2460 		return (error);
2461 
2462 	umtxq_lock(&key);
2463 	umtxq_busy(&key);
2464 	umtxq_signal(&key, INT_MAX);
2465 	umtxq_unlock(&key);
2466 
2467 	error = suword32(__DEVOLATILE(uint32_t *, &cv->c_has_waiters), 0);
2468 
2469 	umtxq_lock(&key);
2470 	umtxq_unbusy(&key);
2471 	umtxq_unlock(&key);
2472 
2473 	umtx_key_release(&key);
2474 	return (error);
2475 }
2476 
2477 static int
2478 do_rw_rdlock(struct thread *td, struct urwlock *rwlock, long fflag, int timo)
2479 {
2480 	struct umtx_q *uq;
2481 	uint32_t flags, wrflags;
2482 	int32_t state, oldstate;
2483 	int32_t blocked_readers;
2484 	int error;
2485 
2486 	uq = td->td_umtxq;
2487 	flags = fuword32(&rwlock->rw_flags);
2488 	error = umtx_key_get(rwlock, TYPE_RWLOCK, GET_SHARE(flags), &uq->uq_key);
2489 	if (error != 0)
2490 		return (error);
2491 
2492 	wrflags = URWLOCK_WRITE_OWNER;
2493 	if (!(fflag & URWLOCK_PREFER_READER) && !(flags & URWLOCK_PREFER_READER))
2494 		wrflags |= URWLOCK_WRITE_WAITERS;
2495 
2496 	for (;;) {
2497 		state = fuword32(__DEVOLATILE(int32_t *, &rwlock->rw_state));
2498 		/* try to lock it */
2499 		while (!(state & wrflags)) {
2500 			if (__predict_false(URWLOCK_READER_COUNT(state) == URWLOCK_MAX_READERS)) {
2501 				umtx_key_release(&uq->uq_key);
2502 				return (EAGAIN);
2503 			}
2504 			oldstate = casuword32(&rwlock->rw_state, state, state + 1);
2505 			if (oldstate == state) {
2506 				umtx_key_release(&uq->uq_key);
2507 				return (0);
2508 			}
2509 			state = oldstate;
2510 		}
2511 
2512 		if (error)
2513 			break;
2514 
2515 		/* grab monitor lock */
2516 		umtxq_lock(&uq->uq_key);
2517 		umtxq_busy(&uq->uq_key);
2518 		umtxq_unlock(&uq->uq_key);
2519 
2520 		/*
2521 		 * re-read the state, in case it changed between the try-lock above
2522 		 * and the check below
2523 		 */
2524 		state = fuword32(__DEVOLATILE(int32_t *, &rwlock->rw_state));
2525 
2526 		/* set read contention bit */
2527 		while ((state & wrflags) && !(state & URWLOCK_READ_WAITERS)) {
2528 			oldstate = casuword32(&rwlock->rw_state, state, state | URWLOCK_READ_WAITERS);
2529 			if (oldstate == state)
2530 				goto sleep;
2531 			state = oldstate;
2532 		}
2533 
2534 		/* state is changed while setting flags, restart */
2535 		if (!(state & wrflags)) {
2536 			umtxq_lock(&uq->uq_key);
2537 			umtxq_unbusy(&uq->uq_key);
2538 			umtxq_unlock(&uq->uq_key);
2539 			continue;
2540 		}
2541 
2542 sleep:
2543 		/* contention bit is set, before sleeping, increase read waiter count */
2544 		blocked_readers = fuword32(&rwlock->rw_blocked_readers);
2545 		suword32(&rwlock->rw_blocked_readers, blocked_readers+1);
2546 
2547 		while (state & wrflags) {
2548 			umtxq_lock(&uq->uq_key);
2549 			umtxq_insert(uq);
2550 			umtxq_unbusy(&uq->uq_key);
2551 
2552 			error = umtxq_sleep(uq, "urdlck", timo);
2553 
2554 			umtxq_busy(&uq->uq_key);
2555 			umtxq_remove(uq);
2556 			umtxq_unlock(&uq->uq_key);
2557 			if (error)
2558 				break;
2559 			state = fuword32(__DEVOLATILE(int32_t *, &rwlock->rw_state));
2560 		}
2561 
2562 		/* decrease read waiter count, and may clear read contention bit */
2563 		blocked_readers = fuword32(&rwlock->rw_blocked_readers);
2564 		suword32(&rwlock->rw_blocked_readers, blocked_readers-1);
2565 		if (blocked_readers == 1) {
2566 			state = fuword32(__DEVOLATILE(int32_t *, &rwlock->rw_state));
2567 			for (;;) {
2568 				oldstate = casuword32(&rwlock->rw_state, state,
2569 					 state & ~URWLOCK_READ_WAITERS);
2570 				if (oldstate == state)
2571 					break;
2572 				state = oldstate;
2573 			}
2574 		}
2575 
2576 		umtxq_lock(&uq->uq_key);
2577 		umtxq_unbusy(&uq->uq_key);
2578 		umtxq_unlock(&uq->uq_key);
2579 	}
2580 	umtx_key_release(&uq->uq_key);
2581 	return (error);
2582 }
2583 
2584 static int
2585 do_rw_rdlock2(struct thread *td, void *obj, long val, struct timespec *timeout)
2586 {
2587 	struct timespec ts, ts2, ts3;
2588 	struct timeval tv;
2589 	int error;
2590 
2591 	getnanouptime(&ts);
2592 	timespecadd(&ts, timeout);
2593 	TIMESPEC_TO_TIMEVAL(&tv, timeout);
2594 	for (;;) {
2595 		error = do_rw_rdlock(td, obj, val, tvtohz(&tv));
2596 		if (error != ETIMEDOUT)
2597 			break;
2598 		getnanouptime(&ts2);
2599 		if (timespeccmp(&ts2, &ts, >=)) {
2600 			error = ETIMEDOUT;
2601 			break;
2602 		}
2603 		ts3 = ts;
2604 		timespecsub(&ts3, &ts2);
2605 		TIMESPEC_TO_TIMEVAL(&tv, &ts3);
2606 	}
2607 	if (error == ERESTART)
2608 		error = EINTR;
2609 	return (error);
2610 }
2611 
2612 static int
2613 do_rw_wrlock(struct thread *td, struct urwlock *rwlock, int timo)
2614 {
2615 	struct umtx_q *uq;
2616 	uint32_t flags;
2617 	int32_t state, oldstate;
2618 	int32_t blocked_writers;
2619 	int32_t blocked_readers;
2620 	int error;
2621 
2622 	uq = td->td_umtxq;
2623 	flags = fuword32(&rwlock->rw_flags);
2624 	error = umtx_key_get(rwlock, TYPE_RWLOCK, GET_SHARE(flags), &uq->uq_key);
2625 	if (error != 0)
2626 		return (error);
2627 
2628 	blocked_readers = 0;
2629 	for (;;) {
2630 		state = fuword32(__DEVOLATILE(int32_t *, &rwlock->rw_state));
2631 		while (!(state & URWLOCK_WRITE_OWNER) && URWLOCK_READER_COUNT(state) == 0) {
2632 			oldstate = casuword32(&rwlock->rw_state, state, state | URWLOCK_WRITE_OWNER);
2633 			if (oldstate == state) {
2634 				umtx_key_release(&uq->uq_key);
2635 				return (0);
2636 			}
2637 			state = oldstate;
2638 		}
2639 
2640 		if (error) {
2641 			if (!(state & (URWLOCK_WRITE_OWNER|URWLOCK_WRITE_WAITERS)) &&
2642 			    blocked_readers != 0) {
2643 				umtxq_lock(&uq->uq_key);
2644 				umtxq_busy(&uq->uq_key);
2645 				umtxq_signal_queue(&uq->uq_key, INT_MAX, UMTX_SHARED_QUEUE);
2646 				umtxq_unbusy(&uq->uq_key);
2647 				umtxq_unlock(&uq->uq_key);
2648 			}
2649 
2650 			break;
2651 		}
2652 
2653 		/* grab monitor lock */
2654 		umtxq_lock(&uq->uq_key);
2655 		umtxq_busy(&uq->uq_key);
2656 		umtxq_unlock(&uq->uq_key);
2657 
2658 		/*
2659 		 * re-read the state, in case it changed between the try-lock above
2660 		 * and the check below
2661 		 */
2662 		state = fuword32(__DEVOLATILE(int32_t *, &rwlock->rw_state));
2663 
2664 		while (((state & URWLOCK_WRITE_OWNER) || URWLOCK_READER_COUNT(state) != 0) &&
2665 		       (state & URWLOCK_WRITE_WAITERS) == 0) {
2666 			oldstate = casuword32(&rwlock->rw_state, state, state | URWLOCK_WRITE_WAITERS);
2667 			if (oldstate == state)
2668 				goto sleep;
2669 			state = oldstate;
2670 		}
2671 
2672 		if (!(state & URWLOCK_WRITE_OWNER) && URWLOCK_READER_COUNT(state) == 0) {
2673 			umtxq_lock(&uq->uq_key);
2674 			umtxq_unbusy(&uq->uq_key);
2675 			umtxq_unlock(&uq->uq_key);
2676 			continue;
2677 		}
2678 sleep:
2679 		blocked_writers = fuword32(&rwlock->rw_blocked_writers);
2680 		suword32(&rwlock->rw_blocked_writers, blocked_writers+1);
2681 
2682 		while ((state & URWLOCK_WRITE_OWNER) || URWLOCK_READER_COUNT(state) != 0) {
2683 			umtxq_lock(&uq->uq_key);
2684 			umtxq_insert_queue(uq, UMTX_EXCLUSIVE_QUEUE);
2685 			umtxq_unbusy(&uq->uq_key);
2686 
2687 			error = umtxq_sleep(uq, "uwrlck", timo);
2688 
2689 			umtxq_busy(&uq->uq_key);
2690 			umtxq_remove_queue(uq, UMTX_EXCLUSIVE_QUEUE);
2691 			umtxq_unlock(&uq->uq_key);
2692 			if (error)
2693 				break;
2694 			state = fuword32(__DEVOLATILE(int32_t *, &rwlock->rw_state));
2695 		}
2696 
2697 		blocked_writers = fuword32(&rwlock->rw_blocked_writers);
2698 		suword32(&rwlock->rw_blocked_writers, blocked_writers-1);
2699 		if (blocked_writers == 1) {
2700 			state = fuword32(__DEVOLATILE(int32_t *, &rwlock->rw_state));
2701 			for (;;) {
2702 				oldstate = casuword32(&rwlock->rw_state, state,
2703 					 state & ~URWLOCK_WRITE_WAITERS);
2704 				if (oldstate == state)
2705 					break;
2706 				state = oldstate;
2707 			}
2708 			blocked_readers = fuword32(&rwlock->rw_blocked_readers);
2709 		} else
2710 			blocked_readers = 0;
2711 
2712 		umtxq_lock(&uq->uq_key);
2713 		umtxq_unbusy(&uq->uq_key);
2714 		umtxq_unlock(&uq->uq_key);
2715 	}
2716 
2717 	umtx_key_release(&uq->uq_key);
2718 	return (error);
2719 }
2720 
2721 static int
2722 do_rw_wrlock2(struct thread *td, void *obj, struct timespec *timeout)
2723 {
2724 	struct timespec ts, ts2, ts3;
2725 	struct timeval tv;
2726 	int error;
2727 
2728 	getnanouptime(&ts);
2729 	timespecadd(&ts, timeout);
2730 	TIMESPEC_TO_TIMEVAL(&tv, timeout);
2731 	for (;;) {
2732 		error = do_rw_wrlock(td, obj, tvtohz(&tv));
2733 		if (error != ETIMEDOUT)
2734 			break;
2735 		getnanouptime(&ts2);
2736 		if (timespeccmp(&ts2, &ts, >=)) {
2737 			error = ETIMEDOUT;
2738 			break;
2739 		}
2740 		ts3 = ts;
2741 		timespecsub(&ts3, &ts2);
2742 		TIMESPEC_TO_TIMEVAL(&tv, &ts3);
2743 	}
2744 	if (error == ERESTART)
2745 		error = EINTR;
2746 	return (error);
2747 }
2748 
2749 static int
2750 do_rw_unlock(struct thread *td, struct urwlock *rwlock)
2751 {
2752 	struct umtx_q *uq;
2753 	uint32_t flags;
2754 	int32_t state, oldstate;
2755 	int error, q, count;
2756 
2757 	uq = td->td_umtxq;
2758 	flags = fuword32(&rwlock->rw_flags);
2759 	error = umtx_key_get(rwlock, TYPE_RWLOCK, GET_SHARE(flags), &uq->uq_key);
2760 	if (error != 0)
2761 		return (error);
2762 
2763 	state = fuword32(__DEVOLATILE(int32_t *, &rwlock->rw_state));
2764 	if (state & URWLOCK_WRITE_OWNER) {
2765 		for (;;) {
2766 			oldstate = casuword32(&rwlock->rw_state, state,
2767 				state & ~URWLOCK_WRITE_OWNER);
2768 			if (oldstate != state) {
2769 				state = oldstate;
2770 				if (!(oldstate & URWLOCK_WRITE_OWNER)) {
2771 					error = EPERM;
2772 					goto out;
2773 				}
2774 			} else
2775 				break;
2776 		}
2777 	} else if (URWLOCK_READER_COUNT(state) != 0) {
2778 		for (;;) {
2779 			oldstate = casuword32(&rwlock->rw_state, state,
2780 				state - 1);
2781 			if (oldstate != state) {
2782 				state = oldstate;
2783 				if (URWLOCK_READER_COUNT(oldstate) == 0) {
2784 					error = EPERM;
2785 					goto out;
2786 				}
2787 			}
2788 			else
2789 				break;
2790 		}
2791 	} else {
2792 		error = EPERM;
2793 		goto out;
2794 	}
2795 
2796 	count = 0;
2797 
2798 	if (!(flags & URWLOCK_PREFER_READER)) {
2799 		if (state & URWLOCK_WRITE_WAITERS) {
2800 			count = 1;
2801 			q = UMTX_EXCLUSIVE_QUEUE;
2802 		} else if (state & URWLOCK_READ_WAITERS) {
2803 			count = INT_MAX;
2804 			q = UMTX_SHARED_QUEUE;
2805 		}
2806 	} else {
2807 		if (state & URWLOCK_READ_WAITERS) {
2808 			count = INT_MAX;
2809 			q = UMTX_SHARED_QUEUE;
2810 		} else if (state & URWLOCK_WRITE_WAITERS) {
2811 			count = 1;
2812 			q = UMTX_EXCLUSIVE_QUEUE;
2813 		}
2814 	}
2815 
2816 	if (count) {
2817 		umtxq_lock(&uq->uq_key);
2818 		umtxq_busy(&uq->uq_key);
2819 		umtxq_signal_queue(&uq->uq_key, count, q);
2820 		umtxq_unbusy(&uq->uq_key);
2821 		umtxq_unlock(&uq->uq_key);
2822 	}
2823 out:
2824 	umtx_key_release(&uq->uq_key);
2825 	return (error);
2826 }
2827 
2828 static int
2829 do_sem_wait(struct thread *td, struct _usem *sem, struct timespec *timeout)
2830 {
2831 	struct umtx_q *uq;
2832 	struct timeval tv;
2833 	struct timespec cts, ets, tts;
2834 	uint32_t flags, count;
2835 	int error;
2836 
2837 	uq = td->td_umtxq;
2838 	flags = fuword32(&sem->_flags);
2839 	error = umtx_key_get(sem, TYPE_SEM, GET_SHARE(flags), &uq->uq_key);
2840 	if (error != 0)
2841 		return (error);
2842 	umtxq_lock(&uq->uq_key);
2843 	umtxq_busy(&uq->uq_key);
2844 	umtxq_insert(uq);
2845 	umtxq_unlock(&uq->uq_key);
2846 
2847 	suword32(__DEVOLATILE(uint32_t *, &sem->_has_waiters), 1);
2848 
2849 	count = fuword32(__DEVOLATILE(uint32_t *, &sem->_count));
2850 	if (count != 0) {
2851 		umtxq_lock(&uq->uq_key);
2852 		umtxq_unbusy(&uq->uq_key);
2853 		umtxq_remove(uq);
2854 		umtxq_unlock(&uq->uq_key);
2855 		umtx_key_release(&uq->uq_key);
2856 		return (0);
2857 	}
2858 
2859 	umtxq_lock(&uq->uq_key);
2860 	umtxq_unbusy(&uq->uq_key);
2861 	umtxq_unlock(&uq->uq_key);
2862 
2863 	umtxq_lock(&uq->uq_key);
2864 	if (timeout == NULL) {
2865 		error = umtxq_sleep(uq, "usem", 0);
2866 	} else {
2867 		getnanouptime(&ets);
2868 		timespecadd(&ets, timeout);
2869 		TIMESPEC_TO_TIMEVAL(&tv, timeout);
2870 		for (;;) {
2871 			error = umtxq_sleep(uq, "usem", tvtohz(&tv));
2872 			if (error != ETIMEDOUT)
2873 				break;
2874 			getnanouptime(&cts);
2875 			if (timespeccmp(&cts, &ets, >=)) {
2876 				error = ETIMEDOUT;
2877 				break;
2878 			}
2879 			tts = ets;
2880 			timespecsub(&tts, &cts);
2881 			TIMESPEC_TO_TIMEVAL(&tv, &tts);
2882 		}
2883 	}
2884 
2885 	if ((uq->uq_flags & UQF_UMTXQ) == 0)
2886 		error = 0;
2887 	else {
2888 		umtxq_remove(uq);
2889 		if (error == ERESTART)
2890 			error = EINTR;
2891 	}
2892 	umtxq_unlock(&uq->uq_key);
2893 	umtx_key_release(&uq->uq_key);
2894 	return (error);
2895 }
2896 
2897 /*
2898  * Signal a userland condition variable.
2899  */
2900 static int
2901 do_sem_wake(struct thread *td, struct _usem *sem)
2902 {
2903 	struct umtx_key key;
2904 	int error, cnt, nwake;
2905 	uint32_t flags;
2906 
2907 	flags = fuword32(&sem->_flags);
2908 	if ((error = umtx_key_get(sem, TYPE_SEM, GET_SHARE(flags), &key)) != 0)
2909 		return (error);
2910 	umtxq_lock(&key);
2911 	umtxq_busy(&key);
2912 	cnt = umtxq_count(&key);
2913 	nwake = umtxq_signal(&key, 1);
2914 	if (cnt <= nwake) {
2915 		umtxq_unlock(&key);
2916 		error = suword32(
2917 		    __DEVOLATILE(uint32_t *, &sem->_has_waiters), 0);
2918 		umtxq_lock(&key);
2919 	}
2920 	umtxq_unbusy(&key);
2921 	umtxq_unlock(&key);
2922 	umtx_key_release(&key);
2923 	return (error);
2924 }
2925 
2926 int
2927 _umtx_lock(struct thread *td, struct _umtx_lock_args *uap)
2928     /* struct umtx *umtx */
2929 {
2930 	return _do_lock_umtx(td, uap->umtx, td->td_tid, 0);
2931 }
2932 
2933 int
2934 _umtx_unlock(struct thread *td, struct _umtx_unlock_args *uap)
2935     /* struct umtx *umtx */
2936 {
2937 	return do_unlock_umtx(td, uap->umtx, td->td_tid);
2938 }
2939 
2940 static int
2941 __umtx_op_lock_umtx(struct thread *td, struct _umtx_op_args *uap)
2942 {
2943 	struct timespec *ts, timeout;
2944 	int error;
2945 
2946 	/* Allow a null timespec (wait forever). */
2947 	if (uap->uaddr2 == NULL)
2948 		ts = NULL;
2949 	else {
2950 		error = copyin(uap->uaddr2, &timeout, sizeof(timeout));
2951 		if (error != 0)
2952 			return (error);
2953 		if (timeout.tv_nsec >= 1000000000 ||
2954 		    timeout.tv_nsec < 0) {
2955 			return (EINVAL);
2956 		}
2957 		ts = &timeout;
2958 	}
2959 	return (do_lock_umtx(td, uap->obj, uap->val, ts));
2960 }
2961 
2962 static int
2963 __umtx_op_unlock_umtx(struct thread *td, struct _umtx_op_args *uap)
2964 {
2965 	return (do_unlock_umtx(td, uap->obj, uap->val));
2966 }
2967 
2968 static int
2969 __umtx_op_wait(struct thread *td, struct _umtx_op_args *uap)
2970 {
2971 	struct timespec *ts, timeout;
2972 	int error;
2973 
2974 	if (uap->uaddr2 == NULL)
2975 		ts = NULL;
2976 	else {
2977 		error = copyin(uap->uaddr2, &timeout, sizeof(timeout));
2978 		if (error != 0)
2979 			return (error);
2980 		if (timeout.tv_nsec >= 1000000000 ||
2981 		    timeout.tv_nsec < 0)
2982 			return (EINVAL);
2983 		ts = &timeout;
2984 	}
2985 	return do_wait(td, uap->obj, uap->val, ts, 0, 0);
2986 }
2987 
2988 static int
2989 __umtx_op_wait_uint(struct thread *td, struct _umtx_op_args *uap)
2990 {
2991 	struct timespec *ts, timeout;
2992 	int error;
2993 
2994 	if (uap->uaddr2 == NULL)
2995 		ts = NULL;
2996 	else {
2997 		error = copyin(uap->uaddr2, &timeout, sizeof(timeout));
2998 		if (error != 0)
2999 			return (error);
3000 		if (timeout.tv_nsec >= 1000000000 ||
3001 		    timeout.tv_nsec < 0)
3002 			return (EINVAL);
3003 		ts = &timeout;
3004 	}
3005 	return do_wait(td, uap->obj, uap->val, ts, 1, 0);
3006 }
3007 
3008 static int
3009 __umtx_op_wait_uint_private(struct thread *td, struct _umtx_op_args *uap)
3010 {
3011 	struct timespec *ts, timeout;
3012 	int error;
3013 
3014 	if (uap->uaddr2 == NULL)
3015 		ts = NULL;
3016 	else {
3017 		error = copyin(uap->uaddr2, &timeout, sizeof(timeout));
3018 		if (error != 0)
3019 			return (error);
3020 		if (timeout.tv_nsec >= 1000000000 ||
3021 		    timeout.tv_nsec < 0)
3022 			return (EINVAL);
3023 		ts = &timeout;
3024 	}
3025 	return do_wait(td, uap->obj, uap->val, ts, 1, 1);
3026 }
3027 
3028 static int
3029 __umtx_op_wake(struct thread *td, struct _umtx_op_args *uap)
3030 {
3031 	return (kern_umtx_wake(td, uap->obj, uap->val, 0));
3032 }
3033 
3034 static int
3035 __umtx_op_wake_private(struct thread *td, struct _umtx_op_args *uap)
3036 {
3037 	return (kern_umtx_wake(td, uap->obj, uap->val, 1));
3038 }
3039 
3040 static int
3041 __umtx_op_lock_umutex(struct thread *td, struct _umtx_op_args *uap)
3042 {
3043 	struct timespec *ts, timeout;
3044 	int error;
3045 
3046 	/* Allow a null timespec (wait forever). */
3047 	if (uap->uaddr2 == NULL)
3048 		ts = NULL;
3049 	else {
3050 		error = copyin(uap->uaddr2, &timeout,
3051 		    sizeof(timeout));
3052 		if (error != 0)
3053 			return (error);
3054 		if (timeout.tv_nsec >= 1000000000 ||
3055 		    timeout.tv_nsec < 0) {
3056 			return (EINVAL);
3057 		}
3058 		ts = &timeout;
3059 	}
3060 	return do_lock_umutex(td, uap->obj, ts, 0);
3061 }
3062 
3063 static int
3064 __umtx_op_trylock_umutex(struct thread *td, struct _umtx_op_args *uap)
3065 {
3066 	return do_lock_umutex(td, uap->obj, NULL, _UMUTEX_TRY);
3067 }
3068 
3069 static int
3070 __umtx_op_wait_umutex(struct thread *td, struct _umtx_op_args *uap)
3071 {
3072 	struct timespec *ts, timeout;
3073 	int error;
3074 
3075 	/* Allow a null timespec (wait forever). */
3076 	if (uap->uaddr2 == NULL)
3077 		ts = NULL;
3078 	else {
3079 		error = copyin(uap->uaddr2, &timeout,
3080 		    sizeof(timeout));
3081 		if (error != 0)
3082 			return (error);
3083 		if (timeout.tv_nsec >= 1000000000 ||
3084 		    timeout.tv_nsec < 0) {
3085 			return (EINVAL);
3086 		}
3087 		ts = &timeout;
3088 	}
3089 	return do_lock_umutex(td, uap->obj, ts, _UMUTEX_WAIT);
3090 }
3091 
3092 static int
3093 __umtx_op_wake_umutex(struct thread *td, struct _umtx_op_args *uap)
3094 {
3095 	return do_wake_umutex(td, uap->obj);
3096 }
3097 
3098 static int
3099 __umtx_op_unlock_umutex(struct thread *td, struct _umtx_op_args *uap)
3100 {
3101 	return do_unlock_umutex(td, uap->obj);
3102 }
3103 
3104 static int
3105 __umtx_op_set_ceiling(struct thread *td, struct _umtx_op_args *uap)
3106 {
3107 	return do_set_ceiling(td, uap->obj, uap->val, uap->uaddr1);
3108 }
3109 
3110 static int
3111 __umtx_op_cv_wait(struct thread *td, struct _umtx_op_args *uap)
3112 {
3113 	struct timespec *ts, timeout;
3114 	int error;
3115 
3116 	/* Allow a null timespec (wait forever). */
3117 	if (uap->uaddr2 == NULL)
3118 		ts = NULL;
3119 	else {
3120 		error = copyin(uap->uaddr2, &timeout,
3121 		    sizeof(timeout));
3122 		if (error != 0)
3123 			return (error);
3124 		if (timeout.tv_nsec >= 1000000000 ||
3125 		    timeout.tv_nsec < 0) {
3126 			return (EINVAL);
3127 		}
3128 		ts = &timeout;
3129 	}
3130 	return (do_cv_wait(td, uap->obj, uap->uaddr1, ts, uap->val));
3131 }
3132 
3133 static int
3134 __umtx_op_cv_signal(struct thread *td, struct _umtx_op_args *uap)
3135 {
3136 	return do_cv_signal(td, uap->obj);
3137 }
3138 
3139 static int
3140 __umtx_op_cv_broadcast(struct thread *td, struct _umtx_op_args *uap)
3141 {
3142 	return do_cv_broadcast(td, uap->obj);
3143 }
3144 
3145 static int
3146 __umtx_op_rw_rdlock(struct thread *td, struct _umtx_op_args *uap)
3147 {
3148 	struct timespec timeout;
3149 	int error;
3150 
3151 	/* Allow a null timespec (wait forever). */
3152 	if (uap->uaddr2 == NULL) {
3153 		error = do_rw_rdlock(td, uap->obj, uap->val, 0);
3154 	} else {
3155 		error = copyin(uap->uaddr2, &timeout,
3156 		    sizeof(timeout));
3157 		if (error != 0)
3158 			return (error);
3159 		if (timeout.tv_nsec >= 1000000000 ||
3160 		    timeout.tv_nsec < 0) {
3161 			return (EINVAL);
3162 		}
3163 		error = do_rw_rdlock2(td, uap->obj, uap->val, &timeout);
3164 	}
3165 	return (error);
3166 }
3167 
3168 static int
3169 __umtx_op_rw_wrlock(struct thread *td, struct _umtx_op_args *uap)
3170 {
3171 	struct timespec timeout;
3172 	int error;
3173 
3174 	/* Allow a null timespec (wait forever). */
3175 	if (uap->uaddr2 == NULL) {
3176 		error = do_rw_wrlock(td, uap->obj, 0);
3177 	} else {
3178 		error = copyin(uap->uaddr2, &timeout,
3179 		    sizeof(timeout));
3180 		if (error != 0)
3181 			return (error);
3182 		if (timeout.tv_nsec >= 1000000000 ||
3183 		    timeout.tv_nsec < 0) {
3184 			return (EINVAL);
3185 		}
3186 
3187 		error = do_rw_wrlock2(td, uap->obj, &timeout);
3188 	}
3189 	return (error);
3190 }
3191 
3192 static int
3193 __umtx_op_rw_unlock(struct thread *td, struct _umtx_op_args *uap)
3194 {
3195 	return do_rw_unlock(td, uap->obj);
3196 }
3197 
3198 static int
3199 __umtx_op_sem_wait(struct thread *td, struct _umtx_op_args *uap)
3200 {
3201 	struct timespec *ts, timeout;
3202 	int error;
3203 
3204 	/* Allow a null timespec (wait forever). */
3205 	if (uap->uaddr2 == NULL)
3206 		ts = NULL;
3207 	else {
3208 		error = copyin(uap->uaddr2, &timeout,
3209 		    sizeof(timeout));
3210 		if (error != 0)
3211 			return (error);
3212 		if (timeout.tv_nsec >= 1000000000 ||
3213 		    timeout.tv_nsec < 0) {
3214 			return (EINVAL);
3215 		}
3216 		ts = &timeout;
3217 	}
3218 	return (do_sem_wait(td, uap->obj, ts));
3219 }
3220 
3221 static int
3222 __umtx_op_sem_wake(struct thread *td, struct _umtx_op_args *uap)
3223 {
3224 	return do_sem_wake(td, uap->obj);
3225 }
3226 
3227 typedef int (*_umtx_op_func)(struct thread *td, struct _umtx_op_args *uap);
3228 
3229 static _umtx_op_func op_table[] = {
3230 	__umtx_op_lock_umtx,		/* UMTX_OP_LOCK */
3231 	__umtx_op_unlock_umtx,		/* UMTX_OP_UNLOCK */
3232 	__umtx_op_wait,			/* UMTX_OP_WAIT */
3233 	__umtx_op_wake,			/* UMTX_OP_WAKE */
3234 	__umtx_op_trylock_umutex,	/* UMTX_OP_MUTEX_TRYLOCK */
3235 	__umtx_op_lock_umutex,		/* UMTX_OP_MUTEX_LOCK */
3236 	__umtx_op_unlock_umutex,	/* UMTX_OP_MUTEX_UNLOCK */
3237 	__umtx_op_set_ceiling,		/* UMTX_OP_SET_CEILING */
3238 	__umtx_op_cv_wait,		/* UMTX_OP_CV_WAIT*/
3239 	__umtx_op_cv_signal,		/* UMTX_OP_CV_SIGNAL */
3240 	__umtx_op_cv_broadcast,		/* UMTX_OP_CV_BROADCAST */
3241 	__umtx_op_wait_uint,		/* UMTX_OP_WAIT_UINT */
3242 	__umtx_op_rw_rdlock,		/* UMTX_OP_RW_RDLOCK */
3243 	__umtx_op_rw_wrlock,		/* UMTX_OP_RW_WRLOCK */
3244 	__umtx_op_rw_unlock,		/* UMTX_OP_RW_UNLOCK */
3245 	__umtx_op_wait_uint_private,	/* UMTX_OP_WAIT_UINT_PRIVATE */
3246 	__umtx_op_wake_private,		/* UMTX_OP_WAKE_PRIVATE */
3247 	__umtx_op_wait_umutex,		/* UMTX_OP_UMUTEX_WAIT */
3248 	__umtx_op_wake_umutex,		/* UMTX_OP_UMUTEX_WAKE */
3249 	__umtx_op_sem_wait,		/* UMTX_OP_SEM_WAIT */
3250 	__umtx_op_sem_wake		/* UMTX_OP_SEM_WAKE */
3251 };
3252 
3253 int
3254 _umtx_op(struct thread *td, struct _umtx_op_args *uap)
3255 {
3256 	if ((unsigned)uap->op < UMTX_OP_MAX)
3257 		return (*op_table[uap->op])(td, uap);
3258 	return (EINVAL);
3259 }
3260 
3261 #ifdef COMPAT_FREEBSD32
3262 int
3263 freebsd32_umtx_lock(struct thread *td, struct freebsd32_umtx_lock_args *uap)
3264     /* struct umtx *umtx */
3265 {
3266 	return (do_lock_umtx32(td, (uint32_t *)uap->umtx, td->td_tid, NULL));
3267 }
3268 
3269 int
3270 freebsd32_umtx_unlock(struct thread *td, struct freebsd32_umtx_unlock_args *uap)
3271     /* struct umtx *umtx */
3272 {
3273 	return (do_unlock_umtx32(td, (uint32_t *)uap->umtx, td->td_tid));
3274 }
3275 
3276 struct timespec32 {
3277 	uint32_t tv_sec;
3278 	uint32_t tv_nsec;
3279 };
3280 
3281 static inline int
3282 copyin_timeout32(void *addr, struct timespec *tsp)
3283 {
3284 	struct timespec32 ts32;
3285 	int error;
3286 
3287 	error = copyin(addr, &ts32, sizeof(struct timespec32));
3288 	if (error == 0) {
3289 		tsp->tv_sec = ts32.tv_sec;
3290 		tsp->tv_nsec = ts32.tv_nsec;
3291 	}
3292 	return (error);
3293 }
3294 
3295 static int
3296 __umtx_op_lock_umtx_compat32(struct thread *td, struct _umtx_op_args *uap)
3297 {
3298 	struct timespec *ts, timeout;
3299 	int error;
3300 
3301 	/* Allow a null timespec (wait forever). */
3302 	if (uap->uaddr2 == NULL)
3303 		ts = NULL;
3304 	else {
3305 		error = copyin_timeout32(uap->uaddr2, &timeout);
3306 		if (error != 0)
3307 			return (error);
3308 		if (timeout.tv_nsec >= 1000000000 ||
3309 		    timeout.tv_nsec < 0) {
3310 			return (EINVAL);
3311 		}
3312 		ts = &timeout;
3313 	}
3314 	return (do_lock_umtx32(td, uap->obj, uap->val, ts));
3315 }
3316 
3317 static int
3318 __umtx_op_unlock_umtx_compat32(struct thread *td, struct _umtx_op_args *uap)
3319 {
3320 	return (do_unlock_umtx32(td, uap->obj, (uint32_t)uap->val));
3321 }
3322 
3323 static int
3324 __umtx_op_wait_compat32(struct thread *td, struct _umtx_op_args *uap)
3325 {
3326 	struct timespec *ts, timeout;
3327 	int error;
3328 
3329 	if (uap->uaddr2 == NULL)
3330 		ts = NULL;
3331 	else {
3332 		error = copyin_timeout32(uap->uaddr2, &timeout);
3333 		if (error != 0)
3334 			return (error);
3335 		if (timeout.tv_nsec >= 1000000000 ||
3336 		    timeout.tv_nsec < 0)
3337 			return (EINVAL);
3338 		ts = &timeout;
3339 	}
3340 	return do_wait(td, uap->obj, uap->val, ts, 1, 0);
3341 }
3342 
3343 static int
3344 __umtx_op_lock_umutex_compat32(struct thread *td, struct _umtx_op_args *uap)
3345 {
3346 	struct timespec *ts, timeout;
3347 	int error;
3348 
3349 	/* Allow a null timespec (wait forever). */
3350 	if (uap->uaddr2 == NULL)
3351 		ts = NULL;
3352 	else {
3353 		error = copyin_timeout32(uap->uaddr2, &timeout);
3354 		if (error != 0)
3355 			return (error);
3356 		if (timeout.tv_nsec >= 1000000000 ||
3357 		    timeout.tv_nsec < 0)
3358 			return (EINVAL);
3359 		ts = &timeout;
3360 	}
3361 	return do_lock_umutex(td, uap->obj, ts, 0);
3362 }
3363 
3364 static int
3365 __umtx_op_wait_umutex_compat32(struct thread *td, struct _umtx_op_args *uap)
3366 {
3367 	struct timespec *ts, timeout;
3368 	int error;
3369 
3370 	/* Allow a null timespec (wait forever). */
3371 	if (uap->uaddr2 == NULL)
3372 		ts = NULL;
3373 	else {
3374 		error = copyin_timeout32(uap->uaddr2, &timeout);
3375 		if (error != 0)
3376 			return (error);
3377 		if (timeout.tv_nsec >= 1000000000 ||
3378 		    timeout.tv_nsec < 0)
3379 			return (EINVAL);
3380 		ts = &timeout;
3381 	}
3382 	return do_lock_umutex(td, uap->obj, ts, _UMUTEX_WAIT);
3383 }
3384 
3385 static int
3386 __umtx_op_cv_wait_compat32(struct thread *td, struct _umtx_op_args *uap)
3387 {
3388 	struct timespec *ts, timeout;
3389 	int error;
3390 
3391 	/* Allow a null timespec (wait forever). */
3392 	if (uap->uaddr2 == NULL)
3393 		ts = NULL;
3394 	else {
3395 		error = copyin_timeout32(uap->uaddr2, &timeout);
3396 		if (error != 0)
3397 			return (error);
3398 		if (timeout.tv_nsec >= 1000000000 ||
3399 		    timeout.tv_nsec < 0)
3400 			return (EINVAL);
3401 		ts = &timeout;
3402 	}
3403 	return (do_cv_wait(td, uap->obj, uap->uaddr1, ts, uap->val));
3404 }
3405 
3406 static int
3407 __umtx_op_rw_rdlock_compat32(struct thread *td, struct _umtx_op_args *uap)
3408 {
3409 	struct timespec timeout;
3410 	int error;
3411 
3412 	/* Allow a null timespec (wait forever). */
3413 	if (uap->uaddr2 == NULL) {
3414 		error = do_rw_rdlock(td, uap->obj, uap->val, 0);
3415 	} else {
3416 		error = copyin(uap->uaddr2, &timeout,
3417 		    sizeof(timeout));
3418 		if (error != 0)
3419 			return (error);
3420 		if (timeout.tv_nsec >= 1000000000 ||
3421 		    timeout.tv_nsec < 0) {
3422 			return (EINVAL);
3423 		}
3424 		error = do_rw_rdlock2(td, uap->obj, uap->val, &timeout);
3425 	}
3426 	return (error);
3427 }
3428 
3429 static int
3430 __umtx_op_rw_wrlock_compat32(struct thread *td, struct _umtx_op_args *uap)
3431 {
3432 	struct timespec timeout;
3433 	int error;
3434 
3435 	/* Allow a null timespec (wait forever). */
3436 	if (uap->uaddr2 == NULL) {
3437 		error = do_rw_wrlock(td, uap->obj, 0);
3438 	} else {
3439 		error = copyin_timeout32(uap->uaddr2, &timeout);
3440 		if (error != 0)
3441 			return (error);
3442 		if (timeout.tv_nsec >= 1000000000 ||
3443 		    timeout.tv_nsec < 0) {
3444 			return (EINVAL);
3445 		}
3446 
3447 		error = do_rw_wrlock2(td, uap->obj, &timeout);
3448 	}
3449 	return (error);
3450 }
3451 
3452 static int
3453 __umtx_op_wait_uint_private_compat32(struct thread *td, struct _umtx_op_args *uap)
3454 {
3455 	struct timespec *ts, timeout;
3456 	int error;
3457 
3458 	if (uap->uaddr2 == NULL)
3459 		ts = NULL;
3460 	else {
3461 		error = copyin_timeout32(uap->uaddr2, &timeout);
3462 		if (error != 0)
3463 			return (error);
3464 		if (timeout.tv_nsec >= 1000000000 ||
3465 		    timeout.tv_nsec < 0)
3466 			return (EINVAL);
3467 		ts = &timeout;
3468 	}
3469 	return do_wait(td, uap->obj, uap->val, ts, 1, 1);
3470 }
3471 
3472 static int
3473 __umtx_op_sem_wait_compat32(struct thread *td, struct _umtx_op_args *uap)
3474 {
3475 	struct timespec *ts, timeout;
3476 	int error;
3477 
3478 	/* Allow a null timespec (wait forever). */
3479 	if (uap->uaddr2 == NULL)
3480 		ts = NULL;
3481 	else {
3482 		error = copyin_timeout32(uap->uaddr2, &timeout);
3483 		if (error != 0)
3484 			return (error);
3485 		if (timeout.tv_nsec >= 1000000000 ||
3486 		    timeout.tv_nsec < 0)
3487 			return (EINVAL);
3488 		ts = &timeout;
3489 	}
3490 	return (do_sem_wait(td, uap->obj, ts));
3491 }
3492 
3493 static _umtx_op_func op_table_compat32[] = {
3494 	__umtx_op_lock_umtx_compat32,	/* UMTX_OP_LOCK */
3495 	__umtx_op_unlock_umtx_compat32,	/* UMTX_OP_UNLOCK */
3496 	__umtx_op_wait_compat32,	/* UMTX_OP_WAIT */
3497 	__umtx_op_wake,			/* UMTX_OP_WAKE */
3498 	__umtx_op_trylock_umutex,	/* UMTX_OP_MUTEX_LOCK */
3499 	__umtx_op_lock_umutex_compat32,	/* UMTX_OP_MUTEX_TRYLOCK */
3500 	__umtx_op_unlock_umutex,	/* UMTX_OP_MUTEX_UNLOCK	*/
3501 	__umtx_op_set_ceiling,		/* UMTX_OP_SET_CEILING */
3502 	__umtx_op_cv_wait_compat32,	/* UMTX_OP_CV_WAIT*/
3503 	__umtx_op_cv_signal,		/* UMTX_OP_CV_SIGNAL */
3504 	__umtx_op_cv_broadcast,		/* UMTX_OP_CV_BROADCAST */
3505 	__umtx_op_wait_compat32,	/* UMTX_OP_WAIT_UINT */
3506 	__umtx_op_rw_rdlock_compat32,	/* UMTX_OP_RW_RDLOCK */
3507 	__umtx_op_rw_wrlock_compat32,	/* UMTX_OP_RW_WRLOCK */
3508 	__umtx_op_rw_unlock,		/* UMTX_OP_RW_UNLOCK */
3509 	__umtx_op_wait_uint_private_compat32,	/* UMTX_OP_WAIT_UINT_PRIVATE */
3510 	__umtx_op_wake_private,		/* UMTX_OP_WAKE_PRIVATE */
3511 	__umtx_op_wait_umutex_compat32, /* UMTX_OP_UMUTEX_WAIT */
3512 	__umtx_op_wake_umutex,		/* UMTX_OP_UMUTEX_WAKE */
3513 	__umtx_op_sem_wait_compat32,	/* UMTX_OP_SEM_WAIT */
3514 	__umtx_op_sem_wake		/* UMTX_OP_SEM_WAKE */
3515 };
3516 
3517 int
3518 freebsd32_umtx_op(struct thread *td, struct freebsd32_umtx_op_args *uap)
3519 {
3520 	if ((unsigned)uap->op < UMTX_OP_MAX)
3521 		return (*op_table_compat32[uap->op])(td,
3522 			(struct _umtx_op_args *)uap);
3523 	return (EINVAL);
3524 }
3525 #endif
3526 
3527 void
3528 umtx_thread_init(struct thread *td)
3529 {
3530 	td->td_umtxq = umtxq_alloc();
3531 	td->td_umtxq->uq_thread = td;
3532 }
3533 
3534 void
3535 umtx_thread_fini(struct thread *td)
3536 {
3537 	umtxq_free(td->td_umtxq);
3538 }
3539 
3540 /*
3541  * It will be called when new thread is created, e.g fork().
3542  */
3543 void
3544 umtx_thread_alloc(struct thread *td)
3545 {
3546 	struct umtx_q *uq;
3547 
3548 	uq = td->td_umtxq;
3549 	uq->uq_inherited_pri = PRI_MAX;
3550 
3551 	KASSERT(uq->uq_flags == 0, ("uq_flags != 0"));
3552 	KASSERT(uq->uq_thread == td, ("uq_thread != td"));
3553 	KASSERT(uq->uq_pi_blocked == NULL, ("uq_pi_blocked != NULL"));
3554 	KASSERT(TAILQ_EMPTY(&uq->uq_pi_contested), ("uq_pi_contested is not empty"));
3555 }
3556 
3557 /*
3558  * exec() hook.
3559  */
3560 static void
3561 umtx_exec_hook(void *arg __unused, struct proc *p __unused,
3562 	struct image_params *imgp __unused)
3563 {
3564 	umtx_thread_cleanup(curthread);
3565 }
3566 
3567 /*
3568  * thread_exit() hook.
3569  */
3570 void
3571 umtx_thread_exit(struct thread *td)
3572 {
3573 	umtx_thread_cleanup(td);
3574 }
3575 
3576 /*
3577  * clean up umtx data.
3578  */
3579 static void
3580 umtx_thread_cleanup(struct thread *td)
3581 {
3582 	struct umtx_q *uq;
3583 	struct umtx_pi *pi;
3584 
3585 	if ((uq = td->td_umtxq) == NULL)
3586 		return;
3587 
3588 	mtx_lock_spin(&umtx_lock);
3589 	uq->uq_inherited_pri = PRI_MAX;
3590 	while ((pi = TAILQ_FIRST(&uq->uq_pi_contested)) != NULL) {
3591 		pi->pi_owner = NULL;
3592 		TAILQ_REMOVE(&uq->uq_pi_contested, pi, pi_link);
3593 	}
3594 	thread_lock(td);
3595 	td->td_flags &= ~TDF_UBORROWING;
3596 	thread_unlock(td);
3597 	mtx_unlock_spin(&umtx_lock);
3598 }
3599