xref: /xnu-12377.1.9/osfmk/kern/waitq.c (revision f6217f891ac0bb64f3d375211650a4c1ff8ca1ea)
1 /*
2  * Copyright (c) 2015-2021 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * @OSF_FREE_COPYRIGHT@
30  */
31 /*
32  * Mach Operating System
33  * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
34  * All Rights Reserved.
35  *
36  * Permission to use, copy, modify and distribute this software and its
37  * documentation is hereby granted, provided that both the copyright
38  * notice and this permission notice appear in all copies of the
39  * software, derivative works or modified versions, and any portions
40  * thereof, and that both notices appear in supporting documentation.
41  *
42  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45  *
46  * Carnegie Mellon requests users of this software to return to
47  *
48  *  Software Distribution Coordinator  or  [email protected]
49  *  School of Computer Science
50  *  Carnegie Mellon University
51  *  Pittsburgh PA 15213-3890
52  *
53  * any improvements or extensions that they make and grant Carnegie Mellon
54  * the rights to redistribute these changes.
55  */
56 
57 #include <kern/ast.h>
58 #include <kern/backtrace.h>
59 #include <kern/kern_types.h>
60 #include <kern/mach_param.h>
61 #include <kern/percpu.h>
62 #include <kern/queue.h>
63 #include <kern/sched_prim.h>
64 #include <kern/simple_lock.h>
65 #include <kern/spl.h>
66 #include <kern/waitq.h>
67 #include <kern/zalloc.h>
68 #include <kern/policy_internal.h>
69 #include <kern/turnstile.h>
70 
71 #include <os/hash.h>
72 #include <libkern/section_keywords.h>
73 #include <mach/sync_policy.h>
74 #include <vm/vm_kern_xnu.h>
75 
76 #include <sys/kdebug.h>
77 
78 /*!
79  * @const waitq_set_unlink_batch
80  *
81  * @brief
82  * How many links are unhooked under a single set lock hold.
83  *
84  * @discussion
85  * Holding a waitq set lock for too long can cause
86  * extreme contention (when a set is being torn down concurrently
87  * to messages being sent to ports who used to belong to that set).
88  *
89  * In order to fight this, large wait queue sets will drop
90  * and reacquire their lock for each unlinking batch.
91  */
92 static TUNABLE(uint32_t, waitq_set_unlink_batch, "waitq_set_unlink_batch", 64);
93 
94 /*!
95  * @const WQL_PREPOST_MARKER
96  *
97  * @brief
98  * Marker set in the @c wql_wqs field of wait queue linkages to denote that
99  * this linkage has preposted to its wait queue set already.
100  *
101  * @discussion
102  * This bit is manipulated under both the wait queue and the wait queue set
103  * locks, and is used for two purposes:
104  *
105  * - for port set queues, it denotes in which circle queue the linkage
106  *   is queued on (@c waitq_set::wqset_links or @c waitq_set::wqset_preposts)
107  *
108  * - as an optimization during pre-post to not walk sets this link already
109  *   preposted to.
110  */
111 #define WQL_PREPOST_MARKER 1ul
112 
113 #if __LP64__
114 /*!
115  * @struct waitq_link_hdr
116  *
117  * @brief
118  * Common "header" between all linkages, in order to find the waitq_set
119  * of this linkage.
120  *
121  * @discussion
122  * Due to unfortunate alignment constraints on @c queue_chain_t,
123  * this is wildly different for LP64 and ILP32.
124  *
125  * Do note that `wql
126  */
127 struct waitq_link_hdr {
128 	uintptr_t       wql_wqs;
129 };
130 
131 /*!
132  * @struct waitq_sellink
133  *
134  * @brief
135  * Linkages used for select waitq queues to select wait queue sets.
136  *
137  * @discussion
138  * Select linkages are one way (queue to set) for two reasons:
139  *
140  * 1. select doesn't use the wait queue subsystem to discover which file
141  *    descriptor woke up the set (it will instead scan all fds again),
142  *
143  * 2. all linkages are unhooked on each syscall return, so we minimize
144  *    work to be done to be as quick as possible, using a fast invalidation
145  *    scheme based on unique identifiers and sequestering
146  *    (see @c select_set_nextid()).
147  */
148 struct waitq_sellink {
149 	uintptr_t       wql_wqs;
150 	struct waitq_link_list_entry wql_next;
151 	uint64_t        wql_setid;
152 };
153 
154 /*!
155  * @struct waitq_link
156  *
157  * @brief
158  * Linkages used for port wait queues and port-set wait queue sets.
159  *
160  * @discussion
161  * Those linkages go both ways so that receiving messages through a port-set
162  * can quickly find ports that preposted to the set.
163  *
164  * It also means that unhooking linkages cannot be lazy.
165  */
166 struct waitq_link {
167 	uintptr_t       wql_wqs;       /**< wait queue set for this link      */
168 	queue_chain_t   wql_qlink;     /**< linkage through the waitq list    */
169 	queue_chain_t   wql_slink;     /**< linkage through the wqset list    */
170 	struct waitq   *wql_wq;        /**< wait queue for this link          */
171 };
172 #else
173 struct waitq_link_hdr {
174 	uint64_t        __wql_padding;
175 	uintptr_t       wql_wqs;
176 };
177 
178 struct waitq_sellink {
179 	struct waitq_link_list_entry wql_next;
180 	uintptr_t       __wql_padding;
181 	uintptr_t       wql_wqs;
182 	uint64_t        wql_setid;
183 };
184 
185 struct waitq_link {
186 	queue_chain_t   wql_qlink;
187 	uintptr_t       wql_wqs;
188 	struct waitq   *wql_wq;
189 	queue_chain_t   wql_slink;
190 };
191 #endif
192 
193 static_assert(offsetof(struct waitq_link_hdr, wql_wqs) ==
194     offsetof(struct waitq_sellink, wql_wqs));
195 static_assert(offsetof(struct waitq_link_hdr, wql_wqs) ==
196     offsetof(struct waitq_link, wql_wqs));
197 static_assert(sizeof(struct waitq) <= WQ_OPAQUE_SIZE, "waitq structure size mismatch");
198 static_assert(__alignof(struct waitq) == WQ_OPAQUE_ALIGN, "waitq structure alignment mismatch");
199 
200 static KALLOC_TYPE_DEFINE(waitq_sellink_zone, struct waitq_sellink, KT_PRIV_ACCT);
201 static KALLOC_TYPE_DEFINE(waitq_link_zone, struct waitq_link, KT_PRIV_ACCT);
202 ZONE_DEFINE_ID(ZONE_ID_SELECT_SET, "select_set", struct select_set,
203     ZC_SEQUESTER | ZC_ZFREE_CLEARMEM);
204 
205 static LCK_GRP_DECLARE(waitq_lck_grp, "waitq");
206 
207 static uint64_t PERCPU_DATA(select_setid);
208 struct waitq select_conflict_queue;
209 
210 #pragma mark waitq links
211 
212 static inline bool
waitq_is_sellink(waitq_type_t type)213 waitq_is_sellink(waitq_type_t type)
214 {
215 	return type == WQT_SELECT || type == WQT_SELECT_SET;
216 }
217 
218 static inline bool
wql_sellink_valid(struct select_set * selset,struct waitq_sellink * link)219 wql_sellink_valid(struct select_set *selset, struct waitq_sellink *link)
220 {
221 	return waitq_valid(selset) && selset->selset_id == link->wql_setid;
222 }
223 
224 static waitq_t
wql_wqs(waitq_link_t link)225 wql_wqs(waitq_link_t link)
226 {
227 	return (waitq_t){ (void *)(link.wqlh->wql_wqs & ~WQL_PREPOST_MARKER) };
228 }
229 
230 static bool
wql_wqs_preposted(waitq_link_t link)231 wql_wqs_preposted(waitq_link_t link)
232 {
233 	return link.wqlh->wql_wqs & WQL_PREPOST_MARKER;
234 }
235 
236 static void
wql_wqs_mark_preposted(waitq_link_t link)237 wql_wqs_mark_preposted(waitq_link_t link)
238 {
239 	assert(!wql_wqs_preposted(link));
240 	link.wqlh->wql_wqs |= WQL_PREPOST_MARKER;
241 }
242 
243 static void
wql_wqs_clear_preposted(waitq_link_t link)244 wql_wqs_clear_preposted(waitq_link_t link)
245 {
246 	assert(wql_wqs_preposted(link));
247 	link.wqlh->wql_wqs &= ~WQL_PREPOST_MARKER;
248 }
249 
250 static circle_queue_t
wql_wqs_queue(struct waitq_set * wqs,struct waitq_link * link)251 wql_wqs_queue(struct waitq_set *wqs, struct waitq_link *link)
252 {
253 	return wql_wqs_preposted(link) ? &wqs->wqset_preposts : &wqs->wqset_links;
254 }
255 
256 static void
wql_list_push(waitq_link_list_t * list,waitq_link_t link)257 wql_list_push(waitq_link_list_t *list, waitq_link_t link)
258 {
259 	link.wqls->wql_next.next = list->next;
260 	list->next = &link.wqls->wql_next;
261 }
262 
263 static inline struct waitq_sellink *
wql_list_elem(struct waitq_link_list_entry * e)264 wql_list_elem(struct waitq_link_list_entry *e)
265 {
266 	return e ? __container_of(e, struct waitq_sellink, wql_next) : NULL;
267 }
268 
269 /*!
270  * @function wql_list_next()
271  *
272  * @brief
273  * Helper function to implement wait queue link list enumeration.
274  *
275  * @param e             in: pointer to the current element,
276  *                      out: pointer to the next element or NULL
277  * @param end           which element to stop enumeration at (NULL for lists,
278  *                      or the first element enumerated for circle queues).
279  * @returns true        (makes writing for(;;) based enumerators easier).
280  */
281 static inline bool
wql_list_next(struct waitq_link_list_entry ** e,struct waitq_link_list_entry * end)282 wql_list_next(struct waitq_link_list_entry **e, struct waitq_link_list_entry *end)
283 {
284 	if (*e == NULL || (*e)->next == end) {
285 		*e = NULL;
286 	} else {
287 		*e = (*e)->next;
288 	}
289 	return true;
290 }
291 
292 #define __wql_list_foreach(it, head, end) \
293 	for (struct waitq_link_list_entry *__it = (head)->next, *__end = end; \
294 	    ((it) = wql_list_elem(__it)); wql_list_next(&__it, __end))
295 
296 #define wql_list_foreach(it, head) \
297 	__wql_list_foreach(it, head, NULL)
298 
299 #define wql_list_foreach_safe(it, head) \
300 	for (struct waitq_link_list_entry *__it = (head)->next;                \
301 	    ((it) = wql_list_elem(__it)) && wql_list_next(&__it, NULL); )
302 
303 /*
304  * Gross hack: passing `__it` to `__wql_list_foreach` makes it stop whether
305  * we circle back to the first element or NULL (whichever comes first).
306  *
307  * This allows to have a single enumeration function oblivious to whether
308  * we enumerate a circle queue or a sellink list.
309  */
310 #define waitq_link_foreach(link, waitq) \
311 	__wql_list_foreach((link).wqls, &(waitq).wq_q->waitq_sellinks, __it)
312 
313 static_assert(offsetof(struct waitq, waitq_sellinks) ==
314     offsetof(struct waitq, waitq_links));
315 static_assert(offsetof(struct waitq_sellink, wql_next) ==
316     offsetof(struct waitq_link, wql_qlink.next));
317 
318 static struct waitq_link *
wql_find(struct waitq * waitq,waitq_t wqset)319 wql_find(struct waitq *waitq, waitq_t wqset)
320 {
321 	struct waitq_link *link;
322 
323 	cqe_foreach_element(link, &waitq->waitq_links, wql_qlink) {
324 		if (waitq_same(wql_wqs(link), wqset)) {
325 			return link;
326 		}
327 	}
328 
329 	return NULL;
330 }
331 
332 waitq_link_t
waitq_link_alloc(waitq_type_t type)333 waitq_link_alloc(waitq_type_t type)
334 {
335 	waitq_link_t link;
336 
337 	if (waitq_is_sellink(type)) {
338 		link.wqls = zalloc_flags(waitq_sellink_zone, Z_WAITOK | Z_ZERO);
339 	} else {
340 		link.wqll = zalloc_flags(waitq_link_zone, Z_WAITOK | Z_ZERO);
341 	}
342 	return link;
343 }
344 
345 void
waitq_link_free(waitq_type_t type,waitq_link_t link)346 waitq_link_free(waitq_type_t type, waitq_link_t link)
347 {
348 	if (waitq_is_sellink(type)) {
349 		return zfree(waitq_sellink_zone, link.wqls);
350 	} else {
351 		return zfree(waitq_link_zone, link.wqll);
352 	}
353 }
354 
355 void
waitq_link_free_list(waitq_type_t type,waitq_link_list_t * free_l)356 waitq_link_free_list(waitq_type_t type, waitq_link_list_t *free_l)
357 {
358 	waitq_link_t link;
359 
360 	wql_list_foreach_safe(link.wqls, free_l) {
361 		waitq_link_free(type, link);
362 	}
363 
364 	free_l->next = NULL;
365 }
366 
367 
368 #pragma mark global wait queues
369 
370 static __startup_data struct waitq g_boot_waitq;
371 static SECURITY_READ_ONLY_LATE(struct waitq *) global_waitqs = &g_boot_waitq;
372 static SECURITY_READ_ONLY_LATE(uint32_t) g_num_waitqs = 1;
373 
374 /*
375  * Zero out the used MSBs of the event.
376  */
377 #define _CAST_TO_EVENT_MASK(event) \
378 	((waitq_flags_t)(uintptr_t)(event) & ((1ul << _EVENT_MASK_BITS) - 1ul))
379 
380 /* return a global waitq pointer corresponding to the given event */
381 struct waitq *
_global_eventq(event64_t event)382 _global_eventq(event64_t event)
383 {
384 	/*
385 	 * this doesn't use os_hash_kernel_pointer() because
386 	 * some clients use "numbers" here.
387 	 */
388 	return &global_waitqs[os_hash_uint64(event) & (g_num_waitqs - 1)];
389 }
390 
391 bool
waitq_is_valid(waitq_t waitq)392 waitq_is_valid(waitq_t waitq)
393 {
394 	return waitq_valid(waitq);
395 }
396 
397 static inline bool
waitq_is_global(waitq_t waitq)398 waitq_is_global(waitq_t waitq)
399 {
400 	if (waitq_type(waitq) != WQT_QUEUE) {
401 		return false;
402 	}
403 	return waitq.wq_q >= global_waitqs && waitq.wq_q < global_waitqs + g_num_waitqs;
404 }
405 
406 static inline bool
waitq_empty(waitq_t wq)407 waitq_empty(waitq_t wq)
408 {
409 	struct turnstile *ts;
410 
411 	switch (waitq_type(wq)) {
412 	case WQT_TURNSTILE:
413 		return priority_queue_empty(&wq.wq_q->waitq_prio_queue);
414 	case WQT_PORT:
415 		ts = wq.wq_q->waitq_ts;
416 		return ts == TURNSTILE_NULL ||
417 		       priority_queue_empty(&ts->ts_waitq.waitq_prio_queue);
418 	case WQT_QUEUE:
419 	case WQT_SELECT:
420 	case WQT_PORT_SET:
421 	case WQT_SELECT_SET:
422 		return circle_queue_empty(&wq.wq_q->waitq_queue);
423 
424 	default:
425 		return true;
426 	}
427 }
428 
429 #if CONFIG_WAITQ_STATS
430 #define NWAITQ_BTFRAMES 5
431 
432 struct wq_stats {
433 	uint64_t waits;
434 	uint64_t wakeups;
435 	uint64_t clears;
436 	uint64_t failed_wakeups;
437 
438 	uintptr_t last_wait[NWAITQ_BTFRAMES];
439 	uintptr_t last_wakeup[NWAITQ_BTFRAMES];
440 	uintptr_t last_failed_wakeup[NWAITQ_BTFRAMES];
441 };
442 
443 /* this global is for lldb */
444 const uint32_t g_nwaitq_btframes = NWAITQ_BTFRAMES;
445 struct wq_stats g_boot_stats;
446 struct wq_stats *g_waitq_stats = &g_boot_stats;
447 
448 static __inline__ void
waitq_grab_backtrace(uintptr_t bt[NWAITQ_BTFRAMES],unsigned skip)449 waitq_grab_backtrace(uintptr_t bt[NWAITQ_BTFRAMES], unsigned skip)
450 {
451 	uintptr_t buf[NWAITQ_BTFRAMES + skip];
452 
453 	memset(buf, 0, (NWAITQ_BTFRAMES + skip) * sizeof(uintptr_t));
454 	backtrace(buf, g_nwaitq_btframes + skip, NULL, NULL);
455 	memcpy(&bt[0], &buf[skip], NWAITQ_BTFRAMES * sizeof(uintptr_t));
456 }
457 
458 static __inline__ struct wq_stats *
waitq_global_stats(waitq_t waitq)459 waitq_global_stats(waitq_t waitq)
460 {
461 	struct wq_stats *wqs;
462 	uint32_t idx;
463 
464 	if (!waitq_is_global(waitq)) {
465 		return NULL;
466 	}
467 
468 	idx = (uint32_t)(waitq.wq_q - global_waitqs);
469 	assert(idx < g_num_waitqs);
470 	wqs = &g_waitq_stats[idx];
471 	return wqs;
472 }
473 
474 static __inline__ void
waitq_stats_count_wait(waitq_t waitq)475 waitq_stats_count_wait(waitq_t waitq)
476 {
477 	struct wq_stats *wqs = waitq_global_stats(waitq);
478 	if (wqs != NULL) {
479 		wqs->waits++;
480 		waitq_grab_backtrace(wqs->last_wait, 2);
481 	}
482 }
483 
484 static __inline__ void
waitq_stats_count_wakeup(waitq_t waitq,int n)485 waitq_stats_count_wakeup(waitq_t waitq, int n)
486 {
487 	struct wq_stats *wqs = waitq_global_stats(waitq);
488 	if (wqs != NULL) {
489 		if (n > 0) {
490 			wqs->wakeups += n;
491 			waitq_grab_backtrace(wqs->last_wakeup, 2);
492 		} else {
493 			wqs->failed_wakeups++;
494 			waitq_grab_backtrace(wqs->last_failed_wakeup, 2);
495 		}
496 	}
497 }
498 
499 static __inline__ void
waitq_stats_count_clear_wakeup(waitq_t waitq)500 waitq_stats_count_clear_wakeup(waitq_t waitq)
501 {
502 	struct wq_stats *wqs = waitq_global_stats(waitq);
503 	if (wqs != NULL) {
504 		wqs->wakeups++;
505 		wqs->clears++;
506 		waitq_grab_backtrace(wqs->last_wakeup, 2);
507 	}
508 }
509 #else /* !CONFIG_WAITQ_STATS */
510 #define waitq_stats_count_wait(q)         do { } while (0)
511 #define waitq_stats_count_wakeup(q, n)    do { } while (0)
512 #define waitq_stats_count_clear_wakeup(q) do { } while (0)
513 #endif
514 
515 static struct waitq *
waitq_get_safeq(waitq_t waitq)516 waitq_get_safeq(waitq_t waitq)
517 {
518 	if (waitq_type(waitq) == WQT_PORT) {
519 		struct turnstile *ts = waitq.wq_q->waitq_ts;
520 		return ts ? &ts->ts_waitq : NULL;
521 	}
522 
523 	uint32_t hash = os_hash_kernel_pointer(waitq.wq_q);
524 	return &global_waitqs[hash & (g_num_waitqs - 1)];
525 }
526 
527 /*
528  * Since the priority ordered waitq uses basepri as the
529  * ordering key assert that this value fits in a uint8_t.
530  */
531 static_assert(MAXPRI <= UINT8_MAX);
532 
533 static inline void
waitq_thread_insert(struct waitq * safeq,thread_t thread,waitq_t wq,event64_t event)534 waitq_thread_insert(struct waitq *safeq, thread_t thread,
535     waitq_t wq, event64_t event)
536 {
537 	if (waitq_type(safeq) == WQT_TURNSTILE) {
538 		turnstile_stats_update(0, TSU_TURNSTILE_BLOCK_COUNT, NULL);
539 		turnstile_waitq_add_thread_priority_queue(safeq, thread);
540 	} else {
541 		turnstile_stats_update(0, TSU_REGULAR_WAITQ_BLOCK_COUNT, NULL);
542 		/*
543 		 * This is the extent to which we currently take scheduling
544 		 * attributes into account:
545 		 *
546 		 * - If the thread is vm privileged, we stick it at the front
547 		 *   of the queue, later, these queues will honor the policy
548 		 *   value set at waitq_init time.
549 		 *
550 		 * - Realtime threads get priority for wait queue placements.
551 		 *   This allows wait_queue_wakeup_one to prefer a waiting
552 		 *   realtime thread, similar in principle to performing
553 		 *   a wait_queue_wakeup_all and allowing scheduler
554 		 *   prioritization to run the realtime thread, but without
555 		 *   causing the lock contention of that scenario.
556 		 */
557 		if (thread->sched_pri >= BASEPRI_REALTIME ||
558 		    !safeq->waitq_fifo ||
559 		    (thread->options & TH_OPT_VMPRIV)) {
560 			circle_enqueue_head(&safeq->waitq_queue, &thread->wait_links);
561 		} else {
562 			circle_enqueue_tail(&safeq->waitq_queue, &thread->wait_links);
563 		}
564 	}
565 
566 	/* mark the event and real waitq, even if enqueued on a global safeq */
567 	thread->wait_event = event;
568 	thread->waitq = wq;
569 }
570 
571 /**
572  * clear the thread-related waitq state, moving the thread from
573  * TH_WAIT to TH_WAIT | TH_WAKING, where it is no longer on a waitq and
574  * can expect to be go'ed in the near future.
575  *
576  * Clearing the waitq prevents further propagation of a turnstile boost
577  * on the thread and stops a clear_wait from succeeding.
578  *
579  * Conditions:
580  *	'thread' is locked, thread is waiting
581  */
582 static inline void
thread_clear_waitq_state(thread_t thread)583 thread_clear_waitq_state(thread_t thread)
584 {
585 	assert(thread->state & TH_WAIT);
586 
587 	thread->waitq.wq_q = NULL;
588 	thread->wait_event = NO_EVENT64;
589 	thread->at_safe_point = FALSE;
590 	thread->block_hint = kThreadWaitNone;
591 	thread->state |= TH_WAKING;
592 }
593 
594 static inline void
waitq_thread_remove(waitq_t wq,thread_t thread)595 waitq_thread_remove(waitq_t wq, thread_t thread)
596 {
597 	if (waitq_type(wq) == WQT_TURNSTILE) {
598 		KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
599 		    (TURNSTILE_CODE(TURNSTILE_HEAP_OPERATIONS,
600 		    (THREAD_REMOVED_FROM_TURNSTILE_WAITQ))) | DBG_FUNC_NONE,
601 		    VM_KERNEL_UNSLIDE_OR_PERM(waitq_to_turnstile(wq.wq_q)),
602 		    thread_tid(thread), 0, 0, 0);
603 		priority_queue_remove(&wq.wq_q->waitq_prio_queue,
604 		    &thread->wait_prioq_links);
605 	} else {
606 		circle_dequeue(&wq.wq_q->waitq_queue, &thread->wait_links);
607 		if (waitq_is_global(wq) && waitq_empty(wq)) {
608 			wq.wq_q->waitq_eventmask = 0;
609 		}
610 	}
611 
612 	thread_clear_waitq_state(thread);
613 }
614 
615 bool
waitq_wait_possible(thread_t thread)616 waitq_wait_possible(thread_t thread)
617 {
618 	return waitq_is_null(thread->waitq) &&
619 	       ((thread->state & TH_WAKING) == 0);
620 }
621 
622 __static_testable void waitq_bootstrap(void);
623 
624 __startup_func
625 __static_testable void
waitq_bootstrap(void)626 waitq_bootstrap(void)
627 {
628 	const uint32_t qsz = sizeof(struct waitq);
629 	vm_offset_t whsize;
630 	int cpu = 0;
631 
632 	/*
633 	 * Determine the amount of memory we're willing to reserve for
634 	 * the waitqueue hash table
635 	 */
636 	if (!PE_parse_boot_argn("wqsize", &whsize, sizeof(whsize))) {
637 		whsize = round_page(thread_max * qsz / 5);
638 	}
639 
640 	/*
641 	 * Determine the number of waitqueues we can fit.
642 	 * The hash algorithm requires that this be a power of 2.
643 	 */
644 	g_num_waitqs = 0x80000000u >> __builtin_clzl(whsize / qsz);
645 	assert(g_num_waitqs > 0);
646 	whsize = round_page(g_num_waitqs * qsz);
647 
648 	kmem_alloc(kernel_map, (vm_offset_t *)&global_waitqs, whsize,
649 	    KMA_NOFAIL | KMA_KOBJECT | KMA_NOPAGEWAIT | KMA_PERMANENT,
650 	    VM_KERN_MEMORY_WAITQ);
651 
652 #if CONFIG_WAITQ_STATS
653 	whsize = round_page(g_num_waitqs * sizeof(struct wq_stats));
654 	kmem_alloc(kernel_map, (vm_offset_t *)&g_waitq_stats, whsize,
655 	    KMA_NOFAIL | KMA_KOBJECT | KMA_NOPAGEWAIT | KMA_ZERO | KMA_PERMANENT,
656 	    VM_KERN_MEMORY_WAITQ);
657 #endif
658 
659 	for (uint32_t i = 0; i < g_num_waitqs; i++) {
660 		waitq_init(&global_waitqs[i], WQT_QUEUE, SYNC_POLICY_FIFO);
661 	}
662 
663 	waitq_init(&select_conflict_queue, WQT_SELECT, SYNC_POLICY_FIFO);
664 
665 	percpu_foreach(setid, select_setid) {
666 		/* is not cpu_number() but CPUs haven't been numbered yet */
667 		*setid = cpu++;
668 	}
669 }
670 STARTUP(MACH_IPC, STARTUP_RANK_FIRST, waitq_bootstrap);
671 
672 
673 #pragma mark locking
674 
675 static hw_spin_timeout_status_t
waitq_timeout_handler(void * _lock,hw_spin_timeout_t to,hw_spin_state_t st)676 waitq_timeout_handler(void *_lock, hw_spin_timeout_t to, hw_spin_state_t st)
677 {
678 	lck_spinlock_to_info_t lsti;
679 	hw_lck_ticket_t tmp;
680 	struct waitq *wq = _lock;
681 
682 	if (machine_timeout_suspended()) {
683 		return HW_LOCK_TIMEOUT_CONTINUE;
684 	}
685 
686 	lsti = lck_spinlock_timeout_hit(&wq->waitq_interlock, 0);
687 	tmp.tcurnext = os_atomic_load(&wq->waitq_interlock.tcurnext, relaxed);
688 
689 	panic("waitq(%p) lock " HW_SPIN_TIMEOUT_FMT "; cpu=%d, "
690 	    "cticket: 0x%x, nticket: 0x%x, waiting for 0x%x, "
691 	    HW_SPIN_TIMEOUT_DETAILS_FMT,
692 	    wq, HW_SPIN_TIMEOUT_ARG(to, st), cpu_number(),
693 	    tmp.cticket, tmp.nticket, lsti->extra,
694 	    HW_SPIN_TIMEOUT_DETAILS_ARG(to, st));
695 }
696 
697 static const struct hw_spin_policy waitq_spin_policy = {
698 	.hwsp_name              = "waitq",
699 #if defined(__i386__) || defined(__x86_64__)
700 	.hwsp_timeout           = &LockTimeOutTSC,
701 #else
702 	.hwsp_timeout_atomic    = &LockTimeOut,
703 #endif
704 	/*
705 	 * Double the standard lock timeout, because wait queues tend
706 	 * to iterate over a number of threads - locking each.  If there is
707 	 * a problem with a thread lock, it normally times out at the wait
708 	 * queue level first, hiding the real problem.
709 	 */
710 	.hwsp_timeout_shift     = 1,
711 	.hwsp_lock_offset       = offsetof(struct waitq, waitq_interlock),
712 	.hwsp_op_timeout        = waitq_timeout_handler,
713 };
714 
715 __mockable void
waitq_invalidate(waitq_t waitq)716 waitq_invalidate(waitq_t waitq)
717 {
718 	hw_lck_ticket_invalidate(&waitq.wq_q->waitq_interlock);
719 }
720 
721 __mockable bool
waitq_held(waitq_t wq)722 waitq_held(waitq_t wq)
723 {
724 	return hw_lck_ticket_held(&wq.wq_q->waitq_interlock);
725 }
726 
727 __mockable void
waitq_lock(waitq_t wq)728 waitq_lock(waitq_t wq)
729 {
730 	(void)hw_lck_ticket_lock_to(&wq.wq_q->waitq_interlock,
731 	    &waitq_spin_policy, &waitq_lck_grp);
732 #if defined(__x86_64__)
733 	pltrace(FALSE);
734 #endif
735 }
736 
737 __mockable bool
waitq_lock_try(waitq_t wq)738 waitq_lock_try(waitq_t wq)
739 {
740 	bool rc = hw_lck_ticket_lock_try(&wq.wq_q->waitq_interlock, &waitq_lck_grp);
741 
742 #if defined(__x86_64__)
743 	if (rc) {
744 		pltrace(FALSE);
745 	}
746 #endif
747 	return rc;
748 }
749 
750 bool
waitq_lock_reserve(waitq_t wq,uint32_t * ticket)751 waitq_lock_reserve(waitq_t wq, uint32_t *ticket)
752 {
753 	return hw_lck_ticket_reserve(&wq.wq_q->waitq_interlock, ticket, &waitq_lck_grp);
754 }
755 
756 __mockable void
waitq_lock_wait(waitq_t wq,uint32_t ticket)757 waitq_lock_wait(waitq_t wq, uint32_t ticket)
758 {
759 	(void)hw_lck_ticket_wait(&wq.wq_q->waitq_interlock, ticket,
760 	    &waitq_spin_policy, &waitq_lck_grp);
761 #if defined(__x86_64__)
762 	pltrace(FALSE);
763 #endif
764 }
765 
766 bool
waitq_lock_allow_invalid(waitq_t wq)767 waitq_lock_allow_invalid(waitq_t wq)
768 {
769 	hw_lock_status_t rc;
770 
771 	rc = hw_lck_ticket_lock_allow_invalid(&wq.wq_q->waitq_interlock,
772 	    &waitq_spin_policy, &waitq_lck_grp);
773 
774 #if defined(__x86_64__)
775 	if (rc == HW_LOCK_ACQUIRED) {
776 		pltrace(FALSE);
777 	}
778 #endif
779 	return rc == HW_LOCK_ACQUIRED;
780 }
781 
782 __mockable void
waitq_unlock(waitq_t wq)783 waitq_unlock(waitq_t wq)
784 {
785 	assert(waitq_held(wq));
786 #if defined(__x86_64__)
787 	pltrace(TRUE);
788 #endif
789 	hw_lck_ticket_unlock(&wq.wq_q->waitq_interlock);
790 }
791 
792 
793 #pragma mark assert_wait / wakeup
794 
795 struct waitq_select_args {
796 	/* input parameters */
797 	event64_t               event;
798 	wait_result_t           result;
799 	waitq_wakeup_flags_t    flags;
800 	uint32_t                max_threads;
801 	bool                    is_identified;
802 
803 	/* output parameters */
804 	/* counts all woken threads, may have more threads than on threadq */
805 	uint32_t                nthreads;
806 	/* preemption is disabled while threadq is non-empty */
807 	circle_queue_head_t     threadq;
808 };
809 
810 static inline void
maybe_adjust_thread_pri(thread_t thread,waitq_wakeup_flags_t flags,__kdebug_only waitq_t waitq)811 maybe_adjust_thread_pri(
812 	thread_t                thread,
813 	waitq_wakeup_flags_t    flags,
814 	__kdebug_only waitq_t   waitq)
815 {
816 	/*
817 	 * If the caller is requesting the waitq subsystem to promote the
818 	 * priority of the awoken thread, then boost the thread's priority to
819 	 * the default WAITQ_BOOST_PRIORITY (if it's not already equal or
820 	 * higher priority).  This boost must be removed via a call to
821 	 * waitq_clear_promotion_locked before the thread waits again.
822 	 */
823 	if (flags & WAITQ_PROMOTE_PRIORITY) {
824 		uintptr_t trace_waitq = 0;
825 		if (__improbable(kdebug_enable)) {
826 			trace_waitq = VM_KERNEL_UNSLIDE_OR_PERM(waitq.wq_q);
827 		}
828 
829 		sched_thread_promote_reason(thread, TH_SFLAG_WAITQ_PROMOTED, trace_waitq);
830 	}
831 }
832 
833 static void
waitq_select_queue_add(waitq_t waitq,thread_t thread,struct waitq_select_args * args)834 waitq_select_queue_add(waitq_t waitq, thread_t thread, struct waitq_select_args *args)
835 {
836 	spl_t s = splsched();
837 
838 	thread_lock(thread);
839 	thread_clear_waitq_state(thread);
840 
841 	if (!args->is_identified && thread->state & TH_RUN) {
842 		/*
843 		 * A thread that is currently on core may try to clear its own
844 		 * wait with clear wait or by waking its own event instead of
845 		 * calling thread_block as is normally expected.  After doing
846 		 * this, it expects to be able to immediately wait again.
847 		 *
848 		 * If we are currently on a different CPU and waking that
849 		 * thread, as soon as we unlock the waitq and thread, that
850 		 * operation could complete, but we would still be holding the
851 		 * thread on our flush queue, leaving it in the waking state
852 		 * where it can't yet assert another wait.
853 		 *
854 		 * Since we know that we won't actually need to enqueue the
855 		 * thread on the runq due to it being on core, we can just
856 		 * immediately unblock it here so that the thread will be in a
857 		 * waitable state after we release its thread lock from this
858 		 * lock hold.
859 		 *
860 		 * Wakeups using *_identify can't be allowed to pass
861 		 * thread block until they're resumed, so they can't use
862 		 * this path.  That means they are not allowed to skip calling
863 		 * thread_block.
864 		 */
865 		maybe_adjust_thread_pri(thread, args->flags, waitq);
866 		thread_go(thread, args->result, false);
867 	} else {
868 		if (circle_queue_empty(&args->threadq)) {
869 			/*
870 			 * preemption is disabled while threads are
871 			 * on threadq - balanced in:
872 			 * waitq_resume_identified_thread
873 			 * waitq_select_queue_flush
874 			 */
875 			disable_preemption();
876 		}
877 
878 		circle_enqueue_tail(&args->threadq, &thread->wait_links);
879 	}
880 
881 	thread_unlock(thread);
882 
883 	splx(s);
884 }
885 
886 
887 #if SCHED_HYGIENE_DEBUG
888 
889 TUNABLE_DEV_WRITEABLE(uint32_t, waitq_flush_excess_threads, "waitq_flush_excess_threads", 20);
890 TUNABLE_DEV_WRITEABLE(uint32_t, waitq_flush_excess_time_mt, "waitq_flush_excess_time_mt", 7200); /* 300us */
891 
892 #endif /* SCHED_HYGIENE_DEBUG */
893 
894 
895 static void
waitq_select_queue_flush(waitq_t waitq,struct waitq_select_args * args)896 waitq_select_queue_flush(waitq_t waitq, struct waitq_select_args *args)
897 {
898 	thread_t thread = THREAD_NULL;
899 
900 	assert(!circle_queue_empty(&args->threadq));
901 
902 	int flushed_threads = 0;
903 
904 #if SCHED_HYGIENE_DEBUG
905 	uint64_t start_time = ml_get_sched_hygiene_timebase();
906 	disable_preemption();
907 #endif /* SCHED_HYGIENE_DEBUG */
908 
909 	cqe_foreach_element_safe(thread, &args->threadq, wait_links) {
910 		circle_dequeue(&args->threadq, &thread->wait_links);
911 		assert_thread_magic(thread);
912 
913 		spl_t s = splsched();
914 
915 		thread_lock(thread);
916 		maybe_adjust_thread_pri(thread, args->flags, waitq);
917 		thread_go(thread, args->result, args->flags & WAITQ_HANDOFF);
918 		thread_unlock(thread);
919 
920 		splx(s);
921 
922 		flushed_threads++;
923 	}
924 
925 #if SCHED_HYGIENE_DEBUG
926 	uint64_t end_time = ml_get_sched_hygiene_timebase();
927 
928 	/*
929 	 * Check for a combination of excess threads and long time,
930 	 * so that a single thread wakeup that gets stuck is still caught
931 	 */
932 	if (waitq_flush_excess_threads && waitq_flush_excess_time_mt &&
933 	    flushed_threads > waitq_flush_excess_threads &&
934 	    (end_time - start_time) > waitq_flush_excess_time_mt) {
935 		/*
936 		 * Hack alert:
937 		 *
938 		 * If a wakeup-all is done with interrupts disabled, or if
939 		 * there are enough threads / lock contention to pass the
940 		 * preemption disable threshold, it can take Too Long to get
941 		 * through waking up all the threads, leading to
942 		 * the watchdog going off.
943 		 *
944 		 * While we are working on a change to break up this
945 		 * giant glob of work into smaller chunks, remove this
946 		 * time region from the watchdog's memory to avoid
947 		 * unit tests that wake up hundreds of threads on
948 		 * one semaphore from causing this to blow up.
949 		 *
950 		 * We only trigger this when seeing a combination of
951 		 * excess threads and long time, so that a single
952 		 * thread wakeup that gets stuck is still caught.
953 		 *
954 		 * This was improved with
955 		 * rdar://90325140
956 		 * to enable interrupts during most wakeup-all's
957 		 * and will be removed with
958 		 * rdar://101110793
959 		 */
960 		if (ml_get_interrupts_enabled() == false) {
961 			ml_spin_debug_reset(current_thread());
962 			ml_irq_debug_abandon();
963 		}
964 		abandon_preemption_disable_measurement();
965 
966 		KDBG(MACHDBG_CODE(DBG_MACH_SCHED, MACH_INT_MASKED_RESET), flushed_threads, end_time - start_time);
967 	}
968 
969 	enable_preemption();
970 
971 #endif /* SCHED_HYGIENE_DEBUG */
972 
973 	/*
974 	 * match the disable when making threadq nonempty from
975 	 * waitq_select_queue_add
976 	 */
977 	enable_preemption();
978 }
979 
980 /**
981  * Routine to iterate over the waitq for non-priority ordered waitqs
982  *
983  * Conditions:
984  *	args->waitq (and the posted waitq) is locked
985  *
986  * Notes:
987  *	If one or more threads are selected, this may disable preemption,
988  *	which is balanced when the threadq is flushed in
989  *	waitq_resume_identified_thread or waitq_select_queue_flush.
990  */
991 static waitq_flags_t
waitq_queue_iterate_locked(struct waitq * safeq,struct waitq * waitq,struct waitq_select_args * args)992 waitq_queue_iterate_locked(struct waitq *safeq, struct waitq *waitq,
993     struct waitq_select_args *args)
994 {
995 	thread_t thread = THREAD_NULL;
996 	waitq_flags_t eventmask = 0;
997 
998 	cqe_foreach_element_safe(thread, &safeq->waitq_queue, wait_links) {
999 		assert_thread_magic(thread);
1000 
1001 		/*
1002 		 * For non-priority ordered waitqs, we allow multiple events to be
1003 		 * mux'ed into the same waitq. Also safeqs may contain threads from
1004 		 * multiple waitqs. Only pick threads that match the
1005 		 * requested wait event.
1006 		 */
1007 		if (waitq_same(thread->waitq, waitq) && thread->wait_event == args->event) {
1008 			/* We found a matching thread! Pull it from the queue. */
1009 
1010 			circle_dequeue(&safeq->waitq_queue, &thread->wait_links);
1011 
1012 			waitq_select_queue_add(waitq, thread, args);
1013 
1014 			if (++args->nthreads >= args->max_threads) {
1015 				break;
1016 			}
1017 		} else {
1018 			/* thread wasn't selected so track its event */
1019 			eventmask |= waitq_same(thread->waitq, safeq)
1020 			    ? _CAST_TO_EVENT_MASK(thread->wait_event)
1021 			    : _CAST_TO_EVENT_MASK(thread->waitq.wq_q);
1022 		}
1023 	}
1024 
1025 	return eventmask;
1026 }
1027 
1028 /**
1029  * Routine to iterate and remove threads from priority ordered waitqs
1030  *
1031  * Conditions:
1032  *	args->waitq (and the posted waitq) is locked
1033  *
1034  * Notes:
1035  *	The priority ordered waitqs only support maximum priority element removal.
1036  *
1037  *	Also, the implementation makes sure that all threads in a priority ordered
1038  *	waitq are waiting on the same wait event. This is not necessarily true for
1039  *	non-priority ordered waitqs. If one or more threads are selected, this may
1040  *	disable preemption.
1041  */
1042 static void
waitq_prioq_iterate_locked(struct waitq * ts_wq,struct waitq * waitq,struct waitq_select_args * args)1043 waitq_prioq_iterate_locked(
1044 	struct waitq           *ts_wq,
1045 	struct waitq           *waitq,
1046 	struct waitq_select_args *args)
1047 {
1048 	struct turnstile *ts = waitq_to_turnstile(ts_wq);
1049 	bool update_inheritor = (args->flags & WAITQ_UPDATE_INHERITOR);
1050 
1051 	if (update_inheritor && args->max_threads == UINT32_MAX) {
1052 		/*
1053 		 * If we are going to wake up all threads,
1054 		 * go ahead and set the inheritor to NULL.
1055 		 */
1056 		turnstile_kernel_update_inheritor_on_wake_locked(ts,
1057 		    TURNSTILE_INHERITOR_NULL, TURNSTILE_INHERITOR_THREAD);
1058 		update_inheritor = false;
1059 	}
1060 
1061 	while (!priority_queue_empty(&ts_wq->waitq_prio_queue)) {
1062 		thread_t thread;
1063 
1064 		thread = priority_queue_remove_max(&ts_wq->waitq_prio_queue,
1065 		    struct thread, wait_prioq_links);
1066 
1067 		assert_thread_magic(thread);
1068 
1069 		/*
1070 		 * Ensure the wait event matches since priority ordered waitqs do not
1071 		 * support multiple events in the same waitq.
1072 		 */
1073 		assert(waitq_same(thread->waitq, waitq) && (thread->wait_event == args->event));
1074 
1075 		if (update_inheritor) {
1076 			turnstile_inheritor_t inheritor = thread;
1077 
1078 			if (priority_queue_empty(&ts_wq->waitq_prio_queue)) {
1079 				inheritor = TURNSTILE_INHERITOR_NULL;
1080 			}
1081 			turnstile_kernel_update_inheritor_on_wake_locked(ts,
1082 			    inheritor, TURNSTILE_INHERITOR_THREAD);
1083 			update_inheritor = false;
1084 		}
1085 
1086 		waitq_select_queue_add(waitq, thread, args);
1087 
1088 		if (++args->nthreads >= args->max_threads) {
1089 			break;
1090 		}
1091 	}
1092 }
1093 
1094 /**
1095  * @function do_waitq_select_n_locked_queue
1096  *
1097  * @brief
1098  * Selects threads waiting on a wait queue.
1099  *
1100  * @discussion
1101  * @c waitq is locked.
1102  * If @c waitq is a set, then the wait queue posting to it is locked too.
1103  *
1104  * If one or more threads are selected, this may disable preemption.
1105  */
1106 static void
do_waitq_select_n_locked_queue(waitq_t waitq,struct waitq_select_args * args)1107 do_waitq_select_n_locked_queue(waitq_t waitq, struct waitq_select_args *args)
1108 {
1109 	spl_t s = 0;
1110 
1111 	struct waitq *safeq;
1112 	waitq_flags_t eventmask, remaining_eventmask;
1113 
1114 	if (waitq_irq_safe(waitq)) {
1115 		eventmask = _CAST_TO_EVENT_MASK(args->event);
1116 		safeq = waitq.wq_q;
1117 	} else {
1118 		/* JMM - add flag to waitq to avoid global lookup if no waiters */
1119 		eventmask = _CAST_TO_EVENT_MASK(waitq.wq_q);
1120 		safeq = waitq_get_safeq(waitq);
1121 		if (safeq == NULL) {
1122 			return;
1123 		}
1124 
1125 		s = splsched();
1126 		waitq_lock(safeq);
1127 	}
1128 
1129 	/*
1130 	 * If the safeq doesn't have an eventmask (not global) or the event
1131 	 * we're looking for IS set in its eventmask, then scan the threads
1132 	 * in that queue for ones that match the original <waitq,event> pair.
1133 	 */
1134 	if (waitq_type(safeq) == WQT_TURNSTILE) {
1135 		waitq_prioq_iterate_locked(safeq, waitq.wq_q, args);
1136 	} else if (!waitq_is_global(safeq)) {
1137 		waitq_queue_iterate_locked(safeq, waitq.wq_q, args);
1138 	} else if ((safeq->waitq_eventmask & eventmask) == eventmask) {
1139 		remaining_eventmask = waitq_queue_iterate_locked(safeq,
1140 		    waitq.wq_q, args);
1141 
1142 		/*
1143 		 * Update the eventmask of global queues we just scanned:
1144 		 * - If we selected all the threads in the queue,
1145 		 *   we can clear its eventmask.
1146 		 *
1147 		 * - If we didn't find enough threads to fill our needs,
1148 		 *   then we can assume we looked at every thread in the queue
1149 		 *   and the mask we computed is complete - so reset it.
1150 		 */
1151 		if (waitq_empty(safeq)) {
1152 			safeq->waitq_eventmask = 0;
1153 		} else if (args->nthreads < args->max_threads) {
1154 			safeq->waitq_eventmask = remaining_eventmask;
1155 		}
1156 	}
1157 
1158 	/* unlock the safe queue if we locked one above */
1159 	if (!waitq_same(waitq, safeq)) {
1160 		waitq_unlock(safeq);
1161 		splx(s);
1162 	}
1163 }
1164 
1165 /**
1166  * @function do_waitq_link_select_n_locked()
1167  *
1168  * @brief
1169  * Selects threads waiting on any set a wait queue belongs to,
1170  * or preposts the wait queue onto them.
1171  *
1172  * @discussion
1173  * @c waitq is locked.
1174  */
1175 __attribute__((noinline))
1176 static void
do_waitq_select_n_locked_sets(waitq_t waitq,struct waitq_select_args * args)1177 do_waitq_select_n_locked_sets(waitq_t waitq, struct waitq_select_args *args)
1178 {
1179 	waitq_type_t wq_type = waitq_type(waitq);
1180 	waitq_link_t link;
1181 
1182 	assert(args->event == NO_EVENT64);
1183 	assert(waitq_preposts(waitq));
1184 
1185 	waitq_link_foreach(link, waitq) {
1186 		waitq_t wqset = wql_wqs(link);
1187 
1188 		if (wql_wqs_preposted(link)) {
1189 			/*
1190 			 * The wql_wqs_preposted() bit is cleared
1191 			 * under both the wq/wqset lock.
1192 			 *
1193 			 * If the wqset is still preposted,
1194 			 * we really won't find threads there.
1195 			 *
1196 			 * Just mark the waitq as preposted and move on.
1197 			 */
1198 			if (wq_type == WQT_PORT) {
1199 				waitq.wq_q->waitq_preposted = true;
1200 			}
1201 			continue;
1202 		}
1203 
1204 		if (wq_type == WQT_SELECT) {
1205 			if (!wqset.wqs_sel) {
1206 				continue;
1207 			}
1208 			if (!waitq_lock_allow_invalid(wqset)) {
1209 				continue;
1210 			}
1211 			if (!wql_sellink_valid(wqset.wqs_sel, link.wqls)) {
1212 				goto out_unlock;
1213 			}
1214 		} else {
1215 			waitq_lock(wqset);
1216 			if (!waitq_valid(wqset)) {
1217 				goto out_unlock;
1218 			}
1219 		}
1220 
1221 		/*
1222 		 * Find any threads waiting on this wait queue set as a queue.
1223 		 */
1224 		do_waitq_select_n_locked_queue(wqset, args);
1225 
1226 		if (args->nthreads == 0) {
1227 			/* No thread selected: prepost 'waitq' to 'wqset' */
1228 			wql_wqs_mark_preposted(link);
1229 			if (wq_type == WQT_SELECT) {
1230 				wqset.wqs_sel->selset_preposted = true;
1231 			} else {
1232 				waitq.wq_q->waitq_preposted = true;
1233 				circle_dequeue(&wqset.wqs_set->wqset_links,
1234 				    &link.wqll->wql_slink);
1235 				circle_enqueue_tail(&wqset.wqs_set->wqset_preposts,
1236 				    &link.wqll->wql_slink);
1237 				ipc_pset_prepost(wqset.wqs_set, waitq.wq_q);
1238 			}
1239 		}
1240 
1241 out_unlock:
1242 		waitq_unlock(wqset);
1243 
1244 		if (args->nthreads >= args->max_threads) {
1245 			break;
1246 		}
1247 	}
1248 }
1249 
1250 /**
1251  * @function do_waitq_select_n_locked
1252  *
1253  * @brief
1254  * Selects threads waiting on a wait queue, or preposts it.
1255  *
1256  * @discussion
1257  * @c waitq is locked.
1258  *
1259  * Recurses into all sets this wait queue belongs to.
1260  */
1261 static void
do_waitq_select_n_locked(waitq_t waitq,struct waitq_select_args * args)1262 do_waitq_select_n_locked(waitq_t waitq, struct waitq_select_args *args)
1263 {
1264 	do_waitq_select_n_locked_queue(waitq, args);
1265 
1266 	if (args->nthreads >= args->max_threads) {
1267 		/* already enough threads found */
1268 		return;
1269 	}
1270 
1271 	if (args->event != NO_EVENT64 || !waitq_preposts(waitq)) {
1272 		/* this wakeup should not recurse into sets */
1273 		return;
1274 	}
1275 
1276 	do_waitq_select_n_locked_sets(waitq, args);
1277 }
1278 
1279 static inline bool
waitq_is_preposted_set(waitq_t waitq)1280 waitq_is_preposted_set(waitq_t waitq)
1281 {
1282 	switch (waitq_type(waitq)) {
1283 	case WQT_PORT_SET:
1284 		return waitq_set_first_prepost(waitq.wqs_set, WQS_PREPOST_PEEK) != NULL;
1285 
1286 	case WQT_SELECT_SET:
1287 		return waitq.wqs_sel->selset_preposted;
1288 
1289 	default:
1290 		return false;
1291 	}
1292 }
1293 
1294 wait_result_t
waitq_assert_wait64_locked(waitq_t waitq,event64_t wait_event,wait_interrupt_t interruptible,wait_timeout_urgency_t urgency,uint64_t deadline,uint64_t leeway,thread_t thread)1295 waitq_assert_wait64_locked(waitq_t waitq,
1296     event64_t wait_event,
1297     wait_interrupt_t interruptible,
1298     wait_timeout_urgency_t urgency,
1299     uint64_t deadline,
1300     uint64_t leeway,
1301     thread_t thread)
1302 {
1303 	wait_result_t wait_result;
1304 	struct waitq *safeq;
1305 	uintptr_t eventmask;
1306 	spl_t s;
1307 
1308 	switch (waitq_type(waitq)) {
1309 	case WQT_PORT:
1310 	case WQT_SELECT:
1311 	case WQT_PORT_SET:
1312 	case WQT_SELECT_SET:
1313 		assert(wait_event == NO_EVENT64);
1314 		break;
1315 	default:
1316 		assert(wait_event != NO_EVENT64);
1317 		break;
1318 	}
1319 
1320 	/*
1321 	 * Warning: Do _not_ place debugging print statements here.
1322 	 *          The waitq is locked!
1323 	 */
1324 	assert(!thread->started || thread == current_thread());
1325 
1326 	if (!waitq_wait_possible(thread)) {
1327 		panic("thread already waiting on %p", thread->waitq.wq_q);
1328 	}
1329 
1330 	s = splsched();
1331 
1332 	/*
1333 	 * early-out if the thread is waiting on a wait queue set
1334 	 * that has already been pre-posted.
1335 	 *
1336 	 * Note: waitq_is_preposted_set() may unlock the waitq-set
1337 	 */
1338 	if (waitq_is_preposted_set(waitq)) {
1339 		thread_lock(thread);
1340 		thread->wait_result = THREAD_AWAKENED;
1341 		thread_unlock(thread);
1342 		splx(s);
1343 		return THREAD_AWAKENED;
1344 	}
1345 
1346 	/*
1347 	 * If already dealing with an irq safe wait queue, we are all set.
1348 	 * Otherwise, determine a global queue to use and lock it.
1349 	 */
1350 	if (waitq_irq_safe(waitq)) {
1351 		safeq = waitq.wq_q;
1352 		eventmask = _CAST_TO_EVENT_MASK(wait_event);
1353 	} else {
1354 		safeq = waitq_get_safeq(waitq);
1355 		if (__improbable(safeq == NULL)) {
1356 			panic("Trying to assert_wait on a turnstile proxy "
1357 			    "that hasn't been donated one (waitq: %p)", waitq.wq_q);
1358 		}
1359 		eventmask = _CAST_TO_EVENT_MASK(waitq.wq_q);
1360 		waitq_lock(safeq);
1361 	}
1362 
1363 	/* lock the thread now that we have the irq-safe waitq locked */
1364 	thread_lock(thread);
1365 
1366 	wait_result = thread_mark_wait_locked(thread, interruptible);
1367 	/* thread->wait_result has been set */
1368 	if (wait_result == THREAD_WAITING) {
1369 		waitq_thread_insert(safeq, thread, waitq, wait_event);
1370 
1371 		if (deadline != 0) {
1372 			bool was_active;
1373 
1374 			was_active = timer_call_enter_with_leeway(thread->wait_timer,
1375 			    NULL,
1376 			    deadline, leeway,
1377 			    urgency, FALSE);
1378 			if (!was_active) {
1379 				thread->wait_timer_active++;
1380 			}
1381 			thread->wait_timer_armed = true;
1382 		}
1383 
1384 		if (waitq_is_global(safeq)) {
1385 			safeq->waitq_eventmask |= (waitq_flags_t)eventmask;
1386 		}
1387 
1388 		waitq_stats_count_wait(waitq);
1389 	}
1390 
1391 	/* unlock the thread */
1392 	thread_unlock(thread);
1393 
1394 	/* update the inheritor's thread priority if the waitq is embedded in turnstile */
1395 	if (waitq_type(safeq) == WQT_TURNSTILE && wait_result == THREAD_WAITING) {
1396 		turnstile_recompute_priority_locked(waitq_to_turnstile(safeq));
1397 		turnstile_update_inheritor_locked(waitq_to_turnstile(safeq));
1398 	}
1399 
1400 	/* unlock the safeq if we locked it here */
1401 	if (!waitq_same(waitq, safeq)) {
1402 		waitq_unlock(safeq);
1403 	}
1404 
1405 	splx(s);
1406 
1407 	return wait_result;
1408 }
1409 
1410 bool
waitq_pull_thread_locked(waitq_t waitq,thread_t thread)1411 waitq_pull_thread_locked(waitq_t waitq, thread_t thread)
1412 {
1413 	struct waitq *safeq;
1414 	uint32_t ticket;
1415 
1416 	assert_thread_magic(thread);
1417 
1418 	/* Find the interrupts disabled queue thread is waiting on */
1419 	if (waitq_irq_safe(waitq)) {
1420 		safeq = waitq.wq_q;
1421 	} else {
1422 		safeq = waitq_get_safeq(waitq);
1423 		if (__improbable(safeq == NULL)) {
1424 			panic("Trying to clear_wait on a turnstile proxy "
1425 			    "that hasn't been donated one (waitq: %p)", waitq.wq_q);
1426 		}
1427 	}
1428 
1429 	/*
1430 	 * thread is already locked so have to try for the waitq lock.
1431 	 *
1432 	 * We can't wait for the waitq lock under the thread lock,
1433 	 * however we can reserve our slot in the lock queue,
1434 	 * and if that reservation requires waiting, we are guaranteed
1435 	 * that this waitq can't die until we got our turn!
1436 	 */
1437 	if (!waitq_lock_reserve(safeq, &ticket)) {
1438 		thread_unlock(thread);
1439 		waitq_lock_wait(safeq, ticket);
1440 		thread_lock(thread);
1441 
1442 		if (!waitq_same(waitq, thread->waitq)) {
1443 			/*
1444 			 * While we were waiting for our reservation the thread
1445 			 * stopped waiting on this waitq, bail out.
1446 			 */
1447 			waitq_unlock(safeq);
1448 			return false;
1449 		}
1450 	}
1451 
1452 	waitq_thread_remove(safeq, thread);
1453 	waitq_stats_count_clear_wakeup(waitq);
1454 	waitq_unlock(safeq);
1455 	return true;
1456 }
1457 
1458 
1459 void
waitq_clear_promotion_locked(waitq_t waitq,thread_t thread)1460 waitq_clear_promotion_locked(waitq_t waitq, thread_t thread)
1461 {
1462 	spl_t s = 0;
1463 
1464 	assert(waitq_held(waitq));
1465 	assert(thread != THREAD_NULL);
1466 	assert(thread == current_thread());
1467 
1468 	/* This flag is only cleared by the thread itself, so safe to check outside lock */
1469 	if ((thread->sched_flags & TH_SFLAG_WAITQ_PROMOTED) != TH_SFLAG_WAITQ_PROMOTED) {
1470 		return;
1471 	}
1472 
1473 	if (!waitq_irq_safe(waitq)) {
1474 		s = splsched();
1475 	}
1476 	thread_lock(thread);
1477 
1478 	sched_thread_unpromote_reason(thread, TH_SFLAG_WAITQ_PROMOTED, 0);
1479 
1480 	thread_unlock(thread);
1481 	if (!waitq_irq_safe(waitq)) {
1482 		splx(s);
1483 	}
1484 }
1485 
1486 static inline bool
waitq_should_unlock(waitq_wakeup_flags_t flags)1487 waitq_should_unlock(waitq_wakeup_flags_t flags)
1488 {
1489 	return (flags & (WAITQ_UNLOCK | WAITQ_KEEP_LOCKED)) == WAITQ_UNLOCK;
1490 }
1491 
1492 static inline bool
waitq_should_enable_interrupts(waitq_wakeup_flags_t flags)1493 waitq_should_enable_interrupts(waitq_wakeup_flags_t flags)
1494 {
1495 	return (flags & (WAITQ_UNLOCK | WAITQ_KEEP_LOCKED | WAITQ_ENABLE_INTERRUPTS)) == (WAITQ_UNLOCK | WAITQ_ENABLE_INTERRUPTS);
1496 }
1497 
1498 __mockable uint32_t
waitq_wakeup64_nthreads_locked(waitq_t waitq,event64_t wake_event,wait_result_t result,waitq_wakeup_flags_t flags,uint32_t nthreads)1499 waitq_wakeup64_nthreads_locked(
1500 	waitq_t                 waitq,
1501 	event64_t               wake_event,
1502 	wait_result_t           result,
1503 	waitq_wakeup_flags_t    flags,
1504 	uint32_t                nthreads)
1505 {
1506 	struct waitq_select_args args = {
1507 		.event = wake_event,
1508 		.result = result,
1509 		.flags = (nthreads == 1) ? flags : (flags & ~WAITQ_HANDOFF),
1510 		.max_threads = nthreads,
1511 	};
1512 
1513 	assert(waitq_held(waitq));
1514 
1515 	if (flags & WAITQ_ENABLE_INTERRUPTS) {
1516 		assert(waitq_should_unlock(flags));
1517 		assert(ml_get_interrupts_enabled() == false);
1518 	}
1519 
1520 	do_waitq_select_n_locked(waitq, &args);
1521 	waitq_stats_count_wakeup(waitq, args.nthreads);
1522 
1523 	if (waitq_should_unlock(flags)) {
1524 		waitq_unlock(waitq);
1525 	}
1526 
1527 	if (waitq_should_enable_interrupts(flags)) {
1528 		ml_set_interrupts_enabled(true);
1529 	}
1530 
1531 	if (!circle_queue_empty(&args.threadq)) {
1532 		waitq_select_queue_flush(waitq, &args);
1533 	}
1534 
1535 	return args.nthreads;
1536 }
1537 
1538 kern_return_t
waitq_wakeup64_all_locked(waitq_t waitq,event64_t wake_event,wait_result_t result,waitq_wakeup_flags_t flags)1539 waitq_wakeup64_all_locked(
1540 	waitq_t                 waitq,
1541 	event64_t               wake_event,
1542 	wait_result_t           result,
1543 	waitq_wakeup_flags_t    flags)
1544 {
1545 	uint32_t count;
1546 
1547 	count = waitq_wakeup64_nthreads_locked(waitq, wake_event, result,
1548 	    flags, UINT32_MAX);
1549 	return count ? KERN_SUCCESS : KERN_NOT_WAITING;
1550 }
1551 
1552 kern_return_t
waitq_wakeup64_one_locked(waitq_t waitq,event64_t wake_event,wait_result_t result,waitq_wakeup_flags_t flags)1553 waitq_wakeup64_one_locked(
1554 	waitq_t                 waitq,
1555 	event64_t               wake_event,
1556 	wait_result_t           result,
1557 	waitq_wakeup_flags_t    flags)
1558 {
1559 	uint32_t count;
1560 
1561 	count = waitq_wakeup64_nthreads_locked(waitq, wake_event, result,
1562 	    flags, 1);
1563 	return count ? KERN_SUCCESS : KERN_NOT_WAITING;
1564 }
1565 
1566 __mockable thread_t
waitq_wakeup64_identify_locked(waitq_t waitq,event64_t wake_event,waitq_wakeup_flags_t flags)1567 waitq_wakeup64_identify_locked(
1568 	waitq_t                 waitq,
1569 	event64_t               wake_event,
1570 	waitq_wakeup_flags_t    flags)
1571 {
1572 	struct waitq_select_args args = {
1573 		.event = wake_event,
1574 		.result = THREAD_AWAKENED, /* this won't be used */
1575 		.flags = flags,
1576 		.max_threads = 1,
1577 		.is_identified = true,
1578 	};
1579 
1580 	assert(waitq_held(waitq));
1581 
1582 	do_waitq_select_n_locked(waitq, &args);
1583 	waitq_stats_count_wakeup(waitq, args.nthreads);
1584 
1585 	if (waitq_should_unlock(flags)) {
1586 		waitq_unlock(waitq);
1587 	}
1588 
1589 	if (waitq_should_enable_interrupts(flags)) {
1590 		ml_set_interrupts_enabled(true);
1591 	}
1592 
1593 	if (args.nthreads > 0) {
1594 		thread_t thread = cqe_dequeue_head(&args.threadq, struct thread, wait_links);
1595 
1596 		assert(args.nthreads == 1 && circle_queue_empty(&args.threadq));
1597 
1598 		/* Thread is off waitq, not unblocked yet */
1599 
1600 		return thread;
1601 	}
1602 
1603 	return THREAD_NULL;
1604 }
1605 
1606 __mockable void
waitq_resume_identified_thread(waitq_t waitq,thread_t thread,wait_result_t result,waitq_wakeup_flags_t flags)1607 waitq_resume_identified_thread(
1608 	waitq_t                 waitq,
1609 	thread_t                thread,
1610 	wait_result_t           result,
1611 	waitq_wakeup_flags_t    flags)
1612 {
1613 	spl_t spl = splsched();
1614 
1615 	thread_lock(thread);
1616 
1617 	assert((thread->state & (TH_WAIT | TH_WAKING)) == (TH_WAIT | TH_WAKING));
1618 
1619 	maybe_adjust_thread_pri(thread, flags, waitq);
1620 	thread_go(thread, result, (flags & WAITQ_HANDOFF));
1621 
1622 	thread_unlock(thread);
1623 	splx(spl);
1624 
1625 	enable_preemption(); // balance disable upon pulling thread
1626 }
1627 
1628 void
waitq_resume_and_bind_identified_thread(waitq_t waitq,thread_t thread,processor_t processor,wait_result_t result,waitq_wakeup_flags_t flags)1629 waitq_resume_and_bind_identified_thread(
1630 	waitq_t                 waitq,
1631 	thread_t                thread,
1632 	processor_t             processor,
1633 	wait_result_t           result,
1634 	waitq_wakeup_flags_t    flags)
1635 {
1636 	spl_t spl = splsched();
1637 
1638 	thread_lock(thread);
1639 
1640 	assert((thread->state & (TH_WAIT | TH_WAKING)) == (TH_WAIT | TH_WAKING));
1641 
1642 	maybe_adjust_thread_pri(thread, flags, waitq);
1643 	thread_bind_during_wakeup(thread, processor);
1644 	thread_go(thread, result, (flags & WAITQ_HANDOFF));
1645 
1646 	thread_unlock(thread);
1647 	splx(spl);
1648 
1649 	enable_preemption(); // balance disable upon pulling thread
1650 }
1651 
1652 kern_return_t
waitq_wakeup64_thread_and_unlock(struct waitq * waitq,event64_t event,thread_t thread,wait_result_t result)1653 waitq_wakeup64_thread_and_unlock(
1654 	struct waitq           *waitq,
1655 	event64_t              event,
1656 	thread_t               thread,
1657 	wait_result_t          result)
1658 {
1659 	kern_return_t ret = KERN_NOT_WAITING;
1660 
1661 	assert(waitq_irq_safe(waitq));
1662 	assert(waitq_held(waitq));
1663 	assert_thread_magic(thread);
1664 
1665 	/*
1666 	 * See if the thread was still waiting there.  If so, it got
1667 	 * dequeued and returned locked.
1668 	 *
1669 	 * By holding the thread locked across the go, a thread on another CPU
1670 	 * can't see itself in 'waking' state, even if it uses clear_wait.
1671 	 */
1672 	thread_lock(thread);
1673 
1674 	if (waitq_same(thread->waitq, waitq) && thread->wait_event == event) {
1675 		waitq_thread_remove(waitq, thread);
1676 		ret = KERN_SUCCESS;
1677 	}
1678 	waitq_stats_count_wakeup(waitq, ret == KERN_SUCCESS ? 1 : 0);
1679 
1680 	waitq_unlock(waitq);
1681 
1682 	if (ret == KERN_SUCCESS) {
1683 		thread_go(thread, result, /* handoff */ false);
1684 	}
1685 
1686 	thread_unlock(thread);
1687 
1688 	return ret;
1689 }
1690 
1691 
1692 #pragma mark waitq
1693 
1694 __attribute__((always_inline))
1695 void
waitq_init(waitq_t waitq,waitq_type_t type,int policy)1696 waitq_init(waitq_t waitq, waitq_type_t type, int policy)
1697 {
1698 	assert((policy & SYNC_POLICY_FIXED_PRIORITY) == 0);
1699 
1700 	*waitq.wq_q = (struct waitq){
1701 		.waitq_type  = type,
1702 		.waitq_fifo  = ((policy & SYNC_POLICY_REVERSED) == 0),
1703 	};
1704 
1705 	switch (type) {
1706 	case WQT_INVALID:
1707 		__builtin_trap();
1708 
1709 	case WQT_TURNSTILE:
1710 		/* For turnstile, initialize it as a priority queue */
1711 		priority_queue_init(&waitq.wq_q->waitq_prio_queue);
1712 		assert(waitq.wq_q->waitq_fifo == 0);
1713 		break;
1714 
1715 	case WQT_PORT:
1716 		waitq.wq_q->waitq_ts = TURNSTILE_NULL;
1717 		break;
1718 
1719 	case WQT_PORT_SET:
1720 		circle_queue_init(&waitq.wqs_set->wqset_preposts);
1721 		OS_FALLTHROUGH;
1722 	case WQT_SELECT_SET:
1723 	case WQT_QUEUE:
1724 	case WQT_SELECT:
1725 		circle_queue_init(&waitq.wq_q->waitq_queue);
1726 		break;
1727 	}
1728 
1729 	if (policy & SYNC_POLICY_INIT_LOCKED) {
1730 		hw_lck_ticket_init_locked(&waitq.wq_q->waitq_interlock, &waitq_lck_grp);
1731 	} else {
1732 		hw_lck_ticket_init(&waitq.wq_q->waitq_interlock, &waitq_lck_grp);
1733 	}
1734 }
1735 
1736 void
waitq_deinit(waitq_t waitq)1737 waitq_deinit(waitq_t waitq)
1738 {
1739 	waitq_type_t type = waitq_type(waitq);
1740 
1741 	switch (type) {
1742 	case WQT_QUEUE:
1743 		assert(circle_queue_empty(&waitq.wq_q->waitq_queue));
1744 		waitq_invalidate(waitq);
1745 		break;
1746 
1747 	case WQT_TURNSTILE:
1748 		assert(priority_queue_empty(&waitq.wq_q->waitq_prio_queue));
1749 		assert(waitq.wq_q->waitq_inheritor == TURNSTILE_INHERITOR_NULL);
1750 		waitq_invalidate(waitq);
1751 		break;
1752 
1753 	case WQT_PORT:
1754 		assert(waitq.wq_q->waitq_ts == TURNSTILE_NULL);
1755 		assert(circle_queue_empty(&waitq.wq_q->waitq_links));
1756 		break;
1757 
1758 	case WQT_SELECT:
1759 		assert(waitq.wq_q->waitq_sellinks.next == NULL);
1760 		assert(circle_queue_empty(&waitq.wqs_set->wqset_queue));
1761 		break;
1762 
1763 	case WQT_PORT_SET:
1764 		assert(circle_queue_empty(&waitq.wqs_set->wqset_queue));
1765 		assert(circle_queue_empty(&waitq.wqs_set->wqset_links));
1766 		assert(circle_queue_empty(&waitq.wqs_set->wqset_preposts));
1767 		break;
1768 
1769 	default:
1770 		panic("invalid wait type: %p/%d", waitq.wq_q, type);
1771 	}
1772 
1773 	/*
1774 	 * The waitq must have been invalidated, or hw_lck_ticket_destroy()
1775 	 * below won't wait for reservations from waitq_lock_reserve(),
1776 	 * or waitq_lock_allow_invalid().
1777 	 */
1778 	assert(!waitq_valid(waitq.wqs_set));
1779 	hw_lck_ticket_destroy(&waitq.wq_q->waitq_interlock, &waitq_lck_grp);
1780 }
1781 
1782 
1783 #pragma mark port-set sets
1784 
1785 void
waitq_set_unlink_all_locked(struct waitq_set * wqset,waitq_link_list_t * free_l)1786 waitq_set_unlink_all_locked(struct waitq_set *wqset, waitq_link_list_t *free_l)
1787 {
1788 	uint32_t batch = waitq_set_unlink_batch;
1789 
1790 	waitq_invalidate(wqset);
1791 
1792 	for (;;) {
1793 		struct waitq_link *link;
1794 		queue_entry_t elt;
1795 		circle_queue_t q;
1796 		struct waitq *wq;
1797 		uint32_t ticket;
1798 		bool stable = true;
1799 
1800 		if (!circle_queue_empty(&wqset->wqset_links)) {
1801 			q = &wqset->wqset_links;
1802 		} else if (!circle_queue_empty(&wqset->wqset_preposts)) {
1803 			q = &wqset->wqset_preposts;
1804 		} else {
1805 			break;
1806 		}
1807 
1808 		if (batch-- == 0) {
1809 			waitq_unlock(wqset);
1810 			waitq_lock(wqset);
1811 			batch = waitq_set_unlink_batch;
1812 			continue;
1813 		}
1814 
1815 		elt  = circle_queue_first(q);
1816 		link = cqe_element(elt, struct waitq_link, wql_slink);
1817 		wq   = link->wql_wq;
1818 
1819 		if (__improbable(!waitq_lock_reserve(wq, &ticket))) {
1820 			waitq_unlock(wqset);
1821 			waitq_lock_wait(wq, ticket);
1822 			waitq_lock(wqset);
1823 			stable = (elt == circle_queue_first(q) && link->wql_wq == wq);
1824 		}
1825 
1826 		if (stable) {
1827 			circle_dequeue(q, &link->wql_slink);
1828 			circle_dequeue(&wq->waitq_links, &link->wql_qlink);
1829 			wql_list_push(free_l, link);
1830 		}
1831 
1832 		waitq_unlock(wq);
1833 	}
1834 }
1835 
1836 void
waitq_clear_prepost_locked(struct waitq * waitq)1837 waitq_clear_prepost_locked(struct waitq *waitq)
1838 {
1839 	assert(waitq_type(waitq) == WQT_PORT);
1840 	waitq->waitq_preposted = false;
1841 }
1842 
1843 void
1844 waitq_set_foreach_member_locked(struct waitq_set *wqs, void (^cb)(struct waitq *))
1845 {
1846 	struct waitq_link *link;
1847 
1848 	cqe_foreach_element(link, &wqs->wqset_links, wql_slink) {
1849 		cb(link->wql_wq);
1850 	}
1851 
1852 	cqe_foreach_element(link, &wqs->wqset_preposts, wql_slink) {
1853 		cb(link->wql_wq);
1854 	}
1855 }
1856 
1857 __abortlike
1858 static void
__waitq_link_arguments_panic(struct waitq * waitq,struct waitq_set * wqset)1859 __waitq_link_arguments_panic(struct waitq *waitq, struct waitq_set *wqset)
1860 {
1861 	if (!waitq_valid(waitq)) {
1862 		panic("Invalid waitq: %p", waitq);
1863 	}
1864 	if (waitq_type(waitq) != WQT_PORT) {
1865 		panic("Invalid waitq type: %p:%d", waitq, waitq->waitq_type);
1866 	}
1867 	panic("Invalid waitq-set: %p", wqset);
1868 }
1869 
1870 static inline void
__waitq_link_arguments_validate(struct waitq * waitq,struct waitq_set * wqset)1871 __waitq_link_arguments_validate(struct waitq *waitq, struct waitq_set *wqset)
1872 {
1873 	if (!waitq_valid(waitq) ||
1874 	    waitq_type(waitq) != WQT_PORT ||
1875 	    waitq_type(wqset) != WQT_PORT_SET) {
1876 		__waitq_link_arguments_panic(waitq, wqset);
1877 	}
1878 }
1879 
1880 __abortlike
1881 static void
__waitq_invalid_panic(waitq_t waitq)1882 __waitq_invalid_panic(waitq_t waitq)
1883 {
1884 	panic("Invalid waitq: %p", waitq.wq_q);
1885 }
1886 
1887 static void
__waitq_validate(waitq_t waitq)1888 __waitq_validate(waitq_t waitq)
1889 {
1890 	if (!waitq_valid(waitq)) {
1891 		__waitq_invalid_panic(waitq);
1892 	}
1893 }
1894 
1895 kern_return_t
waitq_link_locked(struct waitq * waitq,struct waitq_set * wqset,waitq_link_t * linkp)1896 waitq_link_locked(struct waitq *waitq, struct waitq_set *wqset,
1897     waitq_link_t *linkp)
1898 {
1899 	assert(linkp->wqlh);
1900 
1901 	__waitq_link_arguments_validate(waitq, wqset);
1902 
1903 	if (wql_find(waitq, wqset)) {
1904 		return KERN_ALREADY_IN_SET;
1905 	}
1906 
1907 	linkp->wqll->wql_wq = waitq;
1908 	linkp->wqll->wql_wqs = (uintptr_t)wqset;
1909 
1910 	if (waitq_valid(wqset)) {
1911 		circle_enqueue_tail(&wqset->wqset_links, &linkp->wqll->wql_slink);
1912 		circle_enqueue_tail(&waitq->waitq_links, &linkp->wqll->wql_qlink);
1913 		*linkp = WQL_NULL;
1914 	}
1915 
1916 	return KERN_SUCCESS;
1917 }
1918 
1919 kern_return_t
waitq_link_prepost_locked(struct waitq * waitq,struct waitq_set * wqset)1920 waitq_link_prepost_locked(struct waitq *waitq, struct waitq_set *wqset)
1921 {
1922 	struct waitq_link *link;
1923 
1924 	__waitq_link_arguments_validate(waitq, wqset);
1925 
1926 	link = wql_find(waitq, wqset);
1927 	if (link == NULL) {
1928 		return KERN_NOT_IN_SET;
1929 	}
1930 
1931 	if (!wql_wqs_preposted(link)) {
1932 		wql_wqs_mark_preposted(link);
1933 		waitq->waitq_preposted = true;
1934 		circle_dequeue(&wqset->wqset_links, &link->wql_slink);
1935 		circle_enqueue_tail(&wqset->wqset_preposts, &link->wql_slink);
1936 		ipc_pset_prepost(wqset, waitq);
1937 	}
1938 
1939 	return KERN_SUCCESS;
1940 }
1941 
1942 waitq_link_t
waitq_unlink_locked(struct waitq * waitq,struct waitq_set * wqset)1943 waitq_unlink_locked(struct waitq *waitq, struct waitq_set *wqset)
1944 {
1945 	struct waitq_link *link;
1946 
1947 	__waitq_link_arguments_validate(waitq, wqset);
1948 
1949 	link = wql_find(waitq, wqset);
1950 	if (link) {
1951 		circle_dequeue(wql_wqs_queue(wqset, link), &link->wql_slink);
1952 		circle_dequeue(&waitq->waitq_links, &link->wql_qlink);
1953 	}
1954 
1955 	return (waitq_link_t){ .wqll = link };
1956 }
1957 
1958 void
waitq_unlink_all_locked(struct waitq * waitq,struct waitq_set * except_wqset,waitq_link_list_t * free_l)1959 waitq_unlink_all_locked(struct waitq *waitq, struct waitq_set *except_wqset,
1960     waitq_link_list_t *free_l)
1961 {
1962 	struct waitq_link *kept_link = NULL;
1963 	struct waitq_link *link;
1964 
1965 	assert(waitq_type(waitq) == WQT_PORT);
1966 
1967 	cqe_foreach_element_safe(link, &waitq->waitq_links, wql_qlink) {
1968 		waitq_t wqs = wql_wqs(link);
1969 
1970 		if (wqs.wqs_set == except_wqset) {
1971 			kept_link = link;
1972 			continue;
1973 		}
1974 
1975 		waitq_lock(wqs);
1976 		circle_dequeue(wql_wqs_queue(wqs.wqs_set, link),
1977 		    &link->wql_slink);
1978 		wql_list_push(free_l, link);
1979 		waitq_unlock(wqs);
1980 	}
1981 
1982 	circle_queue_init(&waitq->waitq_links);
1983 	if (kept_link) {
1984 		circle_enqueue_tail(&waitq->waitq_links, &kept_link->wql_qlink);
1985 	}
1986 }
1987 
1988 struct waitq *
waitq_set_first_prepost(struct waitq_set * wqset,wqs_prepost_flags_t flags)1989 waitq_set_first_prepost(struct waitq_set *wqset, wqs_prepost_flags_t flags)
1990 {
1991 	circle_queue_t q = &wqset->wqset_preposts;
1992 	queue_entry_t elt;
1993 	struct waitq_link *link;
1994 	struct waitq *wq;
1995 	uint32_t ticket;
1996 
1997 	if (__improbable(!waitq_valid(wqset))) {
1998 		return NULL;
1999 	}
2000 
2001 	while (!circle_queue_empty(q)) {
2002 		elt  = circle_queue_first(q);
2003 		link = cqe_element(elt, struct waitq_link, wql_slink);
2004 		wq   = link->wql_wq;
2005 
2006 		if (__improbable(!waitq_lock_reserve(wq, &ticket))) {
2007 			waitq_unlock(wqset);
2008 			waitq_lock_wait(wq, ticket);
2009 			waitq_lock(wqset);
2010 			if (!waitq_valid(wqset)) {
2011 				waitq_unlock(wq);
2012 				return NULL;
2013 			}
2014 
2015 			if (elt != circle_queue_first(q) || link->wql_wq != wq) {
2016 				waitq_unlock(wq);
2017 				continue;
2018 			}
2019 		}
2020 
2021 		if (wq->waitq_preposted) {
2022 			if ((flags & WQS_PREPOST_PEEK) == 0) {
2023 				circle_queue_rotate_head_forward(q);
2024 			}
2025 			if ((flags & WQS_PREPOST_LOCK) == 0) {
2026 				waitq_unlock(wq);
2027 			}
2028 			return wq;
2029 		}
2030 
2031 		/*
2032 		 * We found a link that is no longer preposted,
2033 		 * someone must have called waitq_clear_prepost_locked()
2034 		 * and this set just only noticed.
2035 		 */
2036 		wql_wqs_clear_preposted(link);
2037 		waitq_unlock(wq);
2038 
2039 		circle_dequeue(q, &link->wql_slink);
2040 		circle_enqueue_tail(&wqset->wqset_links, &link->wql_slink);
2041 	}
2042 
2043 	return NULL;
2044 }
2045 
2046 
2047 #pragma mark select sets
2048 
2049 /**
2050  * @function select_set_nextid()
2051  *
2052  * @brief
2053  * Generate a unique ID for a select set "generation"
2054  *
2055  * @discussion
2056  * This mixes the CPU number with a monotonic clock
2057  * (in order to avoid contention on a global atomic).
2058  *
2059  * In order for select sets to be invalidated very quickly,
2060  * they do not have backward linkages to their member queues.
2061  *
2062  * Instead, each time a new @c select() "pass" is initiated,
2063  * a new ID is generated, which is copied onto the @c waitq_sellink
2064  * links at the time of link.
2065  *
2066  * The zone for select sets is sequestered, which allows for select
2067  * wait queues to speculatively lock their set during prepost
2068  * and use this ID to debounce wakeups and avoid spurious wakeups
2069  * (as an "optimization" because select recovers from spurious wakeups,
2070  * we just want those to be very rare).
2071  */
2072 __attribute__((always_inline))
2073 static inline uint64_t
select_set_nextid(bool preemption_enabled)2074 select_set_nextid(bool preemption_enabled)
2075 {
2076 	/* waitq_bootstrap() set the low byte to a unique value per CPU */
2077 	static_assert(MAX_CPUS <= 256);
2078 	const uint64_t inc = 256;
2079 	uint64_t id;
2080 
2081 #ifdef __x86_64__
2082 	/* uncontended atomics are slower than disabling preemption on Intel */
2083 	if (preemption_enabled) {
2084 		disable_preemption();
2085 	}
2086 	id = (*PERCPU_GET(select_setid) += inc);
2087 	if (preemption_enabled) {
2088 		enable_preemption();
2089 	}
2090 #else
2091 	/*
2092 	 * if preemption is enabled this might update another CPU's
2093 	 * setid, which will be rare but is acceptable, it still
2094 	 * produces a unique select ID.
2095 	 *
2096 	 * We chose this because the uncontended atomics on !intel
2097 	 * are faster than disabling/reenabling preemption.
2098 	 */
2099 	(void)preemption_enabled;
2100 	id = os_atomic_add(PERCPU_GET(select_setid), inc, relaxed);
2101 #endif
2102 
2103 	return id;
2104 }
2105 
2106 struct select_set *
select_set_alloc(void)2107 select_set_alloc(void)
2108 {
2109 	struct select_set *selset;
2110 	selset = zalloc_id(ZONE_ID_SELECT_SET, Z_ZERO | Z_WAITOK | Z_NOFAIL);
2111 
2112 	waitq_init(selset, WQT_SELECT_SET, SYNC_POLICY_FIFO);
2113 	selset->selset_id = select_set_nextid(true);
2114 
2115 	return selset;
2116 }
2117 
2118 __abortlike
2119 static void
__select_set_link_arguments_panic(struct waitq * waitq,struct select_set * set)2120 __select_set_link_arguments_panic(struct waitq *waitq, struct select_set *set)
2121 {
2122 	if (!waitq_valid(waitq)) {
2123 		panic("Invalid waitq: %p", waitq);
2124 	}
2125 	if (waitq_type(waitq) != WQT_SELECT) {
2126 		panic("Invalid waitq type: %p:%d", waitq, waitq->waitq_type);
2127 	}
2128 	panic("Invalid waitq-set: %p", set);
2129 }
2130 
2131 static inline void
__select_set_link_arguments_validate(struct waitq * waitq,struct select_set * set)2132 __select_set_link_arguments_validate(struct waitq *waitq, struct select_set *set)
2133 {
2134 	if (!waitq_valid(waitq) ||
2135 	    waitq_type(waitq) != WQT_SELECT ||
2136 	    waitq_type(set) != WQT_SELECT_SET) {
2137 		__select_set_link_arguments_panic(waitq, set);
2138 	}
2139 }
2140 
2141 void
select_set_link(struct waitq * waitq,struct select_set * set,waitq_link_t * linkp)2142 select_set_link(struct waitq *waitq, struct select_set *set,
2143     waitq_link_t *linkp)
2144 {
2145 	struct waitq_sellink *link;
2146 
2147 	__select_set_link_arguments_validate(waitq, set);
2148 
2149 	waitq_lock(waitq);
2150 
2151 	if (waitq == &select_conflict_queue) {
2152 		waitq_lock(set);
2153 		set->selset_conflict = true;
2154 		waitq_unlock(set);
2155 	}
2156 
2157 	wql_list_foreach(link, &waitq->waitq_sellinks) {
2158 		if (waitq_same(wql_wqs(link), set)) {
2159 			goto found;
2160 		}
2161 	}
2162 
2163 	link = linkp->wqls;
2164 	*linkp = WQL_NULL;
2165 	wql_list_push(&waitq->waitq_sellinks, link);
2166 
2167 found:
2168 	link->wql_wqs = (uintptr_t)set;
2169 	link->wql_setid = set->selset_id;
2170 	waitq_unlock(waitq);
2171 }
2172 
2173 static void
select_set_unlink_conflict_queue(struct select_set * set)2174 select_set_unlink_conflict_queue(struct select_set *set)
2175 {
2176 	struct waitq_link_list_entry **prev;
2177 	struct waitq_sellink *link;
2178 
2179 	waitq_lock(&select_conflict_queue);
2180 
2181 	/*
2182 	 * We know the conflict queue is hooked,
2183 	 * so find the linkage and free it.
2184 	 */
2185 	prev = &select_conflict_queue.waitq_sellinks.next;
2186 	for (;;) {
2187 		assert(*prev);
2188 		link = wql_list_elem(*prev);
2189 		if (waitq_same(wql_wqs(link), set)) {
2190 			*prev = link->wql_next.next;
2191 			break;
2192 		}
2193 		prev = &link->wql_next.next;
2194 	}
2195 
2196 	waitq_unlock(&select_conflict_queue);
2197 
2198 	waitq_link_free(WQT_SELECT_SET, link);
2199 }
2200 
2201 static void
__select_set_reset(struct select_set * set,bool invalidate)2202 __select_set_reset(struct select_set *set, bool invalidate)
2203 {
2204 	if (set->selset_conflict) {
2205 		select_set_unlink_conflict_queue(set);
2206 	}
2207 
2208 	waitq_lock(set);
2209 	if (invalidate) {
2210 		waitq_invalidate(set);
2211 	}
2212 	set->selset_id = select_set_nextid(false);
2213 	set->selset_preposted = 0;
2214 	set->selset_conflict = 0;
2215 	waitq_unlock(set);
2216 }
2217 
2218 void
select_set_reset(struct select_set * set)2219 select_set_reset(struct select_set *set)
2220 {
2221 	__select_set_reset(set, false);
2222 }
2223 
2224 void
select_set_free(struct select_set * set)2225 select_set_free(struct select_set *set)
2226 {
2227 	__select_set_reset(set, true);
2228 	hw_lck_ticket_destroy(&set->selset_interlock, &waitq_lck_grp);
2229 	zfree_id(ZONE_ID_SELECT_SET, set);
2230 }
2231 
2232 void
select_waitq_wakeup_and_deinit(struct waitq * waitq,event64_t wake_event,wait_result_t result)2233 select_waitq_wakeup_and_deinit(
2234 	struct waitq           *waitq,
2235 	event64_t               wake_event,
2236 	wait_result_t           result)
2237 {
2238 	waitq_link_list_t free_l = { };
2239 
2240 	if (waitq_is_valid(waitq)) {
2241 		assert(waitq_type(waitq) == WQT_SELECT);
2242 
2243 		waitq_lock(waitq);
2244 
2245 		waitq_wakeup64_all_locked(waitq, wake_event, result,
2246 		    WAITQ_KEEP_LOCKED);
2247 
2248 		waitq_invalidate(waitq);
2249 		free_l = waitq->waitq_sellinks;
2250 		waitq->waitq_sellinks.next = NULL;
2251 
2252 		waitq_unlock(waitq);
2253 
2254 		waitq_link_free_list(WQT_SELECT, &free_l);
2255 
2256 		waitq_deinit(waitq);
2257 	}
2258 }
2259 
2260 #pragma mark assert_wait / wakeup (high level)
2261 
2262 wait_result_t
waitq_assert_wait64(struct waitq * waitq,event64_t wait_event,wait_interrupt_t interruptible,uint64_t deadline)2263 waitq_assert_wait64(struct waitq *waitq,
2264     event64_t wait_event,
2265     wait_interrupt_t interruptible,
2266     uint64_t deadline)
2267 {
2268 	thread_t thread = current_thread();
2269 	wait_result_t ret;
2270 	spl_t s = 0;
2271 
2272 	__waitq_validate(waitq);
2273 
2274 	if (waitq_irq_safe(waitq)) {
2275 		s = splsched();
2276 	}
2277 	waitq_lock(waitq);
2278 
2279 	ret = waitq_assert_wait64_locked(waitq, wait_event, interruptible,
2280 	    TIMEOUT_URGENCY_SYS_NORMAL, deadline, TIMEOUT_NO_LEEWAY, thread);
2281 
2282 	waitq_unlock(waitq);
2283 	if (waitq_irq_safe(waitq)) {
2284 		splx(s);
2285 	}
2286 
2287 	return ret;
2288 }
2289 
2290 wait_result_t
waitq_assert_wait64_leeway(struct waitq * waitq,event64_t wait_event,wait_interrupt_t interruptible,wait_timeout_urgency_t urgency,uint64_t deadline,uint64_t leeway)2291 waitq_assert_wait64_leeway(struct waitq *waitq,
2292     event64_t wait_event,
2293     wait_interrupt_t interruptible,
2294     wait_timeout_urgency_t urgency,
2295     uint64_t deadline,
2296     uint64_t leeway)
2297 {
2298 	wait_result_t ret;
2299 	thread_t thread = current_thread();
2300 	spl_t s = 0;
2301 
2302 	__waitq_validate(waitq);
2303 
2304 	if (waitq_irq_safe(waitq)) {
2305 		s = splsched();
2306 	}
2307 	waitq_lock(waitq);
2308 
2309 	ret = waitq_assert_wait64_locked(waitq, wait_event, interruptible,
2310 	    urgency, deadline, leeway, thread);
2311 
2312 	waitq_unlock(waitq);
2313 	if (waitq_irq_safe(waitq)) {
2314 		splx(s);
2315 	}
2316 
2317 	return ret;
2318 }
2319 
2320 uint32_t
waitq_wakeup64_nthreads(waitq_t waitq,event64_t wake_event,wait_result_t result,waitq_wakeup_flags_t flags,uint32_t nthreads)2321 waitq_wakeup64_nthreads(
2322 	waitq_t                 waitq,
2323 	event64_t               wake_event,
2324 	wait_result_t           result,
2325 	waitq_wakeup_flags_t    flags,
2326 	uint32_t                nthreads)
2327 {
2328 	__waitq_validate(waitq);
2329 
2330 	spl_t spl = 0;
2331 
2332 	if (waitq_irq_safe(waitq)) {
2333 		spl = splsched();
2334 	}
2335 
2336 	waitq_lock(waitq);
2337 
2338 	/* waitq is unlocked upon return, splx is handled */
2339 	return waitq_wakeup64_nthreads_locked(waitq, wake_event, result,
2340 	           flags | waitq_flags_splx(spl) | WAITQ_UNLOCK, nthreads);
2341 }
2342 
2343 kern_return_t
waitq_wakeup64_all(waitq_t waitq,event64_t wake_event,wait_result_t result,waitq_wakeup_flags_t flags)2344 waitq_wakeup64_all(
2345 	waitq_t                 waitq,
2346 	event64_t               wake_event,
2347 	wait_result_t           result,
2348 	waitq_wakeup_flags_t    flags)
2349 {
2350 	uint32_t count;
2351 
2352 	count = waitq_wakeup64_nthreads(waitq, wake_event, result,
2353 	    flags, UINT32_MAX);
2354 	return count ? KERN_SUCCESS : KERN_NOT_WAITING;
2355 }
2356 
2357 kern_return_t
waitq_wakeup64_one(waitq_t waitq,event64_t wake_event,wait_result_t result,waitq_wakeup_flags_t flags)2358 waitq_wakeup64_one(
2359 	waitq_t                 waitq,
2360 	event64_t               wake_event,
2361 	wait_result_t           result,
2362 	waitq_wakeup_flags_t    flags)
2363 {
2364 	uint32_t count;
2365 
2366 	count = waitq_wakeup64_nthreads(waitq, wake_event, result, flags, 1);
2367 	return count ? KERN_SUCCESS : KERN_NOT_WAITING;
2368 }
2369 
2370 kern_return_t
waitq_wakeup64_thread(struct waitq * waitq,event64_t event,thread_t thread,wait_result_t result)2371 waitq_wakeup64_thread(
2372 	struct waitq           *waitq,
2373 	event64_t               event,
2374 	thread_t                thread,
2375 	wait_result_t           result)
2376 {
2377 	spl_t s = splsched();
2378 	kern_return_t ret;
2379 
2380 	__waitq_validate(waitq);
2381 	assert(waitq_irq_safe(waitq));
2382 	waitq_lock(waitq);
2383 
2384 	ret = waitq_wakeup64_thread_and_unlock(waitq, event, thread, result);
2385 
2386 	splx(s);
2387 
2388 	return ret;
2389 }
2390 
2391 thread_t
waitq_wakeup64_identify(waitq_t waitq,event64_t wake_event,wait_result_t result,waitq_wakeup_flags_t flags)2392 waitq_wakeup64_identify(
2393 	waitq_t                 waitq,
2394 	event64_t               wake_event,
2395 	wait_result_t           result,
2396 	waitq_wakeup_flags_t    flags)
2397 {
2398 	__waitq_validate(waitq);
2399 
2400 	spl_t spl = 0;
2401 
2402 	if (waitq_irq_safe(waitq)) {
2403 		spl = splsched();
2404 	}
2405 
2406 	waitq_lock(waitq);
2407 
2408 	thread_t thread = waitq_wakeup64_identify_locked(waitq, wake_event,
2409 	    flags | waitq_flags_splx(spl) | WAITQ_UNLOCK);
2410 	/* waitq is unlocked, thread is not go-ed yet */
2411 	/* preemption disabled if thread non-null */
2412 	/* splx is handled */
2413 
2414 	if (thread != THREAD_NULL) {
2415 		thread_reference(thread);
2416 		waitq_resume_identified_thread(waitq, thread, result, flags);
2417 		/* preemption enabled, thread go-ed */
2418 		/* returns +1 ref to running thread */
2419 		return thread;
2420 	}
2421 
2422 	return THREAD_NULL;
2423 }
2424 
2425 
2426 #pragma mark tests
2427 #if DEBUG || DEVELOPMENT
2428 
2429 #include <ipc/ipc_space.h>
2430 #include <ipc/ipc_pset.h>
2431 #include <sys/errno.h>
2432 
2433 #define MAX_GLOBAL_TEST_QUEUES 64
2434 static struct waitq wqt_waitq_array[MAX_GLOBAL_TEST_QUEUES];
2435 static bool wqt_running;
2436 static bool wqt_init;
2437 
2438 static bool
wqt_start(const char * test,int64_t * out)2439 wqt_start(const char *test, int64_t *out)
2440 {
2441 	if (os_atomic_xchg(&wqt_running, true, acquire)) {
2442 		*out = 0;
2443 		return false;
2444 	}
2445 
2446 	if (!wqt_init) {
2447 		wqt_init = true;
2448 		for (int i = 0; i < MAX_GLOBAL_TEST_QUEUES; i++) {
2449 			waitq_init(&wqt_waitq_array[i], WQT_PORT, SYNC_POLICY_FIFO);
2450 		}
2451 	}
2452 
2453 	printf("[WQ] starting %s\n", test);
2454 	return true;
2455 }
2456 
2457 static int
wqt_end(const char * test,int64_t * out)2458 wqt_end(const char *test, int64_t *out)
2459 {
2460 	os_atomic_store(&wqt_running, false, release);
2461 	printf("[WQ] done %s\n", test);
2462 	*out = 1;
2463 	return 0;
2464 }
2465 
2466 static struct waitq *
wqt_wq(uint32_t index)2467 wqt_wq(uint32_t index)
2468 {
2469 	return &wqt_waitq_array[index];
2470 }
2471 
2472 static uint32_t
wqt_idx(struct waitq * waitq)2473 wqt_idx(struct waitq *waitq)
2474 {
2475 	assert(waitq >= wqt_waitq_array &&
2476 	    waitq < wqt_waitq_array + MAX_GLOBAL_TEST_QUEUES);
2477 	return (uint32_t)(waitq - wqt_waitq_array);
2478 }
2479 
2480 __attribute__((overloadable))
2481 static uint64_t
wqt_bit(uint32_t index)2482 wqt_bit(uint32_t index)
2483 {
2484 	return 1ull << index;
2485 }
2486 
2487 __attribute__((overloadable))
2488 static uint64_t
wqt_bit(struct waitq * waitq)2489 wqt_bit(struct waitq *waitq)
2490 {
2491 	return wqt_bit(wqt_idx(waitq));
2492 }
2493 
2494 static struct waitq_set *
wqt_wqset_create(void)2495 wqt_wqset_create(void)
2496 {
2497 	struct waitq_set *wqset;
2498 
2499 	wqset = &ipc_pset_alloc_special(ipc_space_kernel)->ips_wqset;
2500 	waitq_unlock(wqset);
2501 
2502 	printf("[WQ]: created waitq set %p\n", wqset);
2503 	return wqset;
2504 }
2505 
2506 static void
wqt_wqset_free(struct waitq_set * wqset)2507 wqt_wqset_free(struct waitq_set *wqset)
2508 {
2509 	printf("[WQ]: destroying waitq set %p\n", wqset);
2510 	waitq_lock(wqset);
2511 	ipc_pset_destroy(ipc_space_kernel,
2512 	    __container_of(wqset, struct ipc_pset, ips_wqset));
2513 }
2514 
2515 static void
wqt_link(uint32_t index,struct waitq_set * wqset,kern_return_t want)2516 wqt_link(uint32_t index, struct waitq_set *wqset, kern_return_t want)
2517 {
2518 	struct waitq *waitq = wqt_wq(index);
2519 	waitq_link_t link = waitq_link_alloc(WQT_PORT_SET);
2520 	kern_return_t kr;
2521 
2522 	printf("[WQ]: linking waitq [%d] to global wqset (%p)\n", index, wqset);
2523 
2524 	waitq_lock(waitq);
2525 	waitq_lock(wqset);
2526 	kr = waitq_link_locked(waitq, wqset, &link);
2527 	waitq_unlock(wqset);
2528 	waitq_unlock(waitq);
2529 
2530 	if (link.wqlh) {
2531 		waitq_link_free(WQT_PORT_SET, link);
2532 	}
2533 
2534 	printf("[WQ]:\tkr=%d\texpected=%d\n", kr, want);
2535 	assert(kr == want);
2536 }
2537 
2538 static void
wqt_unlink(uint32_t index,struct waitq_set * wqset,__assert_only kern_return_t want)2539 wqt_unlink(uint32_t index, struct waitq_set *wqset, __assert_only kern_return_t want)
2540 {
2541 	struct waitq *waitq = wqt_wq(index);
2542 	waitq_link_t link;
2543 	kern_return_t kr;
2544 
2545 	printf("[WQ]: unlinking waitq [%d] from global wqset (%p)\n",
2546 	    index, wqset);
2547 
2548 	waitq_lock(waitq);
2549 	waitq_lock(wqset);
2550 	link = waitq_unlink_locked(waitq, wqset);
2551 	waitq_unlock(wqset);
2552 	waitq_unlock(waitq);
2553 
2554 	if (link.wqlh) {
2555 		waitq_link_free(WQT_PORT_SET, link);
2556 		kr = KERN_SUCCESS;
2557 	} else {
2558 		kr = KERN_NOT_IN_SET;
2559 	}
2560 
2561 	printf("[WQ]: \tkr=%d\n", kr);
2562 	assert(kr == want);
2563 }
2564 
2565 static void
wqt_wakeup_one(uint32_t index,event64_t event64,__assert_only kern_return_t want)2566 wqt_wakeup_one(uint32_t index, event64_t event64, __assert_only kern_return_t want)
2567 {
2568 	kern_return_t kr;
2569 
2570 	printf("[WQ]: Waking one thread on waitq [%d] event:0x%llx\n",
2571 	    index, event64);
2572 	kr = waitq_wakeup64_one(wqt_wq(index), event64,
2573 	    THREAD_AWAKENED, WAITQ_WAKEUP_DEFAULT);
2574 	printf("[WQ]: \tkr=%d\n", kr);
2575 	assert(kr == want);
2576 }
2577 
2578 static void
wqt_clear_preposts(uint32_t idx)2579 wqt_clear_preposts(uint32_t idx)
2580 {
2581 	waitq_lock(wqt_wq(idx));
2582 	(void)waitq_clear_prepost_locked(wqt_wq(idx));
2583 	waitq_unlock(wqt_wq(idx));
2584 }
2585 
2586 static void
wqt_preposts_gc_locked(struct waitq_set * wqset)2587 wqt_preposts_gc_locked(struct waitq_set *wqset)
2588 {
2589 	circle_queue_t q = &wqset->wqset_preposts;
2590 	struct waitq_link *link;
2591 	uint32_t ticket;
2592 
2593 again:
2594 	cqe_foreach_element_safe(link, q, wql_slink) {
2595 		struct waitq *wq = link->wql_wq;
2596 
2597 		if (!waitq_lock_reserve(wq, &ticket)) {
2598 			waitq_unlock(wqset);
2599 			waitq_lock_wait(wq, ticket);
2600 			waitq_lock(wqset);
2601 			waitq_unlock(wq);
2602 			/* the list was possibly mutated, restart */
2603 			goto again;
2604 		}
2605 
2606 		if (!wq->waitq_preposted) {
2607 			wql_wqs_clear_preposted(link);
2608 			circle_dequeue(q, &link->wql_slink);
2609 			circle_enqueue_tail(&wqset->wqset_links, &link->wql_slink);
2610 		}
2611 
2612 		waitq_unlock(wq);
2613 	}
2614 }
2615 
2616 static void
wqt_expect_preposts(struct waitq_set * wqset,__assert_only uint64_t preposts)2617 wqt_expect_preposts(struct waitq_set *wqset, __assert_only uint64_t preposts)
2618 {
2619 	struct waitq_link *link;
2620 	uint64_t found = 0;
2621 
2622 	waitq_lock(wqset);
2623 
2624 	wqt_preposts_gc_locked(wqset);
2625 
2626 	cqe_foreach_element(link, &wqset->wqset_preposts, wql_slink) {
2627 		struct waitq *waitq = link->wql_wq;
2628 
2629 		printf("[WQ]: found prepost %d\n", wqt_idx(waitq));
2630 		assertf((found & wqt_bit(waitq)) == 0,
2631 		    "found waitq %d twice", wqt_idx(waitq));
2632 		found |= wqt_bit(waitq);
2633 	}
2634 
2635 	waitq_unlock(wqset);
2636 
2637 	assertf(found == preposts, "preposts expected 0x%llx, but got 0x%llx",
2638 	    preposts, found);
2639 }
2640 
2641 static int
waitq_basic_test(__unused int64_t in,int64_t * out)2642 waitq_basic_test(__unused int64_t in, int64_t *out)
2643 {
2644 	struct waitq_set *wqset;
2645 
2646 	if (!wqt_start(__func__, out)) {
2647 		return EBUSY;
2648 	}
2649 
2650 	wqset = wqt_wqset_create();
2651 	wqt_link(10, wqset, KERN_SUCCESS);
2652 	wqt_link(10, wqset, KERN_ALREADY_IN_SET);
2653 	wqt_link(11, wqset, KERN_SUCCESS);
2654 	wqt_link(11, wqset, KERN_ALREADY_IN_SET);
2655 	wqt_link(12, wqset, KERN_SUCCESS);
2656 	wqt_link(12, wqset, KERN_ALREADY_IN_SET);
2657 
2658 	wqt_wakeup_one(10, NO_EVENT64, KERN_NOT_WAITING);
2659 	wqt_wakeup_one(12, NO_EVENT64, KERN_NOT_WAITING);
2660 
2661 	wqt_expect_preposts(wqset, wqt_bit(10) | wqt_bit(12));
2662 	wqt_clear_preposts(10);
2663 
2664 	wqt_expect_preposts(wqset, wqt_bit(12));
2665 	wqt_clear_preposts(12);
2666 
2667 	wqt_expect_preposts(wqset, 0);
2668 
2669 	wqt_unlink(12, wqset, KERN_SUCCESS);
2670 	wqt_unlink(12, wqset, KERN_NOT_IN_SET);
2671 	wqt_unlink(11, wqset, KERN_SUCCESS);
2672 	wqt_unlink(10, wqset, KERN_SUCCESS);
2673 	wqt_wqset_free(wqset);
2674 
2675 	return wqt_end(__func__, out);
2676 }
2677 SYSCTL_TEST_REGISTER(waitq_basic, waitq_basic_test);
2678 #endif /* DEBUG || DEVELOPMENT */
2679