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