xref: /xnu-8792.41.9/bsd/kern/kern_event.c (revision 5c2921b07a2480ab43ec66f5b9e41cb872bc554f)
1 /*
2  * Copyright (c) 2000-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 /*-
30  * Copyright (c) 1999,2000,2001 Jonathan Lemon <[email protected]>
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  *
42  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
43  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
46  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52  * SUCH DAMAGE.
53  */
54 /*
55  *	@(#)kern_event.c       1.0 (3/31/2000)
56  */
57 #include <stdint.h>
58 #include <machine/atomic.h>
59 
60 #include <sys/param.h>
61 #include <sys/systm.h>
62 #include <sys/filedesc.h>
63 #include <sys/kernel.h>
64 #include <sys/proc_internal.h>
65 #include <sys/kauth.h>
66 #include <sys/malloc.h>
67 #include <sys/unistd.h>
68 #include <sys/file_internal.h>
69 #include <sys/fcntl.h>
70 #include <sys/select.h>
71 #include <sys/queue.h>
72 #include <sys/event.h>
73 #include <sys/eventvar.h>
74 #include <sys/protosw.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/stat.h>
78 #include <sys/syscall.h> // SYS_* constants
79 #include <sys/sysctl.h>
80 #include <sys/uio.h>
81 #include <sys/sysproto.h>
82 #include <sys/user.h>
83 #include <sys/vnode_internal.h>
84 #include <string.h>
85 #include <sys/proc_info.h>
86 #include <sys/codesign.h>
87 #include <sys/pthread_shims.h>
88 #include <sys/kdebug.h>
89 #include <os/base.h>
90 #include <pexpert/pexpert.h>
91 
92 #include <kern/thread_group.h>
93 #include <kern/locks.h>
94 #include <kern/clock.h>
95 #include <kern/cpu_data.h>
96 #include <kern/policy_internal.h>
97 #include <kern/thread_call.h>
98 #include <kern/sched_prim.h>
99 #include <kern/waitq.h>
100 #include <kern/zalloc.h>
101 #include <kern/kalloc.h>
102 #include <kern/assert.h>
103 #include <kern/ast.h>
104 #include <kern/thread.h>
105 #include <kern/kcdata.h>
106 
107 #include <pthread/priority_private.h>
108 #include <pthread/workqueue_syscalls.h>
109 #include <pthread/workqueue_internal.h>
110 #include <libkern/libkern.h>
111 
112 #include <os/log.h>
113 
114 #include "net/net_str_id.h"
115 
116 #if SKYWALK && defined(XNU_TARGET_OS_OSX)
117 #include <skywalk/lib/net_filter_event.h>
118 
119 extern bool net_check_compatible_alf(void);
120 #endif /* SKYWALK && XNU_TARGET_OS_OSX */
121 
122 #include <mach/task.h>
123 #include <libkern/section_keywords.h>
124 
125 #if CONFIG_MEMORYSTATUS
126 #include <sys/kern_memorystatus.h>
127 #endif
128 
129 #if DEVELOPMENT || DEBUG
130 #define KEVENT_PANIC_ON_WORKLOOP_OWNERSHIP_LEAK  (1U << 0)
131 #define KEVENT_PANIC_ON_NON_ENQUEUED_PROCESS     (1U << 1)
132 TUNABLE(uint32_t, kevent_debug_flags, "kevent_debug", 0);
133 #endif
134 
135 static LCK_GRP_DECLARE(kq_lck_grp, "kqueue");
136 SECURITY_READ_ONLY_EARLY(vm_packing_params_t) kn_kq_packing_params =
137     VM_PACKING_PARAMS(KNOTE_KQ_PACKED);
138 
139 extern mach_port_name_t ipc_entry_name_mask(mach_port_name_t name); /* osfmk/ipc/ipc_entry.h */
140 extern int cansignal(struct proc *, kauth_cred_t, struct proc *, int); /* bsd/kern/kern_sig.c */
141 
142 #define KEV_EVTID(code) BSDDBG_CODE(DBG_BSD_KEVENT, (code))
143 
144 static int kqueue_select(struct fileproc *fp, int which, void *wq_link_id,
145     vfs_context_t ctx);
146 static int kqueue_close(struct fileglob *fg, vfs_context_t ctx);
147 static int kqueue_kqfilter(struct fileproc *fp, struct knote *kn,
148     struct kevent_qos_s *kev);
149 static int kqueue_drain(struct fileproc *fp, vfs_context_t ctx);
150 
151 static const struct fileops kqueueops = {
152 	.fo_type     = DTYPE_KQUEUE,
153 	.fo_read     = fo_no_read,
154 	.fo_write    = fo_no_write,
155 	.fo_ioctl    = fo_no_ioctl,
156 	.fo_select   = kqueue_select,
157 	.fo_close    = kqueue_close,
158 	.fo_drain    = kqueue_drain,
159 	.fo_kqfilter = kqueue_kqfilter,
160 };
161 
162 static inline int kevent_modern_copyout(struct kevent_qos_s *, user_addr_t *);
163 static int kevent_register_wait_prepare(struct knote *kn, struct kevent_qos_s *kev, int result);
164 static void kevent_register_wait_block(struct turnstile *ts, thread_t handoff_thread,
165     thread_continue_t cont, struct _kevent_register *cont_args) __dead2;
166 static void kevent_register_wait_return(struct _kevent_register *cont_args) __dead2;
167 static void kevent_register_wait_cleanup(struct knote *kn);
168 
169 static struct kqtailq *kqueue_get_suppressed_queue(kqueue_t kq, struct knote *kn);
170 static void kqueue_threadreq_initiate(struct kqueue *kq, workq_threadreq_t, kq_index_t qos, int flags);
171 
172 static void kqworkq_unbind(proc_t p, workq_threadreq_t);
173 static thread_qos_t kqworkq_unbind_locked(struct kqworkq *kqwq, workq_threadreq_t, thread_t thread);
174 static workq_threadreq_t kqworkq_get_request(struct kqworkq *kqwq, kq_index_t qos_index);
175 static void kqueue_update_iotier_override(kqueue_t kqu);
176 
177 static void kqworkloop_unbind(struct kqworkloop *kwql);
178 
179 enum kqwl_unbind_locked_mode {
180 	KQWL_OVERRIDE_DROP_IMMEDIATELY,
181 	KQWL_OVERRIDE_DROP_DELAYED,
182 };
183 static void kqworkloop_unbind_locked(struct kqworkloop *kwql, thread_t thread,
184     enum kqwl_unbind_locked_mode how);
185 static void kqworkloop_unbind_delayed_override_drop(thread_t thread);
186 static kq_index_t kqworkloop_override(struct kqworkloop *kqwl);
187 static void kqworkloop_set_overcommit(struct kqworkloop *kqwl);
188 enum {
189 	KQWL_UTQ_NONE,
190 	/*
191 	 * The wakeup qos is the qos of QUEUED knotes.
192 	 *
193 	 * This QoS is accounted for with the events override in the
194 	 * kqr_override_index field. It is raised each time a new knote is queued at
195 	 * a given QoS. The kqwl_wakeup_qos field is a superset of the non empty
196 	 * knote buckets and is recomputed after each event delivery.
197 	 */
198 	KQWL_UTQ_UPDATE_WAKEUP_QOS,
199 	KQWL_UTQ_RECOMPUTE_WAKEUP_QOS,
200 	KQWL_UTQ_UNBINDING, /* attempt to rebind */
201 	KQWL_UTQ_PARKING,
202 	/*
203 	 * The wakeup override is for suppressed knotes that have fired again at
204 	 * a higher QoS than the one for which they are suppressed already.
205 	 * This override is cleared when the knote suppressed list becomes empty.
206 	 */
207 	KQWL_UTQ_UPDATE_WAKEUP_OVERRIDE,
208 	KQWL_UTQ_RESET_WAKEUP_OVERRIDE,
209 	/*
210 	 * The QoS is the maximum QoS of an event enqueued on this workloop in
211 	 * userland. It is copied from the only EVFILT_WORKLOOP knote with
212 	 * a NOTE_WL_THREAD_REQUEST bit set allowed on this workloop. If there is no
213 	 * such knote, this QoS is 0.
214 	 */
215 	KQWL_UTQ_SET_QOS_INDEX,
216 	KQWL_UTQ_REDRIVE_EVENTS,
217 };
218 static void kqworkloop_update_threads_qos(struct kqworkloop *kqwl, int op, kq_index_t qos);
219 static int kqworkloop_end_processing(struct kqworkloop *kqwl, int flags, int kevent_flags);
220 
221 static struct knote *knote_alloc(void);
222 static void knote_free(struct knote *kn);
223 static int kq_add_knote(struct kqueue *kq, struct knote *kn,
224     struct knote_lock_ctx *knlc, struct proc *p);
225 static struct knote *kq_find_knote_and_kq_lock(struct kqueue *kq,
226     struct kevent_qos_s *kev, bool is_fd, struct proc *p);
227 
228 static void knote_activate(kqueue_t kqu, struct knote *kn, int result);
229 static void knote_dequeue(kqueue_t kqu, struct knote *kn);
230 
231 static void knote_apply_touch(kqueue_t kqu, struct knote *kn,
232     struct kevent_qos_s *kev, int result);
233 static void knote_suppress(kqueue_t kqu, struct knote *kn);
234 static void knote_unsuppress(kqueue_t kqu, struct knote *kn);
235 static void knote_drop(kqueue_t kqu, struct knote *kn, struct knote_lock_ctx *knlc);
236 
237 // both these functions may dequeue the knote and it is up to the caller
238 // to enqueue the knote back
239 static void knote_adjust_qos(struct kqueue *kq, struct knote *kn, int result);
240 static void knote_reset_priority(kqueue_t kqu, struct knote *kn, pthread_priority_t pp);
241 
242 static ZONE_DEFINE(knote_zone, "knote zone",
243     sizeof(struct knote), ZC_CACHING | ZC_ZFREE_CLEARMEM);
244 static ZONE_DEFINE(kqfile_zone, "kqueue file zone",
245     sizeof(struct kqfile), ZC_ZFREE_CLEARMEM | ZC_NOTBITAG);
246 static ZONE_DEFINE(kqworkq_zone, "kqueue workq zone",
247     sizeof(struct kqworkq), ZC_ZFREE_CLEARMEM | ZC_NOTBITAG);
248 static ZONE_DEFINE(kqworkloop_zone, "kqueue workloop zone",
249     sizeof(struct kqworkloop), ZC_CACHING | ZC_ZFREE_CLEARMEM | ZC_NOTBITAG);
250 
251 #define KN_HASH(val, mask)      (((val) ^ (val >> 8)) & (mask))
252 
253 static int filt_no_attach(struct knote *kn, struct kevent_qos_s *kev);
254 static void filt_no_detach(struct knote *kn);
255 static int filt_bad_event(struct knote *kn, long hint);
256 static int filt_bad_touch(struct knote *kn, struct kevent_qos_s *kev);
257 static int filt_bad_process(struct knote *kn, struct kevent_qos_s *kev);
258 
259 SECURITY_READ_ONLY_EARLY(static struct filterops) bad_filtops = {
260 	.f_attach  = filt_no_attach,
261 	.f_detach  = filt_no_detach,
262 	.f_event   = filt_bad_event,
263 	.f_touch   = filt_bad_touch,
264 	.f_process = filt_bad_process,
265 };
266 
267 #if CONFIG_MEMORYSTATUS
268 extern const struct filterops memorystatus_filtops;
269 #endif /* CONFIG_MEMORYSTATUS */
270 extern const struct filterops fs_filtops;
271 extern const struct filterops sig_filtops;
272 extern const struct filterops machport_filtops;
273 extern const struct filterops pipe_nfiltops;
274 extern const struct filterops pipe_rfiltops;
275 extern const struct filterops pipe_wfiltops;
276 extern const struct filterops ptsd_kqops;
277 extern const struct filterops ptmx_kqops;
278 extern const struct filterops soread_filtops;
279 extern const struct filterops sowrite_filtops;
280 extern const struct filterops sock_filtops;
281 extern const struct filterops soexcept_filtops;
282 extern const struct filterops spec_filtops;
283 extern const struct filterops bpfread_filtops;
284 extern const struct filterops necp_fd_rfiltops;
285 #if SKYWALK
286 extern const struct filterops skywalk_channel_rfiltops;
287 extern const struct filterops skywalk_channel_wfiltops;
288 extern const struct filterops skywalk_channel_efiltops;
289 #endif /* SKYWALK */
290 extern const struct filterops fsevent_filtops;
291 extern const struct filterops vnode_filtops;
292 extern const struct filterops tty_filtops;
293 
294 const static struct filterops file_filtops;
295 const static struct filterops kqread_filtops;
296 const static struct filterops proc_filtops;
297 const static struct filterops timer_filtops;
298 const static struct filterops user_filtops;
299 const static struct filterops workloop_filtops;
300 
301 /*
302  *
303  * Rules for adding new filters to the system:
304  * Public filters:
305  * - Add a new "EVFILT_" option value to bsd/sys/event.h (typically a negative value)
306  *   in the exported section of the header
307  * - Update the EVFILT_SYSCOUNT value to reflect the new addition
308  * - Add a filterops to the sysfilt_ops array. Public filters should be added at the end
309  *   of the Public Filters section in the array.
310  * Private filters:
311  * - Add a new "EVFILT_" value to bsd/sys/event.h (typically a positive value)
312  *   in the XNU_KERNEL_PRIVATE section of the header
313  * - Update the EVFILTID_MAX value to reflect the new addition
314  * - Add a filterops to the sysfilt_ops. Private filters should be added at the end of
315  *   the Private filters section of the array.
316  */
317 static_assert(EVFILTID_MAX < UINT8_MAX, "kn_filtid expects this to be true");
318 static const struct filterops * const sysfilt_ops[EVFILTID_MAX] = {
319 	/* Public Filters */
320 	[~EVFILT_READ]                  = &file_filtops,
321 	[~EVFILT_WRITE]                 = &file_filtops,
322 	[~EVFILT_AIO]                   = &bad_filtops,
323 	[~EVFILT_VNODE]                 = &file_filtops,
324 	[~EVFILT_PROC]                  = &proc_filtops,
325 	[~EVFILT_SIGNAL]                = &sig_filtops,
326 	[~EVFILT_TIMER]                 = &timer_filtops,
327 	[~EVFILT_MACHPORT]              = &machport_filtops,
328 	[~EVFILT_FS]                    = &fs_filtops,
329 	[~EVFILT_USER]                  = &user_filtops,
330 	[~EVFILT_UNUSED_11]             = &bad_filtops,
331 	[~EVFILT_VM]                    = &bad_filtops,
332 	[~EVFILT_SOCK]                  = &file_filtops,
333 #if CONFIG_MEMORYSTATUS
334 	[~EVFILT_MEMORYSTATUS]          = &memorystatus_filtops,
335 #else
336 	[~EVFILT_MEMORYSTATUS]          = &bad_filtops,
337 #endif
338 	[~EVFILT_EXCEPT]                = &file_filtops,
339 #if SKYWALK
340 	[~EVFILT_NW_CHANNEL]            = &file_filtops,
341 #else /* !SKYWALK */
342 	[~EVFILT_NW_CHANNEL]            = &bad_filtops,
343 #endif /* !SKYWALK */
344 	[~EVFILT_WORKLOOP]              = &workloop_filtops,
345 
346 	/* Private filters */
347 	[EVFILTID_KQREAD]               = &kqread_filtops,
348 	[EVFILTID_PIPE_N]               = &pipe_nfiltops,
349 	[EVFILTID_PIPE_R]               = &pipe_rfiltops,
350 	[EVFILTID_PIPE_W]               = &pipe_wfiltops,
351 	[EVFILTID_PTSD]                 = &ptsd_kqops,
352 	[EVFILTID_SOREAD]               = &soread_filtops,
353 	[EVFILTID_SOWRITE]              = &sowrite_filtops,
354 	[EVFILTID_SCK]                  = &sock_filtops,
355 	[EVFILTID_SOEXCEPT]             = &soexcept_filtops,
356 	[EVFILTID_SPEC]                 = &spec_filtops,
357 	[EVFILTID_BPFREAD]              = &bpfread_filtops,
358 	[EVFILTID_NECP_FD]              = &necp_fd_rfiltops,
359 #if SKYWALK
360 	[EVFILTID_SKYWALK_CHANNEL_W]    = &skywalk_channel_wfiltops,
361 	[EVFILTID_SKYWALK_CHANNEL_R]    = &skywalk_channel_rfiltops,
362 	[EVFILTID_SKYWALK_CHANNEL_E]    = &skywalk_channel_efiltops,
363 #else /* !SKYWALK */
364 	[EVFILTID_SKYWALK_CHANNEL_W]    = &bad_filtops,
365 	[EVFILTID_SKYWALK_CHANNEL_R]    = &bad_filtops,
366 	[EVFILTID_SKYWALK_CHANNEL_E]    = &bad_filtops,
367 #endif /* !SKYWALK */
368 	[EVFILTID_FSEVENT]              = &fsevent_filtops,
369 	[EVFILTID_VN]                   = &vnode_filtops,
370 	[EVFILTID_TTY]                  = &tty_filtops,
371 	[EVFILTID_PTMX]                 = &ptmx_kqops,
372 
373 	/* fake filter for detached knotes, keep last */
374 	[EVFILTID_DETACHED]             = &bad_filtops,
375 };
376 
377 static inline bool
kqr_thread_bound(workq_threadreq_t kqr)378 kqr_thread_bound(workq_threadreq_t kqr)
379 {
380 	return kqr->tr_state == WORKQ_TR_STATE_BOUND;
381 }
382 
383 static inline bool
kqr_thread_requested_pending(workq_threadreq_t kqr)384 kqr_thread_requested_pending(workq_threadreq_t kqr)
385 {
386 	workq_tr_state_t tr_state = kqr->tr_state;
387 	return tr_state > WORKQ_TR_STATE_IDLE && tr_state < WORKQ_TR_STATE_BOUND;
388 }
389 
390 static inline bool
kqr_thread_requested(workq_threadreq_t kqr)391 kqr_thread_requested(workq_threadreq_t kqr)
392 {
393 	return kqr->tr_state != WORKQ_TR_STATE_IDLE;
394 }
395 
396 static inline thread_t
kqr_thread_fast(workq_threadreq_t kqr)397 kqr_thread_fast(workq_threadreq_t kqr)
398 {
399 	assert(kqr_thread_bound(kqr));
400 	return kqr->tr_thread;
401 }
402 
403 static inline thread_t
kqr_thread(workq_threadreq_t kqr)404 kqr_thread(workq_threadreq_t kqr)
405 {
406 	return kqr_thread_bound(kqr) ? kqr->tr_thread : THREAD_NULL;
407 }
408 
409 static inline struct kqworkloop *
kqr_kqworkloop(workq_threadreq_t kqr)410 kqr_kqworkloop(workq_threadreq_t kqr)
411 {
412 	if (kqr->tr_flags & WORKQ_TR_FLAG_WORKLOOP) {
413 		return __container_of(kqr, struct kqworkloop, kqwl_request);
414 	}
415 	return NULL;
416 }
417 
418 static inline kqueue_t
kqr_kqueue(proc_t p,workq_threadreq_t kqr)419 kqr_kqueue(proc_t p, workq_threadreq_t kqr)
420 {
421 	kqueue_t kqu;
422 	if (kqr->tr_flags & WORKQ_TR_FLAG_WORKLOOP) {
423 		kqu.kqwl = kqr_kqworkloop(kqr);
424 	} else {
425 		kqu.kqwq = p->p_fd.fd_wqkqueue;
426 		assert(kqr >= kqu.kqwq->kqwq_request &&
427 		    kqr < kqu.kqwq->kqwq_request + KQWQ_NBUCKETS);
428 	}
429 	return kqu;
430 }
431 
432 #if CONFIG_PREADOPT_TG
433 /* There are no guarantees about which locks are held when this is called */
434 inline thread_group_qos_t
kqr_preadopt_thread_group(workq_threadreq_t req)435 kqr_preadopt_thread_group(workq_threadreq_t req)
436 {
437 	struct kqworkloop *kqwl = kqr_kqworkloop(req);
438 	return kqwl ? os_atomic_load(&kqwl->kqwl_preadopt_tg, relaxed) : NULL;
439 }
440 
441 /* There are no guarantees about which locks are held when this is called */
_Atomic(thread_group_qos_t)442 inline _Atomic(thread_group_qos_t) *
443 kqr_preadopt_thread_group_addr(workq_threadreq_t req)
444 {
445 	struct kqworkloop *kqwl = kqr_kqworkloop(req);
446 	return kqwl ? (&kqwl->kqwl_preadopt_tg) : NULL;
447 }
448 #endif
449 
450 /*
451  * kqueue/note lock implementations
452  *
453  *	The kqueue lock guards the kq state, the state of its queues,
454  *	and the kqueue-aware status and locks of individual knotes.
455  *
456  *	The kqueue workq lock is used to protect state guarding the
457  *	interaction of the kqueue with the workq.  This state cannot
458  *	be guarded by the kq lock - as it needs to be taken when we
459  *	already have the waitq set lock held (during the waitq hook
460  *	callback).  It might be better to use the waitq lock itself
461  *	for this, but the IRQ requirements make that difficult).
462  *
463  *	Knote flags, filter flags, and associated data are protected
464  *	by the underlying object lock - and are only ever looked at
465  *	by calling the filter to get a [consistent] snapshot of that
466  *	data.
467  */
468 
469 static inline void
kqlock(kqueue_t kqu)470 kqlock(kqueue_t kqu)
471 {
472 	lck_spin_lock(&kqu.kq->kq_lock);
473 }
474 
475 static inline void
kqlock_held(__assert_only kqueue_t kqu)476 kqlock_held(__assert_only kqueue_t kqu)
477 {
478 	LCK_SPIN_ASSERT(&kqu.kq->kq_lock, LCK_ASSERT_OWNED);
479 }
480 
481 static inline void
kqunlock(kqueue_t kqu)482 kqunlock(kqueue_t kqu)
483 {
484 	lck_spin_unlock(&kqu.kq->kq_lock);
485 }
486 
487 static inline void
knhash_lock(struct filedesc * fdp)488 knhash_lock(struct filedesc *fdp)
489 {
490 	lck_mtx_lock(&fdp->fd_knhashlock);
491 }
492 
493 static inline void
knhash_unlock(struct filedesc * fdp)494 knhash_unlock(struct filedesc *fdp)
495 {
496 	lck_mtx_unlock(&fdp->fd_knhashlock);
497 }
498 
499 /* wait event for knote locks */
500 static inline event_t
knote_lock_wev(struct knote * kn)501 knote_lock_wev(struct knote *kn)
502 {
503 	return (event_t)(&kn->kn_hook);
504 }
505 
506 /* wait event for kevent_register_wait_* */
507 static inline event64_t
knote_filt_wev64(struct knote * kn)508 knote_filt_wev64(struct knote *kn)
509 {
510 	/* kdp_workloop_sync_wait_find_owner knows about this */
511 	return CAST_EVENT64_T(kn);
512 }
513 
514 /* wait event for knote_post/knote_drop */
515 static inline event_t
knote_post_wev(struct knote * kn)516 knote_post_wev(struct knote *kn)
517 {
518 	return &kn->kn_kevent;
519 }
520 
521 /*!
522  * @function knote_has_qos
523  *
524  * @brief
525  * Whether the knote has a regular QoS.
526  *
527  * @discussion
528  * kn_qos_override is:
529  * - 0 on kqfiles
530  * - THREAD_QOS_LAST for special buckets (manager)
531  *
532  * Other values mean the knote participates to QoS propagation.
533  */
534 static inline bool
knote_has_qos(struct knote * kn)535 knote_has_qos(struct knote *kn)
536 {
537 	return kn->kn_qos_override > 0 && kn->kn_qos_override < THREAD_QOS_LAST;
538 }
539 
540 #pragma mark knote locks
541 
542 /*
543  * Enum used by the knote_lock_* functions.
544  *
545  * KNOTE_KQ_LOCK_ALWAYS
546  *   The function will always return with the kq lock held.
547  *
548  * KNOTE_KQ_LOCK_ON_SUCCESS
549  *   The function will return with the kq lock held if it was successful
550  *   (knote_lock() is the only function that can fail).
551  *
552  * KNOTE_KQ_LOCK_ON_FAILURE
553  *   The function will return with the kq lock held if it was unsuccessful
554  *   (knote_lock() is the only function that can fail).
555  *
556  * KNOTE_KQ_UNLOCK:
557  *   The function returns with the kq unlocked.
558  */
559 enum kqlocking {
560 	KNOTE_KQ_LOCK_ALWAYS,
561 	KNOTE_KQ_LOCK_ON_SUCCESS,
562 	KNOTE_KQ_LOCK_ON_FAILURE,
563 	KNOTE_KQ_UNLOCK,
564 };
565 
566 static struct knote_lock_ctx *
knote_lock_ctx_find(kqueue_t kqu,struct knote * kn)567 knote_lock_ctx_find(kqueue_t kqu, struct knote *kn)
568 {
569 	struct knote_lock_ctx *ctx;
570 	LIST_FOREACH(ctx, &kqu.kq->kq_knlocks, knlc_link) {
571 		if (ctx->knlc_knote == kn) {
572 			return ctx;
573 		}
574 	}
575 	panic("knote lock context not found: %p", kn);
576 	__builtin_trap();
577 }
578 
579 /* slowpath of knote_lock() */
580 __attribute__((noinline))
581 static bool __result_use_check
knote_lock_slow(kqueue_t kqu,struct knote * kn,struct knote_lock_ctx * knlc,int kqlocking)582 knote_lock_slow(kqueue_t kqu, struct knote *kn,
583     struct knote_lock_ctx *knlc, int kqlocking)
584 {
585 	struct knote_lock_ctx *owner_lc;
586 	struct uthread *uth = current_uthread();
587 	wait_result_t wr;
588 
589 	kqlock_held(kqu);
590 
591 	owner_lc = knote_lock_ctx_find(kqu, kn);
592 #if DEBUG || DEVELOPMENT
593 	knlc->knlc_state = KNOTE_LOCK_CTX_WAITING;
594 #endif
595 	owner_lc->knlc_waiters++;
596 
597 	/*
598 	 * Make our lock context visible to knote_unlock()
599 	 */
600 	uth->uu_knlock = knlc;
601 
602 	wr = lck_spin_sleep_with_inheritor(&kqu.kq->kq_lock, LCK_SLEEP_UNLOCK,
603 	    knote_lock_wev(kn), owner_lc->knlc_thread,
604 	    THREAD_UNINT | THREAD_WAIT_NOREPORT, TIMEOUT_WAIT_FOREVER);
605 
606 	if (wr == THREAD_RESTART) {
607 		/*
608 		 * We haven't been woken up by knote_unlock() but knote_unlock_cancel.
609 		 * We need to cleanup the state since no one did.
610 		 */
611 		uth->uu_knlock = NULL;
612 #if DEBUG || DEVELOPMENT
613 		assert(knlc->knlc_state == KNOTE_LOCK_CTX_WAITING);
614 		knlc->knlc_state = KNOTE_LOCK_CTX_UNLOCKED;
615 #endif
616 
617 		if (kqlocking == KNOTE_KQ_LOCK_ALWAYS ||
618 		    kqlocking == KNOTE_KQ_LOCK_ON_FAILURE) {
619 			kqlock(kqu);
620 		}
621 		return false;
622 	} else {
623 		if (kqlocking == KNOTE_KQ_LOCK_ALWAYS ||
624 		    kqlocking == KNOTE_KQ_LOCK_ON_SUCCESS) {
625 			kqlock(kqu);
626 #if DEBUG || DEVELOPMENT
627 			/*
628 			 * This state is set under the lock so we can't
629 			 * really assert this unless we hold the lock.
630 			 */
631 			assert(knlc->knlc_state == KNOTE_LOCK_CTX_LOCKED);
632 #endif
633 		}
634 		return true;
635 	}
636 }
637 
638 /*
639  * Attempts to take the "knote" lock.
640  *
641  * Called with the kqueue lock held.
642  *
643  * Returns true if the knote lock is acquired, false if it has been dropped
644  */
645 static bool __result_use_check
knote_lock(kqueue_t kqu,struct knote * kn,struct knote_lock_ctx * knlc,enum kqlocking kqlocking)646 knote_lock(kqueue_t kqu, struct knote *kn, struct knote_lock_ctx *knlc,
647     enum kqlocking kqlocking)
648 {
649 	kqlock_held(kqu);
650 
651 #if DEBUG || DEVELOPMENT
652 	assert(knlc->knlc_state == KNOTE_LOCK_CTX_UNLOCKED);
653 #endif
654 	knlc->knlc_knote = kn;
655 	knlc->knlc_thread = current_thread();
656 	knlc->knlc_waiters = 0;
657 
658 	if (__improbable(kn->kn_status & KN_LOCKED)) {
659 		return knote_lock_slow(kqu, kn, knlc, kqlocking);
660 	}
661 
662 	/*
663 	 * When the knote will be dropped, the knote lock is taken before
664 	 * KN_DROPPING is set, and then the knote will be removed from any
665 	 * hash table that references it before the lock is canceled.
666 	 */
667 	assert((kn->kn_status & KN_DROPPING) == 0);
668 	LIST_INSERT_HEAD(&kqu.kq->kq_knlocks, knlc, knlc_link);
669 	kn->kn_status |= KN_LOCKED;
670 #if DEBUG || DEVELOPMENT
671 	knlc->knlc_state = KNOTE_LOCK_CTX_LOCKED;
672 #endif
673 
674 	if (kqlocking == KNOTE_KQ_UNLOCK ||
675 	    kqlocking == KNOTE_KQ_LOCK_ON_FAILURE) {
676 		kqunlock(kqu);
677 	}
678 	return true;
679 }
680 
681 /*
682  * Unlocks a knote successfully locked with knote_lock().
683  *
684  * Called with the kqueue lock held.
685  *
686  * Returns with the kqueue lock held according to KNOTE_KQ_* mode.
687  */
688 static void
knote_unlock(kqueue_t kqu,struct knote * kn,struct knote_lock_ctx * knlc,enum kqlocking kqlocking)689 knote_unlock(kqueue_t kqu, struct knote *kn,
690     struct knote_lock_ctx *knlc, enum kqlocking kqlocking)
691 {
692 	kqlock_held(kqu);
693 
694 	assert(knlc->knlc_knote == kn);
695 	assert(kn->kn_status & KN_LOCKED);
696 #if DEBUG || DEVELOPMENT
697 	assert(knlc->knlc_state == KNOTE_LOCK_CTX_LOCKED);
698 #endif
699 
700 	LIST_REMOVE(knlc, knlc_link);
701 
702 	if (knlc->knlc_waiters) {
703 		thread_t thread = THREAD_NULL;
704 
705 		wakeup_one_with_inheritor(knote_lock_wev(kn), THREAD_AWAKENED,
706 		    LCK_WAKE_DEFAULT, &thread);
707 
708 		/*
709 		 * knote_lock_slow() publishes the lock context of waiters
710 		 * in uthread::uu_knlock.
711 		 *
712 		 * Reach out and make this context the new owner.
713 		 */
714 		struct uthread *ut = get_bsdthread_info(thread);
715 		struct knote_lock_ctx *next_owner_lc = ut->uu_knlock;
716 
717 		assert(next_owner_lc->knlc_knote == kn);
718 		next_owner_lc->knlc_waiters = knlc->knlc_waiters - 1;
719 		LIST_INSERT_HEAD(&kqu.kq->kq_knlocks, next_owner_lc, knlc_link);
720 #if DEBUG || DEVELOPMENT
721 		next_owner_lc->knlc_state = KNOTE_LOCK_CTX_LOCKED;
722 #endif
723 		ut->uu_knlock = NULL;
724 		thread_deallocate_safe(thread);
725 	} else {
726 		kn->kn_status &= ~KN_LOCKED;
727 	}
728 
729 	if ((kn->kn_status & KN_MERGE_QOS) && !(kn->kn_status & KN_POSTING)) {
730 		/*
731 		 * No f_event() in flight anymore, we can leave QoS "Merge" mode
732 		 *
733 		 * See knote_adjust_qos()
734 		 */
735 		kn->kn_status &= ~KN_MERGE_QOS;
736 	}
737 	if (kqlocking == KNOTE_KQ_UNLOCK) {
738 		kqunlock(kqu);
739 	}
740 #if DEBUG || DEVELOPMENT
741 	knlc->knlc_state = KNOTE_LOCK_CTX_UNLOCKED;
742 #endif
743 }
744 
745 /*
746  * Aborts all waiters for a knote lock, and unlock the knote.
747  *
748  * Called with the kqueue lock held.
749  *
750  * Returns with the kqueue unlocked.
751  */
752 static void
knote_unlock_cancel(struct kqueue * kq,struct knote * kn,struct knote_lock_ctx * knlc)753 knote_unlock_cancel(struct kqueue *kq, struct knote *kn,
754     struct knote_lock_ctx *knlc)
755 {
756 	kqlock_held(kq);
757 
758 	assert(knlc->knlc_knote == kn);
759 	assert(kn->kn_status & KN_LOCKED);
760 	assert(kn->kn_status & KN_DROPPING);
761 
762 	LIST_REMOVE(knlc, knlc_link);
763 	kn->kn_status &= ~KN_LOCKED;
764 	kqunlock(kq);
765 
766 	if (knlc->knlc_waiters) {
767 		wakeup_all_with_inheritor(knote_lock_wev(kn), THREAD_RESTART);
768 	}
769 #if DEBUG || DEVELOPMENT
770 	knlc->knlc_state = KNOTE_LOCK_CTX_UNLOCKED;
771 #endif
772 }
773 
774 /*
775  * Call the f_event hook of a given filter.
776  *
777  * Takes a use count to protect against concurrent drops.
778  */
779 static void
knote_post(struct knote * kn,long hint)780 knote_post(struct knote *kn, long hint)
781 {
782 	struct kqueue *kq = knote_get_kq(kn);
783 	int dropping, result;
784 
785 	kqlock(kq);
786 
787 	/*
788 	 * The select fallback is special, if KNOTE() is called,
789 	 * the contract is that kn->kn_hook _HAS_ to become NULL.
790 	 *
791 	 * the f_event() hook might not be called if we're dropping,
792 	 * so we hardcode it here, which is a little distasteful,
793 	 * but the select fallback is kinda magical in the first place.
794 	 */
795 	if (kn->kn_filtid == EVFILTID_SPEC) {
796 		kn->kn_hook = NULL;
797 	}
798 
799 	if (__improbable(kn->kn_status & (KN_DROPPING | KN_VANISHED))) {
800 		return kqunlock(kq);
801 	}
802 
803 	if (__improbable(kn->kn_status & KN_POSTING)) {
804 		panic("KNOTE() called concurrently on knote %p", kn);
805 	}
806 
807 	kn->kn_status |= KN_POSTING;
808 
809 	kqunlock(kq);
810 	result = filter_call(knote_fops(kn), f_event(kn, hint));
811 	kqlock(kq);
812 
813 	dropping = (kn->kn_status & KN_DROPPING);
814 
815 	if (!dropping && (result & FILTER_ADJUST_EVENT_IOTIER_BIT)) {
816 		kqueue_update_iotier_override(kq);
817 	}
818 
819 	if (!dropping && (result & FILTER_ACTIVE)) {
820 		knote_activate(kq, kn, result);
821 	}
822 
823 	if ((kn->kn_status & KN_LOCKED) == 0) {
824 		/*
825 		 * There's no other f_* call in flight, we can leave QoS "Merge" mode.
826 		 *
827 		 * See knote_adjust_qos()
828 		 */
829 		kn->kn_status &= ~(KN_POSTING | KN_MERGE_QOS);
830 	} else {
831 		kn->kn_status &= ~KN_POSTING;
832 	}
833 
834 	if (__improbable(dropping)) {
835 		thread_wakeup(knote_post_wev(kn));
836 	}
837 
838 	kqunlock(kq);
839 }
840 
841 /*
842  * Called by knote_drop() to wait for the last f_event() caller to be done.
843  *
844  *	- kq locked at entry
845  *	- kq unlocked at exit
846  */
847 static void
knote_wait_for_post(struct kqueue * kq,struct knote * kn)848 knote_wait_for_post(struct kqueue *kq, struct knote *kn)
849 {
850 	kqlock_held(kq);
851 
852 	assert(kn->kn_status & KN_DROPPING);
853 
854 	if (kn->kn_status & KN_POSTING) {
855 		lck_spin_sleep(&kq->kq_lock, LCK_SLEEP_UNLOCK, knote_post_wev(kn),
856 		    THREAD_UNINT | THREAD_WAIT_NOREPORT);
857 	} else {
858 		kqunlock(kq);
859 	}
860 }
861 
862 #pragma mark knote helpers for filters
863 
864 OS_ALWAYS_INLINE
865 void
knote_set_error(struct knote * kn,int error)866 knote_set_error(struct knote *kn, int error)
867 {
868 	kn->kn_flags |= EV_ERROR;
869 	kn->kn_sdata = error;
870 }
871 
872 OS_ALWAYS_INLINE
873 int64_t
knote_low_watermark(const struct knote * kn)874 knote_low_watermark(const struct knote *kn)
875 {
876 	return (kn->kn_sfflags & NOTE_LOWAT) ? kn->kn_sdata : 1;
877 }
878 
879 /*!
880  * @function knote_fill_kevent_with_sdata
881  *
882  * @brief
883  * Fills in a kevent from the current content of a knote.
884  *
885  * @discussion
886  * This is meant to be called from filter's f_event hooks.
887  * The kevent data is filled with kn->kn_sdata.
888  *
889  * kn->kn_fflags is cleared if kn->kn_flags has EV_CLEAR set.
890  *
891  * Using knote_fill_kevent is typically preferred.
892  */
893 OS_ALWAYS_INLINE
894 void
knote_fill_kevent_with_sdata(struct knote * kn,struct kevent_qos_s * kev)895 knote_fill_kevent_with_sdata(struct knote *kn, struct kevent_qos_s *kev)
896 {
897 #define knote_assert_aliases(name1, offs1, name2) \
898 	static_assert(offsetof(struct kevent_qos_s, name1) + offs1 == \
899 	    offsetof(struct kevent_internal_s, name2), \
900 	        "kevent_qos_s::" #name1 " and kevent_internal_s::" #name2 "need to alias")
901 	/*
902 	 * All the code makes assumptions on these aliasing,
903 	 * so make sure we fail the build if we ever ever ever break them.
904 	 */
905 	knote_assert_aliases(ident, 0, kei_ident);
906 #ifdef __LITTLE_ENDIAN__
907 	knote_assert_aliases(filter, 0, kei_filter);  // non trivial overlap
908 	knote_assert_aliases(filter, 1, kei_filtid);  // non trivial overlap
909 #else
910 	knote_assert_aliases(filter, 0, kei_filtid);  // non trivial overlap
911 	knote_assert_aliases(filter, 1, kei_filter);  // non trivial overlap
912 #endif
913 	knote_assert_aliases(flags, 0, kei_flags);
914 	knote_assert_aliases(qos, 0, kei_qos);
915 	knote_assert_aliases(udata, 0, kei_udata);
916 	knote_assert_aliases(fflags, 0, kei_fflags);
917 	knote_assert_aliases(xflags, 0, kei_sfflags); // non trivial overlap
918 	knote_assert_aliases(data, 0, kei_sdata);     // non trivial overlap
919 	knote_assert_aliases(ext, 0, kei_ext);
920 #undef knote_assert_aliases
921 
922 	/*
923 	 * Fix the differences between kevent_qos_s and kevent_internal_s:
924 	 * - xflags is where kn_sfflags lives, we need to zero it
925 	 * - fixup the high bits of `filter` where kn_filtid lives
926 	 */
927 	*kev = *(struct kevent_qos_s *)&kn->kn_kevent;
928 	kev->xflags = 0;
929 	kev->filter |= 0xff00;
930 	if (kn->kn_flags & EV_CLEAR) {
931 		kn->kn_fflags = 0;
932 	}
933 }
934 
935 /*!
936  * @function knote_fill_kevent
937  *
938  * @brief
939  * Fills in a kevent from the current content of a knote.
940  *
941  * @discussion
942  * This is meant to be called from filter's f_event hooks.
943  * The kevent data is filled with the passed in data.
944  *
945  * kn->kn_fflags is cleared if kn->kn_flags has EV_CLEAR set.
946  */
947 OS_ALWAYS_INLINE
948 void
knote_fill_kevent(struct knote * kn,struct kevent_qos_s * kev,int64_t data)949 knote_fill_kevent(struct knote *kn, struct kevent_qos_s *kev, int64_t data)
950 {
951 	knote_fill_kevent_with_sdata(kn, kev);
952 	kev->filter = kn->kn_filter;
953 	kev->data = data;
954 }
955 
956 
957 #pragma mark file_filtops
958 
959 static int
filt_fileattach(struct knote * kn,struct kevent_qos_s * kev)960 filt_fileattach(struct knote *kn, struct kevent_qos_s *kev)
961 {
962 	return fo_kqfilter(kn->kn_fp, kn, kev);
963 }
964 
965 SECURITY_READ_ONLY_EARLY(static struct filterops) file_filtops = {
966 	.f_isfd = 1,
967 	.f_attach = filt_fileattach,
968 };
969 
970 #pragma mark kqread_filtops
971 
972 #define f_flag fp_glob->fg_flag
973 #define f_ops fp_glob->fg_ops
974 #define f_lflags fp_glob->fg_lflags
975 
976 static void
filt_kqdetach(struct knote * kn)977 filt_kqdetach(struct knote *kn)
978 {
979 	struct kqfile *kqf = (struct kqfile *)fp_get_data(kn->kn_fp);
980 	struct kqueue *kq = &kqf->kqf_kqueue;
981 
982 	kqlock(kq);
983 	KNOTE_DETACH(&kqf->kqf_sel.si_note, kn);
984 	kqunlock(kq);
985 }
986 
987 static int
filt_kqueue(struct knote * kn,__unused long hint)988 filt_kqueue(struct knote *kn, __unused long hint)
989 {
990 	struct kqueue *kq = (struct kqueue *)fp_get_data(kn->kn_fp);
991 
992 	return kq->kq_count > 0;
993 }
994 
995 static int
filt_kqtouch(struct knote * kn,struct kevent_qos_s * kev)996 filt_kqtouch(struct knote *kn, struct kevent_qos_s *kev)
997 {
998 #pragma unused(kev)
999 	struct kqueue *kq = (struct kqueue *)fp_get_data(kn->kn_fp);
1000 	int res;
1001 
1002 	kqlock(kq);
1003 	res = (kq->kq_count > 0);
1004 	kqunlock(kq);
1005 
1006 	return res;
1007 }
1008 
1009 static int
filt_kqprocess(struct knote * kn,struct kevent_qos_s * kev)1010 filt_kqprocess(struct knote *kn, struct kevent_qos_s *kev)
1011 {
1012 	struct kqueue *kq = (struct kqueue *)fp_get_data(kn->kn_fp);
1013 	int res = 0;
1014 
1015 	kqlock(kq);
1016 	if (kq->kq_count) {
1017 		knote_fill_kevent(kn, kev, kq->kq_count);
1018 		res = 1;
1019 	}
1020 	kqunlock(kq);
1021 
1022 	return res;
1023 }
1024 
1025 SECURITY_READ_ONLY_EARLY(static struct filterops) kqread_filtops = {
1026 	.f_isfd = 1,
1027 	.f_detach = filt_kqdetach,
1028 	.f_event = filt_kqueue,
1029 	.f_touch = filt_kqtouch,
1030 	.f_process = filt_kqprocess,
1031 };
1032 
1033 #pragma mark proc_filtops
1034 
1035 static int
filt_procattach(struct knote * kn,__unused struct kevent_qos_s * kev)1036 filt_procattach(struct knote *kn, __unused struct kevent_qos_s *kev)
1037 {
1038 	struct proc *p;
1039 
1040 	assert(PID_MAX < NOTE_PDATAMASK);
1041 
1042 	if ((kn->kn_sfflags & (NOTE_TRACK | NOTE_TRACKERR | NOTE_CHILD)) != 0) {
1043 		knote_set_error(kn, ENOTSUP);
1044 		return 0;
1045 	}
1046 
1047 	p = proc_find((int)kn->kn_id);
1048 	if (p == NULL) {
1049 		knote_set_error(kn, ESRCH);
1050 		return 0;
1051 	}
1052 
1053 	const uint32_t NoteExitStatusBits = NOTE_EXIT | NOTE_EXITSTATUS;
1054 
1055 	if ((kn->kn_sfflags & NoteExitStatusBits) == NoteExitStatusBits) {
1056 		do {
1057 			pid_t selfpid = proc_selfpid();
1058 
1059 			if (p->p_ppid == selfpid) {
1060 				break;  /* parent => ok */
1061 			}
1062 			if ((p->p_lflag & P_LTRACED) != 0 &&
1063 			    (p->p_oppid == selfpid)) {
1064 				break;  /* parent-in-waiting => ok */
1065 			}
1066 			if (cansignal(current_proc(), kauth_cred_get(), p, SIGKILL)) {
1067 				break; /* allowed to signal => ok */
1068 			}
1069 			proc_rele(p);
1070 			knote_set_error(kn, EACCES);
1071 			return 0;
1072 		} while (0);
1073 	}
1074 
1075 	kn->kn_proc = p;
1076 	kn->kn_flags |= EV_CLEAR;       /* automatically set */
1077 	kn->kn_sdata = 0;               /* incoming data is ignored */
1078 
1079 	proc_klist_lock();
1080 
1081 	KNOTE_ATTACH(&p->p_klist, kn);
1082 
1083 	proc_klist_unlock();
1084 
1085 	proc_rele(p);
1086 
1087 	/*
1088 	 * only captures edge-triggered events after this point
1089 	 * so it can't already be fired.
1090 	 */
1091 	return 0;
1092 }
1093 
1094 
1095 /*
1096  * The knote may be attached to a different process, which may exit,
1097  * leaving nothing for the knote to be attached to.  In that case,
1098  * the pointer to the process will have already been nulled out.
1099  */
1100 static void
filt_procdetach(struct knote * kn)1101 filt_procdetach(struct knote *kn)
1102 {
1103 	struct proc *p;
1104 
1105 	proc_klist_lock();
1106 
1107 	p = kn->kn_proc;
1108 	if (p != PROC_NULL) {
1109 		kn->kn_proc = PROC_NULL;
1110 		KNOTE_DETACH(&p->p_klist, kn);
1111 	}
1112 
1113 	proc_klist_unlock();
1114 }
1115 
1116 static int
filt_procevent(struct knote * kn,long hint)1117 filt_procevent(struct knote *kn, long hint)
1118 {
1119 	u_int event;
1120 
1121 	/* ALWAYS CALLED WITH proc_klist_lock */
1122 
1123 	/*
1124 	 * Note: a lot of bits in hint may be obtained from the knote
1125 	 * To free some of those bits, see <rdar://problem/12592988> Freeing up
1126 	 * bits in hint for filt_procevent
1127 	 *
1128 	 * mask off extra data
1129 	 */
1130 	event = (u_int)hint & NOTE_PCTRLMASK;
1131 
1132 	/*
1133 	 * termination lifecycle events can happen while a debugger
1134 	 * has reparented a process, in which case notifications
1135 	 * should be quashed except to the tracing parent. When
1136 	 * the debugger reaps the child (either via wait4(2) or
1137 	 * process exit), the child will be reparented to the original
1138 	 * parent and these knotes re-fired.
1139 	 */
1140 	if (event & NOTE_EXIT) {
1141 		if ((kn->kn_proc->p_oppid != 0)
1142 		    && (proc_getpid(knote_get_kq(kn)->kq_p) != kn->kn_proc->p_ppid)) {
1143 			/*
1144 			 * This knote is not for the current ptrace(2) parent, ignore.
1145 			 */
1146 			return 0;
1147 		}
1148 	}
1149 
1150 	/*
1151 	 * if the user is interested in this event, record it.
1152 	 */
1153 	if (kn->kn_sfflags & event) {
1154 		kn->kn_fflags |= event;
1155 	}
1156 
1157 #pragma clang diagnostic push
1158 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1159 	if ((event == NOTE_REAP) || ((event == NOTE_EXIT) && !(kn->kn_sfflags & NOTE_REAP))) {
1160 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
1161 	}
1162 #pragma clang diagnostic pop
1163 
1164 
1165 	/*
1166 	 * The kernel has a wrapper in place that returns the same data
1167 	 * as is collected here, in kn_hook32.  Any changes to how
1168 	 * NOTE_EXITSTATUS and NOTE_EXIT_DETAIL are collected
1169 	 * should also be reflected in the proc_pidnoteexit() wrapper.
1170 	 */
1171 	if (event == NOTE_EXIT) {
1172 		kn->kn_hook32 = 0;
1173 		if ((kn->kn_sfflags & NOTE_EXITSTATUS) != 0) {
1174 			kn->kn_fflags |= NOTE_EXITSTATUS;
1175 			kn->kn_hook32 |= (hint & NOTE_PDATAMASK);
1176 		}
1177 		if ((kn->kn_sfflags & NOTE_EXIT_DETAIL) != 0) {
1178 			kn->kn_fflags |= NOTE_EXIT_DETAIL;
1179 			if ((kn->kn_proc->p_lflag &
1180 			    P_LTERM_DECRYPTFAIL) != 0) {
1181 				kn->kn_hook32 |= NOTE_EXIT_DECRYPTFAIL;
1182 			}
1183 			if ((kn->kn_proc->p_lflag &
1184 			    P_LTERM_JETSAM) != 0) {
1185 				kn->kn_hook32 |= NOTE_EXIT_MEMORY;
1186 				switch (kn->kn_proc->p_lflag & P_JETSAM_MASK) {
1187 				case P_JETSAM_VMPAGESHORTAGE:
1188 					kn->kn_hook32 |= NOTE_EXIT_MEMORY_VMPAGESHORTAGE;
1189 					break;
1190 				case P_JETSAM_VMTHRASHING:
1191 					kn->kn_hook32 |= NOTE_EXIT_MEMORY_VMTHRASHING;
1192 					break;
1193 				case P_JETSAM_FCTHRASHING:
1194 					kn->kn_hook32 |= NOTE_EXIT_MEMORY_FCTHRASHING;
1195 					break;
1196 				case P_JETSAM_VNODE:
1197 					kn->kn_hook32 |= NOTE_EXIT_MEMORY_VNODE;
1198 					break;
1199 				case P_JETSAM_HIWAT:
1200 					kn->kn_hook32 |= NOTE_EXIT_MEMORY_HIWAT;
1201 					break;
1202 				case P_JETSAM_PID:
1203 					kn->kn_hook32 |= NOTE_EXIT_MEMORY_PID;
1204 					break;
1205 				case P_JETSAM_IDLEEXIT:
1206 					kn->kn_hook32 |= NOTE_EXIT_MEMORY_IDLE;
1207 					break;
1208 				}
1209 			}
1210 			if ((proc_getcsflags(kn->kn_proc) &
1211 			    CS_KILLED) != 0) {
1212 				kn->kn_hook32 |= NOTE_EXIT_CSERROR;
1213 			}
1214 		}
1215 	}
1216 
1217 	/* if we have any matching state, activate the knote */
1218 	return kn->kn_fflags != 0;
1219 }
1220 
1221 static int
filt_proctouch(struct knote * kn,struct kevent_qos_s * kev)1222 filt_proctouch(struct knote *kn, struct kevent_qos_s *kev)
1223 {
1224 	int res;
1225 
1226 	proc_klist_lock();
1227 
1228 	/* accept new filter flags and mask off output events no long interesting */
1229 	kn->kn_sfflags = kev->fflags;
1230 
1231 	/* restrict the current results to the (smaller?) set of new interest */
1232 	/*
1233 	 * For compatibility with previous implementations, we leave kn_fflags
1234 	 * as they were before.
1235 	 */
1236 	//kn->kn_fflags &= kn->kn_sfflags;
1237 
1238 	res = (kn->kn_fflags != 0);
1239 
1240 	proc_klist_unlock();
1241 
1242 	return res;
1243 }
1244 
1245 static int
filt_procprocess(struct knote * kn,struct kevent_qos_s * kev)1246 filt_procprocess(struct knote *kn, struct kevent_qos_s *kev)
1247 {
1248 	int res = 0;
1249 
1250 	proc_klist_lock();
1251 	if (kn->kn_fflags) {
1252 		knote_fill_kevent(kn, kev, kn->kn_hook32);
1253 		kn->kn_hook32 = 0;
1254 		res = 1;
1255 	}
1256 	proc_klist_unlock();
1257 	return res;
1258 }
1259 
1260 SECURITY_READ_ONLY_EARLY(static struct filterops) proc_filtops = {
1261 	.f_attach  = filt_procattach,
1262 	.f_detach  = filt_procdetach,
1263 	.f_event   = filt_procevent,
1264 	.f_touch   = filt_proctouch,
1265 	.f_process = filt_procprocess,
1266 };
1267 
1268 #pragma mark timer_filtops
1269 
1270 struct filt_timer_params {
1271 	uint64_t deadline; /* deadline in abs/cont time
1272 	                    *                      (or 0 if NOTE_ABSOLUTE and deadline is in past) */
1273 	uint64_t leeway;   /* leeway in abstime, or 0 if none */
1274 	uint64_t interval; /* interval in abstime or 0 if non-repeating timer */
1275 };
1276 
1277 /*
1278  * Values stored in the knote at rest (using Mach absolute time units)
1279  *
1280  * kn->kn_thcall        where the thread_call object is stored
1281  * kn->kn_ext[0]        next deadline or 0 if immediate expiration
1282  * kn->kn_ext[1]        leeway value
1283  * kn->kn_sdata         interval timer: the interval
1284  *                      absolute/deadline timer: 0
1285  * kn->kn_hook32        timer state (with gencount)
1286  *
1287  * TIMER_IDLE:
1288  *   The timer has either never been scheduled or been cancelled.
1289  *   It is safe to schedule a new one in this state.
1290  *
1291  * TIMER_ARMED:
1292  *   The timer has been scheduled
1293  *
1294  * TIMER_FIRED
1295  *   The timer has fired and an event needs to be delivered.
1296  *   When in this state, the callout may still be running.
1297  *
1298  * TIMER_IMMEDIATE
1299  *   The timer has fired at registration time, and the callout was never
1300  *   dispatched.
1301  */
1302 #define TIMER_IDLE       0x0
1303 #define TIMER_ARMED      0x1
1304 #define TIMER_FIRED      0x2
1305 #define TIMER_IMMEDIATE  0x3
1306 #define TIMER_STATE_MASK 0x3
1307 #define TIMER_GEN_INC    0x4
1308 
1309 static void
filt_timer_set_params(struct knote * kn,struct filt_timer_params * params)1310 filt_timer_set_params(struct knote *kn, struct filt_timer_params *params)
1311 {
1312 	kn->kn_ext[0] = params->deadline;
1313 	kn->kn_ext[1] = params->leeway;
1314 	kn->kn_sdata  = params->interval;
1315 }
1316 
1317 /*
1318  * filt_timervalidate - process data from user
1319  *
1320  * Sets up the deadline, interval, and leeway from the provided user data
1321  *
1322  * Input:
1323  *      kn_sdata        timer deadline or interval time
1324  *      kn_sfflags      style of timer, unit of measurement
1325  *
1326  * Output:
1327  *      struct filter_timer_params to apply to the filter with
1328  *      filt_timer_set_params when changes are ready to be commited.
1329  *
1330  * Returns:
1331  *      EINVAL          Invalid user data parameters
1332  *      ERANGE          Various overflows with the parameters
1333  *
1334  * Called with timer filter lock held.
1335  */
1336 static int
filt_timervalidate(const struct kevent_qos_s * kev,struct filt_timer_params * params)1337 filt_timervalidate(const struct kevent_qos_s *kev,
1338     struct filt_timer_params *params)
1339 {
1340 	/*
1341 	 * There are 5 knobs that need to be chosen for a timer registration:
1342 	 *
1343 	 * A) Units of time (what is the time duration of the specified number)
1344 	 *      Absolute and interval take:
1345 	 *              NOTE_SECONDS, NOTE_USECONDS, NOTE_NSECONDS, NOTE_MACHTIME
1346 	 *      Defaults to milliseconds if not specified
1347 	 *
1348 	 * B) Clock epoch (what is the zero point of the specified number)
1349 	 *      For interval, there is none
1350 	 *      For absolute, defaults to the gettimeofday/calendar epoch
1351 	 *      With NOTE_MACHTIME, uses mach_absolute_time()
1352 	 *      With NOTE_MACHTIME and NOTE_MACH_CONTINUOUS_TIME, uses mach_continuous_time()
1353 	 *
1354 	 * C) The knote's behavior on delivery
1355 	 *      Interval timer causes the knote to arm for the next interval unless one-shot is set
1356 	 *      Absolute is a forced one-shot timer which deletes on delivery
1357 	 *      TODO: Add a way for absolute to be not forced one-shot
1358 	 *
1359 	 * D) Whether the time duration is relative to now or absolute
1360 	 *      Interval fires at now + duration when it is set up
1361 	 *      Absolute fires at now + difference between now walltime and passed in walltime
1362 	 *      With NOTE_MACHTIME it fires at an absolute MAT or MCT.
1363 	 *
1364 	 * E) Whether the timer continues to tick across sleep
1365 	 *      By default all three do not.
1366 	 *      For interval and absolute, NOTE_MACH_CONTINUOUS_TIME causes them to tick across sleep
1367 	 *      With NOTE_ABSOLUTE | NOTE_MACHTIME | NOTE_MACH_CONTINUOUS_TIME:
1368 	 *              expires when mach_continuous_time() is > the passed in value.
1369 	 */
1370 
1371 	uint64_t multiplier;
1372 
1373 	boolean_t use_abstime = FALSE;
1374 
1375 	switch (kev->fflags & (NOTE_SECONDS | NOTE_USECONDS | NOTE_NSECONDS | NOTE_MACHTIME)) {
1376 	case NOTE_SECONDS:
1377 		multiplier = NSEC_PER_SEC;
1378 		break;
1379 	case NOTE_USECONDS:
1380 		multiplier = NSEC_PER_USEC;
1381 		break;
1382 	case NOTE_NSECONDS:
1383 		multiplier = 1;
1384 		break;
1385 	case NOTE_MACHTIME:
1386 		multiplier = 0;
1387 		use_abstime = TRUE;
1388 		break;
1389 	case 0: /* milliseconds (default) */
1390 		multiplier = NSEC_PER_SEC / 1000;
1391 		break;
1392 	default:
1393 		return EINVAL;
1394 	}
1395 
1396 	/* transform the leeway in kn_ext[1] to same time scale */
1397 	if (kev->fflags & NOTE_LEEWAY) {
1398 		uint64_t leeway_abs;
1399 
1400 		if (use_abstime) {
1401 			leeway_abs = (uint64_t)kev->ext[1];
1402 		} else {
1403 			uint64_t leeway_ns;
1404 			if (os_mul_overflow((uint64_t)kev->ext[1], multiplier, &leeway_ns)) {
1405 				return ERANGE;
1406 			}
1407 
1408 			nanoseconds_to_absolutetime(leeway_ns, &leeway_abs);
1409 		}
1410 
1411 		params->leeway = leeway_abs;
1412 	} else {
1413 		params->leeway = 0;
1414 	}
1415 
1416 	if (kev->fflags & NOTE_ABSOLUTE) {
1417 		uint64_t deadline_abs;
1418 
1419 		if (use_abstime) {
1420 			deadline_abs = (uint64_t)kev->data;
1421 		} else {
1422 			uint64_t calendar_deadline_ns;
1423 
1424 			if (os_mul_overflow((uint64_t)kev->data, multiplier, &calendar_deadline_ns)) {
1425 				return ERANGE;
1426 			}
1427 
1428 			/* calendar_deadline_ns is in nanoseconds since the epoch */
1429 
1430 			clock_sec_t seconds;
1431 			clock_nsec_t nanoseconds;
1432 
1433 			/*
1434 			 * Note that the conversion through wall-time is only done once.
1435 			 *
1436 			 * If the relationship between MAT and gettimeofday changes,
1437 			 * the underlying timer does not update.
1438 			 *
1439 			 * TODO: build a wall-time denominated timer_call queue
1440 			 * and a flag to request DTRTing with wall-time timers
1441 			 */
1442 			clock_get_calendar_nanotime(&seconds, &nanoseconds);
1443 
1444 			uint64_t calendar_now_ns = (uint64_t)seconds * NSEC_PER_SEC + nanoseconds;
1445 
1446 			/* if deadline is in the future */
1447 			if (calendar_now_ns < calendar_deadline_ns) {
1448 				uint64_t interval_ns = calendar_deadline_ns - calendar_now_ns;
1449 				uint64_t interval_abs;
1450 
1451 				nanoseconds_to_absolutetime(interval_ns, &interval_abs);
1452 
1453 				/*
1454 				 * Note that the NOTE_MACH_CONTINUOUS_TIME flag here only
1455 				 * causes the timer to keep ticking across sleep, but
1456 				 * it does not change the calendar timebase.
1457 				 */
1458 
1459 				if (kev->fflags & NOTE_MACH_CONTINUOUS_TIME) {
1460 					clock_continuoustime_interval_to_deadline(interval_abs,
1461 					    &deadline_abs);
1462 				} else {
1463 					clock_absolutetime_interval_to_deadline(interval_abs,
1464 					    &deadline_abs);
1465 				}
1466 			} else {
1467 				deadline_abs = 0; /* cause immediate expiration */
1468 			}
1469 		}
1470 
1471 		params->deadline = deadline_abs;
1472 		params->interval = 0; /* NOTE_ABSOLUTE is non-repeating */
1473 	} else if (kev->data < 0) {
1474 		/*
1475 		 * Negative interval timers fire immediately, once.
1476 		 *
1477 		 * Ideally a negative interval would be an error, but certain clients
1478 		 * pass negative values on accident, and expect an event back.
1479 		 *
1480 		 * In the old implementation the timer would repeat with no delay
1481 		 * N times until mach_absolute_time() + (N * interval) underflowed,
1482 		 * then it would wait ~forever by accidentally arming a timer for the far future.
1483 		 *
1484 		 * We now skip the power-wasting hot spin phase and go straight to the idle phase.
1485 		 */
1486 
1487 		params->deadline = 0; /* expire immediately */
1488 		params->interval = 0; /* non-repeating */
1489 	} else {
1490 		uint64_t interval_abs = 0;
1491 
1492 		if (use_abstime) {
1493 			interval_abs = (uint64_t)kev->data;
1494 		} else {
1495 			uint64_t interval_ns;
1496 			if (os_mul_overflow((uint64_t)kev->data, multiplier, &interval_ns)) {
1497 				return ERANGE;
1498 			}
1499 
1500 			nanoseconds_to_absolutetime(interval_ns, &interval_abs);
1501 		}
1502 
1503 		uint64_t deadline = 0;
1504 
1505 		if (kev->fflags & NOTE_MACH_CONTINUOUS_TIME) {
1506 			clock_continuoustime_interval_to_deadline(interval_abs, &deadline);
1507 		} else {
1508 			clock_absolutetime_interval_to_deadline(interval_abs, &deadline);
1509 		}
1510 
1511 		params->deadline = deadline;
1512 		params->interval = interval_abs;
1513 	}
1514 
1515 	return 0;
1516 }
1517 
1518 /*
1519  * filt_timerexpire - the timer callout routine
1520  */
1521 static void
filt_timerexpire(void * knx,void * state_on_arm)1522 filt_timerexpire(void *knx, void *state_on_arm)
1523 {
1524 	struct knote *kn = knx;
1525 
1526 	uint32_t state = (uint32_t)(uintptr_t)state_on_arm;
1527 	uint32_t fired_state = state ^ TIMER_ARMED ^ TIMER_FIRED;
1528 
1529 	if (os_atomic_cmpxchg(&kn->kn_hook32, state, fired_state, relaxed)) {
1530 		// our f_event always would say FILTER_ACTIVE,
1531 		// so be leaner and just do it.
1532 		struct kqueue *kq = knote_get_kq(kn);
1533 		kqlock(kq);
1534 		knote_activate(kq, kn, FILTER_ACTIVE);
1535 		kqunlock(kq);
1536 	} else {
1537 		/*
1538 		 * The timer has been reprogrammed or canceled since it was armed,
1539 		 * and this is a late firing for the timer, just ignore it.
1540 		 */
1541 	}
1542 }
1543 
1544 /*
1545  * Does this deadline needs a timer armed for it, or has it expired?
1546  */
1547 static bool
filt_timer_is_ready(struct knote * kn)1548 filt_timer_is_ready(struct knote *kn)
1549 {
1550 	uint64_t now, deadline = kn->kn_ext[0];
1551 
1552 	if (deadline == 0) {
1553 		return true;
1554 	}
1555 
1556 	if (kn->kn_sfflags & NOTE_MACH_CONTINUOUS_TIME) {
1557 		now = mach_continuous_time();
1558 	} else {
1559 		now = mach_absolute_time();
1560 	}
1561 	return deadline <= now;
1562 }
1563 
1564 /*
1565  * Arm a timer
1566  *
1567  * It is the responsibility of the caller to make sure the timer call
1568  * has completed or been cancelled properly prior to arming it.
1569  */
1570 static void
filt_timerarm(struct knote * kn)1571 filt_timerarm(struct knote *kn)
1572 {
1573 	uint64_t deadline = kn->kn_ext[0];
1574 	uint64_t leeway   = kn->kn_ext[1];
1575 	uint32_t state;
1576 
1577 	int filter_flags = kn->kn_sfflags;
1578 	unsigned int timer_flags = 0;
1579 
1580 	if (filter_flags & NOTE_CRITICAL) {
1581 		timer_flags |= THREAD_CALL_DELAY_USER_CRITICAL;
1582 	} else if (filter_flags & NOTE_BACKGROUND) {
1583 		timer_flags |= THREAD_CALL_DELAY_USER_BACKGROUND;
1584 	} else {
1585 		timer_flags |= THREAD_CALL_DELAY_USER_NORMAL;
1586 	}
1587 
1588 	if (filter_flags & NOTE_LEEWAY) {
1589 		timer_flags |= THREAD_CALL_DELAY_LEEWAY;
1590 	}
1591 
1592 	if (filter_flags & NOTE_MACH_CONTINUOUS_TIME) {
1593 		timer_flags |= THREAD_CALL_CONTINUOUS;
1594 	}
1595 
1596 	/*
1597 	 * Move to ARMED.
1598 	 *
1599 	 * We increase the gencount, and setup the thread call with this expected
1600 	 * state. It means that if there was a previous generation of the timer in
1601 	 * flight that needs to be ignored, then 3 things are possible:
1602 	 *
1603 	 * - the timer fires first, filt_timerexpire() and sets the state to FIRED
1604 	 *   but we clobber it with ARMED and a new gencount. The knote will still
1605 	 *   be activated, but filt_timerprocess() which is serialized with this
1606 	 *   call will not see the FIRED bit set and will not deliver an event.
1607 	 *
1608 	 * - this code runs first, but filt_timerexpire() comes second. Because it
1609 	 *   knows an old gencount, it will debounce and not activate the knote.
1610 	 *
1611 	 * - filt_timerexpire() wasn't in flight yet, and thread_call_enter below
1612 	 *   will just cancel it properly.
1613 	 *
1614 	 * This is important as userspace expects to never be woken up for past
1615 	 * timers after filt_timertouch ran.
1616 	 */
1617 	state = os_atomic_load(&kn->kn_hook32, relaxed);
1618 	state &= ~TIMER_STATE_MASK;
1619 	state += TIMER_GEN_INC + TIMER_ARMED;
1620 	os_atomic_store(&kn->kn_hook32, state, relaxed);
1621 
1622 	thread_call_enter_delayed_with_leeway(kn->kn_thcall,
1623 	    (void *)(uintptr_t)state, deadline, leeway, timer_flags);
1624 }
1625 
1626 /*
1627  * Mark a timer as "already fired" when it is being reprogrammed
1628  *
1629  * If there is a timer in flight, this will do a best effort at canceling it,
1630  * but will not wait. If the thread call was in flight, having set the
1631  * TIMER_IMMEDIATE bit will debounce a filt_timerexpire() racing with this
1632  * cancelation.
1633  */
1634 static void
filt_timerfire_immediate(struct knote * kn)1635 filt_timerfire_immediate(struct knote *kn)
1636 {
1637 	uint32_t state;
1638 
1639 	static_assert(TIMER_IMMEDIATE == TIMER_STATE_MASK,
1640 	    "validate that this atomic or will transition to IMMEDIATE");
1641 	state = os_atomic_or_orig(&kn->kn_hook32, TIMER_IMMEDIATE, relaxed);
1642 
1643 	if ((state & TIMER_STATE_MASK) == TIMER_ARMED) {
1644 		thread_call_cancel(kn->kn_thcall);
1645 	}
1646 }
1647 
1648 /*
1649  * Allocate a thread call for the knote's lifetime, and kick off the timer.
1650  */
1651 static int
filt_timerattach(struct knote * kn,struct kevent_qos_s * kev)1652 filt_timerattach(struct knote *kn, struct kevent_qos_s *kev)
1653 {
1654 	thread_call_t callout;
1655 	struct filt_timer_params params;
1656 	int error;
1657 
1658 	if ((error = filt_timervalidate(kev, &params)) != 0) {
1659 		knote_set_error(kn, error);
1660 		return 0;
1661 	}
1662 
1663 	callout = thread_call_allocate_with_options(filt_timerexpire,
1664 	    (thread_call_param_t)kn, THREAD_CALL_PRIORITY_HIGH,
1665 	    THREAD_CALL_OPTIONS_ONCE);
1666 
1667 	if (NULL == callout) {
1668 		knote_set_error(kn, ENOMEM);
1669 		return 0;
1670 	}
1671 
1672 	filt_timer_set_params(kn, &params);
1673 	kn->kn_thcall = callout;
1674 	kn->kn_flags |= EV_CLEAR;
1675 	os_atomic_store(&kn->kn_hook32, TIMER_IDLE, relaxed);
1676 
1677 	/* NOTE_ABSOLUTE implies EV_ONESHOT */
1678 	if (kn->kn_sfflags & NOTE_ABSOLUTE) {
1679 		kn->kn_flags |= EV_ONESHOT;
1680 	}
1681 
1682 	if (filt_timer_is_ready(kn)) {
1683 		os_atomic_store(&kn->kn_hook32, TIMER_IMMEDIATE, relaxed);
1684 		return FILTER_ACTIVE;
1685 	} else {
1686 		filt_timerarm(kn);
1687 		return 0;
1688 	}
1689 }
1690 
1691 /*
1692  * Shut down the timer if it's running, and free the callout.
1693  */
1694 static void
filt_timerdetach(struct knote * kn)1695 filt_timerdetach(struct knote *kn)
1696 {
1697 	__assert_only boolean_t freed;
1698 
1699 	/*
1700 	 * Unconditionally cancel to make sure there can't be any filt_timerexpire()
1701 	 * running anymore.
1702 	 */
1703 	thread_call_cancel_wait(kn->kn_thcall);
1704 	freed = thread_call_free(kn->kn_thcall);
1705 	assert(freed);
1706 }
1707 
1708 /*
1709  * filt_timertouch - update timer knote with new user input
1710  *
1711  * Cancel and restart the timer based on new user data. When
1712  * the user picks up a knote, clear the count of how many timer
1713  * pops have gone off (in kn_data).
1714  */
1715 static int
filt_timertouch(struct knote * kn,struct kevent_qos_s * kev)1716 filt_timertouch(struct knote *kn, struct kevent_qos_s *kev)
1717 {
1718 	struct filt_timer_params params;
1719 	uint32_t changed_flags = (kn->kn_sfflags ^ kev->fflags);
1720 	int error;
1721 
1722 	if (kev->qos && (knote_get_kq(kn)->kq_state & KQ_WORKLOOP) &&
1723 	    !_pthread_priority_thread_qos(kev->qos)) {
1724 		/* validate usage of FILTER_UPDATE_REQ_QOS */
1725 		kev->flags |= EV_ERROR;
1726 		kev->data = ERANGE;
1727 		return 0;
1728 	}
1729 
1730 	if (changed_flags & NOTE_ABSOLUTE) {
1731 		kev->flags |= EV_ERROR;
1732 		kev->data = EINVAL;
1733 		return 0;
1734 	}
1735 
1736 	if ((error = filt_timervalidate(kev, &params)) != 0) {
1737 		kev->flags |= EV_ERROR;
1738 		kev->data = error;
1739 		return 0;
1740 	}
1741 
1742 	/* capture the new values used to compute deadline */
1743 	filt_timer_set_params(kn, &params);
1744 	kn->kn_sfflags = kev->fflags;
1745 
1746 	if (filt_timer_is_ready(kn)) {
1747 		filt_timerfire_immediate(kn);
1748 		return FILTER_ACTIVE | FILTER_UPDATE_REQ_QOS;
1749 	} else {
1750 		filt_timerarm(kn);
1751 		return FILTER_UPDATE_REQ_QOS;
1752 	}
1753 }
1754 
1755 /*
1756  * filt_timerprocess - query state of knote and snapshot event data
1757  *
1758  * Determine if the timer has fired in the past, snapshot the state
1759  * of the kevent for returning to user-space, and clear pending event
1760  * counters for the next time.
1761  */
1762 static int
filt_timerprocess(struct knote * kn,struct kevent_qos_s * kev)1763 filt_timerprocess(struct knote *kn, struct kevent_qos_s *kev)
1764 {
1765 	uint32_t state = os_atomic_load(&kn->kn_hook32, relaxed);
1766 
1767 	/*
1768 	 * filt_timerprocess is serialized with any filter routine except for
1769 	 * filt_timerexpire which atomically does a TIMER_ARMED -> TIMER_FIRED
1770 	 * transition, and on success, activates the knote.
1771 	 *
1772 	 * Hence, we don't need atomic modifications of the state, only to peek at
1773 	 * whether we see any of the "FIRED" state, and if we do, it is safe to
1774 	 * do simple state machine transitions.
1775 	 */
1776 	switch (state & TIMER_STATE_MASK) {
1777 	case TIMER_IDLE:
1778 	case TIMER_ARMED:
1779 		/*
1780 		 * This can happen if a touch resets a timer that had fired
1781 		 * without being processed
1782 		 */
1783 		return 0;
1784 	}
1785 
1786 	os_atomic_store(&kn->kn_hook32, state & ~TIMER_STATE_MASK, relaxed);
1787 
1788 	/*
1789 	 * Copy out the interesting kevent state,
1790 	 * but don't leak out the raw time calculations.
1791 	 *
1792 	 * TODO: potential enhancements - tell the user about:
1793 	 *      - deadline to which this timer thought it was expiring
1794 	 *      - return kn_sfflags in the fflags field so the client can know
1795 	 *        under what flags the timer fired
1796 	 */
1797 	knote_fill_kevent(kn, kev, 1);
1798 	kev->ext[0] = 0;
1799 	/* kev->ext[1] = 0;  JMM - shouldn't we hide this too? */
1800 
1801 	if (kn->kn_sdata != 0) {
1802 		/*
1803 		 * This is a 'repeating' timer, so we have to emit
1804 		 * how many intervals expired between the arm
1805 		 * and the process.
1806 		 *
1807 		 * A very strange style of interface, because
1808 		 * this could easily be done in the client...
1809 		 */
1810 
1811 		uint64_t now;
1812 
1813 		if (kn->kn_sfflags & NOTE_MACH_CONTINUOUS_TIME) {
1814 			now = mach_continuous_time();
1815 		} else {
1816 			now = mach_absolute_time();
1817 		}
1818 
1819 		uint64_t first_deadline = kn->kn_ext[0];
1820 		uint64_t interval_abs   = kn->kn_sdata;
1821 		uint64_t orig_arm_time  = first_deadline - interval_abs;
1822 
1823 		assert(now > orig_arm_time);
1824 		assert(now > first_deadline);
1825 
1826 		uint64_t elapsed = now - orig_arm_time;
1827 
1828 		uint64_t num_fired = elapsed / interval_abs;
1829 
1830 		/*
1831 		 * To reach this code, we must have seen the timer pop
1832 		 * and be in repeating mode, so therefore it must have been
1833 		 * more than 'interval' time since the attach or last
1834 		 * successful touch.
1835 		 */
1836 		assert(num_fired > 0);
1837 
1838 		/* report how many intervals have elapsed to the user */
1839 		kev->data = (int64_t)num_fired;
1840 
1841 		/* We only need to re-arm the timer if it's not about to be destroyed */
1842 		if ((kn->kn_flags & EV_ONESHOT) == 0) {
1843 			/* fire at the end of the next interval */
1844 			uint64_t new_deadline = first_deadline + num_fired * interval_abs;
1845 
1846 			assert(new_deadline > now);
1847 
1848 			kn->kn_ext[0] = new_deadline;
1849 
1850 			/*
1851 			 * This can't shortcut setting up the thread call, because
1852 			 * knote_process deactivates EV_CLEAR knotes unconditionnally.
1853 			 */
1854 			filt_timerarm(kn);
1855 		}
1856 	}
1857 
1858 	return FILTER_ACTIVE;
1859 }
1860 
1861 SECURITY_READ_ONLY_EARLY(static struct filterops) timer_filtops = {
1862 	.f_extended_codes = true,
1863 	.f_attach   = filt_timerattach,
1864 	.f_detach   = filt_timerdetach,
1865 	.f_event    = filt_bad_event,
1866 	.f_touch    = filt_timertouch,
1867 	.f_process  = filt_timerprocess,
1868 };
1869 
1870 #pragma mark user_filtops
1871 
1872 static int
filt_userattach(struct knote * kn,__unused struct kevent_qos_s * kev)1873 filt_userattach(struct knote *kn, __unused struct kevent_qos_s *kev)
1874 {
1875 	if (kn->kn_sfflags & NOTE_TRIGGER) {
1876 		kn->kn_hook32 = FILTER_ACTIVE;
1877 	} else {
1878 		kn->kn_hook32 = 0;
1879 	}
1880 	return kn->kn_hook32;
1881 }
1882 
1883 static int
filt_usertouch(struct knote * kn,struct kevent_qos_s * kev)1884 filt_usertouch(struct knote *kn, struct kevent_qos_s *kev)
1885 {
1886 	uint32_t ffctrl;
1887 	int fflags;
1888 
1889 	ffctrl = kev->fflags & NOTE_FFCTRLMASK;
1890 	fflags = kev->fflags & NOTE_FFLAGSMASK;
1891 	switch (ffctrl) {
1892 	case NOTE_FFNOP:
1893 		break;
1894 	case NOTE_FFAND:
1895 		kn->kn_sfflags &= fflags;
1896 		break;
1897 	case NOTE_FFOR:
1898 		kn->kn_sfflags |= fflags;
1899 		break;
1900 	case NOTE_FFCOPY:
1901 		kn->kn_sfflags = fflags;
1902 		break;
1903 	}
1904 	kn->kn_sdata = kev->data;
1905 
1906 	if (kev->fflags & NOTE_TRIGGER) {
1907 		kn->kn_hook32 = FILTER_ACTIVE;
1908 	}
1909 	return (int)kn->kn_hook32;
1910 }
1911 
1912 static int
filt_userprocess(struct knote * kn,struct kevent_qos_s * kev)1913 filt_userprocess(struct knote *kn, struct kevent_qos_s *kev)
1914 {
1915 	int result = (int)kn->kn_hook32;
1916 
1917 	if (result) {
1918 		/* EVFILT_USER returns the data that was passed in */
1919 		knote_fill_kevent_with_sdata(kn, kev);
1920 		kev->fflags = kn->kn_sfflags;
1921 		if (kn->kn_flags & EV_CLEAR) {
1922 			/* knote_fill_kevent cleared kn_fflags */
1923 			kn->kn_hook32 = 0;
1924 		}
1925 	}
1926 
1927 	return result;
1928 }
1929 
1930 SECURITY_READ_ONLY_EARLY(static struct filterops) user_filtops = {
1931 	.f_extended_codes = true,
1932 	.f_attach  = filt_userattach,
1933 	.f_detach  = filt_no_detach,
1934 	.f_event   = filt_bad_event,
1935 	.f_touch   = filt_usertouch,
1936 	.f_process = filt_userprocess,
1937 };
1938 
1939 #pragma mark workloop_filtops
1940 
1941 #define EPREEMPTDISABLED (-1)
1942 
1943 static inline void
filt_wllock(struct kqworkloop * kqwl)1944 filt_wllock(struct kqworkloop *kqwl)
1945 {
1946 	lck_spin_lock(&kqwl->kqwl_statelock);
1947 }
1948 
1949 static inline void
filt_wlunlock(struct kqworkloop * kqwl)1950 filt_wlunlock(struct kqworkloop *kqwl)
1951 {
1952 	lck_spin_unlock(&kqwl->kqwl_statelock);
1953 }
1954 
1955 /*
1956  * Returns true when the interlock for the turnstile is the workqueue lock
1957  *
1958  * When this is the case, all turnstiles operations are delegated
1959  * to the workqueue subsystem.
1960  *
1961  * This is required because kqueue_threadreq_bind_prepost only holds the
1962  * workqueue lock but needs to move the inheritor from the workloop turnstile
1963  * away from the creator thread, so that this now fulfilled request cannot be
1964  * picked anymore by other threads.
1965  */
1966 static inline bool
filt_wlturnstile_interlock_is_workq(struct kqworkloop * kqwl)1967 filt_wlturnstile_interlock_is_workq(struct kqworkloop *kqwl)
1968 {
1969 	return kqr_thread_requested_pending(&kqwl->kqwl_request);
1970 }
1971 
1972 static void
filt_wlupdate_inheritor(struct kqworkloop * kqwl,struct turnstile * ts,turnstile_update_flags_t flags)1973 filt_wlupdate_inheritor(struct kqworkloop *kqwl, struct turnstile *ts,
1974     turnstile_update_flags_t flags)
1975 {
1976 	turnstile_inheritor_t inheritor = TURNSTILE_INHERITOR_NULL;
1977 	workq_threadreq_t kqr = &kqwl->kqwl_request;
1978 
1979 	/*
1980 	 * binding to the workq should always happen through
1981 	 * workq_kern_threadreq_update_inheritor()
1982 	 */
1983 	assert(!filt_wlturnstile_interlock_is_workq(kqwl));
1984 
1985 	if ((inheritor = kqwl->kqwl_owner)) {
1986 		flags |= TURNSTILE_INHERITOR_THREAD;
1987 	} else if ((inheritor = kqr_thread(kqr))) {
1988 		flags |= TURNSTILE_INHERITOR_THREAD;
1989 	}
1990 
1991 	turnstile_update_inheritor(ts, inheritor, flags);
1992 }
1993 
1994 #define EVFILT_WORKLOOP_EFAULT_RETRY_COUNT 100
1995 #define FILT_WLATTACH 0
1996 #define FILT_WLTOUCH  1
1997 #define FILT_WLDROP   2
1998 
1999 __result_use_check
2000 static int
filt_wlupdate(struct kqworkloop * kqwl,struct knote * kn,struct kevent_qos_s * kev,kq_index_t qos_index,int op)2001 filt_wlupdate(struct kqworkloop *kqwl, struct knote *kn,
2002     struct kevent_qos_s *kev, kq_index_t qos_index, int op)
2003 {
2004 	user_addr_t uaddr = CAST_USER_ADDR_T(kev->ext[EV_EXTIDX_WL_ADDR]);
2005 	workq_threadreq_t kqr = &kqwl->kqwl_request;
2006 	thread_t cur_owner, new_owner, extra_thread_ref = THREAD_NULL;
2007 	kq_index_t cur_override = THREAD_QOS_UNSPECIFIED;
2008 	int efault_retry = EVFILT_WORKLOOP_EFAULT_RETRY_COUNT;
2009 	int action = KQWL_UTQ_NONE, error = 0;
2010 	bool wl_inheritor_updated = false, needs_wake = false;
2011 	uint64_t kdata = kev->ext[EV_EXTIDX_WL_VALUE];
2012 	uint64_t mask = kev->ext[EV_EXTIDX_WL_MASK];
2013 	uint64_t udata = 0;
2014 	struct turnstile *ts = TURNSTILE_NULL;
2015 
2016 	filt_wllock(kqwl);
2017 
2018 again:
2019 	new_owner = cur_owner = kqwl->kqwl_owner;
2020 
2021 	/*
2022 	 * Phase 1:
2023 	 *
2024 	 * If asked, load the uint64 value at the user provided address and compare
2025 	 * it against the passed in mask and expected value.
2026 	 *
2027 	 * If NOTE_WL_DISCOVER_OWNER is specified, translate the loaded name as
2028 	 * a thread reference.
2029 	 *
2030 	 * If NOTE_WL_END_OWNERSHIP is specified and the currently known owner is
2031 	 * the current thread, then end ownership.
2032 	 *
2033 	 * Lastly decide whether we need to perform a QoS update.
2034 	 */
2035 	if (uaddr) {
2036 		/*
2037 		 * Until <rdar://problem/24999882> exists,
2038 		 * disabling preemption copyin forces any
2039 		 * vm_fault we encounter to fail.
2040 		 */
2041 		error = copyin_atomic64(uaddr, &udata);
2042 
2043 		/*
2044 		 * If we get EFAULT, drop locks, and retry.
2045 		 * If we still get an error report it,
2046 		 * else assume the memory has been faulted
2047 		 * and attempt to copyin under lock again.
2048 		 */
2049 		switch (error) {
2050 		case 0:
2051 			break;
2052 		case EFAULT:
2053 			if (efault_retry-- > 0) {
2054 				filt_wlunlock(kqwl);
2055 				error = copyin_atomic64(uaddr, &udata);
2056 				filt_wllock(kqwl);
2057 				if (error == 0) {
2058 					goto again;
2059 				}
2060 			}
2061 			OS_FALLTHROUGH;
2062 		default:
2063 			goto out;
2064 		}
2065 
2066 		/* Update state as copied in.  */
2067 		kev->ext[EV_EXTIDX_WL_VALUE] = udata;
2068 
2069 		if ((udata & mask) != (kdata & mask)) {
2070 			error = ESTALE;
2071 		} else if (kev->fflags & NOTE_WL_DISCOVER_OWNER) {
2072 			/*
2073 			 * Decipher the owner port name, and translate accordingly.
2074 			 * The low 2 bits were borrowed for other flags, so mask them off.
2075 			 *
2076 			 * Then attempt translation to a thread reference or fail.
2077 			 */
2078 			mach_port_name_t name = (mach_port_name_t)udata & ~0x3;
2079 			if (name != MACH_PORT_NULL) {
2080 				name = ipc_entry_name_mask(name);
2081 				extra_thread_ref = port_name_to_thread(name,
2082 				    PORT_INTRANS_THREAD_IN_CURRENT_TASK);
2083 				if (extra_thread_ref == THREAD_NULL) {
2084 					error = EOWNERDEAD;
2085 					goto out;
2086 				}
2087 				new_owner = extra_thread_ref;
2088 			}
2089 		}
2090 	}
2091 
2092 	if ((kev->fflags & NOTE_WL_END_OWNERSHIP) && new_owner == current_thread()) {
2093 		new_owner = THREAD_NULL;
2094 	}
2095 
2096 	if (error == 0) {
2097 		if ((kev->fflags & NOTE_WL_THREAD_REQUEST) && (kev->flags & EV_DELETE)) {
2098 			action = KQWL_UTQ_SET_QOS_INDEX;
2099 		} else if (qos_index && kqr->tr_kq_qos_index != qos_index) {
2100 			action = KQWL_UTQ_SET_QOS_INDEX;
2101 		}
2102 
2103 		if (op == FILT_WLTOUCH) {
2104 			/*
2105 			 * Save off any additional fflags/data we just accepted
2106 			 * But only keep the last round of "update" bits we acted on which helps
2107 			 * debugging a lot.
2108 			 */
2109 			kn->kn_sfflags &= ~NOTE_WL_UPDATES_MASK;
2110 			kn->kn_sfflags |= kev->fflags;
2111 			if (kev->fflags & NOTE_WL_SYNC_WAKE) {
2112 				needs_wake = (kn->kn_thread != THREAD_NULL);
2113 			}
2114 		} else if (op == FILT_WLDROP) {
2115 			if ((kn->kn_sfflags & (NOTE_WL_SYNC_WAIT | NOTE_WL_SYNC_WAKE)) ==
2116 			    NOTE_WL_SYNC_WAIT) {
2117 				/*
2118 				 * When deleting a SYNC_WAIT knote that hasn't been woken up
2119 				 * explicitly, issue a wake up.
2120 				 */
2121 				kn->kn_sfflags |= NOTE_WL_SYNC_WAKE;
2122 				needs_wake = (kn->kn_thread != THREAD_NULL);
2123 			}
2124 		}
2125 	}
2126 
2127 	/*
2128 	 * Phase 2:
2129 	 *
2130 	 * Commit ownership and QoS changes if any, possibly wake up waiters
2131 	 */
2132 
2133 	if (cur_owner == new_owner && action == KQWL_UTQ_NONE && !needs_wake) {
2134 		goto out;
2135 	}
2136 
2137 	kqlock(kqwl);
2138 
2139 	/* If already tracked as servicer, don't track as owner */
2140 	if (new_owner == kqr_thread(kqr)) {
2141 		new_owner = THREAD_NULL;
2142 	}
2143 
2144 	if (cur_owner != new_owner) {
2145 		kqwl->kqwl_owner = new_owner;
2146 		if (new_owner == extra_thread_ref) {
2147 			/* we just transfered this ref to kqwl_owner */
2148 			extra_thread_ref = THREAD_NULL;
2149 		}
2150 		cur_override = kqworkloop_override(kqwl);
2151 
2152 		if (new_owner) {
2153 			/* override it before we drop the old */
2154 			if (cur_override != THREAD_QOS_UNSPECIFIED) {
2155 				thread_add_kevent_override(new_owner, cur_override);
2156 			}
2157 			if (kqr_thread_requested_pending(kqr)) {
2158 				if (action == KQWL_UTQ_NONE) {
2159 					action = KQWL_UTQ_REDRIVE_EVENTS;
2160 				}
2161 			}
2162 		} else if (action == KQWL_UTQ_NONE &&
2163 		    !kqr_thread_requested(kqr) &&
2164 		    kqwl->kqwl_wakeup_qos) {
2165 			action = KQWL_UTQ_REDRIVE_EVENTS;
2166 		}
2167 	}
2168 
2169 	if (action != KQWL_UTQ_NONE) {
2170 		kqworkloop_update_threads_qos(kqwl, action, qos_index);
2171 	}
2172 
2173 	ts = kqwl->kqwl_turnstile;
2174 	if (cur_owner != new_owner && ts) {
2175 		if (action == KQWL_UTQ_REDRIVE_EVENTS) {
2176 			/*
2177 			 * Note that when action is KQWL_UTQ_REDRIVE_EVENTS,
2178 			 * the code went through workq_kern_threadreq_initiate()
2179 			 * and the workqueue has set the inheritor already
2180 			 */
2181 			assert(filt_wlturnstile_interlock_is_workq(kqwl));
2182 		} else if (filt_wlturnstile_interlock_is_workq(kqwl)) {
2183 			workq_kern_threadreq_lock(kqwl->kqwl_p);
2184 			workq_kern_threadreq_update_inheritor(kqwl->kqwl_p, kqr, new_owner,
2185 			    ts, TURNSTILE_IMMEDIATE_UPDATE);
2186 			workq_kern_threadreq_unlock(kqwl->kqwl_p);
2187 			if (!filt_wlturnstile_interlock_is_workq(kqwl)) {
2188 				/*
2189 				 * If the workq is no longer the interlock, then
2190 				 * workq_kern_threadreq_update_inheritor() has finished a bind
2191 				 * and we need to fallback to the regular path.
2192 				 */
2193 				filt_wlupdate_inheritor(kqwl, ts, TURNSTILE_IMMEDIATE_UPDATE);
2194 			}
2195 			wl_inheritor_updated = true;
2196 		} else {
2197 			filt_wlupdate_inheritor(kqwl, ts, TURNSTILE_IMMEDIATE_UPDATE);
2198 			wl_inheritor_updated = true;
2199 		}
2200 
2201 		/*
2202 		 * We need a turnstile reference because we are dropping the interlock
2203 		 * and the caller has not called turnstile_prepare.
2204 		 */
2205 		if (wl_inheritor_updated) {
2206 			turnstile_reference(ts);
2207 		}
2208 	}
2209 
2210 	if (needs_wake && ts) {
2211 		waitq_wakeup64_thread(&ts->ts_waitq, knote_filt_wev64(kn),
2212 		    kn->kn_thread, THREAD_AWAKENED);
2213 		if (op == FILT_WLATTACH || op == FILT_WLTOUCH) {
2214 			disable_preemption();
2215 			error = EPREEMPTDISABLED;
2216 		}
2217 	}
2218 
2219 	kqunlock(kqwl);
2220 
2221 out:
2222 	/*
2223 	 * Phase 3:
2224 	 *
2225 	 * Unlock and cleanup various lingering references and things.
2226 	 */
2227 	filt_wlunlock(kqwl);
2228 
2229 #if CONFIG_WORKLOOP_DEBUG
2230 	KQWL_HISTORY_WRITE_ENTRY(kqwl, {
2231 		.updater = current_thread(),
2232 		.servicer = kqr_thread(kqr), /* Note: racy */
2233 		.old_owner = cur_owner,
2234 		.new_owner = new_owner,
2235 
2236 		.kev_ident  = kev->ident,
2237 		.error      = (int16_t)error,
2238 		.kev_flags  = kev->flags,
2239 		.kev_fflags = kev->fflags,
2240 
2241 		.kev_mask   = mask,
2242 		.kev_value  = kdata,
2243 		.in_value   = udata,
2244 	});
2245 #endif // CONFIG_WORKLOOP_DEBUG
2246 
2247 	if (wl_inheritor_updated) {
2248 		turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_NOT_HELD);
2249 		turnstile_deallocate_safe(ts);
2250 	}
2251 
2252 	if (cur_owner && new_owner != cur_owner) {
2253 		if (cur_override != THREAD_QOS_UNSPECIFIED) {
2254 			thread_drop_kevent_override(cur_owner);
2255 		}
2256 		thread_deallocate_safe(cur_owner);
2257 	}
2258 	if (extra_thread_ref) {
2259 		thread_deallocate_safe(extra_thread_ref);
2260 	}
2261 	return error;
2262 }
2263 
2264 /*
2265  * Remembers the last updated that came in from userspace for debugging reasons.
2266  * - fflags is mirrored from the userspace kevent
2267  * - ext[i, i != VALUE] is mirrored from the userspace kevent
2268  * - ext[VALUE] is set to what the kernel loaded atomically
2269  * - data is set to the error if any
2270  */
2271 static inline void
filt_wlremember_last_update(struct knote * kn,struct kevent_qos_s * kev,int error)2272 filt_wlremember_last_update(struct knote *kn, struct kevent_qos_s *kev,
2273     int error)
2274 {
2275 	kn->kn_fflags = kev->fflags;
2276 	kn->kn_sdata = error;
2277 	memcpy(kn->kn_ext, kev->ext, sizeof(kev->ext));
2278 }
2279 
2280 static int
filt_wlupdate_sync_ipc(struct kqworkloop * kqwl,struct knote * kn,struct kevent_qos_s * kev,int op)2281 filt_wlupdate_sync_ipc(struct kqworkloop *kqwl, struct knote *kn,
2282     struct kevent_qos_s *kev, int op)
2283 {
2284 	user_addr_t uaddr = (user_addr_t) kev->ext[EV_EXTIDX_WL_ADDR];
2285 	uint64_t kdata = kev->ext[EV_EXTIDX_WL_VALUE];
2286 	uint64_t mask  = kev->ext[EV_EXTIDX_WL_MASK];
2287 	uint64_t udata = 0;
2288 	int efault_retry = EVFILT_WORKLOOP_EFAULT_RETRY_COUNT;
2289 	int error = 0;
2290 
2291 	if (op == FILT_WLATTACH) {
2292 		(void)kqueue_alloc_turnstile(&kqwl->kqwl_kqueue);
2293 	} else if (uaddr == 0) {
2294 		return 0;
2295 	}
2296 
2297 	filt_wllock(kqwl);
2298 
2299 again:
2300 
2301 	/*
2302 	 * Do the debounce thing, the lock serializing the state is the knote lock.
2303 	 */
2304 	if (uaddr) {
2305 		/*
2306 		 * Until <rdar://problem/24999882> exists,
2307 		 * disabling preemption copyin forces any
2308 		 * vm_fault we encounter to fail.
2309 		 */
2310 		error = copyin_atomic64(uaddr, &udata);
2311 
2312 		/*
2313 		 * If we get EFAULT, drop locks, and retry.
2314 		 * If we still get an error report it,
2315 		 * else assume the memory has been faulted
2316 		 * and attempt to copyin under lock again.
2317 		 */
2318 		switch (error) {
2319 		case 0:
2320 			break;
2321 		case EFAULT:
2322 			if (efault_retry-- > 0) {
2323 				filt_wlunlock(kqwl);
2324 				error = copyin_atomic64(uaddr, &udata);
2325 				filt_wllock(kqwl);
2326 				if (error == 0) {
2327 					goto again;
2328 				}
2329 			}
2330 			OS_FALLTHROUGH;
2331 		default:
2332 			goto out;
2333 		}
2334 
2335 		kev->ext[EV_EXTIDX_WL_VALUE] = udata;
2336 		kn->kn_ext[EV_EXTIDX_WL_VALUE] = udata;
2337 
2338 		if ((udata & mask) != (kdata & mask)) {
2339 			error = ESTALE;
2340 			goto out;
2341 		}
2342 	}
2343 
2344 	if (op == FILT_WLATTACH) {
2345 		error = filt_wlattach_sync_ipc(kn);
2346 		if (error == 0) {
2347 			disable_preemption();
2348 			error = EPREEMPTDISABLED;
2349 		}
2350 	}
2351 
2352 out:
2353 	filt_wlunlock(kqwl);
2354 	return error;
2355 }
2356 
2357 static int
filt_wlattach(struct knote * kn,struct kevent_qos_s * kev)2358 filt_wlattach(struct knote *kn, struct kevent_qos_s *kev)
2359 {
2360 	struct kqueue *kq = knote_get_kq(kn);
2361 	struct kqworkloop *kqwl = (struct kqworkloop *)kq;
2362 	int error = 0, result = 0;
2363 	kq_index_t qos_index = 0;
2364 
2365 	if (__improbable((kq->kq_state & KQ_WORKLOOP) == 0)) {
2366 		error = ENOTSUP;
2367 		goto out;
2368 	}
2369 
2370 	uint32_t command = (kn->kn_sfflags & NOTE_WL_COMMANDS_MASK);
2371 	switch (command) {
2372 	case NOTE_WL_THREAD_REQUEST:
2373 		if (kn->kn_id != kqwl->kqwl_dynamicid) {
2374 			error = EINVAL;
2375 			goto out;
2376 		}
2377 		qos_index = _pthread_priority_thread_qos(kn->kn_qos);
2378 		if (qos_index == THREAD_QOS_UNSPECIFIED) {
2379 			error = ERANGE;
2380 			goto out;
2381 		}
2382 		if (kqwl->kqwl_request.tr_kq_qos_index) {
2383 			/*
2384 			 * There already is a thread request, and well, you're only allowed
2385 			 * one per workloop, so fail the attach.
2386 			 */
2387 			error = EALREADY;
2388 			goto out;
2389 		}
2390 		break;
2391 	case NOTE_WL_SYNC_WAIT:
2392 	case NOTE_WL_SYNC_WAKE:
2393 		if (kn->kn_id == kqwl->kqwl_dynamicid) {
2394 			error = EINVAL;
2395 			goto out;
2396 		}
2397 		if ((kn->kn_flags & EV_DISABLE) == 0) {
2398 			error = EINVAL;
2399 			goto out;
2400 		}
2401 		if (kn->kn_sfflags & NOTE_WL_END_OWNERSHIP) {
2402 			error = EINVAL;
2403 			goto out;
2404 		}
2405 		break;
2406 
2407 	case NOTE_WL_SYNC_IPC:
2408 		if ((kn->kn_flags & EV_DISABLE) == 0) {
2409 			error = EINVAL;
2410 			goto out;
2411 		}
2412 		if (kn->kn_sfflags & (NOTE_WL_UPDATE_QOS | NOTE_WL_DISCOVER_OWNER)) {
2413 			error = EINVAL;
2414 			goto out;
2415 		}
2416 		break;
2417 	default:
2418 		error = EINVAL;
2419 		goto out;
2420 	}
2421 
2422 	if (command == NOTE_WL_SYNC_IPC) {
2423 		error = filt_wlupdate_sync_ipc(kqwl, kn, kev, FILT_WLATTACH);
2424 	} else {
2425 		error = filt_wlupdate(kqwl, kn, kev, qos_index, FILT_WLATTACH);
2426 	}
2427 
2428 	if (error == EPREEMPTDISABLED) {
2429 		error = 0;
2430 		result = FILTER_THREADREQ_NODEFEER;
2431 	}
2432 out:
2433 	if (error) {
2434 		/* If userland wants ESTALE to be hidden, fail the attach anyway */
2435 		if (error == ESTALE && (kn->kn_sfflags & NOTE_WL_IGNORE_ESTALE)) {
2436 			error = 0;
2437 		}
2438 		knote_set_error(kn, error);
2439 		return result;
2440 	}
2441 	if (command == NOTE_WL_SYNC_WAIT) {
2442 		return kevent_register_wait_prepare(kn, kev, result);
2443 	}
2444 	/* Just attaching the thread request successfully will fire it */
2445 	if (command == NOTE_WL_THREAD_REQUEST) {
2446 		/*
2447 		 * Thread Request knotes need an explicit touch to be active again,
2448 		 * so delivering an event needs to also consume it.
2449 		 */
2450 		kn->kn_flags |= EV_CLEAR;
2451 		return result | FILTER_ACTIVE;
2452 	}
2453 	return result;
2454 }
2455 
2456 static void __dead2
filt_wlwait_continue(void * parameter,wait_result_t wr)2457 filt_wlwait_continue(void *parameter, wait_result_t wr)
2458 {
2459 	struct _kevent_register *cont_args = parameter;
2460 	struct kqworkloop *kqwl = cont_args->kqwl;
2461 
2462 	kqlock(kqwl);
2463 	if (filt_wlturnstile_interlock_is_workq(kqwl)) {
2464 		workq_kern_threadreq_lock(kqwl->kqwl_p);
2465 		turnstile_complete((uintptr_t)kqwl, &kqwl->kqwl_turnstile, NULL, TURNSTILE_WORKLOOPS);
2466 		workq_kern_threadreq_unlock(kqwl->kqwl_p);
2467 	} else {
2468 		turnstile_complete((uintptr_t)kqwl, &kqwl->kqwl_turnstile, NULL, TURNSTILE_WORKLOOPS);
2469 	}
2470 	kqunlock(kqwl);
2471 
2472 	turnstile_cleanup();
2473 
2474 	if (wr == THREAD_INTERRUPTED) {
2475 		cont_args->kev.flags |= EV_ERROR;
2476 		cont_args->kev.data = EINTR;
2477 	} else if (wr != THREAD_AWAKENED) {
2478 		panic("Unexpected wait result: %d", wr);
2479 	}
2480 
2481 	kevent_register_wait_return(cont_args);
2482 }
2483 
2484 /*
2485  * Called with the workloop mutex held, most of the time never returns as it
2486  * calls filt_wlwait_continue through a continuation.
2487  */
2488 static void __dead2
filt_wlpost_register_wait(struct uthread * uth,struct knote * kn,struct _kevent_register * cont_args)2489 filt_wlpost_register_wait(struct uthread *uth, struct knote *kn,
2490     struct _kevent_register *cont_args)
2491 {
2492 	struct kqworkloop *kqwl = cont_args->kqwl;
2493 	workq_threadreq_t kqr = &kqwl->kqwl_request;
2494 	struct turnstile *ts;
2495 	bool workq_locked = false;
2496 
2497 	kqlock_held(kqwl);
2498 
2499 	if (filt_wlturnstile_interlock_is_workq(kqwl)) {
2500 		workq_kern_threadreq_lock(kqwl->kqwl_p);
2501 		workq_locked = true;
2502 	}
2503 
2504 	ts = turnstile_prepare((uintptr_t)kqwl, &kqwl->kqwl_turnstile,
2505 	    TURNSTILE_NULL, TURNSTILE_WORKLOOPS);
2506 
2507 	if (workq_locked) {
2508 		workq_kern_threadreq_update_inheritor(kqwl->kqwl_p,
2509 		    &kqwl->kqwl_request, kqwl->kqwl_owner, ts,
2510 		    TURNSTILE_DELAYED_UPDATE);
2511 		if (!filt_wlturnstile_interlock_is_workq(kqwl)) {
2512 			/*
2513 			 * if the interlock is no longer the workqueue lock,
2514 			 * then we don't need to hold it anymore.
2515 			 */
2516 			workq_kern_threadreq_unlock(kqwl->kqwl_p);
2517 			workq_locked = false;
2518 		}
2519 	}
2520 	if (!workq_locked) {
2521 		/*
2522 		 * If the interlock is the workloop's, then it's our responsibility to
2523 		 * call update_inheritor, so just do it.
2524 		 */
2525 		filt_wlupdate_inheritor(kqwl, ts, TURNSTILE_DELAYED_UPDATE);
2526 	}
2527 
2528 	thread_set_pending_block_hint(get_machthread(uth), kThreadWaitWorkloopSyncWait);
2529 	waitq_assert_wait64(&ts->ts_waitq, knote_filt_wev64(kn),
2530 	    THREAD_ABORTSAFE, TIMEOUT_WAIT_FOREVER);
2531 
2532 	if (workq_locked) {
2533 		workq_kern_threadreq_unlock(kqwl->kqwl_p);
2534 	}
2535 
2536 	thread_t thread = kqwl->kqwl_owner ?: kqr_thread(kqr);
2537 	if (thread) {
2538 		thread_reference(thread);
2539 	}
2540 
2541 	kevent_register_wait_block(ts, thread, filt_wlwait_continue, cont_args);
2542 }
2543 
2544 /* called in stackshot context to report the thread responsible for blocking this thread */
2545 void
kdp_workloop_sync_wait_find_owner(__assert_only thread_t thread,event64_t event,thread_waitinfo_t * waitinfo)2546 kdp_workloop_sync_wait_find_owner(__assert_only thread_t thread,
2547     event64_t event, thread_waitinfo_t *waitinfo)
2548 {
2549 	struct knote *kn = (struct knote *)event;
2550 
2551 	zone_require(knote_zone, kn);
2552 
2553 	assert(kn->kn_thread == thread);
2554 
2555 	struct kqueue *kq = knote_get_kq(kn);
2556 
2557 	zone_require(kqworkloop_zone, kq);
2558 	assert(kq->kq_state & KQ_WORKLOOP);
2559 
2560 	struct kqworkloop *kqwl = (struct kqworkloop *)kq;
2561 	workq_threadreq_t kqr = &kqwl->kqwl_request;
2562 
2563 	thread_t kqwl_owner = kqwl->kqwl_owner;
2564 
2565 	if (kqwl_owner != THREAD_NULL) {
2566 		thread_require(kqwl_owner);
2567 		waitinfo->owner = thread_tid(kqwl->kqwl_owner);
2568 	} else if ((kqr->tr_state >= WORKQ_TR_STATE_BINDING) && (kqr->tr_thread != NULL)) {
2569 		thread_require(kqr->tr_thread);
2570 		waitinfo->owner = thread_tid(kqr->tr_thread);
2571 	} else if (kqr_thread_requested_pending(kqr)) { /* > idle, < bound */
2572 		waitinfo->owner = STACKSHOT_WAITOWNER_THREQUESTED;
2573 	} else {
2574 		waitinfo->owner = 0;
2575 	}
2576 
2577 	waitinfo->context = kqwl->kqwl_dynamicid;
2578 }
2579 
2580 static void
filt_wldetach(struct knote * kn)2581 filt_wldetach(struct knote *kn)
2582 {
2583 	if (kn->kn_sfflags & NOTE_WL_SYNC_IPC) {
2584 		filt_wldetach_sync_ipc(kn);
2585 	} else if (kn->kn_thread) {
2586 		kevent_register_wait_cleanup(kn);
2587 	}
2588 }
2589 
2590 static int
filt_wlvalidate_kev_flags(struct knote * kn,struct kevent_qos_s * kev,thread_qos_t * qos_index)2591 filt_wlvalidate_kev_flags(struct knote *kn, struct kevent_qos_s *kev,
2592     thread_qos_t *qos_index)
2593 {
2594 	uint32_t new_commands = kev->fflags & NOTE_WL_COMMANDS_MASK;
2595 	uint32_t sav_commands = kn->kn_sfflags & NOTE_WL_COMMANDS_MASK;
2596 
2597 	if ((kev->fflags & NOTE_WL_DISCOVER_OWNER) && (kev->flags & EV_DELETE)) {
2598 		return EINVAL;
2599 	}
2600 	if (kev->fflags & NOTE_WL_UPDATE_QOS) {
2601 		if (kev->flags & EV_DELETE) {
2602 			return EINVAL;
2603 		}
2604 		if (sav_commands != NOTE_WL_THREAD_REQUEST) {
2605 			return EINVAL;
2606 		}
2607 		if (!(*qos_index = _pthread_priority_thread_qos(kev->qos))) {
2608 			return ERANGE;
2609 		}
2610 	}
2611 
2612 	switch (new_commands) {
2613 	case NOTE_WL_THREAD_REQUEST:
2614 		/* thread requests can only update themselves */
2615 		if (sav_commands != NOTE_WL_THREAD_REQUEST) {
2616 			return EINVAL;
2617 		}
2618 		break;
2619 
2620 	case NOTE_WL_SYNC_WAIT:
2621 		if (kev->fflags & NOTE_WL_END_OWNERSHIP) {
2622 			return EINVAL;
2623 		}
2624 		goto sync_checks;
2625 
2626 	case NOTE_WL_SYNC_WAKE:
2627 sync_checks:
2628 		if (!(sav_commands & (NOTE_WL_SYNC_WAIT | NOTE_WL_SYNC_WAKE))) {
2629 			return EINVAL;
2630 		}
2631 		if ((kev->flags & (EV_ENABLE | EV_DELETE)) == EV_ENABLE) {
2632 			return EINVAL;
2633 		}
2634 		break;
2635 
2636 	case NOTE_WL_SYNC_IPC:
2637 		if (sav_commands != NOTE_WL_SYNC_IPC) {
2638 			return EINVAL;
2639 		}
2640 		if ((kev->flags & (EV_ENABLE | EV_DELETE)) == EV_ENABLE) {
2641 			return EINVAL;
2642 		}
2643 		break;
2644 
2645 	default:
2646 		return EINVAL;
2647 	}
2648 	return 0;
2649 }
2650 
2651 static int
filt_wltouch(struct knote * kn,struct kevent_qos_s * kev)2652 filt_wltouch(struct knote *kn, struct kevent_qos_s *kev)
2653 {
2654 	struct kqworkloop *kqwl = (struct kqworkloop *)knote_get_kq(kn);
2655 	thread_qos_t qos_index = THREAD_QOS_UNSPECIFIED;
2656 	int result = 0;
2657 
2658 	int error = filt_wlvalidate_kev_flags(kn, kev, &qos_index);
2659 	if (error) {
2660 		goto out;
2661 	}
2662 
2663 	uint32_t command = kev->fflags & NOTE_WL_COMMANDS_MASK;
2664 	if (command == NOTE_WL_SYNC_IPC) {
2665 		error = filt_wlupdate_sync_ipc(kqwl, kn, kev, FILT_WLTOUCH);
2666 	} else {
2667 		error = filt_wlupdate(kqwl, kn, kev, qos_index, FILT_WLTOUCH);
2668 		filt_wlremember_last_update(kn, kev, error);
2669 	}
2670 	if (error == EPREEMPTDISABLED) {
2671 		error = 0;
2672 		result = FILTER_THREADREQ_NODEFEER;
2673 	}
2674 
2675 out:
2676 	if (error) {
2677 		if (error == ESTALE && (kev->fflags & NOTE_WL_IGNORE_ESTALE)) {
2678 			/* If userland wants ESTALE to be hidden, do not activate */
2679 			return result;
2680 		}
2681 		kev->flags |= EV_ERROR;
2682 		kev->data = error;
2683 		return result;
2684 	}
2685 	if (command == NOTE_WL_SYNC_WAIT && !(kn->kn_sfflags & NOTE_WL_SYNC_WAKE)) {
2686 		return kevent_register_wait_prepare(kn, kev, result);
2687 	}
2688 	/* Just touching the thread request successfully will fire it */
2689 	if (command == NOTE_WL_THREAD_REQUEST) {
2690 		if (kev->fflags & NOTE_WL_UPDATE_QOS) {
2691 			result |= FILTER_UPDATE_REQ_QOS;
2692 		}
2693 		result |= FILTER_ACTIVE;
2694 	}
2695 	return result;
2696 }
2697 
2698 static bool
filt_wlallow_drop(struct knote * kn,struct kevent_qos_s * kev)2699 filt_wlallow_drop(struct knote *kn, struct kevent_qos_s *kev)
2700 {
2701 	struct kqworkloop *kqwl = (struct kqworkloop *)knote_get_kq(kn);
2702 
2703 	int error = filt_wlvalidate_kev_flags(kn, kev, NULL);
2704 	if (error) {
2705 		goto out;
2706 	}
2707 
2708 	uint32_t command = (kev->fflags & NOTE_WL_COMMANDS_MASK);
2709 	if (command == NOTE_WL_SYNC_IPC) {
2710 		error = filt_wlupdate_sync_ipc(kqwl, kn, kev, FILT_WLDROP);
2711 	} else {
2712 		error = filt_wlupdate(kqwl, kn, kev, 0, FILT_WLDROP);
2713 		filt_wlremember_last_update(kn, kev, error);
2714 	}
2715 	assert(error != EPREEMPTDISABLED);
2716 
2717 out:
2718 	if (error) {
2719 		if (error == ESTALE && (kev->fflags & NOTE_WL_IGNORE_ESTALE)) {
2720 			return false;
2721 		}
2722 		kev->flags |= EV_ERROR;
2723 		kev->data = error;
2724 		return false;
2725 	}
2726 	return true;
2727 }
2728 
2729 static int
filt_wlprocess(struct knote * kn,struct kevent_qos_s * kev)2730 filt_wlprocess(struct knote *kn, struct kevent_qos_s *kev)
2731 {
2732 	struct kqworkloop *kqwl = (struct kqworkloop *)knote_get_kq(kn);
2733 	int rc = 0;
2734 
2735 	assert(kn->kn_sfflags & NOTE_WL_THREAD_REQUEST);
2736 
2737 	kqlock(kqwl);
2738 
2739 	if (kqwl->kqwl_owner) {
2740 		/*
2741 		 * <rdar://problem/33584321> userspace sometimes due to events being
2742 		 * delivered but not triggering a drain session can cause a process
2743 		 * of the thread request knote.
2744 		 *
2745 		 * When that happens, the automatic deactivation due to process
2746 		 * would swallow the event, so we have to activate the knote again.
2747 		 */
2748 		knote_activate(kqwl, kn, FILTER_ACTIVE);
2749 	} else {
2750 #if DEBUG || DEVELOPMENT
2751 		if (kevent_debug_flags & KEVENT_PANIC_ON_NON_ENQUEUED_PROCESS) {
2752 			/*
2753 			 * see src/queue_internal.h in libdispatch
2754 			 */
2755 #define DISPATCH_QUEUE_ENQUEUED 0x1ull
2756 			user_addr_t addr = CAST_USER_ADDR_T(kn->kn_ext[EV_EXTIDX_WL_ADDR]);
2757 			task_t t = current_task();
2758 			uint64_t val;
2759 			if (addr && task_is_active(t) && !task_is_halting(t) &&
2760 			    copyin_atomic64(addr, &val) == 0 &&
2761 			    val && (val & DISPATCH_QUEUE_ENQUEUED) == 0 &&
2762 			    (val >> 48) != 0xdead && (val >> 48) != 0 && (val >> 48) != 0xffff) {
2763 				panic("kevent: workloop %#016llx is not enqueued "
2764 				    "(kn:%p dq_state:%#016llx kev.dq_state:%#016llx)",
2765 				    kn->kn_udata, kn, val, kn->kn_ext[EV_EXTIDX_WL_VALUE]);
2766 			}
2767 		}
2768 #endif
2769 		knote_fill_kevent(kn, kev, 0);
2770 		kev->fflags = kn->kn_sfflags;
2771 		rc |= FILTER_ACTIVE;
2772 	}
2773 
2774 	kqunlock(kqwl);
2775 
2776 	if (rc & FILTER_ACTIVE) {
2777 		workq_thread_set_max_qos(kqwl->kqwl_p, &kqwl->kqwl_request);
2778 	}
2779 	return rc;
2780 }
2781 
2782 SECURITY_READ_ONLY_EARLY(static struct filterops) workloop_filtops = {
2783 	.f_extended_codes = true,
2784 	.f_attach  = filt_wlattach,
2785 	.f_detach  = filt_wldetach,
2786 	.f_event   = filt_bad_event,
2787 	.f_touch   = filt_wltouch,
2788 	.f_process = filt_wlprocess,
2789 	.f_allow_drop = filt_wlallow_drop,
2790 	.f_post_register_wait = filt_wlpost_register_wait,
2791 };
2792 
2793 #pragma mark - kqueues allocation and deallocation
2794 
2795 OS_NOINLINE
2796 static void
2797 kqworkloop_dealloc(struct kqworkloop *, bool hash_remove);
2798 
2799 static inline bool
kqworkloop_try_retain(struct kqworkloop * kqwl)2800 kqworkloop_try_retain(struct kqworkloop *kqwl)
2801 {
2802 	return os_ref_retain_try_raw(&kqwl->kqwl_retains, NULL);
2803 }
2804 
2805 static inline void
kqworkloop_retain(struct kqworkloop * kqwl)2806 kqworkloop_retain(struct kqworkloop *kqwl)
2807 {
2808 	return os_ref_retain_raw(&kqwl->kqwl_retains, NULL);
2809 }
2810 
2811 OS_ALWAYS_INLINE
2812 static inline void
kqueue_retain(kqueue_t kqu)2813 kqueue_retain(kqueue_t kqu)
2814 {
2815 	if (kqu.kq->kq_state & KQ_DYNAMIC) {
2816 		kqworkloop_retain(kqu.kqwl);
2817 	}
2818 }
2819 
2820 OS_ALWAYS_INLINE
2821 static inline void
kqworkloop_release_live(struct kqworkloop * kqwl)2822 kqworkloop_release_live(struct kqworkloop *kqwl)
2823 {
2824 	os_ref_release_live_raw(&kqwl->kqwl_retains, NULL);
2825 }
2826 
2827 OS_ALWAYS_INLINE
2828 static inline void
kqueue_release_live(kqueue_t kqu)2829 kqueue_release_live(kqueue_t kqu)
2830 {
2831 	if (kqu.kq->kq_state & KQ_DYNAMIC) {
2832 		kqworkloop_release_live(kqu.kqwl);
2833 	}
2834 }
2835 
2836 OS_ALWAYS_INLINE
2837 static inline void
kqworkloop_release(struct kqworkloop * kqwl)2838 kqworkloop_release(struct kqworkloop *kqwl)
2839 {
2840 	if (os_ref_release_raw(&kqwl->kqwl_retains, NULL) == 0) {
2841 		kqworkloop_dealloc(kqwl, true);
2842 	}
2843 }
2844 
2845 OS_ALWAYS_INLINE
2846 static inline void
kqueue_release(kqueue_t kqu)2847 kqueue_release(kqueue_t kqu)
2848 {
2849 	if (kqu.kq->kq_state & KQ_DYNAMIC) {
2850 		kqworkloop_release(kqu.kqwl);
2851 	}
2852 }
2853 
2854 /*!
2855  * @function kqueue_destroy
2856  *
2857  * @brief
2858  * Common part to all kqueue dealloc functions.
2859  */
2860 OS_NOINLINE
2861 static void
kqueue_destroy(kqueue_t kqu,zone_t zone)2862 kqueue_destroy(kqueue_t kqu, zone_t zone)
2863 {
2864 	lck_spin_destroy(&kqu.kq->kq_lock, &kq_lck_grp);
2865 
2866 	zfree(zone, kqu.kq);
2867 }
2868 
2869 /*!
2870  * @function kqueue_init
2871  *
2872  * @brief
2873  * Common part to all kqueue alloc functions.
2874  */
2875 static kqueue_t
kqueue_init(kqueue_t kqu)2876 kqueue_init(kqueue_t kqu)
2877 {
2878 	lck_spin_init(&kqu.kq->kq_lock, &kq_lck_grp, LCK_ATTR_NULL);
2879 	return kqu;
2880 }
2881 
2882 #pragma mark kqfile allocation and deallocation
2883 
2884 /*!
2885  * @function kqueue_dealloc
2886  *
2887  * @brief
2888  * Detach all knotes from a kqfile and free it.
2889  *
2890  * @discussion
2891  * We walk each list looking for knotes referencing this
2892  * this kqueue.  If we find one, we try to drop it.  But
2893  * if we fail to get a drop reference, that will wait
2894  * until it is dropped.  So, we can just restart again
2895  * safe in the assumption that the list will eventually
2896  * not contain any more references to this kqueue (either
2897  * we dropped them all, or someone else did).
2898  *
2899  * Assumes no new events are being added to the kqueue.
2900  * Nothing locked on entry or exit.
2901  */
2902 void
kqueue_dealloc(struct kqueue * kq)2903 kqueue_dealloc(struct kqueue *kq)
2904 {
2905 	KNOTE_LOCK_CTX(knlc);
2906 	struct proc *p = kq->kq_p;
2907 	struct filedesc *fdp = &p->p_fd;
2908 	struct knote *kn;
2909 
2910 	assert(kq && (kq->kq_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0);
2911 
2912 	proc_fdlock(p);
2913 	for (int i = 0; i < fdp->fd_knlistsize; i++) {
2914 		kn = SLIST_FIRST(&fdp->fd_knlist[i]);
2915 		while (kn != NULL) {
2916 			if (kq == knote_get_kq(kn)) {
2917 				kqlock(kq);
2918 				proc_fdunlock(p);
2919 				if (knote_lock(kq, kn, &knlc, KNOTE_KQ_LOCK_ON_SUCCESS)) {
2920 					knote_drop(kq, kn, &knlc);
2921 				}
2922 				proc_fdlock(p);
2923 				/* start over at beginning of list */
2924 				kn = SLIST_FIRST(&fdp->fd_knlist[i]);
2925 				continue;
2926 			}
2927 			kn = SLIST_NEXT(kn, kn_link);
2928 		}
2929 	}
2930 
2931 	knhash_lock(fdp);
2932 	proc_fdunlock(p);
2933 
2934 	if (fdp->fd_knhashmask != 0) {
2935 		for (int i = 0; i < (int)fdp->fd_knhashmask + 1; i++) {
2936 			kn = SLIST_FIRST(&fdp->fd_knhash[i]);
2937 			while (kn != NULL) {
2938 				if (kq == knote_get_kq(kn)) {
2939 					kqlock(kq);
2940 					knhash_unlock(fdp);
2941 					if (knote_lock(kq, kn, &knlc, KNOTE_KQ_LOCK_ON_SUCCESS)) {
2942 						knote_drop(kq, kn, &knlc);
2943 					}
2944 					knhash_lock(fdp);
2945 					/* start over at beginning of list */
2946 					kn = SLIST_FIRST(&fdp->fd_knhash[i]);
2947 					continue;
2948 				}
2949 				kn = SLIST_NEXT(kn, kn_link);
2950 			}
2951 		}
2952 	}
2953 	knhash_unlock(fdp);
2954 
2955 	kqueue_destroy(kq, kqfile_zone);
2956 }
2957 
2958 /*!
2959  * @function kqueue_alloc
2960  *
2961  * @brief
2962  * Allocate a kqfile.
2963  */
2964 struct kqueue *
kqueue_alloc(struct proc * p)2965 kqueue_alloc(struct proc *p)
2966 {
2967 	struct kqfile *kqf;
2968 
2969 	/*
2970 	 * kqfiles are created with kqueue() so we need to wait for
2971 	 * the first kevent syscall to know which bit among
2972 	 * KQ_KEV_{32,64,QOS} will be set in kqf_state
2973 	 */
2974 	kqf = zalloc_flags(kqfile_zone, Z_WAITOK | Z_ZERO);
2975 	kqf->kqf_p = p;
2976 	TAILQ_INIT_AFTER_BZERO(&kqf->kqf_queue);
2977 	TAILQ_INIT_AFTER_BZERO(&kqf->kqf_suppressed);
2978 
2979 	return kqueue_init(kqf).kq;
2980 }
2981 
2982 /*!
2983  * @function kqueue_internal
2984  *
2985  * @brief
2986  * Core implementation for kqueue and guarded_kqueue_np()
2987  */
2988 int
kqueue_internal(struct proc * p,fp_initfn_t fp_init,void * initarg,int32_t * retval)2989 kqueue_internal(struct proc *p, fp_initfn_t fp_init, void *initarg, int32_t *retval)
2990 {
2991 	struct kqueue *kq;
2992 	struct fileproc *fp;
2993 	int fd, error;
2994 
2995 	error = falloc_withinit(p, &fp, &fd, vfs_context_current(),
2996 	    fp_init, initarg);
2997 	if (error) {
2998 		return error;
2999 	}
3000 
3001 	kq = kqueue_alloc(p);
3002 	if (kq == NULL) {
3003 		fp_free(p, fd, fp);
3004 		return ENOMEM;
3005 	}
3006 
3007 	fp->fp_flags |= FP_CLOEXEC | FP_CLOFORK;
3008 	fp->f_flag = FREAD | FWRITE;
3009 	fp->f_ops = &kqueueops;
3010 	fp_set_data(fp, kq);
3011 	fp->f_lflags |= FG_CONFINED;
3012 
3013 	proc_fdlock(p);
3014 	procfdtbl_releasefd(p, fd, NULL);
3015 	fp_drop(p, fd, fp, 1);
3016 	proc_fdunlock(p);
3017 
3018 	*retval = fd;
3019 	return error;
3020 }
3021 
3022 /*!
3023  * @function kqueue
3024  *
3025  * @brief
3026  * The kqueue syscall.
3027  */
3028 int
kqueue(struct proc * p,__unused struct kqueue_args * uap,int32_t * retval)3029 kqueue(struct proc *p, __unused struct kqueue_args *uap, int32_t *retval)
3030 {
3031 	return kqueue_internal(p, NULL, NULL, retval);
3032 }
3033 
3034 #pragma mark kqworkq allocation and deallocation
3035 
3036 /*!
3037  * @function kqworkq_dealloc
3038  *
3039  * @brief
3040  * Deallocates a workqueue kqueue.
3041  *
3042  * @discussion
3043  * This only happens at process death, or for races with concurrent
3044  * kevent_get_kqwq calls, hence we don't have to care about knotes referencing
3045  * this kqueue, either there are none, or someone else took care of them.
3046  */
3047 void
kqworkq_dealloc(struct kqworkq * kqwq)3048 kqworkq_dealloc(struct kqworkq *kqwq)
3049 {
3050 	kqueue_destroy(kqwq, kqworkq_zone);
3051 }
3052 
3053 /*!
3054  * @function kqworkq_alloc
3055  *
3056  * @brief
3057  * Allocates a workqueue kqueue.
3058  *
3059  * @discussion
3060  * This is the slow path of kevent_get_kqwq.
3061  * This takes care of making sure procs have a single workq kqueue.
3062  */
3063 OS_NOINLINE
3064 static struct kqworkq *
kqworkq_alloc(struct proc * p,unsigned int flags)3065 kqworkq_alloc(struct proc *p, unsigned int flags)
3066 {
3067 	struct kqworkq *kqwq, *tmp;
3068 
3069 	kqwq = zalloc_flags(kqworkq_zone, Z_WAITOK | Z_ZERO);
3070 
3071 	assert((flags & KEVENT_FLAG_LEGACY32) == 0);
3072 	if (flags & KEVENT_FLAG_LEGACY64) {
3073 		kqwq->kqwq_state = KQ_WORKQ | KQ_KEV64;
3074 	} else {
3075 		kqwq->kqwq_state = KQ_WORKQ | KQ_KEV_QOS;
3076 	}
3077 	kqwq->kqwq_p = p;
3078 
3079 	for (int i = 0; i < KQWQ_NBUCKETS; i++) {
3080 		TAILQ_INIT_AFTER_BZERO(&kqwq->kqwq_queue[i]);
3081 		TAILQ_INIT_AFTER_BZERO(&kqwq->kqwq_suppressed[i]);
3082 	}
3083 	for (int i = 0; i < KQWQ_NBUCKETS; i++) {
3084 		/*
3085 		 * Because of how the bucketized system works, we mix overcommit
3086 		 * sources with not overcommit: each time we move a knote from
3087 		 * one bucket to the next due to overrides, we'd had to track
3088 		 * overcommitness, and it's really not worth it in the workloop
3089 		 * enabled world that track this faithfully.
3090 		 *
3091 		 * Incidentally, this behaves like the original manager-based
3092 		 * kqwq where event delivery always happened (hence is
3093 		 * "overcommit")
3094 		 */
3095 		kqwq->kqwq_request[i].tr_state = WORKQ_TR_STATE_IDLE;
3096 		kqwq->kqwq_request[i].tr_flags = WORKQ_TR_FLAG_KEVENT;
3097 		if (i != KQWQ_QOS_MANAGER) {
3098 			kqwq->kqwq_request[i].tr_flags |= WORKQ_TR_FLAG_OVERCOMMIT;
3099 		}
3100 		kqwq->kqwq_request[i].tr_kq_qos_index = (kq_index_t)i + 1;
3101 	}
3102 
3103 	kqueue_init(kqwq);
3104 
3105 	if (!os_atomic_cmpxchgv(&p->p_fd.fd_wqkqueue, NULL, kqwq, &tmp, release)) {
3106 		kqworkq_dealloc(kqwq);
3107 		return tmp;
3108 	}
3109 
3110 	return kqwq;
3111 }
3112 
3113 #pragma mark kqworkloop allocation and deallocation
3114 
3115 #define KQ_HASH(val, mask)  (((val) ^ (val >> 8)) & (mask))
3116 #define CONFIG_KQ_HASHSIZE  CONFIG_KN_HASHSIZE
3117 
3118 OS_ALWAYS_INLINE
3119 static inline void
kqhash_lock(struct filedesc * fdp)3120 kqhash_lock(struct filedesc *fdp)
3121 {
3122 	lck_mtx_lock_spin_always(&fdp->fd_kqhashlock);
3123 }
3124 
3125 OS_ALWAYS_INLINE
3126 static inline void
kqhash_unlock(struct filedesc * fdp)3127 kqhash_unlock(struct filedesc *fdp)
3128 {
3129 	lck_mtx_unlock(&fdp->fd_kqhashlock);
3130 }
3131 
3132 OS_ALWAYS_INLINE
3133 static inline void
kqworkloop_hash_insert_locked(struct filedesc * fdp,kqueue_id_t id,struct kqworkloop * kqwl)3134 kqworkloop_hash_insert_locked(struct filedesc *fdp, kqueue_id_t id,
3135     struct kqworkloop *kqwl)
3136 {
3137 	struct kqwllist *list = &fdp->fd_kqhash[KQ_HASH(id, fdp->fd_kqhashmask)];
3138 	LIST_INSERT_HEAD(list, kqwl, kqwl_hashlink);
3139 }
3140 
3141 OS_ALWAYS_INLINE
3142 static inline struct kqworkloop *
kqworkloop_hash_lookup_locked(struct filedesc * fdp,kqueue_id_t id)3143 kqworkloop_hash_lookup_locked(struct filedesc *fdp, kqueue_id_t id)
3144 {
3145 	struct kqwllist *list = &fdp->fd_kqhash[KQ_HASH(id, fdp->fd_kqhashmask)];
3146 	struct kqworkloop *kqwl;
3147 
3148 	LIST_FOREACH(kqwl, list, kqwl_hashlink) {
3149 		if (kqwl->kqwl_dynamicid == id) {
3150 			return kqwl;
3151 		}
3152 	}
3153 	return NULL;
3154 }
3155 
3156 static struct kqworkloop *
kqworkloop_hash_lookup_and_retain(struct filedesc * fdp,kqueue_id_t kq_id)3157 kqworkloop_hash_lookup_and_retain(struct filedesc *fdp, kqueue_id_t kq_id)
3158 {
3159 	struct kqworkloop *kqwl = NULL;
3160 
3161 	kqhash_lock(fdp);
3162 	if (__probable(fdp->fd_kqhash)) {
3163 		kqwl = kqworkloop_hash_lookup_locked(fdp, kq_id);
3164 		if (kqwl && !kqworkloop_try_retain(kqwl)) {
3165 			kqwl = NULL;
3166 		}
3167 	}
3168 	kqhash_unlock(fdp);
3169 	return kqwl;
3170 }
3171 
3172 OS_NOINLINE
3173 static void
kqworkloop_hash_init(struct filedesc * fdp)3174 kqworkloop_hash_init(struct filedesc *fdp)
3175 {
3176 	struct kqwllist *alloc_hash;
3177 	u_long alloc_mask;
3178 
3179 	kqhash_unlock(fdp);
3180 	alloc_hash = hashinit(CONFIG_KQ_HASHSIZE, M_KQUEUE, &alloc_mask);
3181 	kqhash_lock(fdp);
3182 
3183 	/* See if we won the race */
3184 	if (__probable(fdp->fd_kqhashmask == 0)) {
3185 		fdp->fd_kqhash = alloc_hash;
3186 		fdp->fd_kqhashmask = alloc_mask;
3187 	} else {
3188 		kqhash_unlock(fdp);
3189 		hashdestroy(alloc_hash, M_KQUEUE, alloc_mask);
3190 		kqhash_lock(fdp);
3191 	}
3192 }
3193 
3194 /*
3195  * kqueue iotier override is only supported for kqueue that has
3196  * only one port as a mach port source. Updating the iotier
3197  * override on the mach port source will update the override
3198  * on kqueue as well. Since kqueue with iotier override will
3199  * only have one port attached, there is no logic for saturation
3200  * like qos override, the iotier override of mach port source
3201  * would be reflected in kevent iotier override.
3202  */
3203 void
kqueue_set_iotier_override(kqueue_t kqu,uint8_t iotier_override)3204 kqueue_set_iotier_override(kqueue_t kqu, uint8_t iotier_override)
3205 {
3206 	if (!(kqu.kq->kq_state & KQ_WORKLOOP)) {
3207 		return;
3208 	}
3209 
3210 	struct kqworkloop *kqwl = kqu.kqwl;
3211 	os_atomic_store(&kqwl->kqwl_iotier_override, iotier_override, relaxed);
3212 }
3213 
3214 uint8_t
kqueue_get_iotier_override(kqueue_t kqu)3215 kqueue_get_iotier_override(kqueue_t kqu)
3216 {
3217 	if (!(kqu.kq->kq_state & KQ_WORKLOOP)) {
3218 		return THROTTLE_LEVEL_END;
3219 	}
3220 
3221 	struct kqworkloop *kqwl = kqu.kqwl;
3222 	return os_atomic_load(&kqwl->kqwl_iotier_override, relaxed);
3223 }
3224 
3225 #if CONFIG_PREADOPT_TG
3226 /*
3227  * This function is called with a borrowed reference on the thread group without
3228  * kq lock held with the mqueue lock held. It may or may not have the knote lock
3229  * (called from both fevent as well as fattach/ftouch). Upon success, an
3230  * additional reference on the TG is taken
3231  */
3232 void
kqueue_set_preadopted_thread_group(kqueue_t kqu,struct thread_group * tg,thread_qos_t qos)3233 kqueue_set_preadopted_thread_group(kqueue_t kqu, struct thread_group *tg, thread_qos_t qos)
3234 {
3235 	if (!(kqu.kq->kq_state & KQ_WORKLOOP)) {
3236 		KDBG_RELEASE(MACHDBG_CODE(DBG_MACH_THREAD_GROUP, MACH_THREAD_GROUP_PREADOPT_NA),
3237 		    (uintptr_t)thread_tid(current_thread()), 0, 0, 0);
3238 		return;
3239 	}
3240 
3241 	struct kqworkloop *kqwl = kqu.kqwl;
3242 
3243 	assert(qos < THREAD_QOS_LAST);
3244 
3245 	thread_group_retain(tg);
3246 
3247 	thread_group_qos_t old_tg; thread_group_qos_t new_tg;
3248 	int ret = os_atomic_rmw_loop(&kqwl->kqwl_preadopt_tg, old_tg, new_tg, relaxed, {
3249 		if (!KQWL_CAN_ADOPT_PREADOPT_TG(old_tg)) {
3250 		        os_atomic_rmw_loop_give_up(break);
3251 		}
3252 
3253 		if (old_tg != KQWL_PREADOPTED_TG_NULL) {
3254 		        /*
3255 		         * Note that old_tg could be a NULL TG pointer but with a QoS
3256 		         * set. See also workq_thread_reset_pri.
3257 		         *
3258 		         * Compare the QoS of existing preadopted tg with new one and
3259 		         * only overwrite the thread group if we have one with a higher
3260 		         * QoS.
3261 		         */
3262 		        thread_qos_t existing_qos = KQWL_GET_PREADOPTED_TG_QOS(old_tg);
3263 		        if (existing_qos >= qos) {
3264 		                os_atomic_rmw_loop_give_up(break);
3265 			}
3266 		}
3267 
3268 		// Transfer the ref taken earlier in the function to the kqwl
3269 		new_tg = KQWL_ENCODE_PREADOPTED_TG_QOS(tg, qos);
3270 	});
3271 
3272 	if (ret) {
3273 		KQWL_PREADOPT_TG_HISTORY_WRITE_ENTRY(kqwl, KQWL_PREADOPT_OP_INCOMING_IPC, old_tg, tg);
3274 
3275 		if (KQWL_HAS_VALID_PREADOPTED_TG(old_tg)) {
3276 			thread_group_deallocate_safe(KQWL_GET_PREADOPTED_TG(old_tg));
3277 		}
3278 
3279 		os_atomic_store(&kqwl->kqwl_preadopt_tg_needs_redrive, KQWL_PREADOPT_TG_NEEDS_REDRIVE, release);
3280 	} else {
3281 		// We failed to write to the kqwl_preadopt_tg, drop the ref we took
3282 		// earlier in the function
3283 		thread_group_deallocate_safe(tg);
3284 	}
3285 }
3286 
3287 /*
3288  * Called from fprocess of EVFILT_MACHPORT without the kqueue lock held.
3289  */
3290 bool
kqueue_process_preadopt_thread_group(thread_t thread,struct kqueue * kq,struct thread_group * tg)3291 kqueue_process_preadopt_thread_group(thread_t thread, struct kqueue *kq, struct thread_group *tg)
3292 {
3293 	bool success = false;
3294 	if (kq->kq_state & KQ_WORKLOOP) {
3295 		struct kqworkloop *kqwl = (struct kqworkloop *) kq;
3296 		thread_group_qos_t old_tg;
3297 		success = os_atomic_cmpxchgv(&kqwl->kqwl_preadopt_tg,
3298 		    KQWL_PREADOPTED_TG_SENTINEL, KQWL_PREADOPTED_TG_PROCESSED,
3299 		    &old_tg, relaxed);
3300 		if (success) {
3301 			thread_set_preadopt_thread_group(thread, tg);
3302 		}
3303 
3304 		__assert_only thread_group_qos_t preadopt_tg;
3305 		preadopt_tg = os_atomic_load(&kqwl->kqwl_preadopt_tg, relaxed);
3306 		assert(preadopt_tg == KQWL_PREADOPTED_TG_PROCESSED ||
3307 		    preadopt_tg == KQWL_PREADOPTED_TG_NEVER);
3308 	}
3309 
3310 	return success;
3311 }
3312 #endif
3313 
3314 /*!
3315  * @function kqworkloop_dealloc
3316  *
3317  * @brief
3318  * Deallocates a workloop kqueue.
3319  *
3320  * @discussion
3321  * Knotes hold references on the workloop, so we can't really reach this
3322  * function unless all of these are already gone.
3323  *
3324  * Nothing locked on entry or exit.
3325  *
3326  * @param hash_remove
3327  * Whether to remove the workloop from its hash table.
3328  */
3329 static void
kqworkloop_dealloc(struct kqworkloop * kqwl,bool hash_remove)3330 kqworkloop_dealloc(struct kqworkloop *kqwl, bool hash_remove)
3331 {
3332 	thread_t cur_owner;
3333 
3334 	cur_owner = kqwl->kqwl_owner;
3335 	if (cur_owner) {
3336 		if (kqworkloop_override(kqwl) != THREAD_QOS_UNSPECIFIED) {
3337 			thread_drop_kevent_override(cur_owner);
3338 		}
3339 		thread_deallocate(cur_owner);
3340 		kqwl->kqwl_owner = THREAD_NULL;
3341 	}
3342 
3343 	if (kqwl->kqwl_state & KQ_HAS_TURNSTILE) {
3344 		struct turnstile *ts;
3345 		turnstile_complete((uintptr_t)kqwl, &kqwl->kqwl_turnstile,
3346 		    &ts, TURNSTILE_WORKLOOPS);
3347 		turnstile_cleanup();
3348 		turnstile_deallocate(ts);
3349 	}
3350 
3351 	if (hash_remove) {
3352 		struct filedesc *fdp = &kqwl->kqwl_p->p_fd;
3353 
3354 		kqhash_lock(fdp);
3355 		LIST_REMOVE(kqwl, kqwl_hashlink);
3356 		kqhash_unlock(fdp);
3357 	}
3358 
3359 #if CONFIG_PREADOPT_TG
3360 	thread_group_qos_t tg = os_atomic_load(&kqwl->kqwl_preadopt_tg, relaxed);
3361 	if (KQWL_HAS_VALID_PREADOPTED_TG(tg)) {
3362 		thread_group_release(KQWL_GET_PREADOPTED_TG(tg));
3363 	}
3364 #endif
3365 
3366 	assert(TAILQ_EMPTY(&kqwl->kqwl_suppressed));
3367 	assert(kqwl->kqwl_owner == THREAD_NULL);
3368 	assert(kqwl->kqwl_turnstile == TURNSTILE_NULL);
3369 
3370 	lck_spin_destroy(&kqwl->kqwl_statelock, &kq_lck_grp);
3371 	kqueue_destroy(kqwl, kqworkloop_zone);
3372 }
3373 
3374 /*!
3375  * @function kqworkloop_alloc
3376  *
3377  * @brief
3378  * Allocates a workloop kqueue.
3379  */
3380 static void
kqworkloop_init(struct kqworkloop * kqwl,proc_t p,kqueue_id_t id,workq_threadreq_param_t * trp)3381 kqworkloop_init(struct kqworkloop *kqwl, proc_t p,
3382     kqueue_id_t id, workq_threadreq_param_t *trp)
3383 {
3384 	kqwl->kqwl_state     = KQ_WORKLOOP | KQ_DYNAMIC | KQ_KEV_QOS;
3385 	os_ref_init_raw(&kqwl->kqwl_retains, NULL);
3386 	kqwl->kqwl_dynamicid = id;
3387 	kqwl->kqwl_p         = p;
3388 	if (trp) {
3389 		kqwl->kqwl_params = trp->trp_value;
3390 	}
3391 
3392 	workq_tr_flags_t tr_flags = WORKQ_TR_FLAG_WORKLOOP;
3393 	if (trp) {
3394 		if (trp->trp_flags & TRP_PRIORITY) {
3395 			tr_flags |= WORKQ_TR_FLAG_WL_OUTSIDE_QOS;
3396 		}
3397 		if (trp->trp_flags) {
3398 			tr_flags |= WORKQ_TR_FLAG_WL_PARAMS;
3399 		}
3400 	}
3401 	kqwl->kqwl_request.tr_state = WORKQ_TR_STATE_IDLE;
3402 	kqwl->kqwl_request.tr_flags = tr_flags;
3403 	os_atomic_store(&kqwl->kqwl_iotier_override, (uint8_t)THROTTLE_LEVEL_END, relaxed);
3404 #if CONFIG_PREADOPT_TG
3405 	if (task_is_app(current_task())) {
3406 		/* Apps will never adopt a thread group that is not their own. This is a
3407 		 * gross hack to simulate the post-process that is done in the voucher
3408 		 * subsystem today for thread groups */
3409 		os_atomic_store(&kqwl->kqwl_preadopt_tg, KQWL_PREADOPTED_TG_NEVER, relaxed);
3410 	}
3411 #endif
3412 
3413 	for (int i = 0; i < KQWL_NBUCKETS; i++) {
3414 		TAILQ_INIT_AFTER_BZERO(&kqwl->kqwl_queue[i]);
3415 	}
3416 	TAILQ_INIT_AFTER_BZERO(&kqwl->kqwl_suppressed);
3417 
3418 	lck_spin_init(&kqwl->kqwl_statelock, &kq_lck_grp, LCK_ATTR_NULL);
3419 
3420 	kqueue_init(kqwl);
3421 }
3422 
3423 /*!
3424  * @function kqworkloop_get_or_create
3425  *
3426  * @brief
3427  * Wrapper around kqworkloop_alloc that handles the uniquing of workloops.
3428  *
3429  * @returns
3430  * 0:      success
3431  * EINVAL: invalid parameters
3432  * EEXIST: KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST is set and a collision exists.
3433  * ENOENT: KEVENT_FLAG_DYNAMIC_KQ_MUST_EXIST is set and the entry wasn't found.
3434  * ENOMEM: allocation failed
3435  */
3436 static int
kqworkloop_get_or_create(struct proc * p,kqueue_id_t id,workq_threadreq_param_t * trp,unsigned int flags,struct kqworkloop ** kqwlp)3437 kqworkloop_get_or_create(struct proc *p, kqueue_id_t id,
3438     workq_threadreq_param_t *trp, unsigned int flags, struct kqworkloop **kqwlp)
3439 {
3440 	struct filedesc *fdp = &p->p_fd;
3441 	struct kqworkloop *alloc_kqwl = NULL;
3442 	struct kqworkloop *kqwl = NULL;
3443 	int error = 0;
3444 
3445 	assert(!trp || (flags & KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST));
3446 
3447 	if (id == 0 || id == (kqueue_id_t)-1) {
3448 		return EINVAL;
3449 	}
3450 
3451 	for (;;) {
3452 		kqhash_lock(fdp);
3453 		if (__improbable(fdp->fd_kqhash == NULL)) {
3454 			kqworkloop_hash_init(fdp);
3455 		}
3456 
3457 		kqwl = kqworkloop_hash_lookup_locked(fdp, id);
3458 		if (kqwl) {
3459 			if (__improbable(flags & KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST)) {
3460 				/*
3461 				 * If MUST_NOT_EXIST was passed, even if we would have failed
3462 				 * the try_retain, it could have gone the other way, and
3463 				 * userspace can't tell. Let'em fix their race.
3464 				 */
3465 				error = EEXIST;
3466 				break;
3467 			}
3468 
3469 			if (__probable(kqworkloop_try_retain(kqwl))) {
3470 				/*
3471 				 * This is a valid live workloop !
3472 				 */
3473 				*kqwlp = kqwl;
3474 				error = 0;
3475 				break;
3476 			}
3477 		}
3478 
3479 		if (__improbable(flags & KEVENT_FLAG_DYNAMIC_KQ_MUST_EXIST)) {
3480 			error = ENOENT;
3481 			break;
3482 		}
3483 
3484 		/*
3485 		 * We didn't find what we were looking for.
3486 		 *
3487 		 * If this is the second time we reach this point (alloc_kqwl != NULL),
3488 		 * then we're done.
3489 		 *
3490 		 * If this is the first time we reach this point (alloc_kqwl == NULL),
3491 		 * then try to allocate one without blocking.
3492 		 */
3493 		if (__probable(alloc_kqwl == NULL)) {
3494 			alloc_kqwl = zalloc_flags(kqworkloop_zone, Z_NOWAIT | Z_ZERO);
3495 		}
3496 		if (__probable(alloc_kqwl)) {
3497 			kqworkloop_init(alloc_kqwl, p, id, trp);
3498 			kqworkloop_hash_insert_locked(fdp, id, alloc_kqwl);
3499 			kqhash_unlock(fdp);
3500 			*kqwlp = alloc_kqwl;
3501 			return 0;
3502 		}
3503 
3504 		/*
3505 		 * We have to block to allocate a workloop, drop the lock,
3506 		 * allocate one, but then we need to retry lookups as someone
3507 		 * else could race with us.
3508 		 */
3509 		kqhash_unlock(fdp);
3510 
3511 		alloc_kqwl = zalloc_flags(kqworkloop_zone, Z_WAITOK | Z_ZERO);
3512 	}
3513 
3514 	kqhash_unlock(fdp);
3515 
3516 	if (__improbable(alloc_kqwl)) {
3517 		zfree(kqworkloop_zone, alloc_kqwl);
3518 	}
3519 
3520 	return error;
3521 }
3522 
3523 #pragma mark - knotes
3524 
3525 static int
filt_no_attach(struct knote * kn,__unused struct kevent_qos_s * kev)3526 filt_no_attach(struct knote *kn, __unused struct kevent_qos_s *kev)
3527 {
3528 	knote_set_error(kn, ENOTSUP);
3529 	return 0;
3530 }
3531 
3532 static void
filt_no_detach(__unused struct knote * kn)3533 filt_no_detach(__unused struct knote *kn)
3534 {
3535 }
3536 
3537 static int __dead2
filt_bad_event(struct knote * kn,long hint)3538 filt_bad_event(struct knote *kn, long hint)
3539 {
3540 	panic("%s[%d](%p, %ld)", __func__, kn->kn_filter, kn, hint);
3541 }
3542 
3543 static int __dead2
filt_bad_touch(struct knote * kn,struct kevent_qos_s * kev)3544 filt_bad_touch(struct knote *kn, struct kevent_qos_s *kev)
3545 {
3546 	panic("%s[%d](%p, %p)", __func__, kn->kn_filter, kn, kev);
3547 }
3548 
3549 static int __dead2
filt_bad_process(struct knote * kn,struct kevent_qos_s * kev)3550 filt_bad_process(struct knote *kn, struct kevent_qos_s *kev)
3551 {
3552 	panic("%s[%d](%p, %p)", __func__, kn->kn_filter, kn, kev);
3553 }
3554 
3555 /*
3556  * knotes_dealloc - detach all knotes for the process and drop them
3557  *
3558  *		Process is in such a state that it will not try to allocate
3559  *		any more knotes during this process (stopped for exit or exec).
3560  */
3561 void
knotes_dealloc(proc_t p)3562 knotes_dealloc(proc_t p)
3563 {
3564 	struct filedesc *fdp = &p->p_fd;
3565 	struct kqueue *kq;
3566 	struct knote *kn;
3567 	struct  klist *kn_hash = NULL;
3568 	u_long kn_hashmask;
3569 	int i;
3570 
3571 	proc_fdlock(p);
3572 
3573 	/* Close all the fd-indexed knotes up front */
3574 	if (fdp->fd_knlistsize > 0) {
3575 		for (i = 0; i < fdp->fd_knlistsize; i++) {
3576 			while ((kn = SLIST_FIRST(&fdp->fd_knlist[i])) != NULL) {
3577 				kq = knote_get_kq(kn);
3578 				kqlock(kq);
3579 				proc_fdunlock(p);
3580 				knote_drop(kq, kn, NULL);
3581 				proc_fdlock(p);
3582 			}
3583 		}
3584 		/* free the table */
3585 		kfree_type(struct klist, fdp->fd_knlistsize, fdp->fd_knlist);
3586 	}
3587 	fdp->fd_knlistsize = 0;
3588 
3589 	proc_fdunlock(p);
3590 
3591 	knhash_lock(fdp);
3592 
3593 	/* Clean out all the hashed knotes as well */
3594 	if (fdp->fd_knhashmask != 0) {
3595 		for (i = 0; i <= (int)fdp->fd_knhashmask; i++) {
3596 			while ((kn = SLIST_FIRST(&fdp->fd_knhash[i])) != NULL) {
3597 				kq = knote_get_kq(kn);
3598 				kqlock(kq);
3599 				knhash_unlock(fdp);
3600 				knote_drop(kq, kn, NULL);
3601 				knhash_lock(fdp);
3602 			}
3603 		}
3604 		kn_hash = fdp->fd_knhash;
3605 		kn_hashmask = fdp->fd_knhashmask;
3606 		fdp->fd_knhashmask = 0;
3607 		fdp->fd_knhash = NULL;
3608 	}
3609 
3610 	knhash_unlock(fdp);
3611 
3612 	if (kn_hash) {
3613 		hashdestroy(kn_hash, M_KQUEUE, kn_hashmask);
3614 	}
3615 }
3616 
3617 /*
3618  * kqworkloops_dealloc - rebalance retains on kqworkloops created with
3619  * scheduling parameters
3620  *
3621  *		Process is in such a state that it will not try to allocate
3622  *		any more knotes during this process (stopped for exit or exec).
3623  */
3624 void
kqworkloops_dealloc(proc_t p)3625 kqworkloops_dealloc(proc_t p)
3626 {
3627 	struct filedesc *fdp = &p->p_fd;
3628 	struct kqworkloop *kqwl, *kqwln;
3629 	struct kqwllist tofree;
3630 
3631 	if (!fdt_flag_test(fdp, FD_WORKLOOP)) {
3632 		return;
3633 	}
3634 
3635 	kqhash_lock(fdp);
3636 
3637 	if (fdp->fd_kqhashmask == 0) {
3638 		kqhash_unlock(fdp);
3639 		return;
3640 	}
3641 
3642 	LIST_INIT(&tofree);
3643 
3644 	for (size_t i = 0; i <= fdp->fd_kqhashmask; i++) {
3645 		LIST_FOREACH_SAFE(kqwl, &fdp->fd_kqhash[i], kqwl_hashlink, kqwln) {
3646 			/*
3647 			 * kqworkloops that have scheduling parameters have an
3648 			 * implicit retain from kqueue_workloop_ctl that needs
3649 			 * to be balanced on process exit.
3650 			 */
3651 			assert(kqwl->kqwl_params);
3652 			LIST_REMOVE(kqwl, kqwl_hashlink);
3653 			LIST_INSERT_HEAD(&tofree, kqwl, kqwl_hashlink);
3654 		}
3655 	}
3656 
3657 	kqhash_unlock(fdp);
3658 
3659 	LIST_FOREACH_SAFE(kqwl, &tofree, kqwl_hashlink, kqwln) {
3660 		uint32_t ref = os_ref_get_count_raw(&kqwl->kqwl_retains);
3661 		if (ref != 1) {
3662 			panic("kq(%p) invalid refcount %d", kqwl, ref);
3663 		}
3664 		kqworkloop_dealloc(kqwl, false);
3665 	}
3666 }
3667 
3668 static int
kevent_register_validate_priority(struct kqueue * kq,struct knote * kn,struct kevent_qos_s * kev)3669 kevent_register_validate_priority(struct kqueue *kq, struct knote *kn,
3670     struct kevent_qos_s *kev)
3671 {
3672 	/* We don't care about the priority of a disabled or deleted knote */
3673 	if (kev->flags & (EV_DISABLE | EV_DELETE)) {
3674 		return 0;
3675 	}
3676 
3677 	if (kq->kq_state & KQ_WORKLOOP) {
3678 		/*
3679 		 * Workloops need valid priorities with a QOS (excluding manager) for
3680 		 * any enabled knote.
3681 		 *
3682 		 * When it is pre-existing, just make sure it has a valid QoS as
3683 		 * kevent_register() will not use the incoming priority (filters who do
3684 		 * have the responsibility to validate it again, see filt_wltouch).
3685 		 *
3686 		 * If the knote is being made, validate the incoming priority.
3687 		 */
3688 		if (!_pthread_priority_thread_qos(kn ? kn->kn_qos : kev->qos)) {
3689 			return ERANGE;
3690 		}
3691 	}
3692 
3693 	return 0;
3694 }
3695 
3696 /*
3697  * Prepare a filter for waiting after register.
3698  *
3699  * The f_post_register_wait hook will be called later by kevent_register()
3700  * and should call kevent_register_wait_block()
3701  */
3702 static int
kevent_register_wait_prepare(struct knote * kn,struct kevent_qos_s * kev,int rc)3703 kevent_register_wait_prepare(struct knote *kn, struct kevent_qos_s *kev, int rc)
3704 {
3705 	thread_t thread = current_thread();
3706 
3707 	assert(knote_fops(kn)->f_extended_codes);
3708 
3709 	if (kn->kn_thread == NULL) {
3710 		thread_reference(thread);
3711 		kn->kn_thread = thread;
3712 	} else if (kn->kn_thread != thread) {
3713 		/*
3714 		 * kn_thread may be set from a previous aborted wait
3715 		 * However, it has to be from the same thread.
3716 		 */
3717 		kev->flags |= EV_ERROR;
3718 		kev->data = EXDEV;
3719 		return 0;
3720 	}
3721 
3722 	return FILTER_REGISTER_WAIT | rc;
3723 }
3724 
3725 /*
3726  * Cleanup a kevent_register_wait_prepare() effect for threads that have been
3727  * aborted instead of properly woken up with thread_wakeup_thread().
3728  */
3729 static void
kevent_register_wait_cleanup(struct knote * kn)3730 kevent_register_wait_cleanup(struct knote *kn)
3731 {
3732 	thread_t thread = kn->kn_thread;
3733 	kn->kn_thread = NULL;
3734 	thread_deallocate(thread);
3735 }
3736 
3737 /*
3738  * Must be called at the end of a f_post_register_wait call from a filter.
3739  */
3740 static void
kevent_register_wait_block(struct turnstile * ts,thread_t thread,thread_continue_t cont,struct _kevent_register * cont_args)3741 kevent_register_wait_block(struct turnstile *ts, thread_t thread,
3742     thread_continue_t cont, struct _kevent_register *cont_args)
3743 {
3744 	turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_HELD);
3745 	kqunlock(cont_args->kqwl);
3746 	cont_args->handoff_thread = thread;
3747 	thread_handoff_parameter(thread, cont, cont_args, THREAD_HANDOFF_NONE);
3748 }
3749 
3750 /*
3751  * Called by Filters using a f_post_register_wait to return from their wait.
3752  */
3753 static void
kevent_register_wait_return(struct _kevent_register * cont_args)3754 kevent_register_wait_return(struct _kevent_register *cont_args)
3755 {
3756 	struct kqworkloop *kqwl = cont_args->kqwl;
3757 	struct kevent_qos_s *kev = &cont_args->kev;
3758 	int error = 0;
3759 
3760 	if (cont_args->handoff_thread) {
3761 		thread_deallocate(cont_args->handoff_thread);
3762 	}
3763 
3764 	if (kev->flags & (EV_ERROR | EV_RECEIPT)) {
3765 		if ((kev->flags & EV_ERROR) == 0) {
3766 			kev->flags |= EV_ERROR;
3767 			kev->data = 0;
3768 		}
3769 		error = kevent_modern_copyout(kev, &cont_args->ueventlist);
3770 		if (error == 0) {
3771 			cont_args->eventout++;
3772 		}
3773 	}
3774 
3775 	kqworkloop_release(kqwl);
3776 	if (error == 0) {
3777 		*(int32_t *)&current_uthread()->uu_rval = cont_args->eventout;
3778 	}
3779 	unix_syscall_return(error);
3780 }
3781 
3782 /*
3783  * kevent_register - add a new event to a kqueue
3784  *
3785  *	Creates a mapping between the event source and
3786  *	the kqueue via a knote data structure.
3787  *
3788  *	Because many/most the event sources are file
3789  *	descriptor related, the knote is linked off
3790  *	the filedescriptor table for quick access.
3791  *
3792  *	called with nothing locked
3793  *	caller holds a reference on the kqueue
3794  */
3795 
3796 int
kevent_register(struct kqueue * kq,struct kevent_qos_s * kev,struct knote ** kn_out)3797 kevent_register(struct kqueue *kq, struct kevent_qos_s *kev,
3798     struct knote **kn_out)
3799 {
3800 	struct proc *p = kq->kq_p;
3801 	const struct filterops *fops;
3802 	struct knote *kn = NULL;
3803 	int result = 0, error = 0;
3804 	unsigned short kev_flags = kev->flags;
3805 	KNOTE_LOCK_CTX(knlc);
3806 
3807 	if (__probable(kev->filter < 0 && kev->filter + EVFILT_SYSCOUNT >= 0)) {
3808 		fops = sysfilt_ops[~kev->filter];       /* to 0-base index */
3809 	} else {
3810 		error = EINVAL;
3811 		goto out;
3812 	}
3813 
3814 	/* restrict EV_VANISHED to adding udata-specific dispatch kevents */
3815 	if (__improbable((kev->flags & EV_VANISHED) &&
3816 	    (kev->flags & (EV_ADD | EV_DISPATCH2)) != (EV_ADD | EV_DISPATCH2))) {
3817 		error = EINVAL;
3818 		goto out;
3819 	}
3820 
3821 	/* Simplify the flags - delete and disable overrule */
3822 	if (kev->flags & EV_DELETE) {
3823 		kev->flags &= ~EV_ADD;
3824 	}
3825 	if (kev->flags & EV_DISABLE) {
3826 		kev->flags &= ~EV_ENABLE;
3827 	}
3828 
3829 	if (kq->kq_state & KQ_WORKLOOP) {
3830 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_REGISTER),
3831 		    ((struct kqworkloop *)kq)->kqwl_dynamicid,
3832 		    kev->udata, kev->flags, kev->filter);
3833 	} else if (kq->kq_state & KQ_WORKQ) {
3834 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWQ_REGISTER),
3835 		    0, kev->udata, kev->flags, kev->filter);
3836 	} else {
3837 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQ_REGISTER),
3838 		    VM_KERNEL_UNSLIDE_OR_PERM(kq),
3839 		    kev->udata, kev->flags, kev->filter);
3840 	}
3841 
3842 restart:
3843 	/* find the matching knote from the fd tables/hashes */
3844 	kn = kq_find_knote_and_kq_lock(kq, kev, fops->f_isfd, p);
3845 	error = kevent_register_validate_priority(kq, kn, kev);
3846 	result = 0;
3847 	if (error) {
3848 		if (kn) {
3849 			kqunlock(kq);
3850 		}
3851 		goto out;
3852 	}
3853 
3854 	if (kn == NULL && (kev->flags & EV_ADD) == 0) {
3855 		/*
3856 		 * No knote found, EV_ADD wasn't specified
3857 		 */
3858 
3859 		if ((kev_flags & EV_ADD) && (kev_flags & EV_DELETE) &&
3860 		    (kq->kq_state & KQ_WORKLOOP)) {
3861 			/*
3862 			 * For workloops, understand EV_ADD|EV_DELETE as a "soft" delete
3863 			 * that doesn't care about ENOENT, so just pretend the deletion
3864 			 * happened.
3865 			 */
3866 		} else {
3867 			error = ENOENT;
3868 		}
3869 		goto out;
3870 	} else if (kn == NULL) {
3871 		/*
3872 		 * No knote found, need to attach a new one (attach)
3873 		 */
3874 
3875 		struct fileproc *knote_fp = NULL;
3876 
3877 		/* grab a file reference for the new knote */
3878 		if (fops->f_isfd) {
3879 			if ((error = fp_lookup(p, (int)kev->ident, &knote_fp, 0)) != 0) {
3880 				goto out;
3881 			}
3882 		}
3883 
3884 		kn = knote_alloc();
3885 		kn->kn_fp = knote_fp;
3886 		kn->kn_is_fd = fops->f_isfd;
3887 		kn->kn_kq_packed = VM_PACK_POINTER((vm_offset_t)kq, KNOTE_KQ_PACKED);
3888 		kn->kn_status = 0;
3889 
3890 		/* was vanish support requested */
3891 		if (kev->flags & EV_VANISHED) {
3892 			kev->flags &= ~EV_VANISHED;
3893 			kn->kn_status |= KN_REQVANISH;
3894 		}
3895 
3896 		/* snapshot matching/dispatching protocol flags into knote */
3897 		if (kev->flags & EV_DISABLE) {
3898 			kn->kn_status |= KN_DISABLED;
3899 		}
3900 
3901 		/*
3902 		 * copy the kevent state into knote
3903 		 * protocol is that fflags and data
3904 		 * are saved off, and cleared before
3905 		 * calling the attach routine.
3906 		 *
3907 		 * - kn->kn_sfflags aliases with kev->xflags
3908 		 * - kn->kn_sdata   aliases with kev->data
3909 		 * - kn->kn_filter  is the top 8 bits of kev->filter
3910 		 */
3911 		kn->kn_kevent  = *(struct kevent_internal_s *)kev;
3912 		kn->kn_sfflags = kev->fflags;
3913 		kn->kn_filtid  = (uint8_t)~kev->filter;
3914 		kn->kn_fflags  = 0;
3915 		knote_reset_priority(kq, kn, kev->qos);
3916 
3917 		/* Add the knote for lookup thru the fd table */
3918 		error = kq_add_knote(kq, kn, &knlc, p);
3919 		if (error) {
3920 			knote_free(kn);
3921 			if (knote_fp != NULL) {
3922 				fp_drop(p, (int)kev->ident, knote_fp, 0);
3923 			}
3924 
3925 			if (error == ERESTART) {
3926 				goto restart;
3927 			}
3928 			goto out;
3929 		}
3930 
3931 		/* fp reference count now applies to knote */
3932 
3933 		/*
3934 		 * we can't use filter_call() because f_attach can change the filter ops
3935 		 * for a filter that supports f_extended_codes, so we need to reload
3936 		 * knote_fops() and not use `fops`.
3937 		 */
3938 		result = fops->f_attach(kn, kev);
3939 		if (result && !knote_fops(kn)->f_extended_codes) {
3940 			result = FILTER_ACTIVE;
3941 		}
3942 
3943 		kqlock(kq);
3944 
3945 		if (result & FILTER_THREADREQ_NODEFEER) {
3946 			enable_preemption();
3947 		}
3948 
3949 		if (kn->kn_flags & EV_ERROR) {
3950 			/*
3951 			 * Failed to attach correctly, so drop.
3952 			 */
3953 			kn->kn_filtid = EVFILTID_DETACHED;
3954 			error = (int)kn->kn_sdata;
3955 			knote_drop(kq, kn, &knlc);
3956 			result = 0;
3957 			goto out;
3958 		}
3959 
3960 		/*
3961 		 * end "attaching" phase - now just attached
3962 		 *
3963 		 * Mark the thread request overcommit, if appropos
3964 		 *
3965 		 * If the attach routine indicated that an
3966 		 * event is already fired, activate the knote.
3967 		 */
3968 		if ((kn->kn_qos & _PTHREAD_PRIORITY_OVERCOMMIT_FLAG) &&
3969 		    (kq->kq_state & KQ_WORKLOOP)) {
3970 			kqworkloop_set_overcommit((struct kqworkloop *)kq);
3971 		}
3972 	} else if (!knote_lock(kq, kn, &knlc, KNOTE_KQ_LOCK_ON_SUCCESS)) {
3973 		/*
3974 		 * The knote was dropped while we were waiting for the lock,
3975 		 * we need to re-evaluate entirely
3976 		 */
3977 
3978 		goto restart;
3979 	} else if (kev->flags & EV_DELETE) {
3980 		/*
3981 		 * Deletion of a knote (drop)
3982 		 *
3983 		 * If the filter wants to filter drop events, let it do so.
3984 		 *
3985 		 * defer-delete: when trying to delete a disabled EV_DISPATCH2 knote,
3986 		 * we must wait for the knote to be re-enabled (unless it is being
3987 		 * re-enabled atomically here).
3988 		 */
3989 
3990 		if (knote_fops(kn)->f_allow_drop) {
3991 			bool drop;
3992 
3993 			kqunlock(kq);
3994 			drop = knote_fops(kn)->f_allow_drop(kn, kev);
3995 			kqlock(kq);
3996 
3997 			if (!drop) {
3998 				goto out_unlock;
3999 			}
4000 		}
4001 
4002 		if ((kev->flags & EV_ENABLE) == 0 &&
4003 		    (kn->kn_flags & EV_DISPATCH2) == EV_DISPATCH2 &&
4004 		    (kn->kn_status & KN_DISABLED) != 0) {
4005 			kn->kn_status |= KN_DEFERDELETE;
4006 			error = EINPROGRESS;
4007 			goto out_unlock;
4008 		}
4009 
4010 		knote_drop(kq, kn, &knlc);
4011 		goto out;
4012 	} else {
4013 		/*
4014 		 * Regular update of a knote (touch)
4015 		 *
4016 		 * Call touch routine to notify filter of changes in filter values
4017 		 * (and to re-determine if any events are fired).
4018 		 *
4019 		 * If the knote is in defer-delete, avoid calling the filter touch
4020 		 * routine (it has delivered its last event already).
4021 		 *
4022 		 * If the touch routine had no failure,
4023 		 * apply the requested side effects to the knote.
4024 		 */
4025 
4026 		if (kn->kn_status & (KN_DEFERDELETE | KN_VANISHED)) {
4027 			if (kev->flags & EV_ENABLE) {
4028 				result = FILTER_ACTIVE;
4029 			}
4030 		} else {
4031 			kqunlock(kq);
4032 			result = filter_call(knote_fops(kn), f_touch(kn, kev));
4033 			kqlock(kq);
4034 			if (result & FILTER_THREADREQ_NODEFEER) {
4035 				enable_preemption();
4036 			}
4037 		}
4038 
4039 		if (kev->flags & EV_ERROR) {
4040 			result = 0;
4041 			goto out_unlock;
4042 		}
4043 
4044 		if ((kn->kn_flags & EV_UDATA_SPECIFIC) == 0 &&
4045 		    kn->kn_udata != kev->udata) {
4046 			// this allows klist_copy_udata() not to take locks
4047 			os_atomic_store_wide(&kn->kn_udata, kev->udata, relaxed);
4048 		}
4049 		if ((kev->flags & EV_DISABLE) && !(kn->kn_status & KN_DISABLED)) {
4050 			kn->kn_status |= KN_DISABLED;
4051 			knote_dequeue(kq, kn);
4052 		}
4053 	}
4054 
4055 	/* accept new kevent state */
4056 	knote_apply_touch(kq, kn, kev, result);
4057 
4058 out_unlock:
4059 	/*
4060 	 * When the filter asked for a post-register wait,
4061 	 * we leave the kqueue locked for kevent_register()
4062 	 * to call the filter's f_post_register_wait hook.
4063 	 */
4064 	if (result & FILTER_REGISTER_WAIT) {
4065 		knote_unlock(kq, kn, &knlc, KNOTE_KQ_LOCK_ALWAYS);
4066 		*kn_out = kn;
4067 	} else {
4068 		knote_unlock(kq, kn, &knlc, KNOTE_KQ_UNLOCK);
4069 	}
4070 
4071 out:
4072 	/* output local errors through the kevent */
4073 	if (error) {
4074 		kev->flags |= EV_ERROR;
4075 		kev->data = error;
4076 	}
4077 	return result;
4078 }
4079 
4080 /*
4081  * knote_process - process a triggered event
4082  *
4083  *	Validate that it is really still a triggered event
4084  *	by calling the filter routines (if necessary).  Hold
4085  *	a use reference on the knote to avoid it being detached.
4086  *
4087  *	If it is still considered triggered, we will have taken
4088  *	a copy of the state under the filter lock.  We use that
4089  *	snapshot to dispatch the knote for future processing (or
4090  *	not, if this was a lost event).
4091  *
4092  *	Our caller assures us that nobody else can be processing
4093  *	events from this knote during the whole operation. But
4094  *	others can be touching or posting events to the knote
4095  *	interspersed with our processing it.
4096  *
4097  *	caller holds a reference on the kqueue.
4098  *	kqueue locked on entry and exit - but may be dropped
4099  */
4100 static int
knote_process(struct knote * kn,kevent_ctx_t kectx,kevent_callback_t callback)4101 knote_process(struct knote *kn, kevent_ctx_t kectx,
4102     kevent_callback_t callback)
4103 {
4104 	struct kevent_qos_s kev;
4105 	struct kqueue *kq = knote_get_kq(kn);
4106 	KNOTE_LOCK_CTX(knlc);
4107 	int result = FILTER_ACTIVE;
4108 	int error = 0;
4109 	bool drop = false;
4110 
4111 	/*
4112 	 * Must be active
4113 	 * Must be queued and not disabled/suppressed or dropping
4114 	 */
4115 	assert(kn->kn_status & KN_QUEUED);
4116 	assert(kn->kn_status & KN_ACTIVE);
4117 	assert(!(kn->kn_status & (KN_DISABLED | KN_SUPPRESSED | KN_DROPPING)));
4118 
4119 	if (kq->kq_state & KQ_WORKLOOP) {
4120 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_PROCESS),
4121 		    ((struct kqworkloop *)kq)->kqwl_dynamicid,
4122 		    kn->kn_udata, kn->kn_status | (kn->kn_id << 32),
4123 		    kn->kn_filtid);
4124 	} else if (kq->kq_state & KQ_WORKQ) {
4125 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWQ_PROCESS),
4126 		    0, kn->kn_udata, kn->kn_status | (kn->kn_id << 32),
4127 		    kn->kn_filtid);
4128 	} else {
4129 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQ_PROCESS),
4130 		    VM_KERNEL_UNSLIDE_OR_PERM(kq), kn->kn_udata,
4131 		    kn->kn_status | (kn->kn_id << 32), kn->kn_filtid);
4132 	}
4133 
4134 	if (!knote_lock(kq, kn, &knlc, KNOTE_KQ_LOCK_ALWAYS)) {
4135 		/*
4136 		 * When the knote is dropping or has dropped,
4137 		 * then there's nothing we want to process.
4138 		 */
4139 		return EJUSTRETURN;
4140 	}
4141 
4142 	/*
4143 	 * While waiting for the knote lock, we may have dropped the kq lock.
4144 	 * and a touch may have disabled and dequeued the knote.
4145 	 */
4146 	if (!(kn->kn_status & KN_QUEUED)) {
4147 		knote_unlock(kq, kn, &knlc, KNOTE_KQ_LOCK_ALWAYS);
4148 		return EJUSTRETURN;
4149 	}
4150 
4151 	/*
4152 	 * For deferred-drop or vanished events, we just create a fake
4153 	 * event to acknowledge end-of-life.  Otherwise, we call the
4154 	 * filter's process routine to snapshot the kevent state under
4155 	 * the filter's locking protocol.
4156 	 *
4157 	 * suppress knotes to avoid returning the same event multiple times in
4158 	 * a single call.
4159 	 */
4160 	knote_suppress(kq, kn);
4161 
4162 	if (kn->kn_status & (KN_DEFERDELETE | KN_VANISHED)) {
4163 		uint16_t kev_flags = EV_DISPATCH2 | EV_ONESHOT;
4164 		if (kn->kn_status & KN_DEFERDELETE) {
4165 			kev_flags |= EV_DELETE;
4166 		} else {
4167 			kev_flags |= EV_VANISHED;
4168 		}
4169 
4170 		/* create fake event */
4171 		kev = (struct kevent_qos_s){
4172 			.filter = kn->kn_filter,
4173 			.ident  = kn->kn_id,
4174 			.flags  = kev_flags,
4175 			.udata  = kn->kn_udata,
4176 		};
4177 	} else {
4178 		kqunlock(kq);
4179 		kev = (struct kevent_qos_s) { };
4180 		result = filter_call(knote_fops(kn), f_process(kn, &kev));
4181 		kqlock(kq);
4182 	}
4183 
4184 	/*
4185 	 * Determine how to dispatch the knote for future event handling.
4186 	 * not-fired: just return (do not callout, leave deactivated).
4187 	 * One-shot:  If dispatch2, enter deferred-delete mode (unless this is
4188 	 *            is the deferred delete event delivery itself).  Otherwise,
4189 	 *            drop it.
4190 	 * Dispatch:  don't clear state, just mark it disabled.
4191 	 * Cleared:   just leave it deactivated.
4192 	 * Others:    re-activate as there may be more events to handle.
4193 	 *            This will not wake up more handlers right now, but
4194 	 *            at the completion of handling events it may trigger
4195 	 *            more handler threads (TODO: optimize based on more than
4196 	 *            just this one event being detected by the filter).
4197 	 */
4198 	if ((result & FILTER_ACTIVE) == 0) {
4199 		if ((kn->kn_status & KN_ACTIVE) == 0) {
4200 			/*
4201 			 * Some knotes (like EVFILT_WORKLOOP) can be reactivated from
4202 			 * within f_process() but that doesn't necessarily make them
4203 			 * ready to process, so we should leave them be.
4204 			 *
4205 			 * For other knotes, since we will not return an event,
4206 			 * there's no point keeping the knote suppressed.
4207 			 */
4208 			knote_unsuppress(kq, kn);
4209 		}
4210 		knote_unlock(kq, kn, &knlc, KNOTE_KQ_LOCK_ALWAYS);
4211 		return EJUSTRETURN;
4212 	}
4213 
4214 	if (result & FILTER_ADJUST_EVENT_QOS_BIT) {
4215 		knote_adjust_qos(kq, kn, result);
4216 	}
4217 
4218 	if (result & FILTER_ADJUST_EVENT_IOTIER_BIT) {
4219 		kqueue_update_iotier_override(kq);
4220 	}
4221 
4222 	kev.qos = _pthread_priority_combine(kn->kn_qos, kn->kn_qos_override);
4223 
4224 	if (kev.flags & EV_ONESHOT) {
4225 		if ((kn->kn_flags & EV_DISPATCH2) == EV_DISPATCH2 &&
4226 		    (kn->kn_status & KN_DEFERDELETE) == 0) {
4227 			/* defer dropping non-delete oneshot dispatch2 events */
4228 			kn->kn_status |= KN_DEFERDELETE | KN_DISABLED;
4229 		} else {
4230 			drop = true;
4231 		}
4232 	} else if (kn->kn_flags & EV_DISPATCH) {
4233 		/* disable all dispatch knotes */
4234 		kn->kn_status |= KN_DISABLED;
4235 	} else if ((kn->kn_flags & EV_CLEAR) == 0) {
4236 		/* re-activate in case there are more events */
4237 		knote_activate(kq, kn, FILTER_ACTIVE);
4238 	}
4239 
4240 	/*
4241 	 * callback to handle each event as we find it.
4242 	 * If we have to detach and drop the knote, do
4243 	 * it while we have the kq unlocked.
4244 	 */
4245 	if (drop) {
4246 		knote_drop(kq, kn, &knlc);
4247 	} else {
4248 		knote_unlock(kq, kn, &knlc, KNOTE_KQ_UNLOCK);
4249 	}
4250 
4251 	if (kev.flags & EV_VANISHED) {
4252 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KNOTE_VANISHED),
4253 		    kev.ident, kn->kn_udata, kn->kn_status | (kn->kn_id << 32),
4254 		    kn->kn_filtid);
4255 	}
4256 
4257 	error = (callback)(&kev, kectx);
4258 	kqlock(kq);
4259 	return error;
4260 }
4261 
4262 /*
4263  * Returns -1 if the kqueue was unbound and processing should not happen
4264  */
4265 #define KQWQAE_BEGIN_PROCESSING 1
4266 #define KQWQAE_END_PROCESSING   2
4267 #define KQWQAE_UNBIND           3
4268 static int
kqworkq_acknowledge_events(struct kqworkq * kqwq,workq_threadreq_t kqr,int kevent_flags,int kqwqae_op)4269 kqworkq_acknowledge_events(struct kqworkq *kqwq, workq_threadreq_t kqr,
4270     int kevent_flags, int kqwqae_op)
4271 {
4272 	struct knote *kn;
4273 	int rc = 0;
4274 	bool unbind;
4275 	struct kqtailq *suppressq = &kqwq->kqwq_suppressed[kqr->tr_kq_qos_index - 1];
4276 	struct kqtailq *queue = &kqwq->kqwq_queue[kqr->tr_kq_qos_index - 1];
4277 
4278 	kqlock_held(&kqwq->kqwq_kqueue);
4279 
4280 	/*
4281 	 * Return suppressed knotes to their original state.
4282 	 * For workq kqueues, suppressed ones that are still
4283 	 * truly active (not just forced into the queue) will
4284 	 * set flags we check below to see if anything got
4285 	 * woken up.
4286 	 */
4287 	while ((kn = TAILQ_FIRST(suppressq)) != NULL) {
4288 		knote_unsuppress(kqwq, kn);
4289 	}
4290 
4291 	if (kqwqae_op == KQWQAE_UNBIND) {
4292 		unbind = true;
4293 	} else if ((kevent_flags & KEVENT_FLAG_PARKING) == 0) {
4294 		unbind = false;
4295 	} else {
4296 		unbind = TAILQ_EMPTY(queue);
4297 	}
4298 	if (unbind) {
4299 		thread_t thread = kqr_thread_fast(kqr);
4300 		thread_qos_t old_override;
4301 
4302 #if DEBUG || DEVELOPMENT
4303 		thread_t self = current_thread();
4304 		struct uthread *ut = get_bsdthread_info(self);
4305 
4306 		assert(thread == self);
4307 		assert(ut->uu_kqr_bound == kqr);
4308 #endif // DEBUG || DEVELOPMENT
4309 
4310 		old_override = kqworkq_unbind_locked(kqwq, kqr, thread);
4311 		if (!TAILQ_EMPTY(queue)) {
4312 			/*
4313 			 * Request a new thread if we didn't process the whole
4314 			 * queue.
4315 			 */
4316 			kqueue_threadreq_initiate(&kqwq->kqwq_kqueue, kqr,
4317 			    kqr->tr_kq_qos_index, 0);
4318 		}
4319 		if (old_override) {
4320 			thread_drop_kevent_override(thread);
4321 		}
4322 		rc = -1;
4323 	}
4324 
4325 	return rc;
4326 }
4327 
4328 /*
4329  * Return 0 to indicate that processing should proceed,
4330  * -1 if there is nothing to process.
4331  *
4332  * Called with kqueue locked and returns the same way,
4333  * but may drop lock temporarily.
4334  */
4335 static int
kqworkq_begin_processing(struct kqworkq * kqwq,workq_threadreq_t kqr,int kevent_flags)4336 kqworkq_begin_processing(struct kqworkq *kqwq, workq_threadreq_t kqr,
4337     int kevent_flags)
4338 {
4339 	int rc = 0;
4340 
4341 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWQ_PROCESS_BEGIN) | DBG_FUNC_START,
4342 	    0, kqr->tr_kq_qos_index);
4343 
4344 	rc = kqworkq_acknowledge_events(kqwq, kqr, kevent_flags,
4345 	    KQWQAE_BEGIN_PROCESSING);
4346 
4347 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWQ_PROCESS_BEGIN) | DBG_FUNC_END,
4348 	    thread_tid(kqr_thread(kqr)),
4349 	    !TAILQ_EMPTY(&kqwq->kqwq_queue[kqr->tr_kq_qos_index - 1]));
4350 
4351 	return rc;
4352 }
4353 
4354 static thread_qos_t
kqworkloop_acknowledge_events(struct kqworkloop * kqwl)4355 kqworkloop_acknowledge_events(struct kqworkloop *kqwl)
4356 {
4357 	kq_index_t qos = THREAD_QOS_UNSPECIFIED;
4358 	struct knote *kn, *tmp;
4359 
4360 	kqlock_held(kqwl);
4361 
4362 	TAILQ_FOREACH_SAFE(kn, &kqwl->kqwl_suppressed, kn_tqe, tmp) {
4363 		/*
4364 		 * If a knote that can adjust QoS is disabled because of the automatic
4365 		 * behavior of EV_DISPATCH, the knotes should stay suppressed so that
4366 		 * further overrides keep pushing.
4367 		 */
4368 		if (knote_fops(kn)->f_adjusts_qos &&
4369 		    (kn->kn_status & KN_DISABLED) != 0 &&
4370 		    (kn->kn_status & KN_DROPPING) == 0 &&
4371 		    (kn->kn_flags & (EV_DISPATCH | EV_DISABLE)) == EV_DISPATCH) {
4372 			qos = MAX(qos, kn->kn_qos_override);
4373 			continue;
4374 		}
4375 		knote_unsuppress(kqwl, kn);
4376 	}
4377 
4378 	return qos;
4379 }
4380 
4381 static int
kqworkloop_begin_processing(struct kqworkloop * kqwl,unsigned int kevent_flags)4382 kqworkloop_begin_processing(struct kqworkloop *kqwl, unsigned int kevent_flags)
4383 {
4384 	workq_threadreq_t kqr = &kqwl->kqwl_request;
4385 	struct kqueue *kq = &kqwl->kqwl_kqueue;
4386 	int rc = 0, op = KQWL_UTQ_NONE;
4387 
4388 	kqlock_held(kq);
4389 
4390 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_PROCESS_BEGIN) | DBG_FUNC_START,
4391 	    kqwl->kqwl_dynamicid, 0, 0);
4392 
4393 	/* nobody else should still be processing */
4394 	assert((kq->kq_state & KQ_PROCESSING) == 0);
4395 
4396 	kq->kq_state |= KQ_PROCESSING;
4397 
4398 	if (kevent_flags & KEVENT_FLAG_PARKING) {
4399 		/*
4400 		 * When "parking" we want to process events and if no events are found
4401 		 * unbind.
4402 		 *
4403 		 * However, non overcommit threads sometimes park even when they have
4404 		 * more work so that the pool can narrow.  For these, we need to unbind
4405 		 * early, so that calling kqworkloop_update_threads_qos() can ask the
4406 		 * workqueue subsystem whether the thread should park despite having
4407 		 * pending events.
4408 		 */
4409 		if (kqr->tr_flags & WORKQ_TR_FLAG_OVERCOMMIT) {
4410 			op = KQWL_UTQ_PARKING;
4411 		} else {
4412 			op = KQWL_UTQ_UNBINDING;
4413 		}
4414 	} else if (!TAILQ_EMPTY(&kqwl->kqwl_suppressed)) {
4415 		op = KQWL_UTQ_RESET_WAKEUP_OVERRIDE;
4416 	}
4417 
4418 	if (op != KQWL_UTQ_NONE) {
4419 		thread_qos_t qos_override;
4420 		thread_t thread = kqr_thread_fast(kqr);
4421 
4422 		qos_override = kqworkloop_acknowledge_events(kqwl);
4423 
4424 		if (op == KQWL_UTQ_UNBINDING) {
4425 			kqworkloop_unbind_locked(kqwl, thread,
4426 			    KQWL_OVERRIDE_DROP_IMMEDIATELY);
4427 			kqworkloop_release_live(kqwl);
4428 		}
4429 		kqworkloop_update_threads_qos(kqwl, op, qos_override);
4430 		if (op == KQWL_UTQ_PARKING &&
4431 		    (!kqwl->kqwl_count || kqwl->kqwl_owner)) {
4432 			kqworkloop_unbind_locked(kqwl, thread,
4433 			    KQWL_OVERRIDE_DROP_DELAYED);
4434 			kqworkloop_release_live(kqwl);
4435 			rc = -1;
4436 		} else if (op == KQWL_UTQ_UNBINDING &&
4437 		    kqr_thread(kqr) != thread) {
4438 			rc = -1;
4439 		}
4440 
4441 		if (rc == -1) {
4442 			kq->kq_state &= ~KQ_PROCESSING;
4443 			kqworkloop_unbind_delayed_override_drop(thread);
4444 		}
4445 	}
4446 
4447 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_PROCESS_BEGIN) | DBG_FUNC_END,
4448 	    kqwl->kqwl_dynamicid, 0, 0);
4449 
4450 	return rc;
4451 }
4452 
4453 /*
4454  * Return 0 to indicate that processing should proceed,
4455  * -1 if there is nothing to process.
4456  * EBADF if the kqueue is draining
4457  *
4458  * Called with kqueue locked and returns the same way,
4459  * but may drop lock temporarily.
4460  * May block.
4461  */
4462 static int
kqfile_begin_processing(struct kqfile * kq)4463 kqfile_begin_processing(struct kqfile *kq)
4464 {
4465 	kqlock_held(kq);
4466 
4467 	assert((kq->kqf_state & (KQ_WORKQ | KQ_WORKLOOP)) == 0);
4468 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQ_PROCESS_BEGIN) | DBG_FUNC_START,
4469 	    VM_KERNEL_UNSLIDE_OR_PERM(kq), 0);
4470 
4471 	/* wait to become the exclusive processing thread */
4472 	while ((kq->kqf_state & (KQ_PROCESSING | KQ_DRAIN)) == KQ_PROCESSING) {
4473 		kq->kqf_state |= KQ_PROCWAIT;
4474 		lck_spin_sleep(&kq->kqf_lock, LCK_SLEEP_DEFAULT,
4475 		    &kq->kqf_suppressed, THREAD_UNINT | THREAD_WAIT_NOREPORT);
4476 	}
4477 
4478 	if (kq->kqf_state & KQ_DRAIN) {
4479 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQ_PROCESS_BEGIN) | DBG_FUNC_END,
4480 		    VM_KERNEL_UNSLIDE_OR_PERM(kq), 2);
4481 		return EBADF;
4482 	}
4483 
4484 	/* Nobody else processing */
4485 
4486 	/* anything left to process? */
4487 	if (kq->kqf_count == 0) {
4488 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQ_PROCESS_BEGIN) | DBG_FUNC_END,
4489 		    VM_KERNEL_UNSLIDE_OR_PERM(kq), 1);
4490 		return -1;
4491 	}
4492 
4493 	/* convert to processing mode */
4494 	kq->kqf_state |= KQ_PROCESSING;
4495 
4496 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQ_PROCESS_BEGIN) | DBG_FUNC_END,
4497 	    VM_KERNEL_UNSLIDE_OR_PERM(kq), 0);
4498 	return 0;
4499 }
4500 
4501 /*
4502  * Try to end the processing, only called when a workq thread is attempting to
4503  * park (KEVENT_FLAG_PARKING is set).
4504  *
4505  * When returning -1, the kqworkq is setup again so that it is ready to be
4506  * processed.
4507  */
4508 static int
kqworkq_end_processing(struct kqworkq * kqwq,workq_threadreq_t kqr,int kevent_flags)4509 kqworkq_end_processing(struct kqworkq *kqwq, workq_threadreq_t kqr,
4510     int kevent_flags)
4511 {
4512 	if (kevent_flags & KEVENT_FLAG_PARKING) {
4513 		/*
4514 		 * if acknowledge events "succeeds" it means there are events,
4515 		 * which is a failure condition for end_processing.
4516 		 */
4517 		int rc = kqworkq_acknowledge_events(kqwq, kqr, kevent_flags,
4518 		    KQWQAE_END_PROCESSING);
4519 		if (rc == 0) {
4520 			return -1;
4521 		}
4522 	}
4523 
4524 	return 0;
4525 }
4526 
4527 /*
4528  * Try to end the processing, only called when a workq thread is attempting to
4529  * park (KEVENT_FLAG_PARKING is set).
4530  *
4531  * When returning -1, the kqworkq is setup again so that it is ready to be
4532  * processed (as if kqworkloop_begin_processing had just been called).
4533  *
4534  * If successful and KEVENT_FLAG_PARKING was set in the kevent_flags,
4535  * the kqworkloop is unbound from its servicer as a side effect.
4536  */
4537 static int
kqworkloop_end_processing(struct kqworkloop * kqwl,int flags,int kevent_flags)4538 kqworkloop_end_processing(struct kqworkloop *kqwl, int flags, int kevent_flags)
4539 {
4540 	struct kqueue *kq = &kqwl->kqwl_kqueue;
4541 	workq_threadreq_t kqr = &kqwl->kqwl_request;
4542 	int rc = 0;
4543 
4544 	kqlock_held(kq);
4545 
4546 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_PROCESS_END) | DBG_FUNC_START,
4547 	    kqwl->kqwl_dynamicid, 0, 0);
4548 
4549 	if (kevent_flags & KEVENT_FLAG_PARKING) {
4550 		thread_t thread = kqr_thread_fast(kqr);
4551 		thread_qos_t qos_override;
4552 
4553 		/*
4554 		 * When KEVENT_FLAG_PARKING is set, we need to attempt
4555 		 * an unbind while still under the lock.
4556 		 *
4557 		 * So we do everything kqworkloop_unbind() would do, but because
4558 		 * we're inside kqueue_process(), if the workloop actually
4559 		 * received events while our locks were dropped, we have
4560 		 * the opportunity to fail the end processing and loop again.
4561 		 *
4562 		 * This avoids going through the process-wide workqueue lock
4563 		 * hence scales better.
4564 		 */
4565 		assert(flags & KQ_PROCESSING);
4566 		qos_override = kqworkloop_acknowledge_events(kqwl);
4567 		kqworkloop_update_threads_qos(kqwl, KQWL_UTQ_PARKING, qos_override);
4568 
4569 		if (kqwl->kqwl_wakeup_qos && !kqwl->kqwl_owner) {
4570 			rc = -1;
4571 		} else {
4572 			kqworkloop_unbind_locked(kqwl, thread, KQWL_OVERRIDE_DROP_DELAYED);
4573 			kqworkloop_release_live(kqwl);
4574 			kq->kq_state &= ~flags;
4575 			kqworkloop_unbind_delayed_override_drop(thread);
4576 		}
4577 	} else {
4578 		kq->kq_state &= ~flags;
4579 		kq->kq_state |= KQ_R2K_ARMED;
4580 		kqworkloop_update_threads_qos(kqwl, KQWL_UTQ_RECOMPUTE_WAKEUP_QOS, 0);
4581 	}
4582 
4583 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_PROCESS_END) | DBG_FUNC_END,
4584 	    kqwl->kqwl_dynamicid, 0, 0);
4585 
4586 	return rc;
4587 }
4588 
4589 /*
4590  * Called with kqueue lock held.
4591  *
4592  * 0: no more events
4593  * -1: has more events
4594  * EBADF: kqueue is in draining mode
4595  */
4596 static int
kqfile_end_processing(struct kqfile * kq)4597 kqfile_end_processing(struct kqfile *kq)
4598 {
4599 	struct knote *kn;
4600 	int procwait;
4601 
4602 	kqlock_held(kq);
4603 
4604 	assert((kq->kqf_state & (KQ_WORKQ | KQ_WORKLOOP)) == 0);
4605 
4606 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQ_PROCESS_END),
4607 	    VM_KERNEL_UNSLIDE_OR_PERM(kq), 0);
4608 
4609 	/*
4610 	 * Return suppressed knotes to their original state.
4611 	 */
4612 	while ((kn = TAILQ_FIRST(&kq->kqf_suppressed)) != NULL) {
4613 		knote_unsuppress(kq, kn);
4614 	}
4615 
4616 	procwait = (kq->kqf_state & KQ_PROCWAIT);
4617 	kq->kqf_state &= ~(KQ_PROCESSING | KQ_PROCWAIT);
4618 
4619 	if (procwait) {
4620 		/* first wake up any thread already waiting to process */
4621 		thread_wakeup(&kq->kqf_suppressed);
4622 	}
4623 
4624 	if (kq->kqf_state & KQ_DRAIN) {
4625 		return EBADF;
4626 	}
4627 	return kq->kqf_count != 0 ? -1 : 0;
4628 }
4629 
4630 static int
kqueue_workloop_ctl_internal(proc_t p,uintptr_t cmd,uint64_t __unused options,struct kqueue_workloop_params * params,int * retval)4631 kqueue_workloop_ctl_internal(proc_t p, uintptr_t cmd, uint64_t __unused options,
4632     struct kqueue_workloop_params *params, int *retval)
4633 {
4634 	int error = 0;
4635 	struct kqworkloop *kqwl;
4636 	struct filedesc *fdp = &p->p_fd;
4637 	workq_threadreq_param_t trp = { };
4638 
4639 	switch (cmd) {
4640 	case KQ_WORKLOOP_CREATE:
4641 		if (!params->kqwlp_flags) {
4642 			error = EINVAL;
4643 			break;
4644 		}
4645 
4646 		if ((params->kqwlp_flags & KQ_WORKLOOP_CREATE_SCHED_PRI) &&
4647 		    (params->kqwlp_sched_pri < 1 ||
4648 		    params->kqwlp_sched_pri > 63 /* MAXPRI_USER */)) {
4649 			error = EINVAL;
4650 			break;
4651 		}
4652 
4653 		if ((params->kqwlp_flags & KQ_WORKLOOP_CREATE_SCHED_POL) &&
4654 		    invalid_policy(params->kqwlp_sched_pol)) {
4655 			error = EINVAL;
4656 			break;
4657 		}
4658 
4659 		if ((params->kqwlp_flags & KQ_WORKLOOP_CREATE_CPU_PERCENT) &&
4660 		    (params->kqwlp_cpu_percent <= 0 ||
4661 		    params->kqwlp_cpu_percent > 100 ||
4662 		    params->kqwlp_cpu_refillms <= 0 ||
4663 		    params->kqwlp_cpu_refillms > 0x00ffffff)) {
4664 			error = EINVAL;
4665 			break;
4666 		}
4667 
4668 		if (params->kqwlp_flags & KQ_WORKLOOP_CREATE_SCHED_PRI) {
4669 			trp.trp_flags |= TRP_PRIORITY;
4670 			trp.trp_pri = (uint8_t)params->kqwlp_sched_pri;
4671 		}
4672 		if (params->kqwlp_flags & KQ_WORKLOOP_CREATE_SCHED_POL) {
4673 			trp.trp_flags |= TRP_POLICY;
4674 			trp.trp_pol = (uint8_t)params->kqwlp_sched_pol;
4675 		}
4676 		if (params->kqwlp_flags & KQ_WORKLOOP_CREATE_CPU_PERCENT) {
4677 			trp.trp_flags |= TRP_CPUPERCENT;
4678 			trp.trp_cpupercent = (uint8_t)params->kqwlp_cpu_percent;
4679 			trp.trp_refillms = params->kqwlp_cpu_refillms;
4680 		}
4681 
4682 		error = kqworkloop_get_or_create(p, params->kqwlp_id, &trp,
4683 		    KEVENT_FLAG_DYNAMIC_KQUEUE | KEVENT_FLAG_WORKLOOP |
4684 		    KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST, &kqwl);
4685 		if (error) {
4686 			break;
4687 		}
4688 
4689 		if (!fdt_flag_test(fdp, FD_WORKLOOP)) {
4690 			/* FD_WORKLOOP indicates we've ever created a workloop
4691 			 * via this syscall but its only ever added to a process, never
4692 			 * removed.
4693 			 */
4694 			proc_fdlock(p);
4695 			fdt_flag_set(fdp, FD_WORKLOOP);
4696 			proc_fdunlock(p);
4697 		}
4698 		break;
4699 	case KQ_WORKLOOP_DESTROY:
4700 		error = kqworkloop_get_or_create(p, params->kqwlp_id, NULL,
4701 		    KEVENT_FLAG_DYNAMIC_KQUEUE | KEVENT_FLAG_WORKLOOP |
4702 		    KEVENT_FLAG_DYNAMIC_KQ_MUST_EXIST, &kqwl);
4703 		if (error) {
4704 			break;
4705 		}
4706 		kqlock(kqwl);
4707 		trp.trp_value = kqwl->kqwl_params;
4708 		if (trp.trp_flags && !(trp.trp_flags & TRP_RELEASED)) {
4709 			trp.trp_flags |= TRP_RELEASED;
4710 			kqwl->kqwl_params = trp.trp_value;
4711 			kqworkloop_release_live(kqwl);
4712 		} else {
4713 			error = EINVAL;
4714 		}
4715 		kqunlock(kqwl);
4716 		kqworkloop_release(kqwl);
4717 		break;
4718 	}
4719 	*retval = 0;
4720 	return error;
4721 }
4722 
4723 int
kqueue_workloop_ctl(proc_t p,struct kqueue_workloop_ctl_args * uap,int * retval)4724 kqueue_workloop_ctl(proc_t p, struct kqueue_workloop_ctl_args *uap, int *retval)
4725 {
4726 	struct kqueue_workloop_params params = {
4727 		.kqwlp_id = 0,
4728 	};
4729 	if (uap->sz < sizeof(params.kqwlp_version)) {
4730 		return EINVAL;
4731 	}
4732 
4733 	size_t copyin_sz = MIN(sizeof(params), uap->sz);
4734 	int rv = copyin(uap->addr, &params, copyin_sz);
4735 	if (rv) {
4736 		return rv;
4737 	}
4738 
4739 	if (params.kqwlp_version != (int)uap->sz) {
4740 		return EINVAL;
4741 	}
4742 
4743 	return kqueue_workloop_ctl_internal(p, uap->cmd, uap->options, &params,
4744 	           retval);
4745 }
4746 
4747 static int
kqueue_select(struct fileproc * fp,int which,void * wql,__unused vfs_context_t ctx)4748 kqueue_select(struct fileproc *fp, int which, void *wql, __unused vfs_context_t ctx)
4749 {
4750 	struct kqfile *kq = (struct kqfile *)fp_get_data(fp);
4751 	int retnum = 0;
4752 
4753 	assert((kq->kqf_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0);
4754 
4755 	if (which == FREAD) {
4756 		kqlock(kq);
4757 		if (kqfile_begin_processing(kq) == 0) {
4758 			retnum = kq->kqf_count;
4759 			kqfile_end_processing(kq);
4760 		} else if ((kq->kqf_state & KQ_DRAIN) == 0) {
4761 			selrecord(kq->kqf_p, &kq->kqf_sel, wql);
4762 		}
4763 		kqunlock(kq);
4764 	}
4765 	return retnum;
4766 }
4767 
4768 /*
4769  * kqueue_close -
4770  */
4771 static int
kqueue_close(struct fileglob * fg,__unused vfs_context_t ctx)4772 kqueue_close(struct fileglob *fg, __unused vfs_context_t ctx)
4773 {
4774 	struct kqfile *kqf = fg_get_data(fg);
4775 
4776 	assert((kqf->kqf_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0);
4777 	kqlock(kqf);
4778 	selthreadclear(&kqf->kqf_sel);
4779 	kqunlock(kqf);
4780 	kqueue_dealloc(&kqf->kqf_kqueue);
4781 	fg_set_data(fg, NULL);
4782 	return 0;
4783 }
4784 
4785 /*
4786  * Max depth of the nested kq path that can be created.
4787  * Note that this has to be less than the size of kq_level
4788  * to avoid wrapping around and mislabeling the level.
4789  */
4790 #define MAX_NESTED_KQ 1000
4791 
4792 /*
4793  * The callers has taken a use-count reference on this kqueue and will donate it
4794  * to the kqueue we are being added to.  This keeps the kqueue from closing until
4795  * that relationship is torn down.
4796  */
4797 static int
kqueue_kqfilter(struct fileproc * fp,struct knote * kn,__unused struct kevent_qos_s * kev)4798 kqueue_kqfilter(struct fileproc *fp, struct knote *kn,
4799     __unused struct kevent_qos_s *kev)
4800 {
4801 	struct kqfile *kqf = (struct kqfile *)fp_get_data(fp);
4802 	struct kqueue *kq = &kqf->kqf_kqueue;
4803 	struct kqueue *parentkq = knote_get_kq(kn);
4804 
4805 	assert((kqf->kqf_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0);
4806 
4807 	if (parentkq == kq || kn->kn_filter != EVFILT_READ) {
4808 		knote_set_error(kn, EINVAL);
4809 		return 0;
4810 	}
4811 
4812 	/*
4813 	 * We have to avoid creating a cycle when nesting kqueues
4814 	 * inside another.  Rather than trying to walk the whole
4815 	 * potential DAG of nested kqueues, we just use a simple
4816 	 * ceiling protocol.  When a kqueue is inserted into another,
4817 	 * we check that the (future) parent is not already nested
4818 	 * into another kqueue at a lower level than the potenial
4819 	 * child (because it could indicate a cycle).  If that test
4820 	 * passes, we just mark the nesting levels accordingly.
4821 	 *
4822 	 * Only up to MAX_NESTED_KQ can be nested.
4823 	 *
4824 	 * Note: kqworkq and kqworkloop cannot be nested and have reused their
4825 	 *       kq_level field, so ignore these as parent.
4826 	 */
4827 
4828 	kqlock(parentkq);
4829 
4830 	if ((parentkq->kq_state & (KQ_WORKQ | KQ_WORKLOOP)) == 0) {
4831 		if (parentkq->kq_level > 0 &&
4832 		    parentkq->kq_level < kq->kq_level) {
4833 			kqunlock(parentkq);
4834 			knote_set_error(kn, EINVAL);
4835 			return 0;
4836 		}
4837 
4838 		/* set parent level appropriately */
4839 		uint16_t plevel = (parentkq->kq_level == 0)? 2: parentkq->kq_level;
4840 		if (plevel < kq->kq_level + 1) {
4841 			if (kq->kq_level + 1 > MAX_NESTED_KQ) {
4842 				kqunlock(parentkq);
4843 				knote_set_error(kn, EINVAL);
4844 				return 0;
4845 			}
4846 			plevel = kq->kq_level + 1;
4847 		}
4848 
4849 		parentkq->kq_level = plevel;
4850 	}
4851 
4852 	kqunlock(parentkq);
4853 
4854 	kn->kn_filtid = EVFILTID_KQREAD;
4855 	kqlock(kq);
4856 	KNOTE_ATTACH(&kqf->kqf_sel.si_note, kn);
4857 	/* indicate nesting in child, if needed */
4858 	if (kq->kq_level == 0) {
4859 		kq->kq_level = 1;
4860 	}
4861 
4862 	int count = kq->kq_count;
4863 	kqunlock(kq);
4864 	return count > 0;
4865 }
4866 
4867 __attribute__((noinline))
4868 static void
kqfile_wakeup(struct kqfile * kqf,long hint,wait_result_t wr)4869 kqfile_wakeup(struct kqfile *kqf, long hint, wait_result_t wr)
4870 {
4871 	/* wakeup a thread waiting on this queue */
4872 	selwakeup(&kqf->kqf_sel);
4873 
4874 	/* wake up threads in kqueue_scan() */
4875 	if (kqf->kqf_state & KQ_SLEEP) {
4876 		kqf->kqf_state &= ~KQ_SLEEP;
4877 		thread_wakeup_with_result(&kqf->kqf_count, wr);
4878 	}
4879 
4880 	if (hint == NOTE_REVOKE) {
4881 		/* wakeup threads waiting their turn to process */
4882 		if (kqf->kqf_state & KQ_PROCWAIT) {
4883 			assert(kqf->kqf_state & KQ_PROCESSING);
4884 			kqf->kqf_state &= ~KQ_PROCWAIT;
4885 			thread_wakeup(&kqf->kqf_suppressed);
4886 		}
4887 
4888 		/* no need to KNOTE: knote_fdclose() takes care of it */
4889 	} else {
4890 		/* wakeup other kqueues/select sets we're inside */
4891 		KNOTE(&kqf->kqf_sel.si_note, hint);
4892 	}
4893 }
4894 
4895 /*
4896  * kqueue_drain - called when kq is closed
4897  */
4898 static int
kqueue_drain(struct fileproc * fp,__unused vfs_context_t ctx)4899 kqueue_drain(struct fileproc *fp, __unused vfs_context_t ctx)
4900 {
4901 	struct kqfile *kqf = (struct kqfile *)fp_get_data(fp);
4902 
4903 	assert((kqf->kqf_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0);
4904 
4905 	kqlock(kqf);
4906 	kqf->kqf_state |= KQ_DRAIN;
4907 	kqfile_wakeup(kqf, NOTE_REVOKE, THREAD_RESTART);
4908 	kqunlock(kqf);
4909 	return 0;
4910 }
4911 
4912 int
kqueue_stat(struct kqueue * kq,void * ub,int isstat64,proc_t p)4913 kqueue_stat(struct kqueue *kq, void *ub, int isstat64, proc_t p)
4914 {
4915 	assert((kq->kq_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0);
4916 
4917 	kqlock(kq);
4918 	if (isstat64 != 0) {
4919 		struct stat64 *sb64 = (struct stat64 *)ub;
4920 
4921 		bzero((void *)sb64, sizeof(*sb64));
4922 		sb64->st_size = kq->kq_count;
4923 		if (kq->kq_state & KQ_KEV_QOS) {
4924 			sb64->st_blksize = sizeof(struct kevent_qos_s);
4925 		} else if (kq->kq_state & KQ_KEV64) {
4926 			sb64->st_blksize = sizeof(struct kevent64_s);
4927 		} else if (IS_64BIT_PROCESS(p)) {
4928 			sb64->st_blksize = sizeof(struct user64_kevent);
4929 		} else {
4930 			sb64->st_blksize = sizeof(struct user32_kevent);
4931 		}
4932 		sb64->st_mode = S_IFIFO;
4933 	} else {
4934 		struct stat *sb = (struct stat *)ub;
4935 
4936 		bzero((void *)sb, sizeof(*sb));
4937 		sb->st_size = kq->kq_count;
4938 		if (kq->kq_state & KQ_KEV_QOS) {
4939 			sb->st_blksize = sizeof(struct kevent_qos_s);
4940 		} else if (kq->kq_state & KQ_KEV64) {
4941 			sb->st_blksize = sizeof(struct kevent64_s);
4942 		} else if (IS_64BIT_PROCESS(p)) {
4943 			sb->st_blksize = sizeof(struct user64_kevent);
4944 		} else {
4945 			sb->st_blksize = sizeof(struct user32_kevent);
4946 		}
4947 		sb->st_mode = S_IFIFO;
4948 	}
4949 	kqunlock(kq);
4950 	return 0;
4951 }
4952 
4953 static inline bool
kqueue_threadreq_can_use_ast(struct kqueue * kq)4954 kqueue_threadreq_can_use_ast(struct kqueue *kq)
4955 {
4956 	if (current_proc() == kq->kq_p) {
4957 		/*
4958 		 * Setting an AST from a non BSD syscall is unsafe: mach_msg_trap() can
4959 		 * do combined send/receive and in the case of self-IPC, the AST may bet
4960 		 * set on a thread that will not return to userspace and needs the
4961 		 * thread the AST would create to unblock itself.
4962 		 *
4963 		 * At this time, we really want to target:
4964 		 *
4965 		 * - kevent variants that can cause thread creations, and dispatch
4966 		 *   really only uses kevent_qos and kevent_id,
4967 		 *
4968 		 * - workq_kernreturn (directly about thread creations)
4969 		 *
4970 		 * - bsdthread_ctl which is used for qos changes and has direct impact
4971 		 *   on the creator thread scheduling decisions.
4972 		 */
4973 		switch (current_uthread()->syscall_code) {
4974 		case SYS_kevent_qos:
4975 		case SYS_kevent_id:
4976 		case SYS_workq_kernreturn:
4977 		case SYS_bsdthread_ctl:
4978 			return true;
4979 		}
4980 	}
4981 	return false;
4982 }
4983 
4984 /*
4985  * Interact with the pthread kext to request a servicing there at a specific QoS
4986  * level.
4987  *
4988  * - Caller holds the kqlock
4989  *
4990  * - May be called with the kqueue's wait queue set locked,
4991  *   so cannot do anything that could recurse on that.
4992  */
4993 static void
kqueue_threadreq_initiate(kqueue_t kqu,workq_threadreq_t kqr,kq_index_t qos,int flags)4994 kqueue_threadreq_initiate(kqueue_t kqu, workq_threadreq_t kqr,
4995     kq_index_t qos, int flags)
4996 {
4997 	assert(kqr_thread(kqr) == THREAD_NULL);
4998 	assert(!kqr_thread_requested(kqr));
4999 	struct turnstile *ts = TURNSTILE_NULL;
5000 
5001 	if (workq_is_exiting(kqu.kq->kq_p)) {
5002 		return;
5003 	}
5004 
5005 	kqlock_held(kqu);
5006 
5007 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5008 		struct kqworkloop *kqwl = kqu.kqwl;
5009 
5010 		assert(kqwl->kqwl_owner == THREAD_NULL);
5011 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_THREQUEST),
5012 		    kqwl->kqwl_dynamicid, 0, qos, kqwl->kqwl_wakeup_qos);
5013 		ts = kqwl->kqwl_turnstile;
5014 		/* Add a thread request reference on the kqueue. */
5015 		kqworkloop_retain(kqwl);
5016 
5017 #if CONFIG_PREADOPT_TG
5018 		/* This thread is the one which is ack-ing the thread group on the kqwl
5019 		 * under the kqlock and will take action accordingly, pairs with the
5020 		 * release barrier in kqueue_set_preadopted_thread_group */
5021 		uint16_t tg_acknowledged;
5022 		if (os_atomic_cmpxchgv(&kqwl->kqwl_preadopt_tg_needs_redrive,
5023 		    KQWL_PREADOPT_TG_NEEDS_REDRIVE, KQWL_PREADOPT_TG_CLEAR_REDRIVE,
5024 		    &tg_acknowledged, acquire)) {
5025 			flags |= WORKQ_THREADREQ_REEVALUATE_PREADOPT_TG;
5026 		}
5027 #endif
5028 	} else {
5029 		assert(kqu.kq->kq_state & KQ_WORKQ);
5030 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWQ_THREQUEST), -1, 0, qos,
5031 		    !TAILQ_EMPTY(&kqu.kqwq->kqwq_queue[kqr->tr_kq_qos_index - 1]));
5032 	}
5033 
5034 	/*
5035 	 * New-style thread request supported.
5036 	 * Provide the pthread kext a pointer to a workq_threadreq_s structure for
5037 	 * its use until a corresponding kqueue_threadreq_bind callback.
5038 	 */
5039 	if (kqueue_threadreq_can_use_ast(kqu.kq)) {
5040 		flags |= WORKQ_THREADREQ_SET_AST_ON_FAILURE;
5041 	}
5042 	if (qos == KQWQ_QOS_MANAGER) {
5043 		qos = WORKQ_THREAD_QOS_MANAGER;
5044 	}
5045 
5046 	if (!workq_kern_threadreq_initiate(kqu.kq->kq_p, kqr, ts, qos, flags)) {
5047 		/*
5048 		 * Process is shutting down or exec'ing.
5049 		 * All the kqueues are going to be cleaned up
5050 		 * soon. Forget we even asked for a thread -
5051 		 * and make sure we don't ask for more.
5052 		 */
5053 		kqu.kq->kq_state &= ~KQ_R2K_ARMED;
5054 		kqueue_release_live(kqu);
5055 	}
5056 }
5057 
5058 /*
5059  * kqueue_threadreq_bind_prepost - prepost the bind to kevent
5060  *
5061  * This is used when kqueue_threadreq_bind may cause a lock inversion.
5062  */
5063 __attribute__((always_inline))
5064 void
kqueue_threadreq_bind_prepost(struct proc * p __unused,workq_threadreq_t kqr,struct uthread * ut)5065 kqueue_threadreq_bind_prepost(struct proc *p __unused, workq_threadreq_t kqr,
5066     struct uthread *ut)
5067 {
5068 	ut->uu_kqr_bound = kqr;
5069 	kqr->tr_thread = get_machthread(ut);
5070 	kqr->tr_state = WORKQ_TR_STATE_BINDING;
5071 }
5072 
5073 /*
5074  * kqueue_threadreq_bind_commit - commit a bind prepost
5075  *
5076  * The workq code has to commit any binding prepost before the thread has
5077  * a chance to come back to userspace (and do kevent syscalls) or be aborted.
5078  */
5079 void
kqueue_threadreq_bind_commit(struct proc * p,thread_t thread)5080 kqueue_threadreq_bind_commit(struct proc *p, thread_t thread)
5081 {
5082 	struct uthread *ut = get_bsdthread_info(thread);
5083 	workq_threadreq_t kqr = ut->uu_kqr_bound;
5084 	kqueue_t kqu = kqr_kqueue(p, kqr);
5085 
5086 	kqlock(kqu);
5087 	if (kqr->tr_state == WORKQ_TR_STATE_BINDING) {
5088 		kqueue_threadreq_bind(p, kqr, thread, 0);
5089 	}
5090 	kqunlock(kqu);
5091 }
5092 
5093 static void
kqueue_threadreq_modify(kqueue_t kqu,workq_threadreq_t kqr,kq_index_t qos,workq_kern_threadreq_flags_t flags)5094 kqueue_threadreq_modify(kqueue_t kqu, workq_threadreq_t kqr, kq_index_t qos,
5095     workq_kern_threadreq_flags_t flags)
5096 {
5097 	assert(kqr_thread_requested_pending(kqr));
5098 
5099 	kqlock_held(kqu);
5100 
5101 	if (kqueue_threadreq_can_use_ast(kqu.kq)) {
5102 		flags |= WORKQ_THREADREQ_SET_AST_ON_FAILURE;
5103 	}
5104 
5105 #if CONFIG_PREADOPT_TG
5106 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5107 		uint16_t tg_ack_status;
5108 		struct kqworkloop *kqwl = kqu.kqwl;
5109 
5110 		/* This thread is the one which is ack-ing the thread group on the kqwl
5111 		 * under the kqlock and will take action accordingly, needs acquire
5112 		 * barrier */
5113 		if (os_atomic_cmpxchgv(&kqwl->kqwl_preadopt_tg_needs_redrive, KQWL_PREADOPT_TG_NEEDS_REDRIVE,
5114 		    KQWL_PREADOPT_TG_CLEAR_REDRIVE, &tg_ack_status, acquire)) {
5115 			flags |= WORKQ_THREADREQ_REEVALUATE_PREADOPT_TG;
5116 		}
5117 	}
5118 #endif
5119 
5120 	workq_kern_threadreq_modify(kqu.kq->kq_p, kqr, qos, flags);
5121 }
5122 
5123 /*
5124  * kqueue_threadreq_bind - bind thread to processing kqrequest
5125  *
5126  * The provided thread will be responsible for delivering events
5127  * associated with the given kqrequest.  Bind it and get ready for
5128  * the thread to eventually arrive.
5129  */
5130 void
kqueue_threadreq_bind(struct proc * p,workq_threadreq_t kqr,thread_t thread,unsigned int flags)5131 kqueue_threadreq_bind(struct proc *p, workq_threadreq_t kqr, thread_t thread,
5132     unsigned int flags)
5133 {
5134 	kqueue_t kqu = kqr_kqueue(p, kqr);
5135 	struct uthread *ut = get_bsdthread_info(thread);
5136 
5137 	kqlock_held(kqu);
5138 
5139 	assert(ut->uu_kqueue_override == 0);
5140 
5141 	if (kqr->tr_state == WORKQ_TR_STATE_BINDING) {
5142 		assert(ut->uu_kqr_bound == kqr);
5143 		assert(kqr->tr_thread == thread);
5144 	} else {
5145 		assert(kqr_thread_requested_pending(kqr));
5146 		assert(kqr->tr_thread == THREAD_NULL);
5147 		assert(ut->uu_kqr_bound == NULL);
5148 		ut->uu_kqr_bound = kqr;
5149 		kqr->tr_thread = thread;
5150 	}
5151 
5152 	kqr->tr_state = WORKQ_TR_STATE_BOUND;
5153 
5154 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5155 		struct turnstile *ts = kqu.kqwl->kqwl_turnstile;
5156 
5157 		if (__improbable(thread == kqu.kqwl->kqwl_owner)) {
5158 			/*
5159 			 * <rdar://problem/38626999> shows that asserting here is not ok.
5160 			 *
5161 			 * This is not supposed to happen for correct use of the interface,
5162 			 * but it is sadly possible for userspace (with the help of memory
5163 			 * corruption, such as over-release of a dispatch queue) to make
5164 			 * the creator thread the "owner" of a workloop.
5165 			 *
5166 			 * Once that happens, and that creator thread picks up the same
5167 			 * workloop as a servicer, we trip this codepath. We need to fixup
5168 			 * the state to forget about this thread being the owner, as the
5169 			 * entire workloop state machine expects servicers to never be
5170 			 * owners and everything would basically go downhill from here.
5171 			 */
5172 			kqu.kqwl->kqwl_owner = THREAD_NULL;
5173 			if (kqworkloop_override(kqu.kqwl)) {
5174 				thread_drop_kevent_override(thread);
5175 			}
5176 		}
5177 
5178 		if (ts && (flags & KQUEUE_THREADERQ_BIND_NO_INHERITOR_UPDATE) == 0) {
5179 			/*
5180 			 * Past this point, the interlock is the kq req lock again,
5181 			 * so we can fix the inheritor for good.
5182 			 */
5183 			filt_wlupdate_inheritor(kqu.kqwl, ts, TURNSTILE_IMMEDIATE_UPDATE);
5184 			turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_HELD);
5185 		}
5186 
5187 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_BIND), kqu.kqwl->kqwl_dynamicid,
5188 		    thread_tid(thread), kqr->tr_kq_qos_index,
5189 		    (kqr->tr_kq_override_index << 16) | kqwl->kqwl_wakeup_qos);
5190 
5191 		ut->uu_kqueue_override = kqr->tr_kq_override_index;
5192 		if (kqr->tr_kq_override_index) {
5193 			thread_add_servicer_override(thread, kqr->tr_kq_override_index);
5194 		}
5195 
5196 #if CONFIG_PREADOPT_TG
5197 		/* Remove reference from kqwl and mark it as bound with the SENTINEL */
5198 		thread_group_qos_t old_tg;
5199 		thread_group_qos_t new_tg;
5200 		int ret = os_atomic_rmw_loop(kqr_preadopt_thread_group_addr(kqr), old_tg, new_tg, relaxed, {
5201 			if (old_tg == KQWL_PREADOPTED_TG_NEVER) {
5202 			        os_atomic_rmw_loop_give_up(break); // It's an app, nothing to do
5203 			}
5204 			assert(old_tg != KQWL_PREADOPTED_TG_PROCESSED);
5205 			new_tg = KQWL_PREADOPTED_TG_SENTINEL;
5206 		});
5207 
5208 		if (ret) {
5209 			KQWL_PREADOPT_TG_HISTORY_WRITE_ENTRY(kqu.kqwl, KQWL_PREADOPT_OP_SERVICER_BIND, old_tg, new_tg);
5210 
5211 			if (KQWL_HAS_VALID_PREADOPTED_TG(old_tg)) {
5212 				struct thread_group *tg = KQWL_GET_PREADOPTED_TG(old_tg);
5213 				assert(tg != NULL);
5214 
5215 				thread_set_preadopt_thread_group(thread, tg);
5216 				thread_group_release_live(tg); // The thread has a reference
5217 			} else {
5218 				/*
5219 				 * The thread may already have a preadopt thread group on it -
5220 				 * we need to make sure to clear that.
5221 				 */
5222 				thread_set_preadopt_thread_group(thread, NULL);
5223 			}
5224 
5225 			/* We have taken action on the preadopted thread group set on the
5226 			 * set on the kqwl, clear any redrive requests */
5227 			os_atomic_store(&kqu.kqwl->kqwl_preadopt_tg_needs_redrive, KQWL_PREADOPT_TG_CLEAR_REDRIVE, relaxed);
5228 		}
5229 #endif
5230 		kqueue_update_iotier_override(kqu);
5231 	} else {
5232 		assert(kqr->tr_kq_override_index == 0);
5233 
5234 #if CONFIG_PREADOPT_TG
5235 		/*
5236 		 * The thread may have a preadopt thread group on it already because it
5237 		 * got tagged with it as a creator thread. So we need to make sure to
5238 		 * clear that since we don't have preadopt thread groups for non-kqwl
5239 		 * cases
5240 		 */
5241 		thread_set_preadopt_thread_group(thread, NULL);
5242 #endif
5243 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWQ_BIND), -1,
5244 		    thread_tid(thread), kqr->tr_kq_qos_index,
5245 		    (kqr->tr_kq_override_index << 16) |
5246 		    !TAILQ_EMPTY(&kqu.kqwq->kqwq_queue[kqr->tr_kq_qos_index - 1]));
5247 	}
5248 }
5249 
5250 /*
5251  * kqueue_threadreq_cancel - abort a pending thread request
5252  *
5253  * Called when exiting/exec'ing. Forget our pending request.
5254  */
5255 void
kqueue_threadreq_cancel(struct proc * p,workq_threadreq_t kqr)5256 kqueue_threadreq_cancel(struct proc *p, workq_threadreq_t kqr)
5257 {
5258 	kqueue_release(kqr_kqueue(p, kqr));
5259 }
5260 
5261 workq_threadreq_param_t
kqueue_threadreq_workloop_param(workq_threadreq_t kqr)5262 kqueue_threadreq_workloop_param(workq_threadreq_t kqr)
5263 {
5264 	struct kqworkloop *kqwl;
5265 	workq_threadreq_param_t trp;
5266 
5267 	assert(kqr->tr_flags & WORKQ_TR_FLAG_WORKLOOP);
5268 	kqwl = __container_of(kqr, struct kqworkloop, kqwl_request);
5269 	trp.trp_value = kqwl->kqwl_params;
5270 	return trp;
5271 }
5272 
5273 /*
5274  *	kqueue_threadreq_unbind - unbind thread from processing kqueue
5275  *
5276  *	End processing the per-QoS bucket of events and allow other threads
5277  *	to be requested for future servicing.
5278  *
5279  *	caller holds a reference on the kqueue.
5280  */
5281 void
kqueue_threadreq_unbind(struct proc * p,workq_threadreq_t kqr)5282 kqueue_threadreq_unbind(struct proc *p, workq_threadreq_t kqr)
5283 {
5284 	if (kqr->tr_flags & WORKQ_TR_FLAG_WORKLOOP) {
5285 		kqworkloop_unbind(kqr_kqworkloop(kqr));
5286 	} else {
5287 		kqworkq_unbind(p, kqr);
5288 	}
5289 }
5290 
5291 /*
5292  * If we aren't already busy processing events [for this QoS],
5293  * request workq thread support as appropriate.
5294  *
5295  * TBD - for now, we don't segregate out processing by QoS.
5296  *
5297  * - May be called with the kqueue's wait queue set locked,
5298  *   so cannot do anything that could recurse on that.
5299  */
5300 static void
kqworkq_wakeup(struct kqworkq * kqwq,kq_index_t qos_index)5301 kqworkq_wakeup(struct kqworkq *kqwq, kq_index_t qos_index)
5302 {
5303 	workq_threadreq_t kqr = kqworkq_get_request(kqwq, qos_index);
5304 
5305 	/* convert to thread qos value */
5306 	assert(qos_index > 0 && qos_index <= KQWQ_NBUCKETS);
5307 
5308 	if (!kqr_thread_requested(kqr)) {
5309 		kqueue_threadreq_initiate(&kqwq->kqwq_kqueue, kqr, qos_index, 0);
5310 	}
5311 }
5312 
5313 /*
5314  * This represent the asynchronous QoS a given workloop contributes,
5315  * hence is the max of the current active knotes (override index)
5316  * and the workloop max qos (userspace async qos).
5317  */
5318 static kq_index_t
kqworkloop_override(struct kqworkloop * kqwl)5319 kqworkloop_override(struct kqworkloop *kqwl)
5320 {
5321 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5322 	return MAX(kqr->tr_kq_qos_index, kqr->tr_kq_override_index);
5323 }
5324 
5325 static inline void
kqworkloop_request_fire_r2k_notification(struct kqworkloop * kqwl)5326 kqworkloop_request_fire_r2k_notification(struct kqworkloop *kqwl)
5327 {
5328 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5329 
5330 	kqlock_held(kqwl);
5331 
5332 	if (kqwl->kqwl_state & KQ_R2K_ARMED) {
5333 		kqwl->kqwl_state &= ~KQ_R2K_ARMED;
5334 		act_set_astkevent(kqr_thread_fast(kqr), AST_KEVENT_RETURN_TO_KERNEL);
5335 	}
5336 }
5337 
5338 static void
kqworkloop_update_threads_qos(struct kqworkloop * kqwl,int op,kq_index_t qos)5339 kqworkloop_update_threads_qos(struct kqworkloop *kqwl, int op, kq_index_t qos)
5340 {
5341 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5342 	struct kqueue *kq = &kqwl->kqwl_kqueue;
5343 	kq_index_t old_override = kqworkloop_override(kqwl);
5344 
5345 	kqlock_held(kqwl);
5346 
5347 	switch (op) {
5348 	case KQWL_UTQ_UPDATE_WAKEUP_QOS:
5349 		kqwl->kqwl_wakeup_qos = qos;
5350 		kqworkloop_request_fire_r2k_notification(kqwl);
5351 		goto recompute;
5352 
5353 	case KQWL_UTQ_RESET_WAKEUP_OVERRIDE:
5354 		kqr->tr_kq_override_index = qos;
5355 		goto recompute;
5356 
5357 	case KQWL_UTQ_PARKING:
5358 	case KQWL_UTQ_UNBINDING:
5359 		kqr->tr_kq_override_index = qos;
5360 		OS_FALLTHROUGH;
5361 
5362 	case KQWL_UTQ_RECOMPUTE_WAKEUP_QOS:
5363 		if (op == KQWL_UTQ_RECOMPUTE_WAKEUP_QOS) {
5364 			assert(qos == THREAD_QOS_UNSPECIFIED);
5365 		}
5366 		if (TAILQ_EMPTY(&kqwl->kqwl_suppressed)) {
5367 			kqr->tr_kq_override_index = THREAD_QOS_UNSPECIFIED;
5368 		}
5369 		kqwl->kqwl_wakeup_qos = 0;
5370 		for (kq_index_t i = KQWL_NBUCKETS; i > 0; i--) {
5371 			if (!TAILQ_EMPTY(&kqwl->kqwl_queue[i - 1])) {
5372 				kqwl->kqwl_wakeup_qos = i;
5373 				kqworkloop_request_fire_r2k_notification(kqwl);
5374 				break;
5375 			}
5376 		}
5377 		OS_FALLTHROUGH;
5378 
5379 	case KQWL_UTQ_UPDATE_WAKEUP_OVERRIDE:
5380 recompute:
5381 		/*
5382 		 * When modifying the wakeup QoS or the override QoS, we always need to
5383 		 * maintain our invariant that kqr_override_index is at least as large
5384 		 * as the highest QoS for which an event is fired.
5385 		 *
5386 		 * However this override index can be larger when there is an overriden
5387 		 * suppressed knote pushing on the kqueue.
5388 		 */
5389 		if (qos < kqwl->kqwl_wakeup_qos) {
5390 			qos = kqwl->kqwl_wakeup_qos;
5391 		}
5392 		if (kqr->tr_kq_override_index < qos) {
5393 			kqr->tr_kq_override_index = qos;
5394 		}
5395 		break;
5396 
5397 	case KQWL_UTQ_REDRIVE_EVENTS:
5398 		break;
5399 
5400 	case KQWL_UTQ_SET_QOS_INDEX:
5401 		kqr->tr_kq_qos_index = qos;
5402 		break;
5403 
5404 	default:
5405 		panic("unknown kqwl thread qos update operation: %d", op);
5406 	}
5407 
5408 	thread_t kqwl_owner = kqwl->kqwl_owner;
5409 	thread_t servicer = kqr_thread(kqr);
5410 	boolean_t qos_changed = FALSE;
5411 	kq_index_t new_override = kqworkloop_override(kqwl);
5412 
5413 	/*
5414 	 * Apply the diffs to the owner if applicable
5415 	 */
5416 	if (kqwl_owner) {
5417 #if 0
5418 		/* JMM - need new trace hooks for owner overrides */
5419 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_THADJUST),
5420 		    kqwl->kqwl_dynamicid, thread_tid(kqwl_owner), kqr->tr_kq_qos_index,
5421 		    (kqr->tr_kq_override_index << 16) | kqwl->kqwl_wakeup_qos);
5422 #endif
5423 		if (new_override == old_override) {
5424 			// nothing to do
5425 		} else if (old_override == THREAD_QOS_UNSPECIFIED) {
5426 			thread_add_kevent_override(kqwl_owner, new_override);
5427 		} else if (new_override == THREAD_QOS_UNSPECIFIED) {
5428 			thread_drop_kevent_override(kqwl_owner);
5429 		} else { /*  old_override != new_override */
5430 			thread_update_kevent_override(kqwl_owner, new_override);
5431 		}
5432 	}
5433 
5434 	/*
5435 	 * apply the diffs to the servicer
5436 	 */
5437 
5438 	if (!kqr_thread_requested(kqr)) {
5439 		/*
5440 		 * No servicer, nor thread-request
5441 		 *
5442 		 * Make a new thread request, unless there is an owner (or the workloop
5443 		 * is suspended in userland) or if there is no asynchronous work in the
5444 		 * first place.
5445 		 */
5446 
5447 		if (kqwl_owner == NULL && kqwl->kqwl_wakeup_qos) {
5448 			int initiate_flags = 0;
5449 			if (op == KQWL_UTQ_UNBINDING) {
5450 				initiate_flags = WORKQ_THREADREQ_ATTEMPT_REBIND;
5451 			}
5452 
5453 			/* kqueue_threadreq_initiate handles the acknowledgement of the TG
5454 			 * if needed */
5455 			kqueue_threadreq_initiate(kq, kqr, new_override, initiate_flags);
5456 		}
5457 	} else if (servicer) {
5458 		/*
5459 		 * Servicer in flight
5460 		 *
5461 		 * Just apply the diff to the servicer
5462 		 */
5463 
5464 #if CONFIG_PREADOPT_TG
5465 		/* When there's a servicer for the kqwl already, then the servicer will
5466 		 * adopt the thread group in the kqr, we don't need to poke the
5467 		 * workqueue subsystem to make different decisions due to the thread
5468 		 * group. Consider the current request ack-ed.
5469 		 */
5470 		os_atomic_store(&kqwl->kqwl_preadopt_tg_needs_redrive, KQWL_PREADOPT_TG_CLEAR_REDRIVE, relaxed);
5471 #endif
5472 
5473 		struct uthread *ut = get_bsdthread_info(servicer);
5474 		if (ut->uu_kqueue_override != new_override) {
5475 			if (ut->uu_kqueue_override == THREAD_QOS_UNSPECIFIED) {
5476 				thread_add_servicer_override(servicer, new_override);
5477 			} else if (new_override == THREAD_QOS_UNSPECIFIED) {
5478 				thread_drop_servicer_override(servicer);
5479 			} else { /* ut->uu_kqueue_override != new_override */
5480 				thread_update_servicer_override(servicer, new_override);
5481 			}
5482 			ut->uu_kqueue_override = new_override;
5483 			qos_changed = TRUE;
5484 		}
5485 	} else if (new_override == THREAD_QOS_UNSPECIFIED) {
5486 		/*
5487 		 * No events to deliver anymore.
5488 		 *
5489 		 * However canceling with turnstiles is challenging, so the fact that
5490 		 * the request isn't useful will be discovered by the servicer himself
5491 		 * later on.
5492 		 */
5493 	} else if (old_override != new_override) {
5494 		/*
5495 		 * Request is in flight
5496 		 *
5497 		 * Apply the diff to the thread request.
5498 		 */
5499 		kqueue_threadreq_modify(kq, kqr, new_override, WORKQ_THREADREQ_NONE);
5500 		qos_changed = TRUE;
5501 	}
5502 
5503 	if (qos_changed) {
5504 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_THADJUST), kqwl->kqwl_dynamicid,
5505 		    thread_tid(servicer), kqr->tr_kq_qos_index,
5506 		    (kqr->tr_kq_override_index << 16) | kqwl->kqwl_wakeup_qos);
5507 	}
5508 }
5509 
5510 static void
kqworkloop_update_iotier_override(struct kqworkloop * kqwl)5511 kqworkloop_update_iotier_override(struct kqworkloop *kqwl)
5512 {
5513 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5514 	thread_t servicer = kqr_thread(kqr);
5515 	uint8_t iotier = os_atomic_load(&kqwl->kqwl_iotier_override, relaxed);
5516 
5517 	kqlock_held(kqwl);
5518 
5519 	if (servicer) {
5520 		thread_update_servicer_iotier_override(servicer, iotier);
5521 	}
5522 }
5523 
5524 static void
kqworkloop_wakeup(struct kqworkloop * kqwl,kq_index_t qos)5525 kqworkloop_wakeup(struct kqworkloop *kqwl, kq_index_t qos)
5526 {
5527 	if (qos <= kqwl->kqwl_wakeup_qos) {
5528 		/*
5529 		 * Shortcut wakeups that really do nothing useful
5530 		 */
5531 		return;
5532 	}
5533 
5534 	if ((kqwl->kqwl_state & KQ_PROCESSING) &&
5535 	    kqr_thread(&kqwl->kqwl_request) == current_thread()) {
5536 		/*
5537 		 * kqworkloop_end_processing() will perform the required QoS
5538 		 * computations when it unsets the processing mode.
5539 		 */
5540 		return;
5541 	}
5542 
5543 	kqworkloop_update_threads_qos(kqwl, KQWL_UTQ_UPDATE_WAKEUP_QOS, qos);
5544 }
5545 
5546 static struct kqtailq *
kqueue_get_suppressed_queue(kqueue_t kq,struct knote * kn)5547 kqueue_get_suppressed_queue(kqueue_t kq, struct knote *kn)
5548 {
5549 	if (kq.kq->kq_state & KQ_WORKLOOP) {
5550 		return &kq.kqwl->kqwl_suppressed;
5551 	} else if (kq.kq->kq_state & KQ_WORKQ) {
5552 		return &kq.kqwq->kqwq_suppressed[kn->kn_qos_index - 1];
5553 	} else {
5554 		return &kq.kqf->kqf_suppressed;
5555 	}
5556 }
5557 
5558 struct turnstile *
kqueue_alloc_turnstile(kqueue_t kqu)5559 kqueue_alloc_turnstile(kqueue_t kqu)
5560 {
5561 	struct kqworkloop *kqwl = kqu.kqwl;
5562 	kq_state_t kq_state;
5563 
5564 	kq_state = os_atomic_load(&kqu.kq->kq_state, dependency);
5565 	if (kq_state & KQ_HAS_TURNSTILE) {
5566 		/* force a dependency to pair with the atomic or with release below */
5567 		return os_atomic_load_with_dependency_on(&kqwl->kqwl_turnstile,
5568 		           (uintptr_t)kq_state);
5569 	}
5570 
5571 	if (!(kq_state & KQ_WORKLOOP)) {
5572 		return TURNSTILE_NULL;
5573 	}
5574 
5575 	struct turnstile *ts = turnstile_alloc(), *free_ts = TURNSTILE_NULL;
5576 	bool workq_locked = false;
5577 
5578 	kqlock(kqu);
5579 
5580 	if (filt_wlturnstile_interlock_is_workq(kqwl)) {
5581 		workq_locked = true;
5582 		workq_kern_threadreq_lock(kqwl->kqwl_p);
5583 	}
5584 
5585 	if (kqwl->kqwl_state & KQ_HAS_TURNSTILE) {
5586 		free_ts = ts;
5587 		ts = kqwl->kqwl_turnstile;
5588 	} else {
5589 		ts = turnstile_prepare((uintptr_t)kqwl, &kqwl->kqwl_turnstile,
5590 		    ts, TURNSTILE_WORKLOOPS);
5591 
5592 		/* release-barrier to pair with the unlocked load of kqwl_turnstile above */
5593 		os_atomic_or(&kqwl->kqwl_state, KQ_HAS_TURNSTILE, release);
5594 
5595 		if (filt_wlturnstile_interlock_is_workq(kqwl)) {
5596 			workq_kern_threadreq_update_inheritor(kqwl->kqwl_p,
5597 			    &kqwl->kqwl_request, kqwl->kqwl_owner,
5598 			    ts, TURNSTILE_IMMEDIATE_UPDATE);
5599 			/*
5600 			 * The workq may no longer be the interlock after this.
5601 			 * In which case the inheritor wasn't updated.
5602 			 */
5603 		}
5604 		if (!filt_wlturnstile_interlock_is_workq(kqwl)) {
5605 			filt_wlupdate_inheritor(kqwl, ts, TURNSTILE_IMMEDIATE_UPDATE);
5606 		}
5607 	}
5608 
5609 	if (workq_locked) {
5610 		workq_kern_threadreq_unlock(kqwl->kqwl_p);
5611 	}
5612 
5613 	kqunlock(kqu);
5614 
5615 	if (free_ts) {
5616 		turnstile_deallocate(free_ts);
5617 	} else {
5618 		turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_NOT_HELD);
5619 	}
5620 	return ts;
5621 }
5622 
5623 __attribute__((always_inline))
5624 struct turnstile *
kqueue_turnstile(kqueue_t kqu)5625 kqueue_turnstile(kqueue_t kqu)
5626 {
5627 	kq_state_t kq_state = os_atomic_load(&kqu.kq->kq_state, relaxed);
5628 	if (kq_state & KQ_WORKLOOP) {
5629 		return os_atomic_load(&kqu.kqwl->kqwl_turnstile, relaxed);
5630 	}
5631 	return TURNSTILE_NULL;
5632 }
5633 
5634 __attribute__((always_inline))
5635 struct turnstile *
kqueue_threadreq_get_turnstile(workq_threadreq_t kqr)5636 kqueue_threadreq_get_turnstile(workq_threadreq_t kqr)
5637 {
5638 	struct kqworkloop *kqwl = kqr_kqworkloop(kqr);
5639 	if (kqwl) {
5640 		return os_atomic_load(&kqwl->kqwl_turnstile, relaxed);
5641 	}
5642 	return TURNSTILE_NULL;
5643 }
5644 
5645 static void
kqworkloop_set_overcommit(struct kqworkloop * kqwl)5646 kqworkloop_set_overcommit(struct kqworkloop *kqwl)
5647 {
5648 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5649 
5650 	/*
5651 	 * This test is racy, but since we never remove this bit,
5652 	 * it allows us to avoid taking a lock.
5653 	 */
5654 	if (kqr->tr_flags & WORKQ_TR_FLAG_OVERCOMMIT) {
5655 		return;
5656 	}
5657 
5658 	kqlock_held(kqwl);
5659 
5660 	if (kqr_thread_requested_pending(kqr)) {
5661 		kqueue_threadreq_modify(kqwl, kqr, kqr->tr_qos,
5662 		    WORKQ_THREADREQ_MAKE_OVERCOMMIT);
5663 	} else {
5664 		kqr->tr_flags |= WORKQ_TR_FLAG_OVERCOMMIT;
5665 	}
5666 }
5667 
5668 static void
kqworkq_update_override(struct kqworkq * kqwq,struct knote * kn,kq_index_t override_index)5669 kqworkq_update_override(struct kqworkq *kqwq, struct knote *kn,
5670     kq_index_t override_index)
5671 {
5672 	workq_threadreq_t kqr;
5673 	kq_index_t old_override_index;
5674 	kq_index_t queue_index = kn->kn_qos_index;
5675 
5676 	if (override_index <= queue_index) {
5677 		return;
5678 	}
5679 
5680 	kqr = kqworkq_get_request(kqwq, queue_index);
5681 
5682 	kqlock_held(kqwq);
5683 
5684 	old_override_index = kqr->tr_kq_override_index;
5685 	if (override_index > MAX(kqr->tr_kq_qos_index, old_override_index)) {
5686 		thread_t servicer = kqr_thread(kqr);
5687 		kqr->tr_kq_override_index = override_index;
5688 
5689 		/* apply the override to [incoming?] servicing thread */
5690 		if (servicer) {
5691 			if (old_override_index) {
5692 				thread_update_kevent_override(servicer, override_index);
5693 			} else {
5694 				thread_add_kevent_override(servicer, override_index);
5695 			}
5696 		}
5697 	}
5698 }
5699 
5700 static void
kqueue_update_iotier_override(kqueue_t kqu)5701 kqueue_update_iotier_override(kqueue_t kqu)
5702 {
5703 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5704 		kqworkloop_update_iotier_override(kqu.kqwl);
5705 	}
5706 }
5707 
5708 static void
kqueue_update_override(kqueue_t kqu,struct knote * kn,thread_qos_t qos)5709 kqueue_update_override(kqueue_t kqu, struct knote *kn, thread_qos_t qos)
5710 {
5711 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5712 		kqworkloop_update_threads_qos(kqu.kqwl, KQWL_UTQ_UPDATE_WAKEUP_OVERRIDE,
5713 		    qos);
5714 	} else {
5715 		kqworkq_update_override(kqu.kqwq, kn, qos);
5716 	}
5717 }
5718 
5719 static void
kqworkloop_unbind_locked(struct kqworkloop * kqwl,thread_t thread,enum kqwl_unbind_locked_mode how)5720 kqworkloop_unbind_locked(struct kqworkloop *kqwl, thread_t thread,
5721     enum kqwl_unbind_locked_mode how)
5722 {
5723 	struct uthread *ut = get_bsdthread_info(thread);
5724 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5725 
5726 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_UNBIND), kqwl->kqwl_dynamicid,
5727 	    thread_tid(thread), 0, 0);
5728 
5729 	kqlock_held(kqwl);
5730 
5731 	assert(ut->uu_kqr_bound == kqr);
5732 	ut->uu_kqr_bound = NULL;
5733 	if (how == KQWL_OVERRIDE_DROP_IMMEDIATELY &&
5734 	    ut->uu_kqueue_override != THREAD_QOS_UNSPECIFIED) {
5735 		thread_drop_servicer_override(thread);
5736 		ut->uu_kqueue_override = THREAD_QOS_UNSPECIFIED;
5737 	}
5738 
5739 	if (kqwl->kqwl_owner == NULL && kqwl->kqwl_turnstile) {
5740 		turnstile_update_inheritor(kqwl->kqwl_turnstile,
5741 		    TURNSTILE_INHERITOR_NULL, TURNSTILE_IMMEDIATE_UPDATE);
5742 		turnstile_update_inheritor_complete(kqwl->kqwl_turnstile,
5743 		    TURNSTILE_INTERLOCK_HELD);
5744 	}
5745 
5746 #if CONFIG_PREADOPT_TG
5747 	/* The kqueue is able to adopt a thread group again */
5748 
5749 	thread_group_qos_t old_tg, new_tg = NULL;
5750 	int ret = os_atomic_rmw_loop(kqr_preadopt_thread_group_addr(kqr), old_tg, new_tg, relaxed, {
5751 		new_tg = old_tg;
5752 		if (old_tg == KQWL_PREADOPTED_TG_SENTINEL || old_tg == KQWL_PREADOPTED_TG_PROCESSED) {
5753 		        new_tg = KQWL_PREADOPTED_TG_NULL;
5754 		}
5755 	});
5756 	KQWL_PREADOPT_TG_HISTORY_WRITE_ENTRY(kqwl, KQWL_PREADOPT_OP_SERVICER_UNBIND, old_tg, KQWL_PREADOPTED_TG_NULL);
5757 
5758 	if (ret) {
5759 		// Servicer can drop any preadopt thread group it has since it has
5760 		// unbound.
5761 		thread_set_preadopt_thread_group(thread, NULL);
5762 	}
5763 #endif
5764 	thread_update_servicer_iotier_override(thread, THROTTLE_LEVEL_END);
5765 
5766 	kqr->tr_thread = THREAD_NULL;
5767 	kqr->tr_state = WORKQ_TR_STATE_IDLE;
5768 	kqwl->kqwl_state &= ~KQ_R2K_ARMED;
5769 }
5770 
5771 static void
kqworkloop_unbind_delayed_override_drop(thread_t thread)5772 kqworkloop_unbind_delayed_override_drop(thread_t thread)
5773 {
5774 	struct uthread *ut = get_bsdthread_info(thread);
5775 	assert(ut->uu_kqr_bound == NULL);
5776 	if (ut->uu_kqueue_override != THREAD_QOS_UNSPECIFIED) {
5777 		thread_drop_servicer_override(thread);
5778 		ut->uu_kqueue_override = THREAD_QOS_UNSPECIFIED;
5779 	}
5780 }
5781 
5782 /*
5783  *	kqworkloop_unbind - Unbind the servicer thread of a workloop kqueue
5784  *
5785  *	It will acknowledge events, and possibly request a new thread if:
5786  *	- there were active events left
5787  *	- we pended waitq hook callouts during processing
5788  *	- we pended wakeups while processing (or unsuppressing)
5789  *
5790  *	Called with kqueue lock held.
5791  */
5792 static void
kqworkloop_unbind(struct kqworkloop * kqwl)5793 kqworkloop_unbind(struct kqworkloop *kqwl)
5794 {
5795 	struct kqueue *kq = &kqwl->kqwl_kqueue;
5796 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5797 	thread_t thread = kqr_thread_fast(kqr);
5798 	int op = KQWL_UTQ_PARKING;
5799 	kq_index_t qos_override = THREAD_QOS_UNSPECIFIED;
5800 
5801 	assert(thread == current_thread());
5802 
5803 	kqlock(kqwl);
5804 
5805 	/*
5806 	 * Forcing the KQ_PROCESSING flag allows for QoS updates because of
5807 	 * unsuppressing knotes not to be applied until the eventual call to
5808 	 * kqworkloop_update_threads_qos() below.
5809 	 */
5810 	assert((kq->kq_state & KQ_PROCESSING) == 0);
5811 	if (!TAILQ_EMPTY(&kqwl->kqwl_suppressed)) {
5812 		kq->kq_state |= KQ_PROCESSING;
5813 		qos_override = kqworkloop_acknowledge_events(kqwl);
5814 		kq->kq_state &= ~KQ_PROCESSING;
5815 	}
5816 
5817 	kqworkloop_unbind_locked(kqwl, thread, KQWL_OVERRIDE_DROP_DELAYED);
5818 	kqworkloop_update_threads_qos(kqwl, op, qos_override);
5819 
5820 	kqunlock(kqwl);
5821 
5822 	/*
5823 	 * Drop the override on the current thread last, after the call to
5824 	 * kqworkloop_update_threads_qos above.
5825 	 */
5826 	kqworkloop_unbind_delayed_override_drop(thread);
5827 
5828 	/* If last reference, dealloc the workloop kq */
5829 	kqworkloop_release(kqwl);
5830 }
5831 
5832 static thread_qos_t
kqworkq_unbind_locked(struct kqworkq * kqwq,workq_threadreq_t kqr,thread_t thread)5833 kqworkq_unbind_locked(struct kqworkq *kqwq,
5834     workq_threadreq_t kqr, thread_t thread)
5835 {
5836 	struct uthread *ut = get_bsdthread_info(thread);
5837 	kq_index_t old_override = kqr->tr_kq_override_index;
5838 
5839 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWQ_UNBIND), -1,
5840 	    thread_tid(kqr_thread(kqr)), kqr->tr_kq_qos_index, 0);
5841 
5842 	kqlock_held(kqwq);
5843 
5844 	assert(ut->uu_kqr_bound == kqr);
5845 	ut->uu_kqr_bound = NULL;
5846 	kqr->tr_thread = THREAD_NULL;
5847 	kqr->tr_state = WORKQ_TR_STATE_IDLE;
5848 	kqr->tr_kq_override_index = THREAD_QOS_UNSPECIFIED;
5849 	kqwq->kqwq_state &= ~KQ_R2K_ARMED;
5850 
5851 	return old_override;
5852 }
5853 
5854 /*
5855  *	kqworkq_unbind - unbind of a workq kqueue from a thread
5856  *
5857  *	We may have to request new threads.
5858  *	This can happen there are no waiting processing threads and:
5859  *	- there were active events we never got to (count > 0)
5860  *	- we pended waitq hook callouts during processing
5861  *	- we pended wakeups while processing (or unsuppressing)
5862  */
5863 static void
kqworkq_unbind(proc_t p,workq_threadreq_t kqr)5864 kqworkq_unbind(proc_t p, workq_threadreq_t kqr)
5865 {
5866 	struct kqworkq *kqwq = (struct kqworkq *)p->p_fd.fd_wqkqueue;
5867 	__assert_only int rc;
5868 
5869 	kqlock(kqwq);
5870 	rc = kqworkq_acknowledge_events(kqwq, kqr, 0, KQWQAE_UNBIND);
5871 	assert(rc == -1);
5872 	kqunlock(kqwq);
5873 }
5874 
5875 workq_threadreq_t
kqworkq_get_request(struct kqworkq * kqwq,kq_index_t qos_index)5876 kqworkq_get_request(struct kqworkq *kqwq, kq_index_t qos_index)
5877 {
5878 	assert(qos_index > 0 && qos_index <= KQWQ_NBUCKETS);
5879 	return &kqwq->kqwq_request[qos_index - 1];
5880 }
5881 
5882 static void
knote_reset_priority(kqueue_t kqu,struct knote * kn,pthread_priority_t pp)5883 knote_reset_priority(kqueue_t kqu, struct knote *kn, pthread_priority_t pp)
5884 {
5885 	kq_index_t qos = _pthread_priority_thread_qos(pp);
5886 
5887 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5888 		assert((pp & _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG) == 0);
5889 		pp = _pthread_priority_normalize(pp);
5890 	} else if (kqu.kq->kq_state & KQ_WORKQ) {
5891 		if (qos == THREAD_QOS_UNSPECIFIED) {
5892 			/* On workqueues, outside of QoS means MANAGER */
5893 			qos = KQWQ_QOS_MANAGER;
5894 			pp = _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG;
5895 		} else {
5896 			pp = _pthread_priority_normalize(pp);
5897 		}
5898 	} else {
5899 		pp = _pthread_unspecified_priority();
5900 		qos = THREAD_QOS_UNSPECIFIED;
5901 	}
5902 
5903 	kn->kn_qos = (int32_t)pp;
5904 
5905 	if ((kn->kn_status & KN_MERGE_QOS) == 0 || qos > kn->kn_qos_override) {
5906 		/* Never lower QoS when in "Merge" mode */
5907 		kn->kn_qos_override = qos;
5908 	}
5909 
5910 	/* only adjust in-use qos index when not suppressed */
5911 	if (kn->kn_status & KN_SUPPRESSED) {
5912 		kqueue_update_override(kqu, kn, qos);
5913 	} else if (kn->kn_qos_index != qos) {
5914 		knote_dequeue(kqu, kn);
5915 		kn->kn_qos_index = qos;
5916 	}
5917 }
5918 
5919 static void
knote_adjust_qos(struct kqueue * kq,struct knote * kn,int result)5920 knote_adjust_qos(struct kqueue *kq, struct knote *kn, int result)
5921 {
5922 	thread_qos_t qos_index = (result >> FILTER_ADJUST_EVENT_QOS_SHIFT) & 7;
5923 
5924 	kqlock_held(kq);
5925 
5926 	assert(result & FILTER_ADJUST_EVENT_QOS_BIT);
5927 	assert(qos_index < THREAD_QOS_LAST);
5928 
5929 	/*
5930 	 * Early exit for knotes that should not change QoS
5931 	 */
5932 	if (__improbable(!knote_fops(kn)->f_adjusts_qos)) {
5933 		panic("filter %d cannot change QoS", kn->kn_filtid);
5934 	} else if (__improbable(!knote_has_qos(kn))) {
5935 		return;
5936 	}
5937 
5938 	/*
5939 	 * knotes with the FALLBACK flag will only use their registration QoS if the
5940 	 * incoming event has no QoS, else, the registration QoS acts as a floor.
5941 	 */
5942 	thread_qos_t req_qos = _pthread_priority_thread_qos_fast(kn->kn_qos);
5943 	if (kn->kn_qos & _PTHREAD_PRIORITY_FALLBACK_FLAG) {
5944 		if (qos_index == THREAD_QOS_UNSPECIFIED) {
5945 			qos_index = req_qos;
5946 		}
5947 	} else {
5948 		if (qos_index < req_qos) {
5949 			qos_index = req_qos;
5950 		}
5951 	}
5952 	if ((kn->kn_status & KN_MERGE_QOS) && (qos_index < kn->kn_qos_override)) {
5953 		/* Never lower QoS when in "Merge" mode */
5954 		return;
5955 	}
5956 
5957 	if ((kn->kn_status & KN_LOCKED) && (kn->kn_status & KN_POSTING)) {
5958 		/*
5959 		 * When we're trying to update the QoS override and that both an
5960 		 * f_event() and other f_* calls are running concurrently, any of these
5961 		 * in flight calls may want to perform overrides that aren't properly
5962 		 * serialized with each other.
5963 		 *
5964 		 * The first update that observes this racy situation enters a "Merge"
5965 		 * mode which causes subsequent override requests to saturate the
5966 		 * override instead of replacing its value.
5967 		 *
5968 		 * This mode is left when knote_unlock() or knote_post()
5969 		 * observe that no other f_* routine is in flight.
5970 		 */
5971 		kn->kn_status |= KN_MERGE_QOS;
5972 	}
5973 
5974 	/*
5975 	 * Now apply the override if it changed.
5976 	 */
5977 
5978 	if (kn->kn_qos_override == qos_index) {
5979 		return;
5980 	}
5981 
5982 	kn->kn_qos_override = qos_index;
5983 
5984 	if (kn->kn_status & KN_SUPPRESSED) {
5985 		/*
5986 		 * For suppressed events, the kn_qos_index field cannot be touched as it
5987 		 * allows us to know on which supress queue the knote is for a kqworkq.
5988 		 *
5989 		 * Also, there's no natural push applied on the kqueues when this field
5990 		 * changes anyway. We hence need to apply manual overrides in this case,
5991 		 * which will be cleared when the events are later acknowledged.
5992 		 */
5993 		kqueue_update_override(kq, kn, qos_index);
5994 	} else if (kn->kn_qos_index != qos_index) {
5995 		knote_dequeue(kq, kn);
5996 		kn->kn_qos_index = qos_index;
5997 	}
5998 }
5999 
6000 void
klist_init(struct klist * list)6001 klist_init(struct klist *list)
6002 {
6003 	SLIST_INIT(list);
6004 }
6005 
6006 
6007 /*
6008  * Query/Post each knote in the object's list
6009  *
6010  *	The object lock protects the list. It is assumed
6011  *	that the filter/event routine for the object can
6012  *	determine that the object is already locked (via
6013  *	the hint) and not deadlock itself.
6014  *
6015  *	The object lock should also hold off pending
6016  *	detach/drop operations.
6017  */
6018 void
knote(struct klist * list,long hint)6019 knote(struct klist *list, long hint)
6020 {
6021 	struct knote *kn;
6022 
6023 	SLIST_FOREACH(kn, list, kn_selnext) {
6024 		knote_post(kn, hint);
6025 	}
6026 }
6027 
6028 /*
6029  * attach a knote to the specified list.  Return true if this is the first entry.
6030  * The list is protected by whatever lock the object it is associated with uses.
6031  */
6032 int
knote_attach(struct klist * list,struct knote * kn)6033 knote_attach(struct klist *list, struct knote *kn)
6034 {
6035 	int ret = SLIST_EMPTY(list);
6036 	SLIST_INSERT_HEAD(list, kn, kn_selnext);
6037 	return ret;
6038 }
6039 
6040 /*
6041  * detach a knote from the specified list.  Return true if that was the last entry.
6042  * The list is protected by whatever lock the object it is associated with uses.
6043  */
6044 int
knote_detach(struct klist * list,struct knote * kn)6045 knote_detach(struct klist *list, struct knote *kn)
6046 {
6047 	SLIST_REMOVE(list, kn, knote, kn_selnext);
6048 	return SLIST_EMPTY(list);
6049 }
6050 
6051 /*
6052  * knote_vanish - Indicate that the source has vanished
6053  *
6054  * If the knote has requested EV_VANISHED delivery,
6055  * arrange for that. Otherwise, deliver a NOTE_REVOKE
6056  * event for backward compatibility.
6057  *
6058  * The knote is marked as having vanished, but is not
6059  * actually detached from the source in this instance.
6060  * The actual detach is deferred until the knote drop.
6061  *
6062  * Our caller already has the object lock held. Calling
6063  * the detach routine would try to take that lock
6064  * recursively - which likely is not supported.
6065  */
6066 void
knote_vanish(struct klist * list,bool make_active)6067 knote_vanish(struct klist *list, bool make_active)
6068 {
6069 	struct knote *kn;
6070 	struct knote *kn_next;
6071 
6072 	SLIST_FOREACH_SAFE(kn, list, kn_selnext, kn_next) {
6073 		struct kqueue *kq = knote_get_kq(kn);
6074 
6075 		kqlock(kq);
6076 		if (__probable(kn->kn_status & KN_REQVANISH)) {
6077 			/*
6078 			 * If EV_VANISH supported - prepare to deliver one
6079 			 */
6080 			kn->kn_status |= KN_VANISHED;
6081 		} else {
6082 			/*
6083 			 * Handle the legacy way to indicate that the port/portset was
6084 			 * deallocated or left the current Mach portspace (modern technique
6085 			 * is with an EV_VANISHED protocol).
6086 			 *
6087 			 * Deliver an EV_EOF event for these changes (hopefully it will get
6088 			 * delivered before the port name recycles to the same generation
6089 			 * count and someone tries to re-register a kevent for it or the
6090 			 * events are udata-specific - avoiding a conflict).
6091 			 */
6092 			kn->kn_flags |= EV_EOF | EV_ONESHOT;
6093 		}
6094 		if (make_active) {
6095 			knote_activate(kq, kn, FILTER_ACTIVE);
6096 		}
6097 		kqunlock(kq);
6098 	}
6099 }
6100 
6101 /*
6102  * remove all knotes referencing a specified fd
6103  *
6104  * Entered with the proc_fd lock already held.
6105  * It returns the same way, but may drop it temporarily.
6106  */
6107 void
knote_fdclose(struct proc * p,int fd)6108 knote_fdclose(struct proc *p, int fd)
6109 {
6110 	struct filedesc *fdt = &p->p_fd;
6111 	struct klist *list;
6112 	struct knote *kn;
6113 	KNOTE_LOCK_CTX(knlc);
6114 
6115 restart:
6116 	list = &fdt->fd_knlist[fd];
6117 	SLIST_FOREACH(kn, list, kn_link) {
6118 		struct kqueue *kq = knote_get_kq(kn);
6119 
6120 		kqlock(kq);
6121 
6122 		if (kq->kq_p != p) {
6123 			panic("%s: proc mismatch (kq->kq_p=%p != p=%p)",
6124 			    __func__, kq->kq_p, p);
6125 		}
6126 
6127 		/*
6128 		 * If the knote supports EV_VANISHED delivery,
6129 		 * transition it to vanished mode (or skip over
6130 		 * it if already vanished).
6131 		 */
6132 		if (kn->kn_status & KN_VANISHED) {
6133 			kqunlock(kq);
6134 			continue;
6135 		}
6136 
6137 		proc_fdunlock(p);
6138 		if (!knote_lock(kq, kn, &knlc, KNOTE_KQ_LOCK_ON_SUCCESS)) {
6139 			/* the knote was dropped by someone, nothing to do */
6140 		} else if (kn->kn_status & KN_REQVANISH) {
6141 			kn->kn_status |= KN_VANISHED;
6142 
6143 			kqunlock(kq);
6144 			knote_fops(kn)->f_detach(kn);
6145 			if (kn->kn_is_fd) {
6146 				fp_drop(p, (int)kn->kn_id, kn->kn_fp, 0);
6147 			}
6148 			kn->kn_filtid = EVFILTID_DETACHED;
6149 			kqlock(kq);
6150 
6151 			knote_activate(kq, kn, FILTER_ACTIVE);
6152 			knote_unlock(kq, kn, &knlc, KNOTE_KQ_UNLOCK);
6153 		} else {
6154 			knote_drop(kq, kn, &knlc);
6155 		}
6156 
6157 		proc_fdlock(p);
6158 		goto restart;
6159 	}
6160 }
6161 
6162 /*
6163  * knote_fdfind - lookup a knote in the fd table for process
6164  *
6165  * If the filter is file-based, lookup based on fd index.
6166  * Otherwise use a hash based on the ident.
6167  *
6168  * Matching is based on kq, filter, and ident. Optionally,
6169  * it may also be based on the udata field in the kevent -
6170  * allowing multiple event registration for the file object
6171  * per kqueue.
6172  *
6173  * fd_knhashlock or fdlock held on entry (and exit)
6174  */
6175 static struct knote *
knote_fdfind(struct kqueue * kq,const struct kevent_internal_s * kev,bool is_fd,struct proc * p)6176 knote_fdfind(struct kqueue *kq,
6177     const struct kevent_internal_s *kev,
6178     bool is_fd,
6179     struct proc *p)
6180 {
6181 	struct filedesc *fdp = &p->p_fd;
6182 	struct klist *list = NULL;
6183 	struct knote *kn = NULL;
6184 
6185 	/*
6186 	 * determine where to look for the knote
6187 	 */
6188 	if (is_fd) {
6189 		/* fd-based knotes are linked off the fd table */
6190 		if (kev->kei_ident < (u_int)fdp->fd_knlistsize) {
6191 			list = &fdp->fd_knlist[kev->kei_ident];
6192 		}
6193 	} else if (fdp->fd_knhashmask != 0) {
6194 		/* hash non-fd knotes here too */
6195 		list = &fdp->fd_knhash[KN_HASH((u_long)kev->kei_ident, fdp->fd_knhashmask)];
6196 	}
6197 
6198 	/*
6199 	 * scan the selected list looking for a match
6200 	 */
6201 	if (list != NULL) {
6202 		SLIST_FOREACH(kn, list, kn_link) {
6203 			if (kq == knote_get_kq(kn) &&
6204 			    kev->kei_ident == kn->kn_id &&
6205 			    kev->kei_filter == kn->kn_filter) {
6206 				if (kev->kei_flags & EV_UDATA_SPECIFIC) {
6207 					if ((kn->kn_flags & EV_UDATA_SPECIFIC) &&
6208 					    kev->kei_udata == kn->kn_udata) {
6209 						break; /* matching udata-specific knote */
6210 					}
6211 				} else if ((kn->kn_flags & EV_UDATA_SPECIFIC) == 0) {
6212 					break; /* matching non-udata-specific knote */
6213 				}
6214 			}
6215 		}
6216 	}
6217 	return kn;
6218 }
6219 
6220 /*
6221  * kq_add_knote- Add knote to the fd table for process
6222  * while checking for duplicates.
6223  *
6224  * All file-based filters associate a list of knotes by file
6225  * descriptor index. All other filters hash the knote by ident.
6226  *
6227  * May have to grow the table of knote lists to cover the
6228  * file descriptor index presented.
6229  *
6230  * fd_knhashlock and fdlock unheld on entry (and exit).
6231  *
6232  * Takes a rwlock boost if inserting the knote is successful.
6233  */
6234 static int
kq_add_knote(struct kqueue * kq,struct knote * kn,struct knote_lock_ctx * knlc,struct proc * p)6235 kq_add_knote(struct kqueue *kq, struct knote *kn, struct knote_lock_ctx *knlc,
6236     struct proc *p)
6237 {
6238 	struct filedesc *fdp = &p->p_fd;
6239 	struct klist *list = NULL;
6240 	int ret = 0;
6241 	bool is_fd = kn->kn_is_fd;
6242 
6243 	if (is_fd) {
6244 		proc_fdlock(p);
6245 	} else {
6246 		knhash_lock(fdp);
6247 	}
6248 
6249 	if (knote_fdfind(kq, &kn->kn_kevent, is_fd, p) != NULL) {
6250 		/* found an existing knote: we can't add this one */
6251 		ret = ERESTART;
6252 		goto out_locked;
6253 	}
6254 
6255 	/* knote was not found: add it now */
6256 	if (!is_fd) {
6257 		if (fdp->fd_knhashmask == 0) {
6258 			u_long size = 0;
6259 
6260 			list = hashinit(CONFIG_KN_HASHSIZE, M_KQUEUE, &size);
6261 			if (list == NULL) {
6262 				ret = ENOMEM;
6263 				goto out_locked;
6264 			}
6265 
6266 			fdp->fd_knhash = list;
6267 			fdp->fd_knhashmask = size;
6268 		}
6269 
6270 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
6271 		SLIST_INSERT_HEAD(list, kn, kn_link);
6272 		ret = 0;
6273 		goto out_locked;
6274 	} else {
6275 		/* knote is fd based */
6276 
6277 		if ((u_int)fdp->fd_knlistsize <= kn->kn_id) {
6278 			u_int size = 0;
6279 
6280 			/* Make sure that fd stays below current process's soft limit AND system allowed per-process limits */
6281 			if (kn->kn_id >= (uint64_t)proc_limitgetcur_nofile(p)) {
6282 				ret = EINVAL;
6283 				goto out_locked;
6284 			}
6285 			/* have to grow the fd_knlist */
6286 			size = fdp->fd_knlistsize;
6287 			while (size <= kn->kn_id) {
6288 				size += KQEXTENT;
6289 			}
6290 
6291 			if (size >= (UINT_MAX / sizeof(struct klist))) {
6292 				ret = EINVAL;
6293 				goto out_locked;
6294 			}
6295 
6296 			list = kalloc_type(struct klist, size, Z_WAITOK | Z_ZERO);
6297 			if (list == NULL) {
6298 				ret = ENOMEM;
6299 				goto out_locked;
6300 			}
6301 
6302 			bcopy(fdp->fd_knlist, list,
6303 			    fdp->fd_knlistsize * sizeof(struct klist));
6304 			kfree_type(struct klist, fdp->fd_knlistsize, fdp->fd_knlist);
6305 			fdp->fd_knlist = list;
6306 			fdp->fd_knlistsize = size;
6307 		}
6308 
6309 		list = &fdp->fd_knlist[kn->kn_id];
6310 		SLIST_INSERT_HEAD(list, kn, kn_link);
6311 		ret = 0;
6312 		goto out_locked;
6313 	}
6314 
6315 out_locked:
6316 	if (ret == 0) {
6317 		kqlock(kq);
6318 		assert((kn->kn_status & KN_LOCKED) == 0);
6319 		(void)knote_lock(kq, kn, knlc, KNOTE_KQ_UNLOCK);
6320 		kqueue_retain(kq); /* retain a kq ref */
6321 	}
6322 	if (is_fd) {
6323 		proc_fdunlock(p);
6324 	} else {
6325 		knhash_unlock(fdp);
6326 	}
6327 
6328 	return ret;
6329 }
6330 
6331 /*
6332  * kq_remove_knote - remove a knote from the fd table for process
6333  *
6334  * If the filter is file-based, remove based on fd index.
6335  * Otherwise remove from the hash based on the ident.
6336  *
6337  * fd_knhashlock and fdlock unheld on entry (and exit).
6338  */
6339 static void
kq_remove_knote(struct kqueue * kq,struct knote * kn,struct proc * p,struct knote_lock_ctx * knlc)6340 kq_remove_knote(struct kqueue *kq, struct knote *kn, struct proc *p,
6341     struct knote_lock_ctx *knlc)
6342 {
6343 	struct filedesc *fdp = &p->p_fd;
6344 	struct klist *list = NULL;
6345 	uint16_t kq_state;
6346 	bool is_fd = kn->kn_is_fd;
6347 
6348 	if (is_fd) {
6349 		proc_fdlock(p);
6350 	} else {
6351 		knhash_lock(fdp);
6352 	}
6353 
6354 	if (is_fd) {
6355 		assert((u_int)fdp->fd_knlistsize > kn->kn_id);
6356 		list = &fdp->fd_knlist[kn->kn_id];
6357 	} else {
6358 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
6359 	}
6360 	SLIST_REMOVE(list, kn, knote, kn_link);
6361 
6362 	kqlock(kq);
6363 
6364 	/* Update the servicer iotier override */
6365 	kqueue_update_iotier_override(kq);
6366 
6367 	kq_state = kq->kq_state;
6368 	if (knlc) {
6369 		knote_unlock_cancel(kq, kn, knlc);
6370 	} else {
6371 		kqunlock(kq);
6372 	}
6373 	if (is_fd) {
6374 		proc_fdunlock(p);
6375 	} else {
6376 		knhash_unlock(fdp);
6377 	}
6378 
6379 	if (kq_state & KQ_DYNAMIC) {
6380 		kqworkloop_release((struct kqworkloop *)kq);
6381 	}
6382 }
6383 
6384 /*
6385  * kq_find_knote_and_kq_lock - lookup a knote in the fd table for process
6386  * and, if the knote is found, acquires the kqlock while holding the fd table lock/spinlock.
6387  *
6388  * fd_knhashlock or fdlock unheld on entry (and exit)
6389  */
6390 
6391 static struct knote *
kq_find_knote_and_kq_lock(struct kqueue * kq,struct kevent_qos_s * kev,bool is_fd,struct proc * p)6392 kq_find_knote_and_kq_lock(struct kqueue *kq, struct kevent_qos_s *kev,
6393     bool is_fd, struct proc *p)
6394 {
6395 	struct filedesc *fdp = &p->p_fd;
6396 	struct knote *kn;
6397 
6398 	if (is_fd) {
6399 		proc_fdlock(p);
6400 	} else {
6401 		knhash_lock(fdp);
6402 	}
6403 
6404 	/*
6405 	 * Temporary horrible hack:
6406 	 * this cast is gross and will go away in a future change.
6407 	 * It is OK to do because we don't look at xflags/s_fflags,
6408 	 * and that when we cast down the kev this way,
6409 	 * the truncated filter field works.
6410 	 */
6411 	kn = knote_fdfind(kq, (struct kevent_internal_s *)kev, is_fd, p);
6412 
6413 	if (kn) {
6414 		kqlock(kq);
6415 		assert(knote_get_kq(kn) == kq);
6416 	}
6417 
6418 	if (is_fd) {
6419 		proc_fdunlock(p);
6420 	} else {
6421 		knhash_unlock(fdp);
6422 	}
6423 
6424 	return kn;
6425 }
6426 
6427 static struct kqtailq *
knote_get_tailq(kqueue_t kqu,struct knote * kn)6428 knote_get_tailq(kqueue_t kqu, struct knote *kn)
6429 {
6430 	kq_index_t qos_index = kn->kn_qos_index;
6431 
6432 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
6433 		assert(qos_index > 0 && qos_index <= KQWL_NBUCKETS);
6434 		return &kqu.kqwl->kqwl_queue[qos_index - 1];
6435 	} else if (kqu.kq->kq_state & KQ_WORKQ) {
6436 		assert(qos_index > 0 && qos_index <= KQWQ_NBUCKETS);
6437 		return &kqu.kqwq->kqwq_queue[qos_index - 1];
6438 	} else {
6439 		assert(qos_index == QOS_INDEX_KQFILE);
6440 		return &kqu.kqf->kqf_queue;
6441 	}
6442 }
6443 
6444 static void
knote_enqueue(kqueue_t kqu,struct knote * kn)6445 knote_enqueue(kqueue_t kqu, struct knote *kn)
6446 {
6447 	kqlock_held(kqu);
6448 
6449 	if ((kn->kn_status & KN_ACTIVE) == 0) {
6450 		return;
6451 	}
6452 
6453 	if (kn->kn_status & (KN_DISABLED | KN_SUPPRESSED | KN_DROPPING | KN_QUEUED)) {
6454 		return;
6455 	}
6456 
6457 	struct kqtailq *queue = knote_get_tailq(kqu, kn);
6458 	bool wakeup = TAILQ_EMPTY(queue);
6459 
6460 	TAILQ_INSERT_TAIL(queue, kn, kn_tqe);
6461 	kn->kn_status |= KN_QUEUED;
6462 	kqu.kq->kq_count++;
6463 
6464 	if (wakeup) {
6465 		if (kqu.kq->kq_state & KQ_WORKLOOP) {
6466 			kqworkloop_wakeup(kqu.kqwl, kn->kn_qos_index);
6467 		} else if (kqu.kq->kq_state & KQ_WORKQ) {
6468 			kqworkq_wakeup(kqu.kqwq, kn->kn_qos_index);
6469 		} else {
6470 			kqfile_wakeup(kqu.kqf, 0, THREAD_AWAKENED);
6471 		}
6472 	}
6473 }
6474 
6475 __attribute__((always_inline))
6476 static inline void
knote_dequeue(kqueue_t kqu,struct knote * kn)6477 knote_dequeue(kqueue_t kqu, struct knote *kn)
6478 {
6479 	if (kn->kn_status & KN_QUEUED) {
6480 		struct kqtailq *queue = knote_get_tailq(kqu, kn);
6481 
6482 		// attaching the knote calls knote_reset_priority() without
6483 		// the kqlock which is fine, so we can't call kqlock_held()
6484 		// if we're not queued.
6485 		kqlock_held(kqu);
6486 
6487 		TAILQ_REMOVE(queue, kn, kn_tqe);
6488 		kn->kn_status &= ~KN_QUEUED;
6489 		kqu.kq->kq_count--;
6490 		if ((kqu.kq->kq_state & (KQ_WORKQ | KQ_WORKLOOP)) == 0) {
6491 			assert((kqu.kq->kq_count == 0) ==
6492 			    (bool)TAILQ_EMPTY(queue));
6493 		}
6494 	}
6495 }
6496 
6497 /* called with kqueue lock held */
6498 static void
knote_suppress(kqueue_t kqu,struct knote * kn)6499 knote_suppress(kqueue_t kqu, struct knote *kn)
6500 {
6501 	struct kqtailq *suppressq;
6502 
6503 	kqlock_held(kqu);
6504 
6505 	assert((kn->kn_status & KN_SUPPRESSED) == 0);
6506 	assert(kn->kn_status & KN_QUEUED);
6507 
6508 	knote_dequeue(kqu, kn);
6509 	/* deactivate - so new activations indicate a wakeup */
6510 	kn->kn_status &= ~KN_ACTIVE;
6511 	kn->kn_status |= KN_SUPPRESSED;
6512 	suppressq = kqueue_get_suppressed_queue(kqu, kn);
6513 	TAILQ_INSERT_TAIL(suppressq, kn, kn_tqe);
6514 }
6515 
6516 __attribute__((always_inline))
6517 static inline void
knote_unsuppress_noqueue(kqueue_t kqu,struct knote * kn)6518 knote_unsuppress_noqueue(kqueue_t kqu, struct knote *kn)
6519 {
6520 	struct kqtailq *suppressq;
6521 
6522 	kqlock_held(kqu);
6523 
6524 	assert(kn->kn_status & KN_SUPPRESSED);
6525 
6526 	kn->kn_status &= ~KN_SUPPRESSED;
6527 	suppressq = kqueue_get_suppressed_queue(kqu, kn);
6528 	TAILQ_REMOVE(suppressq, kn, kn_tqe);
6529 
6530 	/*
6531 	 * If the knote is no longer active, reset its push,
6532 	 * and resynchronize kn_qos_index with kn_qos_override
6533 	 * for knotes with a real qos.
6534 	 */
6535 	if ((kn->kn_status & KN_ACTIVE) == 0 && knote_has_qos(kn)) {
6536 		kn->kn_qos_override = _pthread_priority_thread_qos_fast(kn->kn_qos);
6537 	}
6538 	kn->kn_qos_index = kn->kn_qos_override;
6539 }
6540 
6541 /* called with kqueue lock held */
6542 static void
knote_unsuppress(kqueue_t kqu,struct knote * kn)6543 knote_unsuppress(kqueue_t kqu, struct knote *kn)
6544 {
6545 	knote_unsuppress_noqueue(kqu, kn);
6546 	knote_enqueue(kqu, kn);
6547 }
6548 
6549 __attribute__((always_inline))
6550 static inline void
knote_mark_active(struct knote * kn)6551 knote_mark_active(struct knote *kn)
6552 {
6553 	if ((kn->kn_status & KN_ACTIVE) == 0) {
6554 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KNOTE_ACTIVATE),
6555 		    kn->kn_udata, kn->kn_status | (kn->kn_id << 32),
6556 		    kn->kn_filtid);
6557 	}
6558 
6559 	kn->kn_status |= KN_ACTIVE;
6560 }
6561 
6562 /* called with kqueue lock held */
6563 static void
knote_activate(kqueue_t kqu,struct knote * kn,int result)6564 knote_activate(kqueue_t kqu, struct knote *kn, int result)
6565 {
6566 	assert(result & FILTER_ACTIVE);
6567 	if (result & FILTER_ADJUST_EVENT_QOS_BIT) {
6568 		// may dequeue the knote
6569 		knote_adjust_qos(kqu.kq, kn, result);
6570 	}
6571 	knote_mark_active(kn);
6572 	knote_enqueue(kqu, kn);
6573 }
6574 
6575 /*
6576  * This function applies changes requested by f_attach or f_touch for
6577  * a given filter. It proceeds in a carefully chosen order to help
6578  * every single transition do the minimal amount of work possible.
6579  */
6580 static void
knote_apply_touch(kqueue_t kqu,struct knote * kn,struct kevent_qos_s * kev,int result)6581 knote_apply_touch(kqueue_t kqu, struct knote *kn, struct kevent_qos_s *kev,
6582     int result)
6583 {
6584 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
6585 		kn->kn_status &= ~KN_DISABLED;
6586 
6587 		/*
6588 		 * it is possible for userland to have knotes registered for a given
6589 		 * workloop `wl_orig` but really handled on another workloop `wl_new`.
6590 		 *
6591 		 * In that case, rearming will happen from the servicer thread of
6592 		 * `wl_new` which if `wl_orig` is no longer being serviced, would cause
6593 		 * this knote to stay suppressed forever if we only relied on
6594 		 * kqworkloop_acknowledge_events to be called by `wl_orig`.
6595 		 *
6596 		 * However if we see the KQ_PROCESSING bit on `wl_orig` set, we can't
6597 		 * unsuppress because that would mess with the processing phase of
6598 		 * `wl_orig`, however it also means kqworkloop_acknowledge_events()
6599 		 * will be called.
6600 		 */
6601 		if (__improbable(kn->kn_status & KN_SUPPRESSED)) {
6602 			if ((kqu.kq->kq_state & KQ_PROCESSING) == 0) {
6603 				knote_unsuppress_noqueue(kqu, kn);
6604 			}
6605 		}
6606 	}
6607 
6608 	if (result & FILTER_ADJUST_EVENT_IOTIER_BIT) {
6609 		kqueue_update_iotier_override(kqu);
6610 	}
6611 
6612 	if ((result & FILTER_UPDATE_REQ_QOS) && kev->qos && kev->qos != kn->kn_qos) {
6613 		// may dequeue the knote
6614 		knote_reset_priority(kqu, kn, kev->qos);
6615 	}
6616 
6617 	/*
6618 	 * When we unsuppress above, or because of knote_reset_priority(),
6619 	 * the knote may have been dequeued, we need to restore the invariant
6620 	 * that if the knote is active it needs to be queued now that
6621 	 * we're done applying changes.
6622 	 */
6623 	if (result & FILTER_ACTIVE) {
6624 		knote_activate(kqu, kn, result);
6625 	} else {
6626 		knote_enqueue(kqu, kn);
6627 	}
6628 
6629 	if ((result & FILTER_THREADREQ_NODEFEER) &&
6630 	    act_clear_astkevent(current_thread(), AST_KEVENT_REDRIVE_THREADREQ)) {
6631 		workq_kern_threadreq_redrive(kqu.kq->kq_p, WORKQ_THREADREQ_NONE);
6632 	}
6633 }
6634 
6635 /*
6636  * knote_drop - disconnect and drop the knote
6637  *
6638  * Called with the kqueue locked, returns with the kqueue unlocked.
6639  *
6640  * If a knote locking context is passed, it is canceled.
6641  *
6642  * The knote may have already been detached from
6643  * (or not yet attached to) its source object.
6644  */
6645 static void
knote_drop(struct kqueue * kq,struct knote * kn,struct knote_lock_ctx * knlc)6646 knote_drop(struct kqueue *kq, struct knote *kn, struct knote_lock_ctx *knlc)
6647 {
6648 	struct proc *p = kq->kq_p;
6649 
6650 	kqlock_held(kq);
6651 
6652 	assert((kn->kn_status & KN_DROPPING) == 0);
6653 	if (knlc == NULL) {
6654 		assert((kn->kn_status & KN_LOCKED) == 0);
6655 	}
6656 	kn->kn_status |= KN_DROPPING;
6657 
6658 	if (kn->kn_status & KN_SUPPRESSED) {
6659 		knote_unsuppress_noqueue(kq, kn);
6660 	} else {
6661 		knote_dequeue(kq, kn);
6662 	}
6663 	knote_wait_for_post(kq, kn);
6664 
6665 	knote_fops(kn)->f_detach(kn);
6666 
6667 	/* kq may be freed when kq_remove_knote() returns */
6668 	kq_remove_knote(kq, kn, p, knlc);
6669 	if (kn->kn_is_fd && ((kn->kn_status & KN_VANISHED) == 0)) {
6670 		fp_drop(p, (int)kn->kn_id, kn->kn_fp, 0);
6671 	}
6672 
6673 	knote_free(kn);
6674 }
6675 
6676 void
knote_init(void)6677 knote_init(void)
6678 {
6679 #if CONFIG_MEMORYSTATUS
6680 	/* Initialize the memorystatus list lock */
6681 	memorystatus_kevent_init(&kq_lck_grp, LCK_ATTR_NULL);
6682 #endif
6683 }
6684 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
6685 
6686 const struct filterops *
knote_fops(struct knote * kn)6687 knote_fops(struct knote *kn)
6688 {
6689 	return sysfilt_ops[kn->kn_filtid];
6690 }
6691 
6692 static struct knote *
knote_alloc(void)6693 knote_alloc(void)
6694 {
6695 	return zalloc_flags(knote_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
6696 }
6697 
6698 static void
knote_free(struct knote * kn)6699 knote_free(struct knote *kn)
6700 {
6701 	assert((kn->kn_status & (KN_LOCKED | KN_POSTING)) == 0);
6702 	zfree(knote_zone, kn);
6703 }
6704 
6705 #pragma mark - syscalls: kevent, kevent64, kevent_qos, kevent_id
6706 
6707 kevent_ctx_t
kevent_get_context(thread_t thread)6708 kevent_get_context(thread_t thread)
6709 {
6710 	uthread_t ut = get_bsdthread_info(thread);
6711 	return &ut->uu_save.uus_kevent;
6712 }
6713 
6714 static inline bool
kevent_args_requesting_events(unsigned int flags,int nevents)6715 kevent_args_requesting_events(unsigned int flags, int nevents)
6716 {
6717 	return !(flags & KEVENT_FLAG_ERROR_EVENTS) && nevents > 0;
6718 }
6719 
6720 static inline int
kevent_adjust_flags_for_proc(proc_t p,int flags)6721 kevent_adjust_flags_for_proc(proc_t p, int flags)
6722 {
6723 	__builtin_assume(p);
6724 	return flags | (IS_64BIT_PROCESS(p) ? KEVENT_FLAG_PROC64 : 0);
6725 }
6726 
6727 /*!
6728  * @function kevent_get_kqfile
6729  *
6730  * @brief
6731  * Lookup a kqfile by fd.
6732  *
6733  * @discussion
6734  * Callers: kevent, kevent64, kevent_qos
6735  *
6736  * This is not assumed to be a fastpath (kqfile interfaces are legacy)
6737  */
6738 OS_NOINLINE
6739 static int
kevent_get_kqfile(struct proc * p,int fd,int flags,struct fileproc ** fpp,struct kqueue ** kqp)6740 kevent_get_kqfile(struct proc *p, int fd, int flags,
6741     struct fileproc **fpp, struct kqueue **kqp)
6742 {
6743 	int error = 0;
6744 	struct kqueue *kq;
6745 
6746 	error = fp_get_ftype(p, fd, DTYPE_KQUEUE, EBADF, fpp);
6747 	if (__improbable(error)) {
6748 		return error;
6749 	}
6750 	kq = (struct kqueue *)fp_get_data((*fpp));
6751 
6752 	uint16_t kq_state = os_atomic_load(&kq->kq_state, relaxed);
6753 	if (__improbable((kq_state & (KQ_KEV32 | KQ_KEV64 | KQ_KEV_QOS)) == 0)) {
6754 		kqlock(kq);
6755 		kq_state = kq->kq_state;
6756 		if (!(kq_state & (KQ_KEV32 | KQ_KEV64 | KQ_KEV_QOS))) {
6757 			if (flags & KEVENT_FLAG_LEGACY32) {
6758 				kq_state |= KQ_KEV32;
6759 			} else if (flags & KEVENT_FLAG_LEGACY64) {
6760 				kq_state |= KQ_KEV64;
6761 			} else {
6762 				kq_state |= KQ_KEV_QOS;
6763 			}
6764 			kq->kq_state = kq_state;
6765 		}
6766 		kqunlock(kq);
6767 	}
6768 
6769 	/*
6770 	 * kqfiles can't be used through the legacy kevent()
6771 	 * and other interfaces at the same time.
6772 	 */
6773 	if (__improbable((bool)(flags & KEVENT_FLAG_LEGACY32) !=
6774 	    (bool)(kq_state & KQ_KEV32))) {
6775 		fp_drop(p, fd, *fpp, 0);
6776 		return EINVAL;
6777 	}
6778 
6779 	*kqp = kq;
6780 	return 0;
6781 }
6782 
6783 /*!
6784  * @function kevent_get_kqwq
6785  *
6786  * @brief
6787  * Lookup or create the process kqwq (faspath).
6788  *
6789  * @discussion
6790  * Callers: kevent64, kevent_qos
6791  */
6792 OS_ALWAYS_INLINE
6793 static int
kevent_get_kqwq(proc_t p,int flags,int nevents,struct kqueue ** kqp)6794 kevent_get_kqwq(proc_t p, int flags, int nevents, struct kqueue **kqp)
6795 {
6796 	struct kqworkq *kqwq = p->p_fd.fd_wqkqueue;
6797 
6798 	if (__improbable(kevent_args_requesting_events(flags, nevents))) {
6799 		return EINVAL;
6800 	}
6801 	if (__improbable(kqwq == NULL)) {
6802 		kqwq = kqworkq_alloc(p, flags);
6803 		if (__improbable(kqwq == NULL)) {
6804 			return ENOMEM;
6805 		}
6806 	}
6807 
6808 	*kqp = &kqwq->kqwq_kqueue;
6809 	return 0;
6810 }
6811 
6812 #pragma mark kevent copyio
6813 
6814 /*!
6815  * @function kevent_get_data_size
6816  *
6817  * @brief
6818  * Copies in the extra data size from user-space.
6819  */
6820 static int
kevent_get_data_size(int flags,user_addr_t data_avail,user_addr_t data_out,kevent_ctx_t kectx)6821 kevent_get_data_size(int flags, user_addr_t data_avail, user_addr_t data_out,
6822     kevent_ctx_t kectx)
6823 {
6824 	if (!data_avail || !data_out) {
6825 		kectx->kec_data_size  = 0;
6826 		kectx->kec_data_resid = 0;
6827 	} else if (flags & KEVENT_FLAG_PROC64) {
6828 		user64_size_t usize = 0;
6829 		int error = copyin((user_addr_t)data_avail, &usize, sizeof(usize));
6830 		if (__improbable(error)) {
6831 			return error;
6832 		}
6833 		kectx->kec_data_resid = kectx->kec_data_size = (user_size_t)usize;
6834 	} else {
6835 		user32_size_t usize = 0;
6836 		int error = copyin((user_addr_t)data_avail, &usize, sizeof(usize));
6837 		if (__improbable(error)) {
6838 			return error;
6839 		}
6840 		kectx->kec_data_avail = data_avail;
6841 		kectx->kec_data_resid = kectx->kec_data_size = (user_size_t)usize;
6842 	}
6843 	kectx->kec_data_out   = data_out;
6844 	kectx->kec_data_avail = data_avail;
6845 	return 0;
6846 }
6847 
6848 /*!
6849  * @function kevent_put_data_size
6850  *
6851  * @brief
6852  * Copies out the residual data size to user-space if any has been used.
6853  */
6854 static int
kevent_put_data_size(unsigned int flags,kevent_ctx_t kectx)6855 kevent_put_data_size(unsigned int flags, kevent_ctx_t kectx)
6856 {
6857 	if (kectx->kec_data_resid == kectx->kec_data_size) {
6858 		return 0;
6859 	}
6860 	if (flags & KEVENT_FLAG_KERNEL) {
6861 		*(user_size_t *)(uintptr_t)kectx->kec_data_avail = kectx->kec_data_resid;
6862 		return 0;
6863 	}
6864 	if (flags & KEVENT_FLAG_PROC64) {
6865 		user64_size_t usize = (user64_size_t)kectx->kec_data_resid;
6866 		return copyout(&usize, (user_addr_t)kectx->kec_data_avail, sizeof(usize));
6867 	} else {
6868 		user32_size_t usize = (user32_size_t)kectx->kec_data_resid;
6869 		return copyout(&usize, (user_addr_t)kectx->kec_data_avail, sizeof(usize));
6870 	}
6871 }
6872 
6873 /*!
6874  * @function kevent_legacy_copyin
6875  *
6876  * @brief
6877  * Handles the copyin of a kevent/kevent64 event.
6878  */
6879 static int
kevent_legacy_copyin(user_addr_t * addrp,struct kevent_qos_s * kevp,unsigned int flags)6880 kevent_legacy_copyin(user_addr_t *addrp, struct kevent_qos_s *kevp, unsigned int flags)
6881 {
6882 	int error;
6883 
6884 	assert((flags & (KEVENT_FLAG_LEGACY32 | KEVENT_FLAG_LEGACY64)) != 0);
6885 
6886 	if (flags & KEVENT_FLAG_LEGACY64) {
6887 		struct kevent64_s kev64;
6888 
6889 		error = copyin(*addrp, (caddr_t)&kev64, sizeof(kev64));
6890 		if (__improbable(error)) {
6891 			return error;
6892 		}
6893 		*addrp += sizeof(kev64);
6894 		*kevp = (struct kevent_qos_s){
6895 			.ident  = kev64.ident,
6896 			.filter = kev64.filter,
6897 			/* Make sure user doesn't pass in any system flags */
6898 			.flags  = kev64.flags & ~EV_SYSFLAGS,
6899 			.udata  = kev64.udata,
6900 			.fflags = kev64.fflags,
6901 			.data   = kev64.data,
6902 			.ext[0] = kev64.ext[0],
6903 			.ext[1] = kev64.ext[1],
6904 		};
6905 	} else if (flags & KEVENT_FLAG_PROC64) {
6906 		struct user64_kevent kev64;
6907 
6908 		error = copyin(*addrp, (caddr_t)&kev64, sizeof(kev64));
6909 		if (__improbable(error)) {
6910 			return error;
6911 		}
6912 		*addrp += sizeof(kev64);
6913 		*kevp = (struct kevent_qos_s){
6914 			.ident  = kev64.ident,
6915 			.filter = kev64.filter,
6916 			/* Make sure user doesn't pass in any system flags */
6917 			.flags  = kev64.flags & ~EV_SYSFLAGS,
6918 			.udata  = kev64.udata,
6919 			.fflags = kev64.fflags,
6920 			.data   = kev64.data,
6921 		};
6922 	} else {
6923 		struct user32_kevent kev32;
6924 
6925 		error = copyin(*addrp, (caddr_t)&kev32, sizeof(kev32));
6926 		if (__improbable(error)) {
6927 			return error;
6928 		}
6929 		*addrp += sizeof(kev32);
6930 		*kevp = (struct kevent_qos_s){
6931 			.ident  = (uintptr_t)kev32.ident,
6932 			.filter = kev32.filter,
6933 			/* Make sure user doesn't pass in any system flags */
6934 			.flags  = kev32.flags & ~EV_SYSFLAGS,
6935 			.udata  = CAST_USER_ADDR_T(kev32.udata),
6936 			.fflags = kev32.fflags,
6937 			.data   = (intptr_t)kev32.data,
6938 		};
6939 	}
6940 
6941 	return 0;
6942 }
6943 
6944 /*!
6945  * @function kevent_modern_copyin
6946  *
6947  * @brief
6948  * Handles the copyin of a kevent_qos/kevent_id event.
6949  */
6950 static int
kevent_modern_copyin(user_addr_t * addrp,struct kevent_qos_s * kevp)6951 kevent_modern_copyin(user_addr_t *addrp, struct kevent_qos_s *kevp)
6952 {
6953 	int error = copyin(*addrp, (caddr_t)kevp, sizeof(struct kevent_qos_s));
6954 	if (__probable(!error)) {
6955 		/* Make sure user doesn't pass in any system flags */
6956 		*addrp += sizeof(struct kevent_qos_s);
6957 		kevp->flags &= ~EV_SYSFLAGS;
6958 	}
6959 	return error;
6960 }
6961 
6962 /*!
6963  * @function kevent_legacy_copyout
6964  *
6965  * @brief
6966  * Handles the copyout of a kevent/kevent64 event.
6967  */
6968 static int
kevent_legacy_copyout(struct kevent_qos_s * kevp,user_addr_t * addrp,unsigned int flags)6969 kevent_legacy_copyout(struct kevent_qos_s *kevp, user_addr_t *addrp, unsigned int flags)
6970 {
6971 	int advance;
6972 	int error;
6973 
6974 	assert((flags & (KEVENT_FLAG_LEGACY32 | KEVENT_FLAG_LEGACY64)) != 0);
6975 
6976 	/*
6977 	 * fully initialize the differnt output event structure
6978 	 * types from the internal kevent (and some universal
6979 	 * defaults for fields not represented in the internal
6980 	 * form).
6981 	 *
6982 	 * Note: these structures have no padding hence the C99
6983 	 *       initializers below do not leak kernel info.
6984 	 */
6985 	if (flags & KEVENT_FLAG_LEGACY64) {
6986 		struct kevent64_s kev64 = {
6987 			.ident  = kevp->ident,
6988 			.filter = kevp->filter,
6989 			.flags  = kevp->flags,
6990 			.fflags = kevp->fflags,
6991 			.data   = (int64_t)kevp->data,
6992 			.udata  = kevp->udata,
6993 			.ext[0] = kevp->ext[0],
6994 			.ext[1] = kevp->ext[1],
6995 		};
6996 		advance = sizeof(struct kevent64_s);
6997 		error = copyout((caddr_t)&kev64, *addrp, advance);
6998 	} else if (flags & KEVENT_FLAG_PROC64) {
6999 		/*
7000 		 * deal with the special case of a user-supplied
7001 		 * value of (uintptr_t)-1.
7002 		 */
7003 		uint64_t ident = (kevp->ident == (uintptr_t)-1) ?
7004 		    (uint64_t)-1LL : (uint64_t)kevp->ident;
7005 		struct user64_kevent kev64 = {
7006 			.ident  = ident,
7007 			.filter = kevp->filter,
7008 			.flags  = kevp->flags,
7009 			.fflags = kevp->fflags,
7010 			.data   = (int64_t) kevp->data,
7011 			.udata  = (user_addr_t) kevp->udata,
7012 		};
7013 		advance = sizeof(kev64);
7014 		error = copyout((caddr_t)&kev64, *addrp, advance);
7015 	} else {
7016 		struct user32_kevent kev32 = {
7017 			.ident  = (uint32_t)kevp->ident,
7018 			.filter = kevp->filter,
7019 			.flags  = kevp->flags,
7020 			.fflags = kevp->fflags,
7021 			.data   = (int32_t)kevp->data,
7022 			.udata  = (uint32_t)kevp->udata,
7023 		};
7024 		advance = sizeof(kev32);
7025 		error = copyout((caddr_t)&kev32, *addrp, advance);
7026 	}
7027 	if (__probable(!error)) {
7028 		*addrp += advance;
7029 	}
7030 	return error;
7031 }
7032 
7033 /*!
7034  * @function kevent_modern_copyout
7035  *
7036  * @brief
7037  * Handles the copyout of a kevent_qos/kevent_id event.
7038  */
7039 OS_ALWAYS_INLINE
7040 static inline int
kevent_modern_copyout(struct kevent_qos_s * kevp,user_addr_t * addrp)7041 kevent_modern_copyout(struct kevent_qos_s *kevp, user_addr_t *addrp)
7042 {
7043 	int error = copyout((caddr_t)kevp, *addrp, sizeof(struct kevent_qos_s));
7044 	if (__probable(!error)) {
7045 		*addrp += sizeof(struct kevent_qos_s);
7046 	}
7047 	return error;
7048 }
7049 
7050 #pragma mark kevent core implementation
7051 
7052 /*!
7053  * @function kevent_callback_inline
7054  *
7055  * @brief
7056  * Callback for each individual event
7057  *
7058  * @discussion
7059  * This is meant to be inlined in kevent_modern_callback and
7060  * kevent_legacy_callback.
7061  */
7062 OS_ALWAYS_INLINE
7063 static inline int
kevent_callback_inline(struct kevent_qos_s * kevp,kevent_ctx_t kectx,bool legacy)7064 kevent_callback_inline(struct kevent_qos_s *kevp, kevent_ctx_t kectx, bool legacy)
7065 {
7066 	int error;
7067 
7068 	assert(kectx->kec_process_noutputs < kectx->kec_process_nevents);
7069 
7070 	/*
7071 	 * Copy out the appropriate amount of event data for this user.
7072 	 */
7073 	if (legacy) {
7074 		error = kevent_legacy_copyout(kevp, &kectx->kec_process_eventlist,
7075 		    kectx->kec_process_flags);
7076 	} else {
7077 		error = kevent_modern_copyout(kevp, &kectx->kec_process_eventlist);
7078 	}
7079 
7080 	/*
7081 	 * If there isn't space for additional events, return
7082 	 * a harmless error to stop the processing here
7083 	 */
7084 	if (error == 0 && ++kectx->kec_process_noutputs == kectx->kec_process_nevents) {
7085 		error = EWOULDBLOCK;
7086 	}
7087 	return error;
7088 }
7089 
7090 /*!
7091  * @function kevent_modern_callback
7092  *
7093  * @brief
7094  * Callback for each individual modern event.
7095  *
7096  * @discussion
7097  * This callback handles kevent_qos/kevent_id events.
7098  */
7099 static int
kevent_modern_callback(struct kevent_qos_s * kevp,kevent_ctx_t kectx)7100 kevent_modern_callback(struct kevent_qos_s *kevp, kevent_ctx_t kectx)
7101 {
7102 	return kevent_callback_inline(kevp, kectx, /*legacy*/ false);
7103 }
7104 
7105 /*!
7106  * @function kevent_legacy_callback
7107  *
7108  * @brief
7109  * Callback for each individual legacy event.
7110  *
7111  * @discussion
7112  * This callback handles kevent/kevent64 events.
7113  */
7114 static int
kevent_legacy_callback(struct kevent_qos_s * kevp,kevent_ctx_t kectx)7115 kevent_legacy_callback(struct kevent_qos_s *kevp, kevent_ctx_t kectx)
7116 {
7117 	return kevent_callback_inline(kevp, kectx, /*legacy*/ true);
7118 }
7119 
7120 /*!
7121  * @function kevent_cleanup
7122  *
7123  * @brief
7124  * Handles the cleanup returning from a kevent call.
7125  *
7126  * @discussion
7127  * kevent entry points will take a reference on workloops,
7128  * and a usecount on the fileglob of kqfiles.
7129  *
7130  * This function undoes this on the exit paths of kevents.
7131  *
7132  * @returns
7133  * The error to return to userspace.
7134  */
7135 static int
kevent_cleanup(kqueue_t kqu,int flags,int error,kevent_ctx_t kectx)7136 kevent_cleanup(kqueue_t kqu, int flags, int error, kevent_ctx_t kectx)
7137 {
7138 	// poll should not call any codepath leading to this
7139 	assert((flags & KEVENT_FLAG_POLL) == 0);
7140 
7141 	if (flags & KEVENT_FLAG_WORKLOOP) {
7142 		kqworkloop_release(kqu.kqwl);
7143 	} else if (flags & KEVENT_FLAG_WORKQ) {
7144 		/* nothing held */
7145 	} else {
7146 		fp_drop(kqu.kqf->kqf_p, kectx->kec_fd, kectx->kec_fp, 0);
7147 	}
7148 
7149 	/* don't restart after signals... */
7150 	if (error == ERESTART) {
7151 		error = EINTR;
7152 	} else if (error == 0) {
7153 		/* don't abandon other output just because of residual copyout failures */
7154 		(void)kevent_put_data_size(flags, kectx);
7155 	}
7156 
7157 	if (flags & KEVENT_FLAG_PARKING) {
7158 		thread_t th = current_thread();
7159 		struct uthread *uth = get_bsdthread_info(th);
7160 		if (uth->uu_kqr_bound) {
7161 			thread_unfreeze_base_pri(th);
7162 		}
7163 	}
7164 	return error;
7165 }
7166 
7167 /*!
7168  * @function kqueue_process
7169  *
7170  * @brief
7171  * Process the triggered events in a kqueue.
7172  *
7173  * @discussion
7174  * Walk the queued knotes and validate that they are really still triggered
7175  * events by calling the filter routines (if necessary).
7176  *
7177  * For each event that is still considered triggered, invoke the callback
7178  * routine provided.
7179  *
7180  * caller holds a reference on the kqueue.
7181  * kqueue locked on entry and exit - but may be dropped
7182  * kqueue list locked (held for duration of call)
7183  *
7184  * This is only called by kqueue_scan() so that the compiler can inline it.
7185  *
7186  * @returns
7187  * - 0:            no event was returned, no other error occured
7188  * - EBADF:        the kqueue is being destroyed (KQ_DRAIN is set)
7189  * - EWOULDBLOCK:  (not an error) events have been found and we should return
7190  * - EFAULT:       copyout failed
7191  * - filter specific errors
7192  */
7193 static int
kqueue_process(kqueue_t kqu,int flags,kevent_ctx_t kectx,kevent_callback_t callback)7194 kqueue_process(kqueue_t kqu, int flags, kevent_ctx_t kectx,
7195     kevent_callback_t callback)
7196 {
7197 	workq_threadreq_t kqr = current_uthread()->uu_kqr_bound;
7198 	struct knote *kn;
7199 	int error = 0, rc = 0;
7200 	struct kqtailq *base_queue, *queue;
7201 	uint16_t kq_type = (kqu.kq->kq_state & (KQ_WORKQ | KQ_WORKLOOP));
7202 
7203 	if (kq_type & KQ_WORKQ) {
7204 		rc = kqworkq_begin_processing(kqu.kqwq, kqr, flags);
7205 	} else if (kq_type & KQ_WORKLOOP) {
7206 		rc = kqworkloop_begin_processing(kqu.kqwl, flags);
7207 	} else {
7208 kqfile_retry:
7209 		rc = kqfile_begin_processing(kqu.kqf);
7210 		if (rc == EBADF) {
7211 			return EBADF;
7212 		}
7213 	}
7214 
7215 	if (rc == -1) {
7216 		/* Nothing to process */
7217 		return 0;
7218 	}
7219 
7220 	/*
7221 	 * loop through the enqueued knotes associated with this request,
7222 	 * processing each one. Each request may have several queues
7223 	 * of knotes to process (depending on the type of kqueue) so we
7224 	 * have to loop through all the queues as long as we have additional
7225 	 * space.
7226 	 */
7227 
7228 process_again:
7229 	if (kq_type & KQ_WORKQ) {
7230 		base_queue = queue = &kqu.kqwq->kqwq_queue[kqr->tr_kq_qos_index - 1];
7231 	} else if (kq_type & KQ_WORKLOOP) {
7232 		base_queue = &kqu.kqwl->kqwl_queue[0];
7233 		queue = &kqu.kqwl->kqwl_queue[KQWL_NBUCKETS - 1];
7234 	} else {
7235 		base_queue = queue = &kqu.kqf->kqf_queue;
7236 	}
7237 
7238 	do {
7239 		while ((kn = TAILQ_FIRST(queue)) != NULL) {
7240 			error = knote_process(kn, kectx, callback);
7241 			if (error == EJUSTRETURN) {
7242 				error = 0;
7243 			} else if (__improbable(error)) {
7244 				/* error is EWOULDBLOCK when the out event array is full */
7245 				goto stop_processing;
7246 			}
7247 		}
7248 	} while (queue-- > base_queue);
7249 
7250 	if (kectx->kec_process_noutputs) {
7251 		/* callers will transform this into no error */
7252 		error = EWOULDBLOCK;
7253 	}
7254 
7255 stop_processing:
7256 	/*
7257 	 * If KEVENT_FLAG_PARKING is set, and no kevents have been returned,
7258 	 * we want to unbind the kqrequest from the thread.
7259 	 *
7260 	 * However, because the kq locks are dropped several times during process,
7261 	 * new knotes may have fired again, in which case, we want to fail the end
7262 	 * processing and process again, until it converges.
7263 	 *
7264 	 * If we have an error or returned events, end processing never fails.
7265 	 */
7266 	if (error) {
7267 		flags &= ~KEVENT_FLAG_PARKING;
7268 	}
7269 	if (kq_type & KQ_WORKQ) {
7270 		rc = kqworkq_end_processing(kqu.kqwq, kqr, flags);
7271 	} else if (kq_type & KQ_WORKLOOP) {
7272 		rc = kqworkloop_end_processing(kqu.kqwl, KQ_PROCESSING, flags);
7273 	} else {
7274 		rc = kqfile_end_processing(kqu.kqf);
7275 	}
7276 
7277 	if (__probable(error)) {
7278 		return error;
7279 	}
7280 
7281 	if (__probable(rc >= 0)) {
7282 		assert(rc == 0 || rc == EBADF);
7283 		return rc;
7284 	}
7285 
7286 	if (kq_type & (KQ_WORKQ | KQ_WORKLOOP)) {
7287 		assert(flags & KEVENT_FLAG_PARKING);
7288 		goto process_again;
7289 	} else {
7290 		goto kqfile_retry;
7291 	}
7292 }
7293 
7294 /*!
7295  * @function kqueue_scan_continue
7296  *
7297  * @brief
7298  * The continuation used by kqueue_scan for kevent entry points.
7299  *
7300  * @discussion
7301  * Assumes we inherit a use/ref count on the kq or its fileglob.
7302  *
7303  * This is called by kqueue_scan if neither KEVENT_FLAG_POLL nor
7304  * KEVENT_FLAG_KERNEL was set, and the caller had to wait.
7305  */
7306 OS_NORETURN OS_NOINLINE
7307 static void
kqueue_scan_continue(void * data,wait_result_t wait_result)7308 kqueue_scan_continue(void *data, wait_result_t wait_result)
7309 {
7310 	uthread_t ut = current_uthread();
7311 	kevent_ctx_t kectx = &ut->uu_save.uus_kevent;
7312 	int error = 0, flags = kectx->kec_process_flags;
7313 	struct kqueue *kq = data;
7314 
7315 	/*
7316 	 * only kevent variants call in here, so we know the callback is
7317 	 * kevent_legacy_callback or kevent_modern_callback.
7318 	 */
7319 	assert((flags & (KEVENT_FLAG_POLL | KEVENT_FLAG_KERNEL)) == 0);
7320 
7321 	switch (wait_result) {
7322 	case THREAD_AWAKENED:
7323 		if (__improbable(flags & (KEVENT_FLAG_LEGACY32 | KEVENT_FLAG_LEGACY64))) {
7324 			error = kqueue_scan(kq, flags, kectx, kevent_legacy_callback);
7325 		} else {
7326 			error = kqueue_scan(kq, flags, kectx, kevent_modern_callback);
7327 		}
7328 		break;
7329 	case THREAD_TIMED_OUT:
7330 		error = 0;
7331 		break;
7332 	case THREAD_INTERRUPTED:
7333 		error = EINTR;
7334 		break;
7335 	case THREAD_RESTART:
7336 		error = EBADF;
7337 		break;
7338 	default:
7339 		panic("%s: - invalid wait_result (%d)", __func__, wait_result);
7340 	}
7341 
7342 
7343 	error = kevent_cleanup(kq, flags, error, kectx);
7344 	*(int32_t *)&ut->uu_rval = kectx->kec_process_noutputs;
7345 	unix_syscall_return(error);
7346 }
7347 
7348 /*!
7349  * @function kqueue_scan
7350  *
7351  * @brief
7352  * Scan and wait for events in a kqueue (used by poll & kevent).
7353  *
7354  * @discussion
7355  * Process the triggered events in a kqueue.
7356  *
7357  * If there are no events triggered arrange to wait for them:
7358  * - unless KEVENT_FLAG_IMMEDIATE is set in kectx->kec_process_flags
7359  * - possibly until kectx->kec_deadline expires
7360  *
7361  * When it waits, and that neither KEVENT_FLAG_POLL nor KEVENT_FLAG_KERNEL
7362  * are set, then it will wait in the kqueue_scan_continue continuation.
7363  *
7364  * poll() will block in place, and KEVENT_FLAG_KERNEL calls
7365  * all pass KEVENT_FLAG_IMMEDIATE and will not wait.
7366  *
7367  * @param kqu
7368  * The kqueue being scanned.
7369  *
7370  * @param flags
7371  * The KEVENT_FLAG_* flags for this call.
7372  *
7373  * @param kectx
7374  * The context used for this scan.
7375  * The uthread_t::uu_save.uus_kevent storage is used for this purpose.
7376  *
7377  * @param callback
7378  * The callback to be called on events sucessfully processed.
7379  * (Either kevent_legacy_callback, kevent_modern_callback or poll_callback)
7380  */
7381 int
kqueue_scan(kqueue_t kqu,int flags,kevent_ctx_t kectx,kevent_callback_t callback)7382 kqueue_scan(kqueue_t kqu, int flags, kevent_ctx_t kectx,
7383     kevent_callback_t callback)
7384 {
7385 	int error;
7386 
7387 	for (;;) {
7388 		kqlock(kqu);
7389 		error = kqueue_process(kqu, flags, kectx, callback);
7390 
7391 		/*
7392 		 * If we got an error, events returned (EWOULDBLOCK)
7393 		 * or blocking was disallowed (KEVENT_FLAG_IMMEDIATE),
7394 		 * just return.
7395 		 */
7396 		if (__probable(error || (flags & KEVENT_FLAG_IMMEDIATE))) {
7397 			kqunlock(kqu);
7398 			return error == EWOULDBLOCK ? 0 : error;
7399 		}
7400 
7401 		assert((kqu.kq->kq_state & (KQ_WORKQ | KQ_WORKLOOP)) == 0);
7402 
7403 		kqu.kqf->kqf_state |= KQ_SLEEP;
7404 		assert_wait_deadline(&kqu.kqf->kqf_count, THREAD_ABORTSAFE,
7405 		    kectx->kec_deadline);
7406 		kqunlock(kqu);
7407 
7408 		if (__probable((flags & (KEVENT_FLAG_POLL | KEVENT_FLAG_KERNEL)) == 0)) {
7409 			thread_block_parameter(kqueue_scan_continue, kqu.kqf);
7410 			__builtin_unreachable();
7411 		}
7412 
7413 		wait_result_t wr = thread_block(THREAD_CONTINUE_NULL);
7414 		switch (wr) {
7415 		case THREAD_AWAKENED:
7416 			break;
7417 		case THREAD_TIMED_OUT:
7418 			return 0;
7419 		case THREAD_INTERRUPTED:
7420 			return EINTR;
7421 		case THREAD_RESTART:
7422 			return EBADF;
7423 		default:
7424 			panic("%s: - bad wait_result (%d)", __func__, wr);
7425 		}
7426 	}
7427 }
7428 
7429 /*!
7430  * @function kevent_internal
7431  *
7432  * @brief
7433  * Common kevent code.
7434  *
7435  * @discussion
7436  * Needs to be inlined to specialize for legacy or modern and
7437  * eliminate dead code.
7438  *
7439  * This is the core logic of kevent entry points, that will:
7440  * - register kevents
7441  * - optionally scan the kqueue for events
7442  *
7443  * The caller is giving kevent_internal a reference on the kqueue
7444  * or its fileproc that needs to be cleaned up by kevent_cleanup().
7445  */
7446 OS_ALWAYS_INLINE
7447 static inline int
kevent_internal(kqueue_t kqu,user_addr_t changelist,int nchanges,user_addr_t ueventlist,int nevents,int flags,kevent_ctx_t kectx,int32_t * retval,bool legacy)7448 kevent_internal(kqueue_t kqu,
7449     user_addr_t changelist, int nchanges,
7450     user_addr_t ueventlist, int nevents,
7451     int flags, kevent_ctx_t kectx, int32_t *retval,
7452     bool legacy)
7453 {
7454 	int error = 0, noutputs = 0, register_rc;
7455 
7456 	/* only bound threads can receive events on workloops */
7457 	if (!legacy && (flags & KEVENT_FLAG_WORKLOOP)) {
7458 #if CONFIG_WORKLOOP_DEBUG
7459 		UU_KEVENT_HISTORY_WRITE_ENTRY(current_uthread(), {
7460 			.uu_kqid = kqu.kqwl->kqwl_dynamicid,
7461 			.uu_kq = error ? NULL : kqu.kq,
7462 			.uu_error = error,
7463 			.uu_nchanges = nchanges,
7464 			.uu_nevents = nevents,
7465 			.uu_flags = flags,
7466 		});
7467 #endif // CONFIG_WORKLOOP_DEBUG
7468 
7469 		if (flags & KEVENT_FLAG_KERNEL) {
7470 			/* see kevent_workq_internal */
7471 			error = copyout(&kqu.kqwl->kqwl_dynamicid,
7472 			    ueventlist - sizeof(kqueue_id_t), sizeof(kqueue_id_t));
7473 			kectx->kec_data_resid -= sizeof(kqueue_id_t);
7474 			if (__improbable(error)) {
7475 				goto out;
7476 			}
7477 		}
7478 
7479 		if (kevent_args_requesting_events(flags, nevents)) {
7480 			/*
7481 			 * Disable the R2K notification while doing a register, if the
7482 			 * caller wants events too, we don't want the AST to be set if we
7483 			 * will process these events soon.
7484 			 */
7485 			kqlock(kqu);
7486 			kqu.kq->kq_state &= ~KQ_R2K_ARMED;
7487 			kqunlock(kqu);
7488 			flags |= KEVENT_FLAG_NEEDS_END_PROCESSING;
7489 		}
7490 	}
7491 
7492 	/* register all the change requests the user provided... */
7493 	while (nchanges > 0 && error == 0) {
7494 		struct kevent_qos_s kev;
7495 		struct knote *kn = NULL;
7496 
7497 		if (legacy) {
7498 			error = kevent_legacy_copyin(&changelist, &kev, flags);
7499 		} else {
7500 			error = kevent_modern_copyin(&changelist, &kev);
7501 		}
7502 		if (error) {
7503 			break;
7504 		}
7505 
7506 		register_rc = kevent_register(kqu.kq, &kev, &kn);
7507 		if (__improbable(!legacy && (register_rc & FILTER_REGISTER_WAIT))) {
7508 			thread_t thread = current_thread();
7509 
7510 			kqlock_held(kqu);
7511 
7512 			if (act_clear_astkevent(thread, AST_KEVENT_REDRIVE_THREADREQ)) {
7513 				workq_kern_threadreq_redrive(kqu.kq->kq_p, WORKQ_THREADREQ_NONE);
7514 			}
7515 
7516 			// f_post_register_wait is meant to call a continuation and not to
7517 			// return, which is why we don't support FILTER_REGISTER_WAIT if
7518 			// KEVENT_FLAG_ERROR_EVENTS is not passed, or if the event that
7519 			// waits isn't the last.
7520 			//
7521 			// It is implementable, but not used by any userspace code at the
7522 			// moment, so for now return ENOTSUP if someone tries to do it.
7523 			if (nchanges == 1 && noutputs < nevents &&
7524 			    (flags & KEVENT_FLAG_KERNEL) == 0 &&
7525 			    (flags & KEVENT_FLAG_PARKING) == 0 &&
7526 			    (flags & KEVENT_FLAG_ERROR_EVENTS) &&
7527 			    (flags & KEVENT_FLAG_WORKLOOP)) {
7528 				uthread_t ut = get_bsdthread_info(thread);
7529 
7530 				/*
7531 				 * store the continuation/completion data in the uthread
7532 				 *
7533 				 * Note: the kectx aliases with this,
7534 				 * and is destroyed in the process.
7535 				 */
7536 				ut->uu_save.uus_kevent_register = (struct _kevent_register){
7537 					.kev        = kev,
7538 					.kqwl       = kqu.kqwl,
7539 					.eventout   = noutputs,
7540 					.ueventlist = ueventlist,
7541 				};
7542 				knote_fops(kn)->f_post_register_wait(ut, kn,
7543 				    &ut->uu_save.uus_kevent_register);
7544 				__builtin_unreachable();
7545 			}
7546 			kqunlock(kqu);
7547 
7548 			kev.flags |= EV_ERROR;
7549 			kev.data = ENOTSUP;
7550 		} else {
7551 			assert((register_rc & FILTER_REGISTER_WAIT) == 0);
7552 		}
7553 
7554 		// keep in sync with kevent_register_wait_return()
7555 		if (noutputs < nevents && (kev.flags & (EV_ERROR | EV_RECEIPT))) {
7556 			if ((kev.flags & EV_ERROR) == 0) {
7557 				kev.flags |= EV_ERROR;
7558 				kev.data = 0;
7559 			}
7560 			if (legacy) {
7561 				error = kevent_legacy_copyout(&kev, &ueventlist, flags);
7562 			} else {
7563 				error = kevent_modern_copyout(&kev, &ueventlist);
7564 			}
7565 			if (error == 0) {
7566 				noutputs++;
7567 			}
7568 		} else if (kev.flags & EV_ERROR) {
7569 			error = (int)kev.data;
7570 		}
7571 		nchanges--;
7572 	}
7573 
7574 	if ((flags & KEVENT_FLAG_ERROR_EVENTS) == 0 &&
7575 	    nevents > 0 && noutputs == 0 && error == 0) {
7576 		kectx->kec_process_flags = flags;
7577 		kectx->kec_process_nevents = nevents;
7578 		kectx->kec_process_noutputs = 0;
7579 		kectx->kec_process_eventlist = ueventlist;
7580 
7581 		if (legacy) {
7582 			error = kqueue_scan(kqu.kq, flags, kectx, kevent_legacy_callback);
7583 		} else {
7584 			error = kqueue_scan(kqu.kq, flags, kectx, kevent_modern_callback);
7585 		}
7586 
7587 		noutputs = kectx->kec_process_noutputs;
7588 	} else if (!legacy && (flags & KEVENT_FLAG_NEEDS_END_PROCESSING)) {
7589 		/*
7590 		 * If we didn't through kqworkloop_end_processing(),
7591 		 * we need to do it here.
7592 		 *
7593 		 * kqueue_scan will call kqworkloop_end_processing(),
7594 		 * so we only need to do it if we didn't scan.
7595 		 */
7596 		kqlock(kqu);
7597 		kqworkloop_end_processing(kqu.kqwl, 0, 0);
7598 		kqunlock(kqu);
7599 	}
7600 
7601 	*retval = noutputs;
7602 out:
7603 	return kevent_cleanup(kqu.kq, flags, error, kectx);
7604 }
7605 
7606 #pragma mark modern syscalls: kevent_qos, kevent_id, kevent_workq_internal
7607 
7608 /*!
7609  * @function kevent_modern_internal
7610  *
7611  * @brief
7612  * The backend of the kevent_id and kevent_workq_internal entry points.
7613  *
7614  * @discussion
7615  * Needs to be inline due to the number of arguments.
7616  */
7617 OS_NOINLINE
7618 static int
kevent_modern_internal(kqueue_t kqu,user_addr_t changelist,int nchanges,user_addr_t ueventlist,int nevents,int flags,kevent_ctx_t kectx,int32_t * retval)7619 kevent_modern_internal(kqueue_t kqu,
7620     user_addr_t changelist, int nchanges,
7621     user_addr_t ueventlist, int nevents,
7622     int flags, kevent_ctx_t kectx, int32_t *retval)
7623 {
7624 	return kevent_internal(kqu.kq, changelist, nchanges,
7625 	           ueventlist, nevents, flags, kectx, retval, /*legacy*/ false);
7626 }
7627 
7628 /*!
7629  * @function kevent_id
7630  *
7631  * @brief
7632  * The kevent_id() syscall.
7633  */
7634 int
kevent_id(struct proc * p,struct kevent_id_args * uap,int32_t * retval)7635 kevent_id(struct proc *p, struct kevent_id_args *uap, int32_t *retval)
7636 {
7637 	int error, flags = uap->flags & KEVENT_FLAG_USER;
7638 	uthread_t uth = current_uthread();
7639 	workq_threadreq_t kqr = uth->uu_kqr_bound;
7640 	kevent_ctx_t kectx = &uth->uu_save.uus_kevent;
7641 	kqueue_t kqu;
7642 
7643 	flags = kevent_adjust_flags_for_proc(p, flags);
7644 	flags |= KEVENT_FLAG_DYNAMIC_KQUEUE;
7645 
7646 	if (__improbable((flags & (KEVENT_FLAG_WORKQ | KEVENT_FLAG_WORKLOOP)) !=
7647 	    KEVENT_FLAG_WORKLOOP)) {
7648 		return EINVAL;
7649 	}
7650 
7651 	error = kevent_get_data_size(flags, uap->data_available, uap->data_out, kectx);
7652 	if (__improbable(error)) {
7653 		return error;
7654 	}
7655 
7656 	kectx->kec_deadline = 0;
7657 	kectx->kec_fp       = NULL;
7658 	kectx->kec_fd       = -1;
7659 	/* the kec_process_* fields are filled if kqueue_scann is called only */
7660 
7661 	/*
7662 	 * Get the kq we are going to be working on
7663 	 * As a fastpath, look at the currently bound workloop.
7664 	 */
7665 	kqu.kqwl = kqr ? kqr_kqworkloop(kqr) : NULL;
7666 	if (kqu.kqwl && kqu.kqwl->kqwl_dynamicid == uap->id) {
7667 		if (__improbable(flags & KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST)) {
7668 			return EEXIST;
7669 		}
7670 		kqworkloop_retain(kqu.kqwl);
7671 	} else if (__improbable(kevent_args_requesting_events(flags, uap->nevents))) {
7672 		return EXDEV;
7673 	} else {
7674 		error = kqworkloop_get_or_create(p, uap->id, NULL, flags, &kqu.kqwl);
7675 		if (__improbable(error)) {
7676 			return error;
7677 		}
7678 	}
7679 
7680 	return kevent_modern_internal(kqu, uap->changelist, uap->nchanges,
7681 	           uap->eventlist, uap->nevents, flags, kectx, retval);
7682 }
7683 
7684 /**!
7685  * @function kevent_workq_internal
7686  *
7687  * @discussion
7688  * This function is exported for the sake of the workqueue subsystem.
7689  *
7690  * It is called in two ways:
7691  * - when a thread is about to go to userspace to ask for pending event
7692  * - when a thread is returning from userspace with events back
7693  *
7694  * the workqueue subsystem will only use the following flags:
7695  * - KEVENT_FLAG_STACK_DATA (always)
7696  * - KEVENT_FLAG_IMMEDIATE (always)
7697  * - KEVENT_FLAG_PARKING (depending on whether it is going to or returning from
7698  *   userspace).
7699  *
7700  * It implicitly acts on the bound kqueue, and for the case of workloops
7701  * will copyout the kqueue ID before anything else.
7702  *
7703  *
7704  * Pthread will have setup the various arguments to fit this stack layout:
7705  *
7706  * +-------....----+--------------+-----------+--------------------+
7707  * |  user stack   |  data avail  |  nevents  |   pthread_self()   |
7708  * +-------....----+--------------+-----------+--------------------+
7709  *                 ^              ^
7710  *             data_out       eventlist
7711  *
7712  * When a workloop is used, the workloop ID is copied out right before
7713  * the eventlist and is taken from the data buffer.
7714  *
7715  * @warning
7716  * This function is carefuly tailored to not make any call except the final tail
7717  * call into kevent_modern_internal. (LTO inlines current_uthread()).
7718  *
7719  * This function is performance sensitive due to the workq subsystem.
7720  */
7721 int
kevent_workq_internal(struct proc * p,user_addr_t changelist,int nchanges,user_addr_t eventlist,int nevents,user_addr_t data_out,user_size_t * data_available,unsigned int flags,int32_t * retval)7722 kevent_workq_internal(struct proc *p,
7723     user_addr_t changelist, int nchanges,
7724     user_addr_t eventlist, int nevents,
7725     user_addr_t data_out, user_size_t *data_available,
7726     unsigned int flags, int32_t *retval)
7727 {
7728 	uthread_t uth = current_uthread();
7729 	workq_threadreq_t kqr = uth->uu_kqr_bound;
7730 	kevent_ctx_t kectx = &uth->uu_save.uus_kevent;
7731 	kqueue_t kqu;
7732 
7733 	assert(flags == (KEVENT_FLAG_STACK_DATA | KEVENT_FLAG_IMMEDIATE) ||
7734 	    flags == (KEVENT_FLAG_STACK_DATA | KEVENT_FLAG_IMMEDIATE | KEVENT_FLAG_PARKING));
7735 
7736 	kectx->kec_data_out   = data_out;
7737 	kectx->kec_data_avail = (uint64_t)data_available;
7738 	kectx->kec_data_size  = *data_available;
7739 	kectx->kec_data_resid = *data_available;
7740 	kectx->kec_deadline   = 0;
7741 	kectx->kec_fp         = NULL;
7742 	kectx->kec_fd         = -1;
7743 	/* the kec_process_* fields are filled if kqueue_scann is called only */
7744 
7745 	flags = kevent_adjust_flags_for_proc(p, flags);
7746 
7747 	if (kqr->tr_flags & WORKQ_TR_FLAG_WORKLOOP) {
7748 		kqu.kqwl = __container_of(kqr, struct kqworkloop, kqwl_request);
7749 		kqworkloop_retain(kqu.kqwl);
7750 
7751 		flags |= KEVENT_FLAG_WORKLOOP | KEVENT_FLAG_DYNAMIC_KQUEUE |
7752 		    KEVENT_FLAG_KERNEL;
7753 	} else {
7754 		kqu.kqwq = p->p_fd.fd_wqkqueue;
7755 
7756 		flags |= KEVENT_FLAG_WORKQ | KEVENT_FLAG_KERNEL;
7757 	}
7758 
7759 	return kevent_modern_internal(kqu, changelist, nchanges,
7760 	           eventlist, nevents, flags, kectx, retval);
7761 }
7762 
7763 /*!
7764  * @function kevent_qos
7765  *
7766  * @brief
7767  * The kevent_qos() syscall.
7768  */
7769 int
kevent_qos(struct proc * p,struct kevent_qos_args * uap,int32_t * retval)7770 kevent_qos(struct proc *p, struct kevent_qos_args *uap, int32_t *retval)
7771 {
7772 	uthread_t uth = current_uthread();
7773 	kevent_ctx_t kectx = &uth->uu_save.uus_kevent;
7774 	int error, flags = uap->flags & KEVENT_FLAG_USER;
7775 	struct kqueue *kq;
7776 
7777 	if (__improbable(flags & KEVENT_ID_FLAG_USER)) {
7778 		return EINVAL;
7779 	}
7780 
7781 	flags = kevent_adjust_flags_for_proc(p, flags);
7782 
7783 	error = kevent_get_data_size(flags, uap->data_available, uap->data_out, kectx);
7784 	if (__improbable(error)) {
7785 		return error;
7786 	}
7787 
7788 	kectx->kec_deadline = 0;
7789 	kectx->kec_fp       = NULL;
7790 	kectx->kec_fd       = uap->fd;
7791 	/* the kec_process_* fields are filled if kqueue_scann is called only */
7792 
7793 	/* get the kq we are going to be working on */
7794 	if (__probable(flags & KEVENT_FLAG_WORKQ)) {
7795 		error = kevent_get_kqwq(p, flags, uap->nevents, &kq);
7796 	} else {
7797 		error = kevent_get_kqfile(p, uap->fd, flags, &kectx->kec_fp, &kq);
7798 	}
7799 	if (__improbable(error)) {
7800 		return error;
7801 	}
7802 
7803 	return kevent_modern_internal(kq, uap->changelist, uap->nchanges,
7804 	           uap->eventlist, uap->nevents, flags, kectx, retval);
7805 }
7806 
7807 #pragma mark legacy syscalls: kevent, kevent64
7808 
7809 /*!
7810  * @function kevent_legacy_get_deadline
7811  *
7812  * @brief
7813  * Compute the deadline for the legacy kevent syscalls.
7814  *
7815  * @discussion
7816  * This is not necessary if KEVENT_FLAG_IMMEDIATE is specified,
7817  * as this takes precedence over the deadline.
7818  *
7819  * This function will fail if utimeout is USER_ADDR_NULL
7820  * (the caller should check).
7821  */
7822 static int
kevent_legacy_get_deadline(int flags,user_addr_t utimeout,uint64_t * deadline)7823 kevent_legacy_get_deadline(int flags, user_addr_t utimeout, uint64_t *deadline)
7824 {
7825 	struct timespec ts;
7826 
7827 	if (flags & KEVENT_FLAG_PROC64) {
7828 		struct user64_timespec ts64;
7829 		int error = copyin(utimeout, &ts64, sizeof(ts64));
7830 		if (__improbable(error)) {
7831 			return error;
7832 		}
7833 		ts.tv_sec = (unsigned long)ts64.tv_sec;
7834 		ts.tv_nsec = (long)ts64.tv_nsec;
7835 	} else {
7836 		struct user32_timespec ts32;
7837 		int error = copyin(utimeout, &ts32, sizeof(ts32));
7838 		if (__improbable(error)) {
7839 			return error;
7840 		}
7841 		ts.tv_sec = ts32.tv_sec;
7842 		ts.tv_nsec = ts32.tv_nsec;
7843 	}
7844 	if (!timespec_is_valid(&ts)) {
7845 		return EINVAL;
7846 	}
7847 
7848 	clock_absolutetime_interval_to_deadline(tstoabstime(&ts), deadline);
7849 	return 0;
7850 }
7851 
7852 /*!
7853  * @function kevent_legacy_internal
7854  *
7855  * @brief
7856  * The core implementation for kevent and kevent64
7857  */
7858 OS_NOINLINE
7859 static int
kevent_legacy_internal(struct proc * p,struct kevent64_args * uap,int32_t * retval,int flags)7860 kevent_legacy_internal(struct proc *p, struct kevent64_args *uap,
7861     int32_t *retval, int flags)
7862 {
7863 	uthread_t uth = current_uthread();
7864 	kevent_ctx_t kectx = &uth->uu_save.uus_kevent;
7865 	struct kqueue *kq;
7866 	int error;
7867 
7868 	if (__improbable(uap->flags & KEVENT_ID_FLAG_USER)) {
7869 		return EINVAL;
7870 	}
7871 
7872 	flags = kevent_adjust_flags_for_proc(p, flags);
7873 
7874 	kectx->kec_data_out   = 0;
7875 	kectx->kec_data_avail = 0;
7876 	kectx->kec_data_size  = 0;
7877 	kectx->kec_data_resid = 0;
7878 	kectx->kec_deadline   = 0;
7879 	kectx->kec_fp         = NULL;
7880 	kectx->kec_fd         = uap->fd;
7881 	/* the kec_process_* fields are filled if kqueue_scann is called only */
7882 
7883 	/* convert timeout to absolute - if we have one (and not immediate) */
7884 	if (__improbable(uap->timeout && !(flags & KEVENT_FLAG_IMMEDIATE))) {
7885 		error = kevent_legacy_get_deadline(flags, uap->timeout,
7886 		    &kectx->kec_deadline);
7887 		if (__improbable(error)) {
7888 			return error;
7889 		}
7890 	}
7891 
7892 	/* get the kq we are going to be working on */
7893 	if (flags & KEVENT_FLAG_WORKQ) {
7894 		error = kevent_get_kqwq(p, flags, uap->nevents, &kq);
7895 	} else {
7896 		error = kevent_get_kqfile(p, uap->fd, flags, &kectx->kec_fp, &kq);
7897 	}
7898 	if (__improbable(error)) {
7899 		return error;
7900 	}
7901 
7902 	return kevent_internal(kq, uap->changelist, uap->nchanges,
7903 	           uap->eventlist, uap->nevents, flags, kectx, retval,
7904 	           /*legacy*/ true);
7905 }
7906 
7907 /*!
7908  * @function kevent
7909  *
7910  * @brief
7911  * The legacy kevent() syscall.
7912  */
7913 int
kevent(struct proc * p,struct kevent_args * uap,int32_t * retval)7914 kevent(struct proc *p, struct kevent_args *uap, int32_t *retval)
7915 {
7916 	struct kevent64_args args = {
7917 		.fd         = uap->fd,
7918 		.changelist = uap->changelist,
7919 		.nchanges   = uap->nchanges,
7920 		.eventlist  = uap->eventlist,
7921 		.nevents    = uap->nevents,
7922 		.timeout    = uap->timeout,
7923 	};
7924 
7925 	return kevent_legacy_internal(p, &args, retval, KEVENT_FLAG_LEGACY32);
7926 }
7927 
7928 /*!
7929  * @function kevent64
7930  *
7931  * @brief
7932  * The legacy kevent64() syscall.
7933  */
7934 int
kevent64(struct proc * p,struct kevent64_args * uap,int32_t * retval)7935 kevent64(struct proc *p, struct kevent64_args *uap, int32_t *retval)
7936 {
7937 	int flags = (uap->flags & KEVENT_FLAG_USER) | KEVENT_FLAG_LEGACY64;
7938 	return kevent_legacy_internal(p, uap, retval, flags);
7939 }
7940 
7941 #pragma mark - socket interface
7942 
7943 #if SOCKETS
7944 #include <sys/param.h>
7945 #include <sys/socket.h>
7946 #include <sys/protosw.h>
7947 #include <sys/domain.h>
7948 #include <sys/mbuf.h>
7949 #include <sys/kern_event.h>
7950 #include <sys/malloc.h>
7951 #include <sys/sys_domain.h>
7952 #include <sys/syslog.h>
7953 
7954 #ifndef ROUNDUP64
7955 #define ROUNDUP64(x) P2ROUNDUP((x), sizeof (u_int64_t))
7956 #endif
7957 
7958 #ifndef ADVANCE64
7959 #define ADVANCE64(p, n) (void*)((char *)(p) + ROUNDUP64(n))
7960 #endif
7961 
7962 static LCK_GRP_DECLARE(kev_lck_grp, "Kernel Event Protocol");
7963 static LCK_RW_DECLARE(kev_rwlock, &kev_lck_grp);
7964 
7965 static int kev_attach(struct socket *so, int proto, struct proc *p);
7966 static int kev_detach(struct socket *so);
7967 static int kev_control(struct socket *so, u_long cmd, caddr_t data,
7968     struct ifnet *ifp, struct proc *p);
7969 static lck_mtx_t * event_getlock(struct socket *, int);
7970 static int event_lock(struct socket *, int, void *);
7971 static int event_unlock(struct socket *, int, void *);
7972 
7973 static int event_sofreelastref(struct socket *);
7974 static void kev_delete(struct kern_event_pcb *);
7975 
7976 static struct pr_usrreqs event_usrreqs = {
7977 	.pru_attach =           kev_attach,
7978 	.pru_control =          kev_control,
7979 	.pru_detach =           kev_detach,
7980 	.pru_soreceive =        soreceive,
7981 };
7982 
7983 static struct protosw eventsw[] = {
7984 	{
7985 		.pr_type =              SOCK_RAW,
7986 		.pr_protocol =          SYSPROTO_EVENT,
7987 		.pr_flags =             PR_ATOMIC,
7988 		.pr_usrreqs =           &event_usrreqs,
7989 		.pr_lock =              event_lock,
7990 		.pr_unlock =            event_unlock,
7991 		.pr_getlock =           event_getlock,
7992 	}
7993 };
7994 
7995 __private_extern__ int kevt_getstat SYSCTL_HANDLER_ARGS;
7996 __private_extern__ int kevt_pcblist SYSCTL_HANDLER_ARGS;
7997 
7998 SYSCTL_NODE(_net_systm, OID_AUTO, kevt,
7999     CTLFLAG_RW | CTLFLAG_LOCKED, 0, "Kernel event family");
8000 
8001 struct kevtstat kevtstat;
8002 SYSCTL_PROC(_net_systm_kevt, OID_AUTO, stats,
8003     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
8004     kevt_getstat, "S,kevtstat", "");
8005 
8006 SYSCTL_PROC(_net_systm_kevt, OID_AUTO, pcblist,
8007     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
8008     kevt_pcblist, "S,xkevtpcb", "");
8009 
8010 static lck_mtx_t *
event_getlock(struct socket * so,int flags)8011 event_getlock(struct socket *so, int flags)
8012 {
8013 #pragma unused(flags)
8014 	struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *)so->so_pcb;
8015 
8016 	if (so->so_pcb != NULL) {
8017 		if (so->so_usecount < 0) {
8018 			panic("%s: so=%p usecount=%d lrh= %s", __func__,
8019 			    so, so->so_usecount, solockhistory_nr(so));
8020 		}
8021 		/* NOTREACHED */
8022 	} else {
8023 		panic("%s: so=%p NULL NO so_pcb %s", __func__,
8024 		    so, solockhistory_nr(so));
8025 		/* NOTREACHED */
8026 	}
8027 	return &ev_pcb->evp_mtx;
8028 }
8029 
8030 static int
event_lock(struct socket * so,int refcount,void * lr)8031 event_lock(struct socket *so, int refcount, void *lr)
8032 {
8033 	void *lr_saved;
8034 
8035 	if (lr == NULL) {
8036 		lr_saved = __builtin_return_address(0);
8037 	} else {
8038 		lr_saved = lr;
8039 	}
8040 
8041 	if (so->so_pcb != NULL) {
8042 		lck_mtx_lock(&((struct kern_event_pcb *)so->so_pcb)->evp_mtx);
8043 	} else {
8044 		panic("%s: so=%p NO PCB! lr=%p lrh= %s", __func__,
8045 		    so, lr_saved, solockhistory_nr(so));
8046 		/* NOTREACHED */
8047 	}
8048 
8049 	if (so->so_usecount < 0) {
8050 		panic("%s: so=%p so_pcb=%p lr=%p ref=%d lrh= %s", __func__,
8051 		    so, so->so_pcb, lr_saved, so->so_usecount,
8052 		    solockhistory_nr(so));
8053 		/* NOTREACHED */
8054 	}
8055 
8056 	if (refcount) {
8057 		so->so_usecount++;
8058 	}
8059 
8060 	so->lock_lr[so->next_lock_lr] = lr_saved;
8061 	so->next_lock_lr = (so->next_lock_lr + 1) % SO_LCKDBG_MAX;
8062 	return 0;
8063 }
8064 
8065 static int
event_unlock(struct socket * so,int refcount,void * lr)8066 event_unlock(struct socket *so, int refcount, void *lr)
8067 {
8068 	void *lr_saved;
8069 	lck_mtx_t *mutex_held;
8070 
8071 	if (lr == NULL) {
8072 		lr_saved = __builtin_return_address(0);
8073 	} else {
8074 		lr_saved = lr;
8075 	}
8076 
8077 	if (refcount) {
8078 		so->so_usecount--;
8079 	}
8080 	if (so->so_usecount < 0) {
8081 		panic("%s: so=%p usecount=%d lrh= %s", __func__,
8082 		    so, so->so_usecount, solockhistory_nr(so));
8083 		/* NOTREACHED */
8084 	}
8085 	if (so->so_pcb == NULL) {
8086 		panic("%s: so=%p NO PCB usecount=%d lr=%p lrh= %s", __func__,
8087 		    so, so->so_usecount, (void *)lr_saved,
8088 		    solockhistory_nr(so));
8089 		/* NOTREACHED */
8090 	}
8091 	mutex_held = (&((struct kern_event_pcb *)so->so_pcb)->evp_mtx);
8092 
8093 	LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
8094 	so->unlock_lr[so->next_unlock_lr] = lr_saved;
8095 	so->next_unlock_lr = (so->next_unlock_lr + 1) % SO_LCKDBG_MAX;
8096 
8097 	if (so->so_usecount == 0) {
8098 		VERIFY(so->so_flags & SOF_PCBCLEARING);
8099 		event_sofreelastref(so);
8100 	} else {
8101 		lck_mtx_unlock(mutex_held);
8102 	}
8103 
8104 	return 0;
8105 }
8106 
8107 static int
event_sofreelastref(struct socket * so)8108 event_sofreelastref(struct socket *so)
8109 {
8110 	struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *)so->so_pcb;
8111 
8112 	LCK_MTX_ASSERT(&(ev_pcb->evp_mtx), LCK_MTX_ASSERT_OWNED);
8113 
8114 	so->so_pcb = NULL;
8115 
8116 	/*
8117 	 * Disable upcall in the event another thread is in kev_post_msg()
8118 	 * appending record to the receive socket buffer, since sbwakeup()
8119 	 * may release the socket lock otherwise.
8120 	 */
8121 	so->so_rcv.sb_flags &= ~SB_UPCALL;
8122 	so->so_snd.sb_flags &= ~SB_UPCALL;
8123 	so->so_event = sonullevent;
8124 	lck_mtx_unlock(&(ev_pcb->evp_mtx));
8125 
8126 	LCK_MTX_ASSERT(&(ev_pcb->evp_mtx), LCK_MTX_ASSERT_NOTOWNED);
8127 	lck_rw_lock_exclusive(&kev_rwlock);
8128 	LIST_REMOVE(ev_pcb, evp_link);
8129 	kevtstat.kes_pcbcount--;
8130 	kevtstat.kes_gencnt++;
8131 	lck_rw_done(&kev_rwlock);
8132 	kev_delete(ev_pcb);
8133 
8134 	sofreelastref(so, 1);
8135 	return 0;
8136 }
8137 
8138 static int event_proto_count = (sizeof(eventsw) / sizeof(struct protosw));
8139 
8140 static
8141 struct kern_event_head kern_event_head;
8142 
8143 static u_int32_t static_event_id = 0;
8144 
8145 static ZONE_DEFINE(ev_pcb_zone, "kerneventpcb",
8146     sizeof(struct kern_event_pcb), ZC_ZFREE_CLEARMEM);
8147 
8148 /*
8149  * Install the protosw's for the NKE manager.  Invoked at extension load time
8150  */
8151 void
kern_event_init(struct domain * dp)8152 kern_event_init(struct domain *dp)
8153 {
8154 	struct protosw *pr;
8155 	int i;
8156 
8157 	VERIFY(!(dp->dom_flags & DOM_INITIALIZED));
8158 	VERIFY(dp == systemdomain);
8159 
8160 	for (i = 0, pr = &eventsw[0]; i < event_proto_count; i++, pr++) {
8161 		net_add_proto(pr, dp, 1);
8162 	}
8163 }
8164 
8165 static int
kev_attach(struct socket * so,__unused int proto,__unused struct proc * p)8166 kev_attach(struct socket *so, __unused int proto, __unused struct proc *p)
8167 {
8168 	int error = 0;
8169 	struct kern_event_pcb *ev_pcb;
8170 
8171 	error = soreserve(so, KEV_SNDSPACE, KEV_RECVSPACE);
8172 	if (error != 0) {
8173 		return error;
8174 	}
8175 
8176 	ev_pcb = zalloc_flags(ev_pcb_zone, Z_WAITOK | Z_ZERO);
8177 	lck_mtx_init(&ev_pcb->evp_mtx, &kev_lck_grp, LCK_ATTR_NULL);
8178 
8179 	ev_pcb->evp_socket = so;
8180 	ev_pcb->evp_vendor_code_filter = 0xffffffff;
8181 
8182 	so->so_pcb = (caddr_t) ev_pcb;
8183 	lck_rw_lock_exclusive(&kev_rwlock);
8184 	LIST_INSERT_HEAD(&kern_event_head, ev_pcb, evp_link);
8185 	kevtstat.kes_pcbcount++;
8186 	kevtstat.kes_gencnt++;
8187 	lck_rw_done(&kev_rwlock);
8188 
8189 	return error;
8190 }
8191 
8192 static void
kev_delete(struct kern_event_pcb * ev_pcb)8193 kev_delete(struct kern_event_pcb *ev_pcb)
8194 {
8195 	VERIFY(ev_pcb != NULL);
8196 	lck_mtx_destroy(&ev_pcb->evp_mtx, &kev_lck_grp);
8197 	zfree(ev_pcb_zone, ev_pcb);
8198 }
8199 
8200 static int
kev_detach(struct socket * so)8201 kev_detach(struct socket *so)
8202 {
8203 	struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *) so->so_pcb;
8204 
8205 	if (ev_pcb != NULL) {
8206 		soisdisconnected(so);
8207 		so->so_flags |= SOF_PCBCLEARING;
8208 	}
8209 
8210 	return 0;
8211 }
8212 
8213 /*
8214  * For now, kev_vendor_code and mbuf_tags use the same
8215  * mechanism.
8216  */
8217 errno_t
kev_vendor_code_find(const char * string,u_int32_t * out_vendor_code)8218 kev_vendor_code_find(
8219 	const char      *string,
8220 	u_int32_t       *out_vendor_code)
8221 {
8222 	if (strlen(string) >= KEV_VENDOR_CODE_MAX_STR_LEN) {
8223 		return EINVAL;
8224 	}
8225 	return net_str_id_find_internal(string, out_vendor_code,
8226 	           NSI_VENDOR_CODE, 1);
8227 }
8228 
8229 errno_t
kev_msg_post(struct kev_msg * event_msg)8230 kev_msg_post(struct kev_msg *event_msg)
8231 {
8232 	mbuf_tag_id_t min_vendor, max_vendor;
8233 
8234 	net_str_id_first_last(&min_vendor, &max_vendor, NSI_VENDOR_CODE);
8235 
8236 	if (event_msg == NULL) {
8237 		return EINVAL;
8238 	}
8239 
8240 	/*
8241 	 * Limit third parties to posting events for registered vendor codes
8242 	 * only
8243 	 */
8244 	if (event_msg->vendor_code < min_vendor ||
8245 	    event_msg->vendor_code > max_vendor) {
8246 		os_atomic_inc(&kevtstat.kes_badvendor, relaxed);
8247 		return EINVAL;
8248 	}
8249 	return kev_post_msg(event_msg);
8250 }
8251 
8252 static int
kev_post_msg_internal(struct kev_msg * event_msg,int wait)8253 kev_post_msg_internal(struct kev_msg *event_msg, int wait)
8254 {
8255 	struct mbuf *m, *m2;
8256 	struct kern_event_pcb *ev_pcb;
8257 	struct kern_event_msg *ev;
8258 	char *tmp;
8259 	u_int32_t total_size;
8260 	int i;
8261 
8262 #if SKYWALK && defined(XNU_TARGET_OS_OSX)
8263 	/*
8264 	 * Special hook for ALF state updates
8265 	 */
8266 	if (event_msg->vendor_code == KEV_VENDOR_APPLE &&
8267 	    event_msg->kev_class == KEV_NKE_CLASS &&
8268 	    event_msg->kev_subclass == KEV_NKE_ALF_SUBCLASS &&
8269 	    event_msg->event_code == KEV_NKE_ALF_STATE_CHANGED) {
8270 #if (DEBUG || DEVELOPMENT)
8271 		os_log_info(OS_LOG_DEFAULT, "KEV_NKE_ALF_STATE_CHANGED posted");
8272 #endif /* DEBUG || DEVELOPMENT */
8273 		net_filter_event_mark(NET_FILTER_EVENT_ALF,
8274 		    net_check_compatible_alf());
8275 	}
8276 #endif /* SKYWALK && XNU_TARGET_OS_OSX */
8277 
8278 	/* Verify the message is small enough to fit in one mbuf w/o cluster */
8279 	total_size = KEV_MSG_HEADER_SIZE;
8280 
8281 	for (i = 0; i < 5; i++) {
8282 		if (event_msg->dv[i].data_length == 0) {
8283 			break;
8284 		}
8285 		total_size += event_msg->dv[i].data_length;
8286 	}
8287 
8288 	if (total_size > MLEN) {
8289 		os_atomic_inc(&kevtstat.kes_toobig, relaxed);
8290 		return EMSGSIZE;
8291 	}
8292 
8293 	m = m_get(wait, MT_DATA);
8294 	if (m == 0) {
8295 		os_atomic_inc(&kevtstat.kes_nomem, relaxed);
8296 		return ENOMEM;
8297 	}
8298 	ev = mtod(m, struct kern_event_msg *);
8299 	total_size = KEV_MSG_HEADER_SIZE;
8300 
8301 	tmp = (char *) &ev->event_data[0];
8302 	for (i = 0; i < 5; i++) {
8303 		if (event_msg->dv[i].data_length == 0) {
8304 			break;
8305 		}
8306 
8307 		total_size += event_msg->dv[i].data_length;
8308 		bcopy(event_msg->dv[i].data_ptr, tmp,
8309 		    event_msg->dv[i].data_length);
8310 		tmp += event_msg->dv[i].data_length;
8311 	}
8312 
8313 	ev->id = ++static_event_id;
8314 	ev->total_size   = total_size;
8315 	ev->vendor_code  = event_msg->vendor_code;
8316 	ev->kev_class    = event_msg->kev_class;
8317 	ev->kev_subclass = event_msg->kev_subclass;
8318 	ev->event_code   = event_msg->event_code;
8319 
8320 	m->m_len = total_size;
8321 	lck_rw_lock_shared(&kev_rwlock);
8322 	for (ev_pcb = LIST_FIRST(&kern_event_head);
8323 	    ev_pcb;
8324 	    ev_pcb = LIST_NEXT(ev_pcb, evp_link)) {
8325 		lck_mtx_lock(&ev_pcb->evp_mtx);
8326 		if (ev_pcb->evp_socket->so_pcb == NULL) {
8327 			lck_mtx_unlock(&ev_pcb->evp_mtx);
8328 			continue;
8329 		}
8330 		if (ev_pcb->evp_vendor_code_filter != KEV_ANY_VENDOR) {
8331 			if (ev_pcb->evp_vendor_code_filter != ev->vendor_code) {
8332 				lck_mtx_unlock(&ev_pcb->evp_mtx);
8333 				continue;
8334 			}
8335 
8336 			if (ev_pcb->evp_class_filter != KEV_ANY_CLASS) {
8337 				if (ev_pcb->evp_class_filter != ev->kev_class) {
8338 					lck_mtx_unlock(&ev_pcb->evp_mtx);
8339 					continue;
8340 				}
8341 
8342 				if ((ev_pcb->evp_subclass_filter !=
8343 				    KEV_ANY_SUBCLASS) &&
8344 				    (ev_pcb->evp_subclass_filter !=
8345 				    ev->kev_subclass)) {
8346 					lck_mtx_unlock(&ev_pcb->evp_mtx);
8347 					continue;
8348 				}
8349 			}
8350 		}
8351 
8352 		m2 = m_copym(m, 0, m->m_len, wait);
8353 		if (m2 == 0) {
8354 			os_atomic_inc(&kevtstat.kes_nomem, relaxed);
8355 			m_free(m);
8356 			lck_mtx_unlock(&ev_pcb->evp_mtx);
8357 			lck_rw_done(&kev_rwlock);
8358 			return ENOMEM;
8359 		}
8360 		if (sbappendrecord(&ev_pcb->evp_socket->so_rcv, m2)) {
8361 			/*
8362 			 * We use "m" for the socket stats as it would be
8363 			 * unsafe to use "m2"
8364 			 */
8365 			so_inc_recv_data_stat(ev_pcb->evp_socket,
8366 			    1, m->m_len, MBUF_TC_BE);
8367 
8368 			sorwakeup(ev_pcb->evp_socket);
8369 			os_atomic_inc(&kevtstat.kes_posted, relaxed);
8370 		} else {
8371 			os_atomic_inc(&kevtstat.kes_fullsock, relaxed);
8372 		}
8373 		lck_mtx_unlock(&ev_pcb->evp_mtx);
8374 	}
8375 	m_free(m);
8376 	lck_rw_done(&kev_rwlock);
8377 
8378 	return 0;
8379 }
8380 
8381 int
kev_post_msg(struct kev_msg * event_msg)8382 kev_post_msg(struct kev_msg *event_msg)
8383 {
8384 	return kev_post_msg_internal(event_msg, M_WAIT);
8385 }
8386 
8387 int
kev_post_msg_nowait(struct kev_msg * event_msg)8388 kev_post_msg_nowait(struct kev_msg *event_msg)
8389 {
8390 	return kev_post_msg_internal(event_msg, M_NOWAIT);
8391 }
8392 
8393 static int
kev_control(struct socket * so,u_long cmd,caddr_t data,__unused struct ifnet * ifp,__unused struct proc * p)8394 kev_control(struct socket *so,
8395     u_long cmd,
8396     caddr_t data,
8397     __unused struct ifnet *ifp,
8398     __unused struct proc *p)
8399 {
8400 	struct kev_request *kev_req = (struct kev_request *) data;
8401 	struct kern_event_pcb  *ev_pcb;
8402 	struct kev_vendor_code *kev_vendor;
8403 	u_int32_t  *id_value = (u_int32_t *) data;
8404 
8405 	switch (cmd) {
8406 	case SIOCGKEVID:
8407 		*id_value = static_event_id;
8408 		break;
8409 	case SIOCSKEVFILT:
8410 		ev_pcb = (struct kern_event_pcb *) so->so_pcb;
8411 		ev_pcb->evp_vendor_code_filter = kev_req->vendor_code;
8412 		ev_pcb->evp_class_filter = kev_req->kev_class;
8413 		ev_pcb->evp_subclass_filter  = kev_req->kev_subclass;
8414 		break;
8415 	case SIOCGKEVFILT:
8416 		ev_pcb = (struct kern_event_pcb *) so->so_pcb;
8417 		kev_req->vendor_code = ev_pcb->evp_vendor_code_filter;
8418 		kev_req->kev_class   = ev_pcb->evp_class_filter;
8419 		kev_req->kev_subclass = ev_pcb->evp_subclass_filter;
8420 		break;
8421 	case SIOCGKEVVENDOR:
8422 		kev_vendor = (struct kev_vendor_code *)data;
8423 		/* Make sure string is NULL terminated */
8424 		kev_vendor->vendor_string[KEV_VENDOR_CODE_MAX_STR_LEN - 1] = 0;
8425 		return net_str_id_find_internal(kev_vendor->vendor_string,
8426 		           &kev_vendor->vendor_code, NSI_VENDOR_CODE, 0);
8427 	default:
8428 		return ENOTSUP;
8429 	}
8430 
8431 	return 0;
8432 }
8433 
8434 int
8435 kevt_getstat SYSCTL_HANDLER_ARGS
8436 {
8437 #pragma unused(oidp, arg1, arg2)
8438 	int error = 0;
8439 
8440 	lck_rw_lock_shared(&kev_rwlock);
8441 
8442 	if (req->newptr != USER_ADDR_NULL) {
8443 		error = EPERM;
8444 		goto done;
8445 	}
8446 	if (req->oldptr == USER_ADDR_NULL) {
8447 		req->oldidx = sizeof(struct kevtstat);
8448 		goto done;
8449 	}
8450 
8451 	error = SYSCTL_OUT(req, &kevtstat,
8452 	    MIN(sizeof(struct kevtstat), req->oldlen));
8453 done:
8454 	lck_rw_done(&kev_rwlock);
8455 
8456 	return error;
8457 }
8458 
8459 __private_extern__ int
8460 kevt_pcblist SYSCTL_HANDLER_ARGS
8461 {
8462 #pragma unused(oidp, arg1, arg2)
8463 	int error = 0;
8464 	uint64_t n, i;
8465 	struct xsystmgen xsg;
8466 	void *buf = NULL;
8467 	size_t item_size = ROUNDUP64(sizeof(struct xkevtpcb)) +
8468 	    ROUNDUP64(sizeof(struct xsocket_n)) +
8469 	    2 * ROUNDUP64(sizeof(struct xsockbuf_n)) +
8470 	    ROUNDUP64(sizeof(struct xsockstat_n));
8471 	struct kern_event_pcb  *ev_pcb;
8472 
8473 	buf = kalloc_data(item_size, Z_WAITOK | Z_ZERO);
8474 	if (buf == NULL) {
8475 		return ENOMEM;
8476 	}
8477 
8478 	lck_rw_lock_shared(&kev_rwlock);
8479 
8480 	n = kevtstat.kes_pcbcount;
8481 
8482 	if (req->oldptr == USER_ADDR_NULL) {
8483 		req->oldidx = (size_t) ((n + n / 8) * item_size);
8484 		goto done;
8485 	}
8486 	if (req->newptr != USER_ADDR_NULL) {
8487 		error = EPERM;
8488 		goto done;
8489 	}
8490 	bzero(&xsg, sizeof(xsg));
8491 	xsg.xg_len = sizeof(xsg);
8492 	xsg.xg_count = n;
8493 	xsg.xg_gen = kevtstat.kes_gencnt;
8494 	xsg.xg_sogen = so_gencnt;
8495 	error = SYSCTL_OUT(req, &xsg, sizeof(xsg));
8496 	if (error) {
8497 		goto done;
8498 	}
8499 	/*
8500 	 * We are done if there is no pcb
8501 	 */
8502 	if (n == 0) {
8503 		goto done;
8504 	}
8505 
8506 	i = 0;
8507 	for (i = 0, ev_pcb = LIST_FIRST(&kern_event_head);
8508 	    i < n && ev_pcb != NULL;
8509 	    i++, ev_pcb = LIST_NEXT(ev_pcb, evp_link)) {
8510 		struct xkevtpcb *xk = (struct xkevtpcb *)buf;
8511 		struct xsocket_n *xso = (struct xsocket_n *)
8512 		    ADVANCE64(xk, sizeof(*xk));
8513 		struct xsockbuf_n *xsbrcv = (struct xsockbuf_n *)
8514 		    ADVANCE64(xso, sizeof(*xso));
8515 		struct xsockbuf_n *xsbsnd = (struct xsockbuf_n *)
8516 		    ADVANCE64(xsbrcv, sizeof(*xsbrcv));
8517 		struct xsockstat_n *xsostats = (struct xsockstat_n *)
8518 		    ADVANCE64(xsbsnd, sizeof(*xsbsnd));
8519 
8520 		bzero(buf, item_size);
8521 
8522 		lck_mtx_lock(&ev_pcb->evp_mtx);
8523 
8524 		xk->kep_len = sizeof(struct xkevtpcb);
8525 		xk->kep_kind = XSO_EVT;
8526 		xk->kep_evtpcb = (uint64_t)VM_KERNEL_ADDRPERM(ev_pcb);
8527 		xk->kep_vendor_code_filter = ev_pcb->evp_vendor_code_filter;
8528 		xk->kep_class_filter = ev_pcb->evp_class_filter;
8529 		xk->kep_subclass_filter = ev_pcb->evp_subclass_filter;
8530 
8531 		sotoxsocket_n(ev_pcb->evp_socket, xso);
8532 		sbtoxsockbuf_n(ev_pcb->evp_socket ?
8533 		    &ev_pcb->evp_socket->so_rcv : NULL, xsbrcv);
8534 		sbtoxsockbuf_n(ev_pcb->evp_socket ?
8535 		    &ev_pcb->evp_socket->so_snd : NULL, xsbsnd);
8536 		sbtoxsockstat_n(ev_pcb->evp_socket, xsostats);
8537 
8538 		lck_mtx_unlock(&ev_pcb->evp_mtx);
8539 
8540 		error = SYSCTL_OUT(req, buf, item_size);
8541 	}
8542 
8543 	if (error == 0) {
8544 		/*
8545 		 * Give the user an updated idea of our state.
8546 		 * If the generation differs from what we told
8547 		 * her before, she knows that something happened
8548 		 * while we were processing this request, and it
8549 		 * might be necessary to retry.
8550 		 */
8551 		bzero(&xsg, sizeof(xsg));
8552 		xsg.xg_len = sizeof(xsg);
8553 		xsg.xg_count = n;
8554 		xsg.xg_gen = kevtstat.kes_gencnt;
8555 		xsg.xg_sogen = so_gencnt;
8556 		error = SYSCTL_OUT(req, &xsg, sizeof(xsg));
8557 		if (error) {
8558 			goto done;
8559 		}
8560 	}
8561 
8562 done:
8563 	lck_rw_done(&kev_rwlock);
8564 
8565 	kfree_data(buf, item_size);
8566 	return error;
8567 }
8568 
8569 #endif /* SOCKETS */
8570 
8571 
8572 int
fill_kqueueinfo(kqueue_t kqu,struct kqueue_info * kinfo)8573 fill_kqueueinfo(kqueue_t kqu, struct kqueue_info * kinfo)
8574 {
8575 	struct vinfo_stat * st;
8576 
8577 	st = &kinfo->kq_stat;
8578 
8579 	st->vst_size = kqu.kq->kq_count;
8580 	if (kqu.kq->kq_state & KQ_KEV_QOS) {
8581 		st->vst_blksize = sizeof(struct kevent_qos_s);
8582 	} else if (kqu.kq->kq_state & KQ_KEV64) {
8583 		st->vst_blksize = sizeof(struct kevent64_s);
8584 	} else {
8585 		st->vst_blksize = sizeof(struct kevent);
8586 	}
8587 	st->vst_mode = S_IFIFO;
8588 	st->vst_ino = (kqu.kq->kq_state & KQ_DYNAMIC) ?
8589 	    kqu.kqwl->kqwl_dynamicid : 0;
8590 
8591 	/* flags exported to libproc as PROC_KQUEUE_* (sys/proc_info.h) */
8592 #define PROC_KQUEUE_MASK (KQ_SLEEP|KQ_KEV32|KQ_KEV64|KQ_KEV_QOS|KQ_WORKQ|KQ_WORKLOOP)
8593 	static_assert(PROC_KQUEUE_SLEEP == KQ_SLEEP);
8594 	static_assert(PROC_KQUEUE_32 == KQ_KEV32);
8595 	static_assert(PROC_KQUEUE_64 == KQ_KEV64);
8596 	static_assert(PROC_KQUEUE_QOS == KQ_KEV_QOS);
8597 	static_assert(PROC_KQUEUE_WORKQ == KQ_WORKQ);
8598 	static_assert(PROC_KQUEUE_WORKLOOP == KQ_WORKLOOP);
8599 	kinfo->kq_state = kqu.kq->kq_state & PROC_KQUEUE_MASK;
8600 	if ((kqu.kq->kq_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0) {
8601 		if (kqu.kqf->kqf_sel.si_flags & SI_RECORDED) {
8602 			kinfo->kq_state |= PROC_KQUEUE_SELECT;
8603 		}
8604 	}
8605 
8606 	return 0;
8607 }
8608 
8609 static int
fill_kqueue_dyninfo(struct kqworkloop * kqwl,struct kqueue_dyninfo * kqdi)8610 fill_kqueue_dyninfo(struct kqworkloop *kqwl, struct kqueue_dyninfo *kqdi)
8611 {
8612 	workq_threadreq_t kqr = &kqwl->kqwl_request;
8613 	workq_threadreq_param_t trp = {};
8614 	int err;
8615 
8616 	if ((kqwl->kqwl_state & KQ_WORKLOOP) == 0) {
8617 		return EINVAL;
8618 	}
8619 
8620 	if ((err = fill_kqueueinfo(&kqwl->kqwl_kqueue, &kqdi->kqdi_info))) {
8621 		return err;
8622 	}
8623 
8624 	kqlock(kqwl);
8625 
8626 	kqdi->kqdi_servicer = thread_tid(kqr_thread(kqr));
8627 	kqdi->kqdi_owner = thread_tid(kqwl->kqwl_owner);
8628 	kqdi->kqdi_request_state = kqr->tr_state;
8629 	kqdi->kqdi_async_qos = kqr->tr_kq_qos_index;
8630 	kqdi->kqdi_events_qos = kqr->tr_kq_override_index;
8631 	kqdi->kqdi_sync_waiters = 0;
8632 	kqdi->kqdi_sync_waiter_qos = 0;
8633 
8634 	trp.trp_value = kqwl->kqwl_params;
8635 	if (trp.trp_flags & TRP_PRIORITY) {
8636 		kqdi->kqdi_pri = trp.trp_pri;
8637 	} else {
8638 		kqdi->kqdi_pri = 0;
8639 	}
8640 
8641 	if (trp.trp_flags & TRP_POLICY) {
8642 		kqdi->kqdi_pol = trp.trp_pol;
8643 	} else {
8644 		kqdi->kqdi_pol = 0;
8645 	}
8646 
8647 	if (trp.trp_flags & TRP_CPUPERCENT) {
8648 		kqdi->kqdi_cpupercent = trp.trp_cpupercent;
8649 	} else {
8650 		kqdi->kqdi_cpupercent = 0;
8651 	}
8652 
8653 	kqunlock(kqwl);
8654 
8655 	return 0;
8656 }
8657 
8658 
8659 static unsigned long
kevent_extinfo_emit(struct kqueue * kq,struct knote * kn,struct kevent_extinfo * buf,unsigned long buflen,unsigned long nknotes)8660 kevent_extinfo_emit(struct kqueue *kq, struct knote *kn, struct kevent_extinfo *buf,
8661     unsigned long buflen, unsigned long nknotes)
8662 {
8663 	for (; kn; kn = SLIST_NEXT(kn, kn_link)) {
8664 		if (kq == knote_get_kq(kn)) {
8665 			if (nknotes < buflen) {
8666 				struct kevent_extinfo *info = &buf[nknotes];
8667 
8668 				kqlock(kq);
8669 
8670 				info->kqext_kev         = *(struct kevent_qos_s *)&kn->kn_kevent;
8671 				if (knote_has_qos(kn)) {
8672 					info->kqext_kev.qos =
8673 					    _pthread_priority_thread_qos_fast(kn->kn_qos);
8674 				} else {
8675 					info->kqext_kev.qos = kn->kn_qos_override;
8676 				}
8677 				info->kqext_kev.filter |= 0xff00; /* sign extend filter */
8678 				info->kqext_kev.xflags  = 0; /* this is where sfflags lives */
8679 				info->kqext_kev.data    = 0; /* this is where sdata lives */
8680 				info->kqext_sdata       = kn->kn_sdata;
8681 				info->kqext_status      = kn->kn_status;
8682 				info->kqext_sfflags     = kn->kn_sfflags;
8683 
8684 				kqunlock(kq);
8685 			}
8686 
8687 			/* we return total number of knotes, which may be more than requested */
8688 			nknotes++;
8689 		}
8690 	}
8691 
8692 	return nknotes;
8693 }
8694 
8695 int
kevent_copyout_proc_dynkqids(void * proc,user_addr_t ubuf,uint32_t ubufsize,int32_t * nkqueues_out)8696 kevent_copyout_proc_dynkqids(void *proc, user_addr_t ubuf, uint32_t ubufsize,
8697     int32_t *nkqueues_out)
8698 {
8699 	proc_t p = (proc_t)proc;
8700 	struct filedesc *fdp = &p->p_fd;
8701 	unsigned int nkqueues = 0;
8702 	unsigned long ubuflen = ubufsize / sizeof(kqueue_id_t);
8703 	size_t buflen, bufsize;
8704 	kqueue_id_t *kq_ids = NULL;
8705 	int err = 0;
8706 
8707 	assert(p != NULL);
8708 
8709 	if (ubuf == USER_ADDR_NULL && ubufsize != 0) {
8710 		err = EINVAL;
8711 		goto out;
8712 	}
8713 
8714 	buflen = MIN(ubuflen, PROC_PIDDYNKQUEUES_MAX);
8715 
8716 	if (ubuflen != 0) {
8717 		if (os_mul_overflow(sizeof(kqueue_id_t), buflen, &bufsize)) {
8718 			err = ERANGE;
8719 			goto out;
8720 		}
8721 		kq_ids = (kqueue_id_t *)kalloc_data(bufsize, Z_WAITOK | Z_ZERO);
8722 		if (!kq_ids) {
8723 			err = ENOMEM;
8724 			goto out;
8725 		}
8726 	}
8727 
8728 	kqhash_lock(fdp);
8729 
8730 	if (fdp->fd_kqhashmask > 0) {
8731 		for (uint32_t i = 0; i < fdp->fd_kqhashmask + 1; i++) {
8732 			struct kqworkloop *kqwl;
8733 
8734 			LIST_FOREACH(kqwl, &fdp->fd_kqhash[i], kqwl_hashlink) {
8735 				/* report the number of kqueues, even if they don't all fit */
8736 				if (nkqueues < buflen) {
8737 					kq_ids[nkqueues] = kqwl->kqwl_dynamicid;
8738 				}
8739 				nkqueues++;
8740 			}
8741 		}
8742 	}
8743 
8744 	kqhash_unlock(fdp);
8745 
8746 	if (kq_ids) {
8747 		size_t copysize;
8748 		if (os_mul_overflow(sizeof(kqueue_id_t), MIN(buflen, nkqueues), &copysize)) {
8749 			err = ERANGE;
8750 			goto out;
8751 		}
8752 
8753 		assert(ubufsize >= copysize);
8754 		err = copyout(kq_ids, ubuf, copysize);
8755 	}
8756 
8757 out:
8758 	if (kq_ids) {
8759 		kfree_data(kq_ids, bufsize);
8760 	}
8761 
8762 	if (!err) {
8763 		*nkqueues_out = (int)min(nkqueues, PROC_PIDDYNKQUEUES_MAX);
8764 	}
8765 	return err;
8766 }
8767 
8768 int
kevent_copyout_dynkqinfo(void * proc,kqueue_id_t kq_id,user_addr_t ubuf,uint32_t ubufsize,int32_t * size_out)8769 kevent_copyout_dynkqinfo(void *proc, kqueue_id_t kq_id, user_addr_t ubuf,
8770     uint32_t ubufsize, int32_t *size_out)
8771 {
8772 	proc_t p = (proc_t)proc;
8773 	struct kqworkloop *kqwl;
8774 	int err = 0;
8775 	struct kqueue_dyninfo kqdi = { };
8776 
8777 	assert(p != NULL);
8778 
8779 	if (ubufsize < sizeof(struct kqueue_info)) {
8780 		return ENOBUFS;
8781 	}
8782 
8783 	kqwl = kqworkloop_hash_lookup_and_retain(&p->p_fd, kq_id);
8784 	if (!kqwl) {
8785 		return ESRCH;
8786 	}
8787 
8788 	/*
8789 	 * backward compatibility: allow the argument to this call to only be
8790 	 * a struct kqueue_info
8791 	 */
8792 	if (ubufsize >= sizeof(struct kqueue_dyninfo)) {
8793 		ubufsize = sizeof(struct kqueue_dyninfo);
8794 		err = fill_kqueue_dyninfo(kqwl, &kqdi);
8795 	} else {
8796 		ubufsize = sizeof(struct kqueue_info);
8797 		err = fill_kqueueinfo(&kqwl->kqwl_kqueue, &kqdi.kqdi_info);
8798 	}
8799 	if (err == 0 && (err = copyout(&kqdi, ubuf, ubufsize)) == 0) {
8800 		*size_out = ubufsize;
8801 	}
8802 	kqworkloop_release(kqwl);
8803 	return err;
8804 }
8805 
8806 int
kevent_copyout_dynkqextinfo(void * proc,kqueue_id_t kq_id,user_addr_t ubuf,uint32_t ubufsize,int32_t * nknotes_out)8807 kevent_copyout_dynkqextinfo(void *proc, kqueue_id_t kq_id, user_addr_t ubuf,
8808     uint32_t ubufsize, int32_t *nknotes_out)
8809 {
8810 	proc_t p = (proc_t)proc;
8811 	struct kqworkloop *kqwl;
8812 	int err;
8813 
8814 	kqwl = kqworkloop_hash_lookup_and_retain(&p->p_fd, kq_id);
8815 	if (!kqwl) {
8816 		return ESRCH;
8817 	}
8818 
8819 	err = pid_kqueue_extinfo(p, &kqwl->kqwl_kqueue, ubuf, ubufsize, nknotes_out);
8820 	kqworkloop_release(kqwl);
8821 	return err;
8822 }
8823 
8824 int
pid_kqueue_extinfo(proc_t p,struct kqueue * kq,user_addr_t ubuf,uint32_t bufsize,int32_t * retval)8825 pid_kqueue_extinfo(proc_t p, struct kqueue *kq, user_addr_t ubuf,
8826     uint32_t bufsize, int32_t *retval)
8827 {
8828 	struct knote *kn;
8829 	int i;
8830 	int err = 0;
8831 	struct filedesc *fdp = &p->p_fd;
8832 	unsigned long nknotes = 0;
8833 	unsigned long buflen = bufsize / sizeof(struct kevent_extinfo);
8834 	struct kevent_extinfo *kqext = NULL;
8835 
8836 	/* arbitrary upper limit to cap kernel memory usage, copyout size, etc. */
8837 	buflen = MIN(buflen, PROC_PIDFDKQUEUE_KNOTES_MAX);
8838 
8839 	kqext = (struct kevent_extinfo *)kalloc_data(buflen * sizeof(struct kevent_extinfo), Z_WAITOK | Z_ZERO);
8840 	if (kqext == NULL) {
8841 		err = ENOMEM;
8842 		goto out;
8843 	}
8844 
8845 	proc_fdlock(p);
8846 	for (i = 0; i < fdp->fd_knlistsize; i++) {
8847 		kn = SLIST_FIRST(&fdp->fd_knlist[i]);
8848 		nknotes = kevent_extinfo_emit(kq, kn, kqext, buflen, nknotes);
8849 	}
8850 	proc_fdunlock(p);
8851 
8852 	if (fdp->fd_knhashmask != 0) {
8853 		for (i = 0; i < (int)fdp->fd_knhashmask + 1; i++) {
8854 			knhash_lock(fdp);
8855 			kn = SLIST_FIRST(&fdp->fd_knhash[i]);
8856 			nknotes = kevent_extinfo_emit(kq, kn, kqext, buflen, nknotes);
8857 			knhash_unlock(fdp);
8858 		}
8859 	}
8860 
8861 	assert(bufsize >= sizeof(struct kevent_extinfo) * MIN(buflen, nknotes));
8862 	err = copyout(kqext, ubuf, sizeof(struct kevent_extinfo) * MIN(buflen, nknotes));
8863 
8864 out:
8865 	kfree_data(kqext, buflen * sizeof(struct kevent_extinfo));
8866 
8867 	if (!err) {
8868 		*retval = (int32_t)MIN(nknotes, PROC_PIDFDKQUEUE_KNOTES_MAX);
8869 	}
8870 	return err;
8871 }
8872 
8873 static unsigned int
klist_copy_udata(struct klist * list,uint64_t * buf,unsigned int buflen,unsigned int nknotes)8874 klist_copy_udata(struct klist *list, uint64_t *buf,
8875     unsigned int buflen, unsigned int nknotes)
8876 {
8877 	struct knote *kn;
8878 	SLIST_FOREACH(kn, list, kn_link) {
8879 		if (nknotes < buflen) {
8880 			/*
8881 			 * kevent_register will always set kn_udata atomically
8882 			 * so that we don't have to take any kqlock here.
8883 			 */
8884 			buf[nknotes] = os_atomic_load_wide(&kn->kn_udata, relaxed);
8885 		}
8886 		/* we return total number of knotes, which may be more than requested */
8887 		nknotes++;
8888 	}
8889 
8890 	return nknotes;
8891 }
8892 
8893 int
kevent_proc_copy_uptrs(void * proc,uint64_t * buf,uint32_t bufsize)8894 kevent_proc_copy_uptrs(void *proc, uint64_t *buf, uint32_t bufsize)
8895 {
8896 	proc_t p = (proc_t)proc;
8897 	struct filedesc *fdp = &p->p_fd;
8898 	unsigned int nuptrs = 0;
8899 	unsigned int buflen = bufsize / sizeof(uint64_t);
8900 	struct kqworkloop *kqwl;
8901 
8902 	if (buflen > 0) {
8903 		assert(buf != NULL);
8904 	}
8905 
8906 	proc_fdlock(p);
8907 	for (int i = 0; i < fdp->fd_knlistsize; i++) {
8908 		nuptrs = klist_copy_udata(&fdp->fd_knlist[i], buf, buflen, nuptrs);
8909 	}
8910 	proc_fdunlock(p);
8911 
8912 	knhash_lock(fdp);
8913 	if (fdp->fd_knhashmask != 0) {
8914 		for (size_t i = 0; i < fdp->fd_knhashmask + 1; i++) {
8915 			nuptrs = klist_copy_udata(&fdp->fd_knhash[i], buf, buflen, nuptrs);
8916 		}
8917 	}
8918 	knhash_unlock(fdp);
8919 
8920 	kqhash_lock(fdp);
8921 	if (fdp->fd_kqhashmask != 0) {
8922 		for (size_t i = 0; i < fdp->fd_kqhashmask + 1; i++) {
8923 			LIST_FOREACH(kqwl, &fdp->fd_kqhash[i], kqwl_hashlink) {
8924 				if (nuptrs < buflen) {
8925 					buf[nuptrs] = kqwl->kqwl_dynamicid;
8926 				}
8927 				nuptrs++;
8928 			}
8929 		}
8930 	}
8931 	kqhash_unlock(fdp);
8932 
8933 	return (int)nuptrs;
8934 }
8935 
8936 static void
kevent_set_return_to_kernel_user_tsd(proc_t p,thread_t thread)8937 kevent_set_return_to_kernel_user_tsd(proc_t p, thread_t thread)
8938 {
8939 	uint64_t ast_addr;
8940 	bool proc_is_64bit = !!(p->p_flag & P_LP64);
8941 	size_t user_addr_size = proc_is_64bit ? 8 : 4;
8942 	uint32_t ast_flags32 = 0;
8943 	uint64_t ast_flags64 = 0;
8944 	struct uthread *ut = get_bsdthread_info(thread);
8945 
8946 	if (ut->uu_kqr_bound != NULL) {
8947 		ast_flags64 |= R2K_WORKLOOP_PENDING_EVENTS;
8948 	}
8949 
8950 	if (ast_flags64 == 0) {
8951 		return;
8952 	}
8953 
8954 	if (!(p->p_flag & P_LP64)) {
8955 		ast_flags32 = (uint32_t)ast_flags64;
8956 		assert(ast_flags64 < 0x100000000ull);
8957 	}
8958 
8959 	ast_addr = thread_rettokern_addr(thread);
8960 	if (ast_addr == 0) {
8961 		return;
8962 	}
8963 
8964 	if (copyout((proc_is_64bit ? (void *)&ast_flags64 : (void *)&ast_flags32),
8965 	    (user_addr_t)ast_addr,
8966 	    user_addr_size) != 0) {
8967 		printf("pid %d (tid:%llu): copyout of return_to_kernel ast flags failed with "
8968 		    "ast_addr = %llu\n", proc_getpid(p), thread_tid(current_thread()), ast_addr);
8969 	}
8970 }
8971 
8972 /*
8973  * Semantics of writing to TSD value:
8974  *
8975  * 1. It is written to by the kernel and cleared by userspace.
8976  * 2. When the userspace code clears the TSD field, it takes responsibility for
8977  * taking action on the quantum expiry action conveyed by kernel.
8978  * 3. The TSD value is always cleared upon entry into userspace and upon exit of
8979  * userspace back to kernel to make sure that it is never leaked across thread
8980  * requests.
8981  */
8982 void
kevent_set_workq_quantum_expiry_user_tsd(proc_t p,thread_t thread,uint64_t flags)8983 kevent_set_workq_quantum_expiry_user_tsd(proc_t p, thread_t thread,
8984     uint64_t flags)
8985 {
8986 	uint64_t ast_addr;
8987 	bool proc_is_64bit = !!(p->p_flag & P_LP64);
8988 	uint32_t ast_flags32 = 0;
8989 	uint64_t ast_flags64 = flags;
8990 
8991 	if (ast_flags64 == 0) {
8992 		return;
8993 	}
8994 
8995 	if (!(p->p_flag & P_LP64)) {
8996 		ast_flags32 = (uint32_t)ast_flags64;
8997 		assert(ast_flags64 < 0x100000000ull);
8998 	}
8999 
9000 	ast_addr = thread_wqquantum_addr(thread);
9001 	assert(ast_addr != 0);
9002 
9003 	if (proc_is_64bit) {
9004 		if (copyout_atomic64(ast_flags64, (user_addr_t) ast_addr)) {
9005 #if DEBUG || DEVELOPMENT
9006 			printf("pid %d (tid:%llu): copyout of workq quantum ast flags failed with "
9007 			    "ast_addr = %llu\n", proc_getpid(p), thread_tid(thread), ast_addr);
9008 #endif
9009 		}
9010 	} else {
9011 		if (copyout_atomic32(ast_flags32, (user_addr_t) ast_addr)) {
9012 #if DEBUG || DEVELOPMENT
9013 			printf("pid %d (tid:%llu): copyout of workq quantum ast flags failed with "
9014 			    "ast_addr = %llu\n", proc_getpid(p), thread_tid(thread), ast_addr);
9015 #endif
9016 		}
9017 	}
9018 }
9019 
9020 void
kevent_ast(thread_t thread,uint16_t bits)9021 kevent_ast(thread_t thread, uint16_t bits)
9022 {
9023 	proc_t p = current_proc();
9024 
9025 
9026 	if (bits & AST_KEVENT_REDRIVE_THREADREQ) {
9027 		workq_kern_threadreq_redrive(p, WORKQ_THREADREQ_CAN_CREATE_THREADS);
9028 	}
9029 	if (bits & AST_KEVENT_RETURN_TO_KERNEL) {
9030 		kevent_set_return_to_kernel_user_tsd(p, thread);
9031 	}
9032 
9033 	if (bits & AST_KEVENT_WORKQ_QUANTUM_EXPIRED) {
9034 		workq_kern_quantum_expiry_reevaluate(p, thread);
9035 	}
9036 }
9037 
9038 #if DEVELOPMENT || DEBUG
9039 
9040 #define KEVENT_SYSCTL_BOUND_ID 1
9041 
9042 static int
9043 kevent_sysctl SYSCTL_HANDLER_ARGS
9044 {
9045 #pragma unused(oidp, arg2)
9046 	uintptr_t type = (uintptr_t)arg1;
9047 	uint64_t bound_id = 0;
9048 
9049 	if (type != KEVENT_SYSCTL_BOUND_ID) {
9050 		return EINVAL;
9051 	}
9052 
9053 	if (req->newptr) {
9054 		return EINVAL;
9055 	}
9056 
9057 	struct uthread *ut = current_uthread();
9058 	if (!ut) {
9059 		return EFAULT;
9060 	}
9061 
9062 	workq_threadreq_t kqr = ut->uu_kqr_bound;
9063 	if (kqr) {
9064 		if (kqr->tr_flags & WORKQ_TR_FLAG_WORKLOOP) {
9065 			bound_id = kqr_kqworkloop(kqr)->kqwl_dynamicid;
9066 		} else {
9067 			bound_id = -1;
9068 		}
9069 	}
9070 
9071 	return sysctl_io_number(req, bound_id, sizeof(bound_id), NULL, NULL);
9072 }
9073 
9074 SYSCTL_NODE(_kern, OID_AUTO, kevent, CTLFLAG_RW | CTLFLAG_LOCKED, 0,
9075     "kevent information");
9076 
9077 SYSCTL_PROC(_kern_kevent, OID_AUTO, bound_id,
9078     CTLTYPE_QUAD | CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_MASKED,
9079     (void *)KEVENT_SYSCTL_BOUND_ID,
9080     sizeof(kqueue_id_t), kevent_sysctl, "Q",
9081     "get the ID of the bound kqueue");
9082 
9083 #endif /* DEVELOPMENT || DEBUG */
9084