xref: /xnu-8792.61.2/bsd/kern/kern_event.c (revision 42e220869062b56f8d7d0726fd4c88954f87902c)
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. We also
4789  * want to be aggressive about this so that we don't overflow the
4790  * kernel stack while posting kevents
4791  */
4792 #define MAX_NESTED_KQ 10
4793 
4794 /*
4795  * The callers has taken a use-count reference on this kqueue and will donate it
4796  * to the kqueue we are being added to.  This keeps the kqueue from closing until
4797  * that relationship is torn down.
4798  */
4799 static int
kqueue_kqfilter(struct fileproc * fp,struct knote * kn,__unused struct kevent_qos_s * kev)4800 kqueue_kqfilter(struct fileproc *fp, struct knote *kn,
4801     __unused struct kevent_qos_s *kev)
4802 {
4803 	struct kqfile *kqf = (struct kqfile *)fp_get_data(fp);
4804 	struct kqueue *kq = &kqf->kqf_kqueue;
4805 	struct kqueue *parentkq = knote_get_kq(kn);
4806 
4807 	assert((kqf->kqf_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0);
4808 
4809 	if (parentkq == kq || kn->kn_filter != EVFILT_READ) {
4810 		knote_set_error(kn, EINVAL);
4811 		return 0;
4812 	}
4813 
4814 	/*
4815 	 * We have to avoid creating a cycle when nesting kqueues
4816 	 * inside another.  Rather than trying to walk the whole
4817 	 * potential DAG of nested kqueues, we just use a simple
4818 	 * ceiling protocol.  When a kqueue is inserted into another,
4819 	 * we check that the (future) parent is not already nested
4820 	 * into another kqueue at a lower level than the potenial
4821 	 * child (because it could indicate a cycle).  If that test
4822 	 * passes, we just mark the nesting levels accordingly.
4823 	 *
4824 	 * Only up to MAX_NESTED_KQ can be nested.
4825 	 *
4826 	 * Note: kqworkq and kqworkloop cannot be nested and have reused their
4827 	 *       kq_level field, so ignore these as parent.
4828 	 */
4829 
4830 	kqlock(parentkq);
4831 
4832 	if ((parentkq->kq_state & (KQ_WORKQ | KQ_WORKLOOP)) == 0) {
4833 		if (parentkq->kq_level > 0 &&
4834 		    parentkq->kq_level < kq->kq_level) {
4835 			kqunlock(parentkq);
4836 			knote_set_error(kn, EINVAL);
4837 			return 0;
4838 		}
4839 
4840 		/* set parent level appropriately */
4841 		uint16_t plevel = (parentkq->kq_level == 0)? 2: parentkq->kq_level;
4842 		if (plevel < kq->kq_level + 1) {
4843 			if (kq->kq_level + 1 > MAX_NESTED_KQ) {
4844 				kqunlock(parentkq);
4845 				knote_set_error(kn, EINVAL);
4846 				return 0;
4847 			}
4848 			plevel = kq->kq_level + 1;
4849 		}
4850 
4851 		parentkq->kq_level = plevel;
4852 	}
4853 
4854 	kqunlock(parentkq);
4855 
4856 	kn->kn_filtid = EVFILTID_KQREAD;
4857 	kqlock(kq);
4858 	KNOTE_ATTACH(&kqf->kqf_sel.si_note, kn);
4859 	/* indicate nesting in child, if needed */
4860 	if (kq->kq_level == 0) {
4861 		kq->kq_level = 1;
4862 	}
4863 
4864 	int count = kq->kq_count;
4865 	kqunlock(kq);
4866 	return count > 0;
4867 }
4868 
4869 __attribute__((noinline))
4870 static void
kqfile_wakeup(struct kqfile * kqf,long hint,wait_result_t wr)4871 kqfile_wakeup(struct kqfile *kqf, long hint, wait_result_t wr)
4872 {
4873 	/* wakeup a thread waiting on this queue */
4874 	selwakeup(&kqf->kqf_sel);
4875 
4876 	/* wake up threads in kqueue_scan() */
4877 	if (kqf->kqf_state & KQ_SLEEP) {
4878 		kqf->kqf_state &= ~KQ_SLEEP;
4879 		thread_wakeup_with_result(&kqf->kqf_count, wr);
4880 	}
4881 
4882 	if (hint == NOTE_REVOKE) {
4883 		/* wakeup threads waiting their turn to process */
4884 		if (kqf->kqf_state & KQ_PROCWAIT) {
4885 			assert(kqf->kqf_state & KQ_PROCESSING);
4886 			kqf->kqf_state &= ~KQ_PROCWAIT;
4887 			thread_wakeup(&kqf->kqf_suppressed);
4888 		}
4889 
4890 		/* no need to KNOTE: knote_fdclose() takes care of it */
4891 	} else {
4892 		/* wakeup other kqueues/select sets we're inside */
4893 		KNOTE(&kqf->kqf_sel.si_note, hint);
4894 	}
4895 }
4896 
4897 /*
4898  * kqueue_drain - called when kq is closed
4899  */
4900 static int
kqueue_drain(struct fileproc * fp,__unused vfs_context_t ctx)4901 kqueue_drain(struct fileproc *fp, __unused vfs_context_t ctx)
4902 {
4903 	struct kqfile *kqf = (struct kqfile *)fp_get_data(fp);
4904 
4905 	assert((kqf->kqf_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0);
4906 
4907 	kqlock(kqf);
4908 	kqf->kqf_state |= KQ_DRAIN;
4909 	kqfile_wakeup(kqf, NOTE_REVOKE, THREAD_RESTART);
4910 	kqunlock(kqf);
4911 	return 0;
4912 }
4913 
4914 int
kqueue_stat(struct kqueue * kq,void * ub,int isstat64,proc_t p)4915 kqueue_stat(struct kqueue *kq, void *ub, int isstat64, proc_t p)
4916 {
4917 	assert((kq->kq_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0);
4918 
4919 	kqlock(kq);
4920 	if (isstat64 != 0) {
4921 		struct stat64 *sb64 = (struct stat64 *)ub;
4922 
4923 		bzero((void *)sb64, sizeof(*sb64));
4924 		sb64->st_size = kq->kq_count;
4925 		if (kq->kq_state & KQ_KEV_QOS) {
4926 			sb64->st_blksize = sizeof(struct kevent_qos_s);
4927 		} else if (kq->kq_state & KQ_KEV64) {
4928 			sb64->st_blksize = sizeof(struct kevent64_s);
4929 		} else if (IS_64BIT_PROCESS(p)) {
4930 			sb64->st_blksize = sizeof(struct user64_kevent);
4931 		} else {
4932 			sb64->st_blksize = sizeof(struct user32_kevent);
4933 		}
4934 		sb64->st_mode = S_IFIFO;
4935 	} else {
4936 		struct stat *sb = (struct stat *)ub;
4937 
4938 		bzero((void *)sb, sizeof(*sb));
4939 		sb->st_size = kq->kq_count;
4940 		if (kq->kq_state & KQ_KEV_QOS) {
4941 			sb->st_blksize = sizeof(struct kevent_qos_s);
4942 		} else if (kq->kq_state & KQ_KEV64) {
4943 			sb->st_blksize = sizeof(struct kevent64_s);
4944 		} else if (IS_64BIT_PROCESS(p)) {
4945 			sb->st_blksize = sizeof(struct user64_kevent);
4946 		} else {
4947 			sb->st_blksize = sizeof(struct user32_kevent);
4948 		}
4949 		sb->st_mode = S_IFIFO;
4950 	}
4951 	kqunlock(kq);
4952 	return 0;
4953 }
4954 
4955 static inline bool
kqueue_threadreq_can_use_ast(struct kqueue * kq)4956 kqueue_threadreq_can_use_ast(struct kqueue *kq)
4957 {
4958 	if (current_proc() == kq->kq_p) {
4959 		/*
4960 		 * Setting an AST from a non BSD syscall is unsafe: mach_msg_trap() can
4961 		 * do combined send/receive and in the case of self-IPC, the AST may bet
4962 		 * set on a thread that will not return to userspace and needs the
4963 		 * thread the AST would create to unblock itself.
4964 		 *
4965 		 * At this time, we really want to target:
4966 		 *
4967 		 * - kevent variants that can cause thread creations, and dispatch
4968 		 *   really only uses kevent_qos and kevent_id,
4969 		 *
4970 		 * - workq_kernreturn (directly about thread creations)
4971 		 *
4972 		 * - bsdthread_ctl which is used for qos changes and has direct impact
4973 		 *   on the creator thread scheduling decisions.
4974 		 */
4975 		switch (current_uthread()->syscall_code) {
4976 		case SYS_kevent_qos:
4977 		case SYS_kevent_id:
4978 		case SYS_workq_kernreturn:
4979 		case SYS_bsdthread_ctl:
4980 			return true;
4981 		}
4982 	}
4983 	return false;
4984 }
4985 
4986 /*
4987  * Interact with the pthread kext to request a servicing there at a specific QoS
4988  * level.
4989  *
4990  * - Caller holds the kqlock
4991  *
4992  * - May be called with the kqueue's wait queue set locked,
4993  *   so cannot do anything that could recurse on that.
4994  */
4995 static void
kqueue_threadreq_initiate(kqueue_t kqu,workq_threadreq_t kqr,kq_index_t qos,int flags)4996 kqueue_threadreq_initiate(kqueue_t kqu, workq_threadreq_t kqr,
4997     kq_index_t qos, int flags)
4998 {
4999 	assert(kqr_thread(kqr) == THREAD_NULL);
5000 	assert(!kqr_thread_requested(kqr));
5001 	struct turnstile *ts = TURNSTILE_NULL;
5002 
5003 	if (workq_is_exiting(kqu.kq->kq_p)) {
5004 		return;
5005 	}
5006 
5007 	kqlock_held(kqu);
5008 
5009 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5010 		struct kqworkloop *kqwl = kqu.kqwl;
5011 
5012 		assert(kqwl->kqwl_owner == THREAD_NULL);
5013 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_THREQUEST),
5014 		    kqwl->kqwl_dynamicid, 0, qos, kqwl->kqwl_wakeup_qos);
5015 		ts = kqwl->kqwl_turnstile;
5016 		/* Add a thread request reference on the kqueue. */
5017 		kqworkloop_retain(kqwl);
5018 
5019 #if CONFIG_PREADOPT_TG
5020 		/* This thread is the one which is ack-ing the thread group on the kqwl
5021 		 * under the kqlock and will take action accordingly, pairs with the
5022 		 * release barrier in kqueue_set_preadopted_thread_group */
5023 		uint16_t tg_acknowledged;
5024 		if (os_atomic_cmpxchgv(&kqwl->kqwl_preadopt_tg_needs_redrive,
5025 		    KQWL_PREADOPT_TG_NEEDS_REDRIVE, KQWL_PREADOPT_TG_CLEAR_REDRIVE,
5026 		    &tg_acknowledged, acquire)) {
5027 			flags |= WORKQ_THREADREQ_REEVALUATE_PREADOPT_TG;
5028 		}
5029 #endif
5030 	} else {
5031 		assert(kqu.kq->kq_state & KQ_WORKQ);
5032 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWQ_THREQUEST), -1, 0, qos,
5033 		    !TAILQ_EMPTY(&kqu.kqwq->kqwq_queue[kqr->tr_kq_qos_index - 1]));
5034 	}
5035 
5036 	/*
5037 	 * New-style thread request supported.
5038 	 * Provide the pthread kext a pointer to a workq_threadreq_s structure for
5039 	 * its use until a corresponding kqueue_threadreq_bind callback.
5040 	 */
5041 	if (kqueue_threadreq_can_use_ast(kqu.kq)) {
5042 		flags |= WORKQ_THREADREQ_SET_AST_ON_FAILURE;
5043 	}
5044 	if (qos == KQWQ_QOS_MANAGER) {
5045 		qos = WORKQ_THREAD_QOS_MANAGER;
5046 	}
5047 
5048 	if (!workq_kern_threadreq_initiate(kqu.kq->kq_p, kqr, ts, qos, flags)) {
5049 		/*
5050 		 * Process is shutting down or exec'ing.
5051 		 * All the kqueues are going to be cleaned up
5052 		 * soon. Forget we even asked for a thread -
5053 		 * and make sure we don't ask for more.
5054 		 */
5055 		kqu.kq->kq_state &= ~KQ_R2K_ARMED;
5056 		kqueue_release_live(kqu);
5057 	}
5058 }
5059 
5060 /*
5061  * kqueue_threadreq_bind_prepost - prepost the bind to kevent
5062  *
5063  * This is used when kqueue_threadreq_bind may cause a lock inversion.
5064  */
5065 __attribute__((always_inline))
5066 void
kqueue_threadreq_bind_prepost(struct proc * p __unused,workq_threadreq_t kqr,struct uthread * ut)5067 kqueue_threadreq_bind_prepost(struct proc *p __unused, workq_threadreq_t kqr,
5068     struct uthread *ut)
5069 {
5070 	ut->uu_kqr_bound = kqr;
5071 	kqr->tr_thread = get_machthread(ut);
5072 	kqr->tr_state = WORKQ_TR_STATE_BINDING;
5073 }
5074 
5075 /*
5076  * kqueue_threadreq_bind_commit - commit a bind prepost
5077  *
5078  * The workq code has to commit any binding prepost before the thread has
5079  * a chance to come back to userspace (and do kevent syscalls) or be aborted.
5080  */
5081 void
kqueue_threadreq_bind_commit(struct proc * p,thread_t thread)5082 kqueue_threadreq_bind_commit(struct proc *p, thread_t thread)
5083 {
5084 	struct uthread *ut = get_bsdthread_info(thread);
5085 	workq_threadreq_t kqr = ut->uu_kqr_bound;
5086 	kqueue_t kqu = kqr_kqueue(p, kqr);
5087 
5088 	kqlock(kqu);
5089 	if (kqr->tr_state == WORKQ_TR_STATE_BINDING) {
5090 		kqueue_threadreq_bind(p, kqr, thread, 0);
5091 	}
5092 	kqunlock(kqu);
5093 }
5094 
5095 static void
kqueue_threadreq_modify(kqueue_t kqu,workq_threadreq_t kqr,kq_index_t qos,workq_kern_threadreq_flags_t flags)5096 kqueue_threadreq_modify(kqueue_t kqu, workq_threadreq_t kqr, kq_index_t qos,
5097     workq_kern_threadreq_flags_t flags)
5098 {
5099 	assert(kqr_thread_requested_pending(kqr));
5100 
5101 	kqlock_held(kqu);
5102 
5103 	if (kqueue_threadreq_can_use_ast(kqu.kq)) {
5104 		flags |= WORKQ_THREADREQ_SET_AST_ON_FAILURE;
5105 	}
5106 
5107 #if CONFIG_PREADOPT_TG
5108 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5109 		uint16_t tg_ack_status;
5110 		struct kqworkloop *kqwl = kqu.kqwl;
5111 
5112 		/* This thread is the one which is ack-ing the thread group on the kqwl
5113 		 * under the kqlock and will take action accordingly, needs acquire
5114 		 * barrier */
5115 		if (os_atomic_cmpxchgv(&kqwl->kqwl_preadopt_tg_needs_redrive, KQWL_PREADOPT_TG_NEEDS_REDRIVE,
5116 		    KQWL_PREADOPT_TG_CLEAR_REDRIVE, &tg_ack_status, acquire)) {
5117 			flags |= WORKQ_THREADREQ_REEVALUATE_PREADOPT_TG;
5118 		}
5119 	}
5120 #endif
5121 
5122 	workq_kern_threadreq_modify(kqu.kq->kq_p, kqr, qos, flags);
5123 }
5124 
5125 /*
5126  * kqueue_threadreq_bind - bind thread to processing kqrequest
5127  *
5128  * The provided thread will be responsible for delivering events
5129  * associated with the given kqrequest.  Bind it and get ready for
5130  * the thread to eventually arrive.
5131  */
5132 void
kqueue_threadreq_bind(struct proc * p,workq_threadreq_t kqr,thread_t thread,unsigned int flags)5133 kqueue_threadreq_bind(struct proc *p, workq_threadreq_t kqr, thread_t thread,
5134     unsigned int flags)
5135 {
5136 	kqueue_t kqu = kqr_kqueue(p, kqr);
5137 	struct uthread *ut = get_bsdthread_info(thread);
5138 
5139 	kqlock_held(kqu);
5140 
5141 	assert(ut->uu_kqueue_override == 0);
5142 
5143 	if (kqr->tr_state == WORKQ_TR_STATE_BINDING) {
5144 		assert(ut->uu_kqr_bound == kqr);
5145 		assert(kqr->tr_thread == thread);
5146 	} else {
5147 		assert(kqr_thread_requested_pending(kqr));
5148 		assert(kqr->tr_thread == THREAD_NULL);
5149 		assert(ut->uu_kqr_bound == NULL);
5150 		ut->uu_kqr_bound = kqr;
5151 		kqr->tr_thread = thread;
5152 	}
5153 
5154 	kqr->tr_state = WORKQ_TR_STATE_BOUND;
5155 
5156 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5157 		struct turnstile *ts = kqu.kqwl->kqwl_turnstile;
5158 
5159 		if (__improbable(thread == kqu.kqwl->kqwl_owner)) {
5160 			/*
5161 			 * <rdar://problem/38626999> shows that asserting here is not ok.
5162 			 *
5163 			 * This is not supposed to happen for correct use of the interface,
5164 			 * but it is sadly possible for userspace (with the help of memory
5165 			 * corruption, such as over-release of a dispatch queue) to make
5166 			 * the creator thread the "owner" of a workloop.
5167 			 *
5168 			 * Once that happens, and that creator thread picks up the same
5169 			 * workloop as a servicer, we trip this codepath. We need to fixup
5170 			 * the state to forget about this thread being the owner, as the
5171 			 * entire workloop state machine expects servicers to never be
5172 			 * owners and everything would basically go downhill from here.
5173 			 */
5174 			kqu.kqwl->kqwl_owner = THREAD_NULL;
5175 			if (kqworkloop_override(kqu.kqwl)) {
5176 				thread_drop_kevent_override(thread);
5177 			}
5178 		}
5179 
5180 		if (ts && (flags & KQUEUE_THREADERQ_BIND_NO_INHERITOR_UPDATE) == 0) {
5181 			/*
5182 			 * Past this point, the interlock is the kq req lock again,
5183 			 * so we can fix the inheritor for good.
5184 			 */
5185 			filt_wlupdate_inheritor(kqu.kqwl, ts, TURNSTILE_IMMEDIATE_UPDATE);
5186 			turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_HELD);
5187 		}
5188 
5189 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_BIND), kqu.kqwl->kqwl_dynamicid,
5190 		    thread_tid(thread), kqr->tr_kq_qos_index,
5191 		    (kqr->tr_kq_override_index << 16) | kqwl->kqwl_wakeup_qos);
5192 
5193 		ut->uu_kqueue_override = kqr->tr_kq_override_index;
5194 		if (kqr->tr_kq_override_index) {
5195 			thread_add_servicer_override(thread, kqr->tr_kq_override_index);
5196 		}
5197 
5198 #if CONFIG_PREADOPT_TG
5199 		/* Remove reference from kqwl and mark it as bound with the SENTINEL */
5200 		thread_group_qos_t old_tg;
5201 		thread_group_qos_t new_tg;
5202 		int ret = os_atomic_rmw_loop(kqr_preadopt_thread_group_addr(kqr), old_tg, new_tg, relaxed, {
5203 			if (old_tg == KQWL_PREADOPTED_TG_NEVER) {
5204 			        os_atomic_rmw_loop_give_up(break); // It's an app, nothing to do
5205 			}
5206 			assert(old_tg != KQWL_PREADOPTED_TG_PROCESSED);
5207 			new_tg = KQWL_PREADOPTED_TG_SENTINEL;
5208 		});
5209 
5210 		if (ret) {
5211 			KQWL_PREADOPT_TG_HISTORY_WRITE_ENTRY(kqu.kqwl, KQWL_PREADOPT_OP_SERVICER_BIND, old_tg, new_tg);
5212 
5213 			if (KQWL_HAS_VALID_PREADOPTED_TG(old_tg)) {
5214 				struct thread_group *tg = KQWL_GET_PREADOPTED_TG(old_tg);
5215 				assert(tg != NULL);
5216 
5217 				thread_set_preadopt_thread_group(thread, tg);
5218 				thread_group_release_live(tg); // The thread has a reference
5219 			} else {
5220 				/*
5221 				 * The thread may already have a preadopt thread group on it -
5222 				 * we need to make sure to clear that.
5223 				 */
5224 				thread_set_preadopt_thread_group(thread, NULL);
5225 			}
5226 
5227 			/* We have taken action on the preadopted thread group set on the
5228 			 * set on the kqwl, clear any redrive requests */
5229 			os_atomic_store(&kqu.kqwl->kqwl_preadopt_tg_needs_redrive, KQWL_PREADOPT_TG_CLEAR_REDRIVE, relaxed);
5230 		}
5231 #endif
5232 		kqueue_update_iotier_override(kqu);
5233 	} else {
5234 		assert(kqr->tr_kq_override_index == 0);
5235 
5236 #if CONFIG_PREADOPT_TG
5237 		/*
5238 		 * The thread may have a preadopt thread group on it already because it
5239 		 * got tagged with it as a creator thread. So we need to make sure to
5240 		 * clear that since we don't have preadopt thread groups for non-kqwl
5241 		 * cases
5242 		 */
5243 		thread_set_preadopt_thread_group(thread, NULL);
5244 #endif
5245 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWQ_BIND), -1,
5246 		    thread_tid(thread), kqr->tr_kq_qos_index,
5247 		    (kqr->tr_kq_override_index << 16) |
5248 		    !TAILQ_EMPTY(&kqu.kqwq->kqwq_queue[kqr->tr_kq_qos_index - 1]));
5249 	}
5250 }
5251 
5252 /*
5253  * kqueue_threadreq_cancel - abort a pending thread request
5254  *
5255  * Called when exiting/exec'ing. Forget our pending request.
5256  */
5257 void
kqueue_threadreq_cancel(struct proc * p,workq_threadreq_t kqr)5258 kqueue_threadreq_cancel(struct proc *p, workq_threadreq_t kqr)
5259 {
5260 	kqueue_release(kqr_kqueue(p, kqr));
5261 }
5262 
5263 workq_threadreq_param_t
kqueue_threadreq_workloop_param(workq_threadreq_t kqr)5264 kqueue_threadreq_workloop_param(workq_threadreq_t kqr)
5265 {
5266 	struct kqworkloop *kqwl;
5267 	workq_threadreq_param_t trp;
5268 
5269 	assert(kqr->tr_flags & WORKQ_TR_FLAG_WORKLOOP);
5270 	kqwl = __container_of(kqr, struct kqworkloop, kqwl_request);
5271 	trp.trp_value = kqwl->kqwl_params;
5272 	return trp;
5273 }
5274 
5275 /*
5276  *	kqueue_threadreq_unbind - unbind thread from processing kqueue
5277  *
5278  *	End processing the per-QoS bucket of events and allow other threads
5279  *	to be requested for future servicing.
5280  *
5281  *	caller holds a reference on the kqueue.
5282  */
5283 void
kqueue_threadreq_unbind(struct proc * p,workq_threadreq_t kqr)5284 kqueue_threadreq_unbind(struct proc *p, workq_threadreq_t kqr)
5285 {
5286 	if (kqr->tr_flags & WORKQ_TR_FLAG_WORKLOOP) {
5287 		kqworkloop_unbind(kqr_kqworkloop(kqr));
5288 	} else {
5289 		kqworkq_unbind(p, kqr);
5290 	}
5291 }
5292 
5293 /*
5294  * If we aren't already busy processing events [for this QoS],
5295  * request workq thread support as appropriate.
5296  *
5297  * TBD - for now, we don't segregate out processing by QoS.
5298  *
5299  * - May be called with the kqueue's wait queue set locked,
5300  *   so cannot do anything that could recurse on that.
5301  */
5302 static void
kqworkq_wakeup(struct kqworkq * kqwq,kq_index_t qos_index)5303 kqworkq_wakeup(struct kqworkq *kqwq, kq_index_t qos_index)
5304 {
5305 	workq_threadreq_t kqr = kqworkq_get_request(kqwq, qos_index);
5306 
5307 	/* convert to thread qos value */
5308 	assert(qos_index > 0 && qos_index <= KQWQ_NBUCKETS);
5309 
5310 	if (!kqr_thread_requested(kqr)) {
5311 		kqueue_threadreq_initiate(&kqwq->kqwq_kqueue, kqr, qos_index, 0);
5312 	}
5313 }
5314 
5315 /*
5316  * This represent the asynchronous QoS a given workloop contributes,
5317  * hence is the max of the current active knotes (override index)
5318  * and the workloop max qos (userspace async qos).
5319  */
5320 static kq_index_t
kqworkloop_override(struct kqworkloop * kqwl)5321 kqworkloop_override(struct kqworkloop *kqwl)
5322 {
5323 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5324 	return MAX(kqr->tr_kq_qos_index, kqr->tr_kq_override_index);
5325 }
5326 
5327 static inline void
kqworkloop_request_fire_r2k_notification(struct kqworkloop * kqwl)5328 kqworkloop_request_fire_r2k_notification(struct kqworkloop *kqwl)
5329 {
5330 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5331 
5332 	kqlock_held(kqwl);
5333 
5334 	if (kqwl->kqwl_state & KQ_R2K_ARMED) {
5335 		kqwl->kqwl_state &= ~KQ_R2K_ARMED;
5336 		act_set_astkevent(kqr_thread_fast(kqr), AST_KEVENT_RETURN_TO_KERNEL);
5337 	}
5338 }
5339 
5340 static void
kqworkloop_update_threads_qos(struct kqworkloop * kqwl,int op,kq_index_t qos)5341 kqworkloop_update_threads_qos(struct kqworkloop *kqwl, int op, kq_index_t qos)
5342 {
5343 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5344 	struct kqueue *kq = &kqwl->kqwl_kqueue;
5345 	kq_index_t old_override = kqworkloop_override(kqwl);
5346 
5347 	kqlock_held(kqwl);
5348 
5349 	switch (op) {
5350 	case KQWL_UTQ_UPDATE_WAKEUP_QOS:
5351 		kqwl->kqwl_wakeup_qos = qos;
5352 		kqworkloop_request_fire_r2k_notification(kqwl);
5353 		goto recompute;
5354 
5355 	case KQWL_UTQ_RESET_WAKEUP_OVERRIDE:
5356 		kqr->tr_kq_override_index = qos;
5357 		goto recompute;
5358 
5359 	case KQWL_UTQ_PARKING:
5360 	case KQWL_UTQ_UNBINDING:
5361 		kqr->tr_kq_override_index = qos;
5362 		OS_FALLTHROUGH;
5363 
5364 	case KQWL_UTQ_RECOMPUTE_WAKEUP_QOS:
5365 		if (op == KQWL_UTQ_RECOMPUTE_WAKEUP_QOS) {
5366 			assert(qos == THREAD_QOS_UNSPECIFIED);
5367 		}
5368 		if (TAILQ_EMPTY(&kqwl->kqwl_suppressed)) {
5369 			kqr->tr_kq_override_index = THREAD_QOS_UNSPECIFIED;
5370 		}
5371 		kqwl->kqwl_wakeup_qos = 0;
5372 		for (kq_index_t i = KQWL_NBUCKETS; i > 0; i--) {
5373 			if (!TAILQ_EMPTY(&kqwl->kqwl_queue[i - 1])) {
5374 				kqwl->kqwl_wakeup_qos = i;
5375 				kqworkloop_request_fire_r2k_notification(kqwl);
5376 				break;
5377 			}
5378 		}
5379 		OS_FALLTHROUGH;
5380 
5381 	case KQWL_UTQ_UPDATE_WAKEUP_OVERRIDE:
5382 recompute:
5383 		/*
5384 		 * When modifying the wakeup QoS or the override QoS, we always need to
5385 		 * maintain our invariant that kqr_override_index is at least as large
5386 		 * as the highest QoS for which an event is fired.
5387 		 *
5388 		 * However this override index can be larger when there is an overriden
5389 		 * suppressed knote pushing on the kqueue.
5390 		 */
5391 		if (qos < kqwl->kqwl_wakeup_qos) {
5392 			qos = kqwl->kqwl_wakeup_qos;
5393 		}
5394 		if (kqr->tr_kq_override_index < qos) {
5395 			kqr->tr_kq_override_index = qos;
5396 		}
5397 		break;
5398 
5399 	case KQWL_UTQ_REDRIVE_EVENTS:
5400 		break;
5401 
5402 	case KQWL_UTQ_SET_QOS_INDEX:
5403 		kqr->tr_kq_qos_index = qos;
5404 		break;
5405 
5406 	default:
5407 		panic("unknown kqwl thread qos update operation: %d", op);
5408 	}
5409 
5410 	thread_t kqwl_owner = kqwl->kqwl_owner;
5411 	thread_t servicer = kqr_thread(kqr);
5412 	boolean_t qos_changed = FALSE;
5413 	kq_index_t new_override = kqworkloop_override(kqwl);
5414 
5415 	/*
5416 	 * Apply the diffs to the owner if applicable
5417 	 */
5418 	if (kqwl_owner) {
5419 #if 0
5420 		/* JMM - need new trace hooks for owner overrides */
5421 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_THADJUST),
5422 		    kqwl->kqwl_dynamicid, thread_tid(kqwl_owner), kqr->tr_kq_qos_index,
5423 		    (kqr->tr_kq_override_index << 16) | kqwl->kqwl_wakeup_qos);
5424 #endif
5425 		if (new_override == old_override) {
5426 			// nothing to do
5427 		} else if (old_override == THREAD_QOS_UNSPECIFIED) {
5428 			thread_add_kevent_override(kqwl_owner, new_override);
5429 		} else if (new_override == THREAD_QOS_UNSPECIFIED) {
5430 			thread_drop_kevent_override(kqwl_owner);
5431 		} else { /*  old_override != new_override */
5432 			thread_update_kevent_override(kqwl_owner, new_override);
5433 		}
5434 	}
5435 
5436 	/*
5437 	 * apply the diffs to the servicer
5438 	 */
5439 
5440 	if (!kqr_thread_requested(kqr)) {
5441 		/*
5442 		 * No servicer, nor thread-request
5443 		 *
5444 		 * Make a new thread request, unless there is an owner (or the workloop
5445 		 * is suspended in userland) or if there is no asynchronous work in the
5446 		 * first place.
5447 		 */
5448 
5449 		if (kqwl_owner == NULL && kqwl->kqwl_wakeup_qos) {
5450 			int initiate_flags = 0;
5451 			if (op == KQWL_UTQ_UNBINDING) {
5452 				initiate_flags = WORKQ_THREADREQ_ATTEMPT_REBIND;
5453 			}
5454 
5455 			/* kqueue_threadreq_initiate handles the acknowledgement of the TG
5456 			 * if needed */
5457 			kqueue_threadreq_initiate(kq, kqr, new_override, initiate_flags);
5458 		}
5459 	} else if (servicer) {
5460 		/*
5461 		 * Servicer in flight
5462 		 *
5463 		 * Just apply the diff to the servicer
5464 		 */
5465 
5466 #if CONFIG_PREADOPT_TG
5467 		/* When there's a servicer for the kqwl already, then the servicer will
5468 		 * adopt the thread group in the kqr, we don't need to poke the
5469 		 * workqueue subsystem to make different decisions due to the thread
5470 		 * group. Consider the current request ack-ed.
5471 		 */
5472 		os_atomic_store(&kqwl->kqwl_preadopt_tg_needs_redrive, KQWL_PREADOPT_TG_CLEAR_REDRIVE, relaxed);
5473 #endif
5474 
5475 		struct uthread *ut = get_bsdthread_info(servicer);
5476 		if (ut->uu_kqueue_override != new_override) {
5477 			if (ut->uu_kqueue_override == THREAD_QOS_UNSPECIFIED) {
5478 				thread_add_servicer_override(servicer, new_override);
5479 			} else if (new_override == THREAD_QOS_UNSPECIFIED) {
5480 				thread_drop_servicer_override(servicer);
5481 			} else { /* ut->uu_kqueue_override != new_override */
5482 				thread_update_servicer_override(servicer, new_override);
5483 			}
5484 			ut->uu_kqueue_override = new_override;
5485 			qos_changed = TRUE;
5486 		}
5487 	} else if (new_override == THREAD_QOS_UNSPECIFIED) {
5488 		/*
5489 		 * No events to deliver anymore.
5490 		 *
5491 		 * However canceling with turnstiles is challenging, so the fact that
5492 		 * the request isn't useful will be discovered by the servicer himself
5493 		 * later on.
5494 		 */
5495 	} else if (old_override != new_override) {
5496 		/*
5497 		 * Request is in flight
5498 		 *
5499 		 * Apply the diff to the thread request.
5500 		 */
5501 		kqueue_threadreq_modify(kq, kqr, new_override, WORKQ_THREADREQ_NONE);
5502 		qos_changed = TRUE;
5503 	}
5504 
5505 	if (qos_changed) {
5506 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_THADJUST), kqwl->kqwl_dynamicid,
5507 		    thread_tid(servicer), kqr->tr_kq_qos_index,
5508 		    (kqr->tr_kq_override_index << 16) | kqwl->kqwl_wakeup_qos);
5509 	}
5510 }
5511 
5512 static void
kqworkloop_update_iotier_override(struct kqworkloop * kqwl)5513 kqworkloop_update_iotier_override(struct kqworkloop *kqwl)
5514 {
5515 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5516 	thread_t servicer = kqr_thread(kqr);
5517 	uint8_t iotier = os_atomic_load(&kqwl->kqwl_iotier_override, relaxed);
5518 
5519 	kqlock_held(kqwl);
5520 
5521 	if (servicer) {
5522 		thread_update_servicer_iotier_override(servicer, iotier);
5523 	}
5524 }
5525 
5526 static void
kqworkloop_wakeup(struct kqworkloop * kqwl,kq_index_t qos)5527 kqworkloop_wakeup(struct kqworkloop *kqwl, kq_index_t qos)
5528 {
5529 	if (qos <= kqwl->kqwl_wakeup_qos) {
5530 		/*
5531 		 * Shortcut wakeups that really do nothing useful
5532 		 */
5533 		return;
5534 	}
5535 
5536 	if ((kqwl->kqwl_state & KQ_PROCESSING) &&
5537 	    kqr_thread(&kqwl->kqwl_request) == current_thread()) {
5538 		/*
5539 		 * kqworkloop_end_processing() will perform the required QoS
5540 		 * computations when it unsets the processing mode.
5541 		 */
5542 		return;
5543 	}
5544 
5545 	kqworkloop_update_threads_qos(kqwl, KQWL_UTQ_UPDATE_WAKEUP_QOS, qos);
5546 }
5547 
5548 static struct kqtailq *
kqueue_get_suppressed_queue(kqueue_t kq,struct knote * kn)5549 kqueue_get_suppressed_queue(kqueue_t kq, struct knote *kn)
5550 {
5551 	if (kq.kq->kq_state & KQ_WORKLOOP) {
5552 		return &kq.kqwl->kqwl_suppressed;
5553 	} else if (kq.kq->kq_state & KQ_WORKQ) {
5554 		return &kq.kqwq->kqwq_suppressed[kn->kn_qos_index - 1];
5555 	} else {
5556 		return &kq.kqf->kqf_suppressed;
5557 	}
5558 }
5559 
5560 struct turnstile *
kqueue_alloc_turnstile(kqueue_t kqu)5561 kqueue_alloc_turnstile(kqueue_t kqu)
5562 {
5563 	struct kqworkloop *kqwl = kqu.kqwl;
5564 	kq_state_t kq_state;
5565 
5566 	kq_state = os_atomic_load(&kqu.kq->kq_state, dependency);
5567 	if (kq_state & KQ_HAS_TURNSTILE) {
5568 		/* force a dependency to pair with the atomic or with release below */
5569 		return os_atomic_load_with_dependency_on(&kqwl->kqwl_turnstile,
5570 		           (uintptr_t)kq_state);
5571 	}
5572 
5573 	if (!(kq_state & KQ_WORKLOOP)) {
5574 		return TURNSTILE_NULL;
5575 	}
5576 
5577 	struct turnstile *ts = turnstile_alloc(), *free_ts = TURNSTILE_NULL;
5578 	bool workq_locked = false;
5579 
5580 	kqlock(kqu);
5581 
5582 	if (filt_wlturnstile_interlock_is_workq(kqwl)) {
5583 		workq_locked = true;
5584 		workq_kern_threadreq_lock(kqwl->kqwl_p);
5585 	}
5586 
5587 	if (kqwl->kqwl_state & KQ_HAS_TURNSTILE) {
5588 		free_ts = ts;
5589 		ts = kqwl->kqwl_turnstile;
5590 	} else {
5591 		ts = turnstile_prepare((uintptr_t)kqwl, &kqwl->kqwl_turnstile,
5592 		    ts, TURNSTILE_WORKLOOPS);
5593 
5594 		/* release-barrier to pair with the unlocked load of kqwl_turnstile above */
5595 		os_atomic_or(&kqwl->kqwl_state, KQ_HAS_TURNSTILE, release);
5596 
5597 		if (filt_wlturnstile_interlock_is_workq(kqwl)) {
5598 			workq_kern_threadreq_update_inheritor(kqwl->kqwl_p,
5599 			    &kqwl->kqwl_request, kqwl->kqwl_owner,
5600 			    ts, TURNSTILE_IMMEDIATE_UPDATE);
5601 			/*
5602 			 * The workq may no longer be the interlock after this.
5603 			 * In which case the inheritor wasn't updated.
5604 			 */
5605 		}
5606 		if (!filt_wlturnstile_interlock_is_workq(kqwl)) {
5607 			filt_wlupdate_inheritor(kqwl, ts, TURNSTILE_IMMEDIATE_UPDATE);
5608 		}
5609 	}
5610 
5611 	if (workq_locked) {
5612 		workq_kern_threadreq_unlock(kqwl->kqwl_p);
5613 	}
5614 
5615 	kqunlock(kqu);
5616 
5617 	if (free_ts) {
5618 		turnstile_deallocate(free_ts);
5619 	} else {
5620 		turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_NOT_HELD);
5621 	}
5622 	return ts;
5623 }
5624 
5625 __attribute__((always_inline))
5626 struct turnstile *
kqueue_turnstile(kqueue_t kqu)5627 kqueue_turnstile(kqueue_t kqu)
5628 {
5629 	kq_state_t kq_state = os_atomic_load(&kqu.kq->kq_state, relaxed);
5630 	if (kq_state & KQ_WORKLOOP) {
5631 		return os_atomic_load(&kqu.kqwl->kqwl_turnstile, relaxed);
5632 	}
5633 	return TURNSTILE_NULL;
5634 }
5635 
5636 __attribute__((always_inline))
5637 struct turnstile *
kqueue_threadreq_get_turnstile(workq_threadreq_t kqr)5638 kqueue_threadreq_get_turnstile(workq_threadreq_t kqr)
5639 {
5640 	struct kqworkloop *kqwl = kqr_kqworkloop(kqr);
5641 	if (kqwl) {
5642 		return os_atomic_load(&kqwl->kqwl_turnstile, relaxed);
5643 	}
5644 	return TURNSTILE_NULL;
5645 }
5646 
5647 static void
kqworkloop_set_overcommit(struct kqworkloop * kqwl)5648 kqworkloop_set_overcommit(struct kqworkloop *kqwl)
5649 {
5650 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5651 
5652 	/*
5653 	 * This test is racy, but since we never remove this bit,
5654 	 * it allows us to avoid taking a lock.
5655 	 */
5656 	if (kqr->tr_flags & WORKQ_TR_FLAG_OVERCOMMIT) {
5657 		return;
5658 	}
5659 
5660 	kqlock_held(kqwl);
5661 
5662 	if (kqr_thread_requested_pending(kqr)) {
5663 		kqueue_threadreq_modify(kqwl, kqr, kqr->tr_qos,
5664 		    WORKQ_THREADREQ_MAKE_OVERCOMMIT);
5665 	} else {
5666 		kqr->tr_flags |= WORKQ_TR_FLAG_OVERCOMMIT;
5667 	}
5668 }
5669 
5670 static void
kqworkq_update_override(struct kqworkq * kqwq,struct knote * kn,kq_index_t override_index)5671 kqworkq_update_override(struct kqworkq *kqwq, struct knote *kn,
5672     kq_index_t override_index)
5673 {
5674 	workq_threadreq_t kqr;
5675 	kq_index_t old_override_index;
5676 	kq_index_t queue_index = kn->kn_qos_index;
5677 
5678 	if (override_index <= queue_index) {
5679 		return;
5680 	}
5681 
5682 	kqr = kqworkq_get_request(kqwq, queue_index);
5683 
5684 	kqlock_held(kqwq);
5685 
5686 	old_override_index = kqr->tr_kq_override_index;
5687 	if (override_index > MAX(kqr->tr_kq_qos_index, old_override_index)) {
5688 		thread_t servicer = kqr_thread(kqr);
5689 		kqr->tr_kq_override_index = override_index;
5690 
5691 		/* apply the override to [incoming?] servicing thread */
5692 		if (servicer) {
5693 			if (old_override_index) {
5694 				thread_update_kevent_override(servicer, override_index);
5695 			} else {
5696 				thread_add_kevent_override(servicer, override_index);
5697 			}
5698 		}
5699 	}
5700 }
5701 
5702 static void
kqueue_update_iotier_override(kqueue_t kqu)5703 kqueue_update_iotier_override(kqueue_t kqu)
5704 {
5705 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5706 		kqworkloop_update_iotier_override(kqu.kqwl);
5707 	}
5708 }
5709 
5710 static void
kqueue_update_override(kqueue_t kqu,struct knote * kn,thread_qos_t qos)5711 kqueue_update_override(kqueue_t kqu, struct knote *kn, thread_qos_t qos)
5712 {
5713 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5714 		kqworkloop_update_threads_qos(kqu.kqwl, KQWL_UTQ_UPDATE_WAKEUP_OVERRIDE,
5715 		    qos);
5716 	} else {
5717 		kqworkq_update_override(kqu.kqwq, kn, qos);
5718 	}
5719 }
5720 
5721 static void
kqworkloop_unbind_locked(struct kqworkloop * kqwl,thread_t thread,enum kqwl_unbind_locked_mode how)5722 kqworkloop_unbind_locked(struct kqworkloop *kqwl, thread_t thread,
5723     enum kqwl_unbind_locked_mode how)
5724 {
5725 	struct uthread *ut = get_bsdthread_info(thread);
5726 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5727 
5728 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWL_UNBIND), kqwl->kqwl_dynamicid,
5729 	    thread_tid(thread), 0, 0);
5730 
5731 	kqlock_held(kqwl);
5732 
5733 	assert(ut->uu_kqr_bound == kqr);
5734 	ut->uu_kqr_bound = NULL;
5735 	if (how == KQWL_OVERRIDE_DROP_IMMEDIATELY &&
5736 	    ut->uu_kqueue_override != THREAD_QOS_UNSPECIFIED) {
5737 		thread_drop_servicer_override(thread);
5738 		ut->uu_kqueue_override = THREAD_QOS_UNSPECIFIED;
5739 	}
5740 
5741 	if (kqwl->kqwl_owner == NULL && kqwl->kqwl_turnstile) {
5742 		turnstile_update_inheritor(kqwl->kqwl_turnstile,
5743 		    TURNSTILE_INHERITOR_NULL, TURNSTILE_IMMEDIATE_UPDATE);
5744 		turnstile_update_inheritor_complete(kqwl->kqwl_turnstile,
5745 		    TURNSTILE_INTERLOCK_HELD);
5746 	}
5747 
5748 #if CONFIG_PREADOPT_TG
5749 	/* The kqueue is able to adopt a thread group again */
5750 
5751 	thread_group_qos_t old_tg, new_tg = NULL;
5752 	int ret = os_atomic_rmw_loop(kqr_preadopt_thread_group_addr(kqr), old_tg, new_tg, relaxed, {
5753 		new_tg = old_tg;
5754 		if (old_tg == KQWL_PREADOPTED_TG_SENTINEL || old_tg == KQWL_PREADOPTED_TG_PROCESSED) {
5755 		        new_tg = KQWL_PREADOPTED_TG_NULL;
5756 		}
5757 	});
5758 	KQWL_PREADOPT_TG_HISTORY_WRITE_ENTRY(kqwl, KQWL_PREADOPT_OP_SERVICER_UNBIND, old_tg, KQWL_PREADOPTED_TG_NULL);
5759 
5760 	if (ret) {
5761 		// Servicer can drop any preadopt thread group it has since it has
5762 		// unbound.
5763 		thread_set_preadopt_thread_group(thread, NULL);
5764 	}
5765 #endif
5766 	thread_update_servicer_iotier_override(thread, THROTTLE_LEVEL_END);
5767 
5768 	kqr->tr_thread = THREAD_NULL;
5769 	kqr->tr_state = WORKQ_TR_STATE_IDLE;
5770 	kqwl->kqwl_state &= ~KQ_R2K_ARMED;
5771 }
5772 
5773 static void
kqworkloop_unbind_delayed_override_drop(thread_t thread)5774 kqworkloop_unbind_delayed_override_drop(thread_t thread)
5775 {
5776 	struct uthread *ut = get_bsdthread_info(thread);
5777 	assert(ut->uu_kqr_bound == NULL);
5778 	if (ut->uu_kqueue_override != THREAD_QOS_UNSPECIFIED) {
5779 		thread_drop_servicer_override(thread);
5780 		ut->uu_kqueue_override = THREAD_QOS_UNSPECIFIED;
5781 	}
5782 }
5783 
5784 /*
5785  *	kqworkloop_unbind - Unbind the servicer thread of a workloop kqueue
5786  *
5787  *	It will acknowledge events, and possibly request a new thread if:
5788  *	- there were active events left
5789  *	- we pended waitq hook callouts during processing
5790  *	- we pended wakeups while processing (or unsuppressing)
5791  *
5792  *	Called with kqueue lock held.
5793  */
5794 static void
kqworkloop_unbind(struct kqworkloop * kqwl)5795 kqworkloop_unbind(struct kqworkloop *kqwl)
5796 {
5797 	struct kqueue *kq = &kqwl->kqwl_kqueue;
5798 	workq_threadreq_t kqr = &kqwl->kqwl_request;
5799 	thread_t thread = kqr_thread_fast(kqr);
5800 	int op = KQWL_UTQ_PARKING;
5801 	kq_index_t qos_override = THREAD_QOS_UNSPECIFIED;
5802 
5803 	assert(thread == current_thread());
5804 
5805 	kqlock(kqwl);
5806 
5807 	/*
5808 	 * Forcing the KQ_PROCESSING flag allows for QoS updates because of
5809 	 * unsuppressing knotes not to be applied until the eventual call to
5810 	 * kqworkloop_update_threads_qos() below.
5811 	 */
5812 	assert((kq->kq_state & KQ_PROCESSING) == 0);
5813 	if (!TAILQ_EMPTY(&kqwl->kqwl_suppressed)) {
5814 		kq->kq_state |= KQ_PROCESSING;
5815 		qos_override = kqworkloop_acknowledge_events(kqwl);
5816 		kq->kq_state &= ~KQ_PROCESSING;
5817 	}
5818 
5819 	kqworkloop_unbind_locked(kqwl, thread, KQWL_OVERRIDE_DROP_DELAYED);
5820 	kqworkloop_update_threads_qos(kqwl, op, qos_override);
5821 
5822 	kqunlock(kqwl);
5823 
5824 	/*
5825 	 * Drop the override on the current thread last, after the call to
5826 	 * kqworkloop_update_threads_qos above.
5827 	 */
5828 	kqworkloop_unbind_delayed_override_drop(thread);
5829 
5830 	/* If last reference, dealloc the workloop kq */
5831 	kqworkloop_release(kqwl);
5832 }
5833 
5834 static thread_qos_t
kqworkq_unbind_locked(struct kqworkq * kqwq,workq_threadreq_t kqr,thread_t thread)5835 kqworkq_unbind_locked(struct kqworkq *kqwq,
5836     workq_threadreq_t kqr, thread_t thread)
5837 {
5838 	struct uthread *ut = get_bsdthread_info(thread);
5839 	kq_index_t old_override = kqr->tr_kq_override_index;
5840 
5841 	KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KQWQ_UNBIND), -1,
5842 	    thread_tid(kqr_thread(kqr)), kqr->tr_kq_qos_index, 0);
5843 
5844 	kqlock_held(kqwq);
5845 
5846 	assert(ut->uu_kqr_bound == kqr);
5847 	ut->uu_kqr_bound = NULL;
5848 	kqr->tr_thread = THREAD_NULL;
5849 	kqr->tr_state = WORKQ_TR_STATE_IDLE;
5850 	kqr->tr_kq_override_index = THREAD_QOS_UNSPECIFIED;
5851 	kqwq->kqwq_state &= ~KQ_R2K_ARMED;
5852 
5853 	return old_override;
5854 }
5855 
5856 /*
5857  *	kqworkq_unbind - unbind of a workq kqueue from a thread
5858  *
5859  *	We may have to request new threads.
5860  *	This can happen there are no waiting processing threads and:
5861  *	- there were active events we never got to (count > 0)
5862  *	- we pended waitq hook callouts during processing
5863  *	- we pended wakeups while processing (or unsuppressing)
5864  */
5865 static void
kqworkq_unbind(proc_t p,workq_threadreq_t kqr)5866 kqworkq_unbind(proc_t p, workq_threadreq_t kqr)
5867 {
5868 	struct kqworkq *kqwq = (struct kqworkq *)p->p_fd.fd_wqkqueue;
5869 	__assert_only int rc;
5870 
5871 	kqlock(kqwq);
5872 	rc = kqworkq_acknowledge_events(kqwq, kqr, 0, KQWQAE_UNBIND);
5873 	assert(rc == -1);
5874 	kqunlock(kqwq);
5875 }
5876 
5877 workq_threadreq_t
kqworkq_get_request(struct kqworkq * kqwq,kq_index_t qos_index)5878 kqworkq_get_request(struct kqworkq *kqwq, kq_index_t qos_index)
5879 {
5880 	assert(qos_index > 0 && qos_index <= KQWQ_NBUCKETS);
5881 	return &kqwq->kqwq_request[qos_index - 1];
5882 }
5883 
5884 static void
knote_reset_priority(kqueue_t kqu,struct knote * kn,pthread_priority_t pp)5885 knote_reset_priority(kqueue_t kqu, struct knote *kn, pthread_priority_t pp)
5886 {
5887 	kq_index_t qos = _pthread_priority_thread_qos(pp);
5888 
5889 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
5890 		assert((pp & _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG) == 0);
5891 		pp = _pthread_priority_normalize(pp);
5892 	} else if (kqu.kq->kq_state & KQ_WORKQ) {
5893 		if (qos == THREAD_QOS_UNSPECIFIED) {
5894 			/* On workqueues, outside of QoS means MANAGER */
5895 			qos = KQWQ_QOS_MANAGER;
5896 			pp = _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG;
5897 		} else {
5898 			pp = _pthread_priority_normalize(pp);
5899 		}
5900 	} else {
5901 		pp = _pthread_unspecified_priority();
5902 		qos = THREAD_QOS_UNSPECIFIED;
5903 	}
5904 
5905 	kn->kn_qos = (int32_t)pp;
5906 
5907 	if ((kn->kn_status & KN_MERGE_QOS) == 0 || qos > kn->kn_qos_override) {
5908 		/* Never lower QoS when in "Merge" mode */
5909 		kn->kn_qos_override = qos;
5910 	}
5911 
5912 	/* only adjust in-use qos index when not suppressed */
5913 	if (kn->kn_status & KN_SUPPRESSED) {
5914 		kqueue_update_override(kqu, kn, qos);
5915 	} else if (kn->kn_qos_index != qos) {
5916 		knote_dequeue(kqu, kn);
5917 		kn->kn_qos_index = qos;
5918 	}
5919 }
5920 
5921 static void
knote_adjust_qos(struct kqueue * kq,struct knote * kn,int result)5922 knote_adjust_qos(struct kqueue *kq, struct knote *kn, int result)
5923 {
5924 	thread_qos_t qos_index = (result >> FILTER_ADJUST_EVENT_QOS_SHIFT) & 7;
5925 
5926 	kqlock_held(kq);
5927 
5928 	assert(result & FILTER_ADJUST_EVENT_QOS_BIT);
5929 	assert(qos_index < THREAD_QOS_LAST);
5930 
5931 	/*
5932 	 * Early exit for knotes that should not change QoS
5933 	 */
5934 	if (__improbable(!knote_fops(kn)->f_adjusts_qos)) {
5935 		panic("filter %d cannot change QoS", kn->kn_filtid);
5936 	} else if (__improbable(!knote_has_qos(kn))) {
5937 		return;
5938 	}
5939 
5940 	/*
5941 	 * knotes with the FALLBACK flag will only use their registration QoS if the
5942 	 * incoming event has no QoS, else, the registration QoS acts as a floor.
5943 	 */
5944 	thread_qos_t req_qos = _pthread_priority_thread_qos_fast(kn->kn_qos);
5945 	if (kn->kn_qos & _PTHREAD_PRIORITY_FALLBACK_FLAG) {
5946 		if (qos_index == THREAD_QOS_UNSPECIFIED) {
5947 			qos_index = req_qos;
5948 		}
5949 	} else {
5950 		if (qos_index < req_qos) {
5951 			qos_index = req_qos;
5952 		}
5953 	}
5954 	if ((kn->kn_status & KN_MERGE_QOS) && (qos_index < kn->kn_qos_override)) {
5955 		/* Never lower QoS when in "Merge" mode */
5956 		return;
5957 	}
5958 
5959 	if ((kn->kn_status & KN_LOCKED) && (kn->kn_status & KN_POSTING)) {
5960 		/*
5961 		 * When we're trying to update the QoS override and that both an
5962 		 * f_event() and other f_* calls are running concurrently, any of these
5963 		 * in flight calls may want to perform overrides that aren't properly
5964 		 * serialized with each other.
5965 		 *
5966 		 * The first update that observes this racy situation enters a "Merge"
5967 		 * mode which causes subsequent override requests to saturate the
5968 		 * override instead of replacing its value.
5969 		 *
5970 		 * This mode is left when knote_unlock() or knote_post()
5971 		 * observe that no other f_* routine is in flight.
5972 		 */
5973 		kn->kn_status |= KN_MERGE_QOS;
5974 	}
5975 
5976 	/*
5977 	 * Now apply the override if it changed.
5978 	 */
5979 
5980 	if (kn->kn_qos_override == qos_index) {
5981 		return;
5982 	}
5983 
5984 	kn->kn_qos_override = qos_index;
5985 
5986 	if (kn->kn_status & KN_SUPPRESSED) {
5987 		/*
5988 		 * For suppressed events, the kn_qos_index field cannot be touched as it
5989 		 * allows us to know on which supress queue the knote is for a kqworkq.
5990 		 *
5991 		 * Also, there's no natural push applied on the kqueues when this field
5992 		 * changes anyway. We hence need to apply manual overrides in this case,
5993 		 * which will be cleared when the events are later acknowledged.
5994 		 */
5995 		kqueue_update_override(kq, kn, qos_index);
5996 	} else if (kn->kn_qos_index != qos_index) {
5997 		knote_dequeue(kq, kn);
5998 		kn->kn_qos_index = qos_index;
5999 	}
6000 }
6001 
6002 void
klist_init(struct klist * list)6003 klist_init(struct klist *list)
6004 {
6005 	SLIST_INIT(list);
6006 }
6007 
6008 
6009 /*
6010  * Query/Post each knote in the object's list
6011  *
6012  *	The object lock protects the list. It is assumed
6013  *	that the filter/event routine for the object can
6014  *	determine that the object is already locked (via
6015  *	the hint) and not deadlock itself.
6016  *
6017  *	The object lock should also hold off pending
6018  *	detach/drop operations.
6019  */
6020 void
knote(struct klist * list,long hint)6021 knote(struct klist *list, long hint)
6022 {
6023 	struct knote *kn;
6024 
6025 	SLIST_FOREACH(kn, list, kn_selnext) {
6026 		knote_post(kn, hint);
6027 	}
6028 }
6029 
6030 /*
6031  * attach a knote to the specified list.  Return true if this is the first entry.
6032  * The list is protected by whatever lock the object it is associated with uses.
6033  */
6034 int
knote_attach(struct klist * list,struct knote * kn)6035 knote_attach(struct klist *list, struct knote *kn)
6036 {
6037 	int ret = SLIST_EMPTY(list);
6038 	SLIST_INSERT_HEAD(list, kn, kn_selnext);
6039 	return ret;
6040 }
6041 
6042 /*
6043  * detach a knote from the specified list.  Return true if that was the last entry.
6044  * The list is protected by whatever lock the object it is associated with uses.
6045  */
6046 int
knote_detach(struct klist * list,struct knote * kn)6047 knote_detach(struct klist *list, struct knote *kn)
6048 {
6049 	SLIST_REMOVE(list, kn, knote, kn_selnext);
6050 	return SLIST_EMPTY(list);
6051 }
6052 
6053 /*
6054  * knote_vanish - Indicate that the source has vanished
6055  *
6056  * If the knote has requested EV_VANISHED delivery,
6057  * arrange for that. Otherwise, deliver a NOTE_REVOKE
6058  * event for backward compatibility.
6059  *
6060  * The knote is marked as having vanished, but is not
6061  * actually detached from the source in this instance.
6062  * The actual detach is deferred until the knote drop.
6063  *
6064  * Our caller already has the object lock held. Calling
6065  * the detach routine would try to take that lock
6066  * recursively - which likely is not supported.
6067  */
6068 void
knote_vanish(struct klist * list,bool make_active)6069 knote_vanish(struct klist *list, bool make_active)
6070 {
6071 	struct knote *kn;
6072 	struct knote *kn_next;
6073 
6074 	SLIST_FOREACH_SAFE(kn, list, kn_selnext, kn_next) {
6075 		struct kqueue *kq = knote_get_kq(kn);
6076 
6077 		kqlock(kq);
6078 		if (__probable(kn->kn_status & KN_REQVANISH)) {
6079 			/*
6080 			 * If EV_VANISH supported - prepare to deliver one
6081 			 */
6082 			kn->kn_status |= KN_VANISHED;
6083 		} else {
6084 			/*
6085 			 * Handle the legacy way to indicate that the port/portset was
6086 			 * deallocated or left the current Mach portspace (modern technique
6087 			 * is with an EV_VANISHED protocol).
6088 			 *
6089 			 * Deliver an EV_EOF event for these changes (hopefully it will get
6090 			 * delivered before the port name recycles to the same generation
6091 			 * count and someone tries to re-register a kevent for it or the
6092 			 * events are udata-specific - avoiding a conflict).
6093 			 */
6094 			kn->kn_flags |= EV_EOF | EV_ONESHOT;
6095 		}
6096 		if (make_active) {
6097 			knote_activate(kq, kn, FILTER_ACTIVE);
6098 		}
6099 		kqunlock(kq);
6100 	}
6101 }
6102 
6103 /*
6104  * remove all knotes referencing a specified fd
6105  *
6106  * Entered with the proc_fd lock already held.
6107  * It returns the same way, but may drop it temporarily.
6108  */
6109 void
knote_fdclose(struct proc * p,int fd)6110 knote_fdclose(struct proc *p, int fd)
6111 {
6112 	struct filedesc *fdt = &p->p_fd;
6113 	struct klist *list;
6114 	struct knote *kn;
6115 	KNOTE_LOCK_CTX(knlc);
6116 
6117 restart:
6118 	list = &fdt->fd_knlist[fd];
6119 	SLIST_FOREACH(kn, list, kn_link) {
6120 		struct kqueue *kq = knote_get_kq(kn);
6121 
6122 		kqlock(kq);
6123 
6124 		if (kq->kq_p != p) {
6125 			panic("%s: proc mismatch (kq->kq_p=%p != p=%p)",
6126 			    __func__, kq->kq_p, p);
6127 		}
6128 
6129 		/*
6130 		 * If the knote supports EV_VANISHED delivery,
6131 		 * transition it to vanished mode (or skip over
6132 		 * it if already vanished).
6133 		 */
6134 		if (kn->kn_status & KN_VANISHED) {
6135 			kqunlock(kq);
6136 			continue;
6137 		}
6138 
6139 		proc_fdunlock(p);
6140 		if (!knote_lock(kq, kn, &knlc, KNOTE_KQ_LOCK_ON_SUCCESS)) {
6141 			/* the knote was dropped by someone, nothing to do */
6142 		} else if (kn->kn_status & KN_REQVANISH) {
6143 			kn->kn_status |= KN_VANISHED;
6144 
6145 			kqunlock(kq);
6146 			knote_fops(kn)->f_detach(kn);
6147 			if (kn->kn_is_fd) {
6148 				fp_drop(p, (int)kn->kn_id, kn->kn_fp, 0);
6149 			}
6150 			kn->kn_filtid = EVFILTID_DETACHED;
6151 			kqlock(kq);
6152 
6153 			knote_activate(kq, kn, FILTER_ACTIVE);
6154 			knote_unlock(kq, kn, &knlc, KNOTE_KQ_UNLOCK);
6155 		} else {
6156 			knote_drop(kq, kn, &knlc);
6157 		}
6158 
6159 		proc_fdlock(p);
6160 		goto restart;
6161 	}
6162 }
6163 
6164 /*
6165  * knote_fdfind - lookup a knote in the fd table for process
6166  *
6167  * If the filter is file-based, lookup based on fd index.
6168  * Otherwise use a hash based on the ident.
6169  *
6170  * Matching is based on kq, filter, and ident. Optionally,
6171  * it may also be based on the udata field in the kevent -
6172  * allowing multiple event registration for the file object
6173  * per kqueue.
6174  *
6175  * fd_knhashlock or fdlock held on entry (and exit)
6176  */
6177 static struct knote *
knote_fdfind(struct kqueue * kq,const struct kevent_internal_s * kev,bool is_fd,struct proc * p)6178 knote_fdfind(struct kqueue *kq,
6179     const struct kevent_internal_s *kev,
6180     bool is_fd,
6181     struct proc *p)
6182 {
6183 	struct filedesc *fdp = &p->p_fd;
6184 	struct klist *list = NULL;
6185 	struct knote *kn = NULL;
6186 
6187 	/*
6188 	 * determine where to look for the knote
6189 	 */
6190 	if (is_fd) {
6191 		/* fd-based knotes are linked off the fd table */
6192 		if (kev->kei_ident < (u_int)fdp->fd_knlistsize) {
6193 			list = &fdp->fd_knlist[kev->kei_ident];
6194 		}
6195 	} else if (fdp->fd_knhashmask != 0) {
6196 		/* hash non-fd knotes here too */
6197 		list = &fdp->fd_knhash[KN_HASH((u_long)kev->kei_ident, fdp->fd_knhashmask)];
6198 	}
6199 
6200 	/*
6201 	 * scan the selected list looking for a match
6202 	 */
6203 	if (list != NULL) {
6204 		SLIST_FOREACH(kn, list, kn_link) {
6205 			if (kq == knote_get_kq(kn) &&
6206 			    kev->kei_ident == kn->kn_id &&
6207 			    kev->kei_filter == kn->kn_filter) {
6208 				if (kev->kei_flags & EV_UDATA_SPECIFIC) {
6209 					if ((kn->kn_flags & EV_UDATA_SPECIFIC) &&
6210 					    kev->kei_udata == kn->kn_udata) {
6211 						break; /* matching udata-specific knote */
6212 					}
6213 				} else if ((kn->kn_flags & EV_UDATA_SPECIFIC) == 0) {
6214 					break; /* matching non-udata-specific knote */
6215 				}
6216 			}
6217 		}
6218 	}
6219 	return kn;
6220 }
6221 
6222 /*
6223  * kq_add_knote- Add knote to the fd table for process
6224  * while checking for duplicates.
6225  *
6226  * All file-based filters associate a list of knotes by file
6227  * descriptor index. All other filters hash the knote by ident.
6228  *
6229  * May have to grow the table of knote lists to cover the
6230  * file descriptor index presented.
6231  *
6232  * fd_knhashlock and fdlock unheld on entry (and exit).
6233  *
6234  * Takes a rwlock boost if inserting the knote is successful.
6235  */
6236 static int
kq_add_knote(struct kqueue * kq,struct knote * kn,struct knote_lock_ctx * knlc,struct proc * p)6237 kq_add_knote(struct kqueue *kq, struct knote *kn, struct knote_lock_ctx *knlc,
6238     struct proc *p)
6239 {
6240 	struct filedesc *fdp = &p->p_fd;
6241 	struct klist *list = NULL;
6242 	int ret = 0;
6243 	bool is_fd = kn->kn_is_fd;
6244 
6245 	if (is_fd) {
6246 		proc_fdlock(p);
6247 	} else {
6248 		knhash_lock(fdp);
6249 	}
6250 
6251 	if (knote_fdfind(kq, &kn->kn_kevent, is_fd, p) != NULL) {
6252 		/* found an existing knote: we can't add this one */
6253 		ret = ERESTART;
6254 		goto out_locked;
6255 	}
6256 
6257 	/* knote was not found: add it now */
6258 	if (!is_fd) {
6259 		if (fdp->fd_knhashmask == 0) {
6260 			u_long size = 0;
6261 
6262 			list = hashinit(CONFIG_KN_HASHSIZE, M_KQUEUE, &size);
6263 			if (list == NULL) {
6264 				ret = ENOMEM;
6265 				goto out_locked;
6266 			}
6267 
6268 			fdp->fd_knhash = list;
6269 			fdp->fd_knhashmask = size;
6270 		}
6271 
6272 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
6273 		SLIST_INSERT_HEAD(list, kn, kn_link);
6274 		ret = 0;
6275 		goto out_locked;
6276 	} else {
6277 		/* knote is fd based */
6278 
6279 		if ((u_int)fdp->fd_knlistsize <= kn->kn_id) {
6280 			u_int size = 0;
6281 
6282 			/* Make sure that fd stays below current process's soft limit AND system allowed per-process limits */
6283 			if (kn->kn_id >= (uint64_t)proc_limitgetcur_nofile(p)) {
6284 				ret = EINVAL;
6285 				goto out_locked;
6286 			}
6287 			/* have to grow the fd_knlist */
6288 			size = fdp->fd_knlistsize;
6289 			while (size <= kn->kn_id) {
6290 				size += KQEXTENT;
6291 			}
6292 
6293 			if (size >= (UINT_MAX / sizeof(struct klist))) {
6294 				ret = EINVAL;
6295 				goto out_locked;
6296 			}
6297 
6298 			list = kalloc_type(struct klist, size, Z_WAITOK | Z_ZERO);
6299 			if (list == NULL) {
6300 				ret = ENOMEM;
6301 				goto out_locked;
6302 			}
6303 
6304 			bcopy(fdp->fd_knlist, list,
6305 			    fdp->fd_knlistsize * sizeof(struct klist));
6306 			kfree_type(struct klist, fdp->fd_knlistsize, fdp->fd_knlist);
6307 			fdp->fd_knlist = list;
6308 			fdp->fd_knlistsize = size;
6309 		}
6310 
6311 		list = &fdp->fd_knlist[kn->kn_id];
6312 		SLIST_INSERT_HEAD(list, kn, kn_link);
6313 		ret = 0;
6314 		goto out_locked;
6315 	}
6316 
6317 out_locked:
6318 	if (ret == 0) {
6319 		kqlock(kq);
6320 		assert((kn->kn_status & KN_LOCKED) == 0);
6321 		(void)knote_lock(kq, kn, knlc, KNOTE_KQ_UNLOCK);
6322 		kqueue_retain(kq); /* retain a kq ref */
6323 	}
6324 	if (is_fd) {
6325 		proc_fdunlock(p);
6326 	} else {
6327 		knhash_unlock(fdp);
6328 	}
6329 
6330 	return ret;
6331 }
6332 
6333 /*
6334  * kq_remove_knote - remove a knote from the fd table for process
6335  *
6336  * If the filter is file-based, remove based on fd index.
6337  * Otherwise remove from the hash based on the ident.
6338  *
6339  * fd_knhashlock and fdlock unheld on entry (and exit).
6340  */
6341 static void
kq_remove_knote(struct kqueue * kq,struct knote * kn,struct proc * p,struct knote_lock_ctx * knlc)6342 kq_remove_knote(struct kqueue *kq, struct knote *kn, struct proc *p,
6343     struct knote_lock_ctx *knlc)
6344 {
6345 	struct filedesc *fdp = &p->p_fd;
6346 	struct klist *list = NULL;
6347 	uint16_t kq_state;
6348 	bool is_fd = kn->kn_is_fd;
6349 
6350 	if (is_fd) {
6351 		proc_fdlock(p);
6352 	} else {
6353 		knhash_lock(fdp);
6354 	}
6355 
6356 	if (is_fd) {
6357 		assert((u_int)fdp->fd_knlistsize > kn->kn_id);
6358 		list = &fdp->fd_knlist[kn->kn_id];
6359 	} else {
6360 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
6361 	}
6362 	SLIST_REMOVE(list, kn, knote, kn_link);
6363 
6364 	kqlock(kq);
6365 
6366 	/* Update the servicer iotier override */
6367 	kqueue_update_iotier_override(kq);
6368 
6369 	kq_state = kq->kq_state;
6370 	if (knlc) {
6371 		knote_unlock_cancel(kq, kn, knlc);
6372 	} else {
6373 		kqunlock(kq);
6374 	}
6375 	if (is_fd) {
6376 		proc_fdunlock(p);
6377 	} else {
6378 		knhash_unlock(fdp);
6379 	}
6380 
6381 	if (kq_state & KQ_DYNAMIC) {
6382 		kqworkloop_release((struct kqworkloop *)kq);
6383 	}
6384 }
6385 
6386 /*
6387  * kq_find_knote_and_kq_lock - lookup a knote in the fd table for process
6388  * and, if the knote is found, acquires the kqlock while holding the fd table lock/spinlock.
6389  *
6390  * fd_knhashlock or fdlock unheld on entry (and exit)
6391  */
6392 
6393 static struct knote *
kq_find_knote_and_kq_lock(struct kqueue * kq,struct kevent_qos_s * kev,bool is_fd,struct proc * p)6394 kq_find_knote_and_kq_lock(struct kqueue *kq, struct kevent_qos_s *kev,
6395     bool is_fd, struct proc *p)
6396 {
6397 	struct filedesc *fdp = &p->p_fd;
6398 	struct knote *kn;
6399 
6400 	if (is_fd) {
6401 		proc_fdlock(p);
6402 	} else {
6403 		knhash_lock(fdp);
6404 	}
6405 
6406 	/*
6407 	 * Temporary horrible hack:
6408 	 * this cast is gross and will go away in a future change.
6409 	 * It is OK to do because we don't look at xflags/s_fflags,
6410 	 * and that when we cast down the kev this way,
6411 	 * the truncated filter field works.
6412 	 */
6413 	kn = knote_fdfind(kq, (struct kevent_internal_s *)kev, is_fd, p);
6414 
6415 	if (kn) {
6416 		kqlock(kq);
6417 		assert(knote_get_kq(kn) == kq);
6418 	}
6419 
6420 	if (is_fd) {
6421 		proc_fdunlock(p);
6422 	} else {
6423 		knhash_unlock(fdp);
6424 	}
6425 
6426 	return kn;
6427 }
6428 
6429 static struct kqtailq *
knote_get_tailq(kqueue_t kqu,struct knote * kn)6430 knote_get_tailq(kqueue_t kqu, struct knote *kn)
6431 {
6432 	kq_index_t qos_index = kn->kn_qos_index;
6433 
6434 	if (kqu.kq->kq_state & KQ_WORKLOOP) {
6435 		assert(qos_index > 0 && qos_index <= KQWL_NBUCKETS);
6436 		return &kqu.kqwl->kqwl_queue[qos_index - 1];
6437 	} else if (kqu.kq->kq_state & KQ_WORKQ) {
6438 		assert(qos_index > 0 && qos_index <= KQWQ_NBUCKETS);
6439 		return &kqu.kqwq->kqwq_queue[qos_index - 1];
6440 	} else {
6441 		assert(qos_index == QOS_INDEX_KQFILE);
6442 		return &kqu.kqf->kqf_queue;
6443 	}
6444 }
6445 
6446 static void
knote_enqueue(kqueue_t kqu,struct knote * kn)6447 knote_enqueue(kqueue_t kqu, struct knote *kn)
6448 {
6449 	kqlock_held(kqu);
6450 
6451 	if ((kn->kn_status & KN_ACTIVE) == 0) {
6452 		return;
6453 	}
6454 
6455 	if (kn->kn_status & (KN_DISABLED | KN_SUPPRESSED | KN_DROPPING | KN_QUEUED)) {
6456 		return;
6457 	}
6458 
6459 	struct kqtailq *queue = knote_get_tailq(kqu, kn);
6460 	bool wakeup = TAILQ_EMPTY(queue);
6461 
6462 	TAILQ_INSERT_TAIL(queue, kn, kn_tqe);
6463 	kn->kn_status |= KN_QUEUED;
6464 	kqu.kq->kq_count++;
6465 
6466 	if (wakeup) {
6467 		if (kqu.kq->kq_state & KQ_WORKLOOP) {
6468 			kqworkloop_wakeup(kqu.kqwl, kn->kn_qos_index);
6469 		} else if (kqu.kq->kq_state & KQ_WORKQ) {
6470 			kqworkq_wakeup(kqu.kqwq, kn->kn_qos_index);
6471 		} else {
6472 			kqfile_wakeup(kqu.kqf, 0, THREAD_AWAKENED);
6473 		}
6474 	}
6475 }
6476 
6477 __attribute__((always_inline))
6478 static inline void
knote_dequeue(kqueue_t kqu,struct knote * kn)6479 knote_dequeue(kqueue_t kqu, struct knote *kn)
6480 {
6481 	if (kn->kn_status & KN_QUEUED) {
6482 		struct kqtailq *queue = knote_get_tailq(kqu, kn);
6483 
6484 		// attaching the knote calls knote_reset_priority() without
6485 		// the kqlock which is fine, so we can't call kqlock_held()
6486 		// if we're not queued.
6487 		kqlock_held(kqu);
6488 
6489 		TAILQ_REMOVE(queue, kn, kn_tqe);
6490 		kn->kn_status &= ~KN_QUEUED;
6491 		kqu.kq->kq_count--;
6492 		if ((kqu.kq->kq_state & (KQ_WORKQ | KQ_WORKLOOP)) == 0) {
6493 			assert((kqu.kq->kq_count == 0) ==
6494 			    (bool)TAILQ_EMPTY(queue));
6495 		}
6496 	}
6497 }
6498 
6499 /* called with kqueue lock held */
6500 static void
knote_suppress(kqueue_t kqu,struct knote * kn)6501 knote_suppress(kqueue_t kqu, struct knote *kn)
6502 {
6503 	struct kqtailq *suppressq;
6504 
6505 	kqlock_held(kqu);
6506 
6507 	assert((kn->kn_status & KN_SUPPRESSED) == 0);
6508 	assert(kn->kn_status & KN_QUEUED);
6509 
6510 	knote_dequeue(kqu, kn);
6511 	/* deactivate - so new activations indicate a wakeup */
6512 	kn->kn_status &= ~KN_ACTIVE;
6513 	kn->kn_status |= KN_SUPPRESSED;
6514 	suppressq = kqueue_get_suppressed_queue(kqu, kn);
6515 	TAILQ_INSERT_TAIL(suppressq, kn, kn_tqe);
6516 }
6517 
6518 __attribute__((always_inline))
6519 static inline void
knote_unsuppress_noqueue(kqueue_t kqu,struct knote * kn)6520 knote_unsuppress_noqueue(kqueue_t kqu, struct knote *kn)
6521 {
6522 	struct kqtailq *suppressq;
6523 
6524 	kqlock_held(kqu);
6525 
6526 	assert(kn->kn_status & KN_SUPPRESSED);
6527 
6528 	kn->kn_status &= ~KN_SUPPRESSED;
6529 	suppressq = kqueue_get_suppressed_queue(kqu, kn);
6530 	TAILQ_REMOVE(suppressq, kn, kn_tqe);
6531 
6532 	/*
6533 	 * If the knote is no longer active, reset its push,
6534 	 * and resynchronize kn_qos_index with kn_qos_override
6535 	 * for knotes with a real qos.
6536 	 */
6537 	if ((kn->kn_status & KN_ACTIVE) == 0 && knote_has_qos(kn)) {
6538 		kn->kn_qos_override = _pthread_priority_thread_qos_fast(kn->kn_qos);
6539 	}
6540 	kn->kn_qos_index = kn->kn_qos_override;
6541 }
6542 
6543 /* called with kqueue lock held */
6544 static void
knote_unsuppress(kqueue_t kqu,struct knote * kn)6545 knote_unsuppress(kqueue_t kqu, struct knote *kn)
6546 {
6547 	knote_unsuppress_noqueue(kqu, kn);
6548 	knote_enqueue(kqu, kn);
6549 }
6550 
6551 __attribute__((always_inline))
6552 static inline void
knote_mark_active(struct knote * kn)6553 knote_mark_active(struct knote *kn)
6554 {
6555 	if ((kn->kn_status & KN_ACTIVE) == 0) {
6556 		KDBG_DEBUG(KEV_EVTID(BSD_KEVENT_KNOTE_ACTIVATE),
6557 		    kn->kn_udata, kn->kn_status | (kn->kn_id << 32),
6558 		    kn->kn_filtid);
6559 	}
6560 
6561 	kn->kn_status |= KN_ACTIVE;
6562 }
6563 
6564 /* called with kqueue lock held */
6565 static void
knote_activate(kqueue_t kqu,struct knote * kn,int result)6566 knote_activate(kqueue_t kqu, struct knote *kn, int result)
6567 {
6568 	assert(result & FILTER_ACTIVE);
6569 	if (result & FILTER_ADJUST_EVENT_QOS_BIT) {
6570 		// may dequeue the knote
6571 		knote_adjust_qos(kqu.kq, kn, result);
6572 	}
6573 	knote_mark_active(kn);
6574 	knote_enqueue(kqu, kn);
6575 }
6576 
6577 /*
6578  * This function applies changes requested by f_attach or f_touch for
6579  * a given filter. It proceeds in a carefully chosen order to help
6580  * every single transition do the minimal amount of work possible.
6581  */
6582 static void
knote_apply_touch(kqueue_t kqu,struct knote * kn,struct kevent_qos_s * kev,int result)6583 knote_apply_touch(kqueue_t kqu, struct knote *kn, struct kevent_qos_s *kev,
6584     int result)
6585 {
6586 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
6587 		kn->kn_status &= ~KN_DISABLED;
6588 
6589 		/*
6590 		 * it is possible for userland to have knotes registered for a given
6591 		 * workloop `wl_orig` but really handled on another workloop `wl_new`.
6592 		 *
6593 		 * In that case, rearming will happen from the servicer thread of
6594 		 * `wl_new` which if `wl_orig` is no longer being serviced, would cause
6595 		 * this knote to stay suppressed forever if we only relied on
6596 		 * kqworkloop_acknowledge_events to be called by `wl_orig`.
6597 		 *
6598 		 * However if we see the KQ_PROCESSING bit on `wl_orig` set, we can't
6599 		 * unsuppress because that would mess with the processing phase of
6600 		 * `wl_orig`, however it also means kqworkloop_acknowledge_events()
6601 		 * will be called.
6602 		 */
6603 		if (__improbable(kn->kn_status & KN_SUPPRESSED)) {
6604 			if ((kqu.kq->kq_state & KQ_PROCESSING) == 0) {
6605 				knote_unsuppress_noqueue(kqu, kn);
6606 			}
6607 		}
6608 	}
6609 
6610 	if (result & FILTER_ADJUST_EVENT_IOTIER_BIT) {
6611 		kqueue_update_iotier_override(kqu);
6612 	}
6613 
6614 	if ((result & FILTER_UPDATE_REQ_QOS) && kev->qos && kev->qos != kn->kn_qos) {
6615 		// may dequeue the knote
6616 		knote_reset_priority(kqu, kn, kev->qos);
6617 	}
6618 
6619 	/*
6620 	 * When we unsuppress above, or because of knote_reset_priority(),
6621 	 * the knote may have been dequeued, we need to restore the invariant
6622 	 * that if the knote is active it needs to be queued now that
6623 	 * we're done applying changes.
6624 	 */
6625 	if (result & FILTER_ACTIVE) {
6626 		knote_activate(kqu, kn, result);
6627 	} else {
6628 		knote_enqueue(kqu, kn);
6629 	}
6630 
6631 	if ((result & FILTER_THREADREQ_NODEFEER) &&
6632 	    act_clear_astkevent(current_thread(), AST_KEVENT_REDRIVE_THREADREQ)) {
6633 		workq_kern_threadreq_redrive(kqu.kq->kq_p, WORKQ_THREADREQ_NONE);
6634 	}
6635 }
6636 
6637 /*
6638  * knote_drop - disconnect and drop the knote
6639  *
6640  * Called with the kqueue locked, returns with the kqueue unlocked.
6641  *
6642  * If a knote locking context is passed, it is canceled.
6643  *
6644  * The knote may have already been detached from
6645  * (or not yet attached to) its source object.
6646  */
6647 static void
knote_drop(struct kqueue * kq,struct knote * kn,struct knote_lock_ctx * knlc)6648 knote_drop(struct kqueue *kq, struct knote *kn, struct knote_lock_ctx *knlc)
6649 {
6650 	struct proc *p = kq->kq_p;
6651 
6652 	kqlock_held(kq);
6653 
6654 	assert((kn->kn_status & KN_DROPPING) == 0);
6655 	if (knlc == NULL) {
6656 		assert((kn->kn_status & KN_LOCKED) == 0);
6657 	}
6658 	kn->kn_status |= KN_DROPPING;
6659 
6660 	if (kn->kn_status & KN_SUPPRESSED) {
6661 		knote_unsuppress_noqueue(kq, kn);
6662 	} else {
6663 		knote_dequeue(kq, kn);
6664 	}
6665 	knote_wait_for_post(kq, kn);
6666 
6667 	knote_fops(kn)->f_detach(kn);
6668 
6669 	/* kq may be freed when kq_remove_knote() returns */
6670 	kq_remove_knote(kq, kn, p, knlc);
6671 	if (kn->kn_is_fd && ((kn->kn_status & KN_VANISHED) == 0)) {
6672 		fp_drop(p, (int)kn->kn_id, kn->kn_fp, 0);
6673 	}
6674 
6675 	knote_free(kn);
6676 }
6677 
6678 void
knote_init(void)6679 knote_init(void)
6680 {
6681 #if CONFIG_MEMORYSTATUS
6682 	/* Initialize the memorystatus list lock */
6683 	memorystatus_kevent_init(&kq_lck_grp, LCK_ATTR_NULL);
6684 #endif
6685 }
6686 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
6687 
6688 const struct filterops *
knote_fops(struct knote * kn)6689 knote_fops(struct knote *kn)
6690 {
6691 	return sysfilt_ops[kn->kn_filtid];
6692 }
6693 
6694 static struct knote *
knote_alloc(void)6695 knote_alloc(void)
6696 {
6697 	return zalloc_flags(knote_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
6698 }
6699 
6700 static void
knote_free(struct knote * kn)6701 knote_free(struct knote *kn)
6702 {
6703 	assert((kn->kn_status & (KN_LOCKED | KN_POSTING)) == 0);
6704 	zfree(knote_zone, kn);
6705 }
6706 
6707 #pragma mark - syscalls: kevent, kevent64, kevent_qos, kevent_id
6708 
6709 kevent_ctx_t
kevent_get_context(thread_t thread)6710 kevent_get_context(thread_t thread)
6711 {
6712 	uthread_t ut = get_bsdthread_info(thread);
6713 	return &ut->uu_save.uus_kevent;
6714 }
6715 
6716 static inline bool
kevent_args_requesting_events(unsigned int flags,int nevents)6717 kevent_args_requesting_events(unsigned int flags, int nevents)
6718 {
6719 	return !(flags & KEVENT_FLAG_ERROR_EVENTS) && nevents > 0;
6720 }
6721 
6722 static inline int
kevent_adjust_flags_for_proc(proc_t p,int flags)6723 kevent_adjust_flags_for_proc(proc_t p, int flags)
6724 {
6725 	__builtin_assume(p);
6726 	return flags | (IS_64BIT_PROCESS(p) ? KEVENT_FLAG_PROC64 : 0);
6727 }
6728 
6729 /*!
6730  * @function kevent_get_kqfile
6731  *
6732  * @brief
6733  * Lookup a kqfile by fd.
6734  *
6735  * @discussion
6736  * Callers: kevent, kevent64, kevent_qos
6737  *
6738  * This is not assumed to be a fastpath (kqfile interfaces are legacy)
6739  */
6740 OS_NOINLINE
6741 static int
kevent_get_kqfile(struct proc * p,int fd,int flags,struct fileproc ** fpp,struct kqueue ** kqp)6742 kevent_get_kqfile(struct proc *p, int fd, int flags,
6743     struct fileproc **fpp, struct kqueue **kqp)
6744 {
6745 	int error = 0;
6746 	struct kqueue *kq;
6747 
6748 	error = fp_get_ftype(p, fd, DTYPE_KQUEUE, EBADF, fpp);
6749 	if (__improbable(error)) {
6750 		return error;
6751 	}
6752 	kq = (struct kqueue *)fp_get_data((*fpp));
6753 
6754 	uint16_t kq_state = os_atomic_load(&kq->kq_state, relaxed);
6755 	if (__improbable((kq_state & (KQ_KEV32 | KQ_KEV64 | KQ_KEV_QOS)) == 0)) {
6756 		kqlock(kq);
6757 		kq_state = kq->kq_state;
6758 		if (!(kq_state & (KQ_KEV32 | KQ_KEV64 | KQ_KEV_QOS))) {
6759 			if (flags & KEVENT_FLAG_LEGACY32) {
6760 				kq_state |= KQ_KEV32;
6761 			} else if (flags & KEVENT_FLAG_LEGACY64) {
6762 				kq_state |= KQ_KEV64;
6763 			} else {
6764 				kq_state |= KQ_KEV_QOS;
6765 			}
6766 			kq->kq_state = kq_state;
6767 		}
6768 		kqunlock(kq);
6769 	}
6770 
6771 	/*
6772 	 * kqfiles can't be used through the legacy kevent()
6773 	 * and other interfaces at the same time.
6774 	 */
6775 	if (__improbable((bool)(flags & KEVENT_FLAG_LEGACY32) !=
6776 	    (bool)(kq_state & KQ_KEV32))) {
6777 		fp_drop(p, fd, *fpp, 0);
6778 		return EINVAL;
6779 	}
6780 
6781 	*kqp = kq;
6782 	return 0;
6783 }
6784 
6785 /*!
6786  * @function kevent_get_kqwq
6787  *
6788  * @brief
6789  * Lookup or create the process kqwq (faspath).
6790  *
6791  * @discussion
6792  * Callers: kevent64, kevent_qos
6793  */
6794 OS_ALWAYS_INLINE
6795 static int
kevent_get_kqwq(proc_t p,int flags,int nevents,struct kqueue ** kqp)6796 kevent_get_kqwq(proc_t p, int flags, int nevents, struct kqueue **kqp)
6797 {
6798 	struct kqworkq *kqwq = p->p_fd.fd_wqkqueue;
6799 
6800 	if (__improbable(kevent_args_requesting_events(flags, nevents))) {
6801 		return EINVAL;
6802 	}
6803 	if (__improbable(kqwq == NULL)) {
6804 		kqwq = kqworkq_alloc(p, flags);
6805 		if (__improbable(kqwq == NULL)) {
6806 			return ENOMEM;
6807 		}
6808 	}
6809 
6810 	*kqp = &kqwq->kqwq_kqueue;
6811 	return 0;
6812 }
6813 
6814 #pragma mark kevent copyio
6815 
6816 /*!
6817  * @function kevent_get_data_size
6818  *
6819  * @brief
6820  * Copies in the extra data size from user-space.
6821  */
6822 static int
kevent_get_data_size(int flags,user_addr_t data_avail,user_addr_t data_out,kevent_ctx_t kectx)6823 kevent_get_data_size(int flags, user_addr_t data_avail, user_addr_t data_out,
6824     kevent_ctx_t kectx)
6825 {
6826 	if (!data_avail || !data_out) {
6827 		kectx->kec_data_size  = 0;
6828 		kectx->kec_data_resid = 0;
6829 	} else if (flags & KEVENT_FLAG_PROC64) {
6830 		user64_size_t usize = 0;
6831 		int error = copyin((user_addr_t)data_avail, &usize, sizeof(usize));
6832 		if (__improbable(error)) {
6833 			return error;
6834 		}
6835 		kectx->kec_data_resid = kectx->kec_data_size = (user_size_t)usize;
6836 	} else {
6837 		user32_size_t usize = 0;
6838 		int error = copyin((user_addr_t)data_avail, &usize, sizeof(usize));
6839 		if (__improbable(error)) {
6840 			return error;
6841 		}
6842 		kectx->kec_data_avail = data_avail;
6843 		kectx->kec_data_resid = kectx->kec_data_size = (user_size_t)usize;
6844 	}
6845 	kectx->kec_data_out   = data_out;
6846 	kectx->kec_data_avail = data_avail;
6847 	return 0;
6848 }
6849 
6850 /*!
6851  * @function kevent_put_data_size
6852  *
6853  * @brief
6854  * Copies out the residual data size to user-space if any has been used.
6855  */
6856 static int
kevent_put_data_size(unsigned int flags,kevent_ctx_t kectx)6857 kevent_put_data_size(unsigned int flags, kevent_ctx_t kectx)
6858 {
6859 	if (kectx->kec_data_resid == kectx->kec_data_size) {
6860 		return 0;
6861 	}
6862 	if (flags & KEVENT_FLAG_KERNEL) {
6863 		*(user_size_t *)(uintptr_t)kectx->kec_data_avail = kectx->kec_data_resid;
6864 		return 0;
6865 	}
6866 	if (flags & KEVENT_FLAG_PROC64) {
6867 		user64_size_t usize = (user64_size_t)kectx->kec_data_resid;
6868 		return copyout(&usize, (user_addr_t)kectx->kec_data_avail, sizeof(usize));
6869 	} else {
6870 		user32_size_t usize = (user32_size_t)kectx->kec_data_resid;
6871 		return copyout(&usize, (user_addr_t)kectx->kec_data_avail, sizeof(usize));
6872 	}
6873 }
6874 
6875 /*!
6876  * @function kevent_legacy_copyin
6877  *
6878  * @brief
6879  * Handles the copyin of a kevent/kevent64 event.
6880  */
6881 static int
kevent_legacy_copyin(user_addr_t * addrp,struct kevent_qos_s * kevp,unsigned int flags)6882 kevent_legacy_copyin(user_addr_t *addrp, struct kevent_qos_s *kevp, unsigned int flags)
6883 {
6884 	int error;
6885 
6886 	assert((flags & (KEVENT_FLAG_LEGACY32 | KEVENT_FLAG_LEGACY64)) != 0);
6887 
6888 	if (flags & KEVENT_FLAG_LEGACY64) {
6889 		struct kevent64_s kev64;
6890 
6891 		error = copyin(*addrp, (caddr_t)&kev64, sizeof(kev64));
6892 		if (__improbable(error)) {
6893 			return error;
6894 		}
6895 		*addrp += sizeof(kev64);
6896 		*kevp = (struct kevent_qos_s){
6897 			.ident  = kev64.ident,
6898 			.filter = kev64.filter,
6899 			/* Make sure user doesn't pass in any system flags */
6900 			.flags  = kev64.flags & ~EV_SYSFLAGS,
6901 			.udata  = kev64.udata,
6902 			.fflags = kev64.fflags,
6903 			.data   = kev64.data,
6904 			.ext[0] = kev64.ext[0],
6905 			.ext[1] = kev64.ext[1],
6906 		};
6907 	} else if (flags & KEVENT_FLAG_PROC64) {
6908 		struct user64_kevent kev64;
6909 
6910 		error = copyin(*addrp, (caddr_t)&kev64, sizeof(kev64));
6911 		if (__improbable(error)) {
6912 			return error;
6913 		}
6914 		*addrp += sizeof(kev64);
6915 		*kevp = (struct kevent_qos_s){
6916 			.ident  = kev64.ident,
6917 			.filter = kev64.filter,
6918 			/* Make sure user doesn't pass in any system flags */
6919 			.flags  = kev64.flags & ~EV_SYSFLAGS,
6920 			.udata  = kev64.udata,
6921 			.fflags = kev64.fflags,
6922 			.data   = kev64.data,
6923 		};
6924 	} else {
6925 		struct user32_kevent kev32;
6926 
6927 		error = copyin(*addrp, (caddr_t)&kev32, sizeof(kev32));
6928 		if (__improbable(error)) {
6929 			return error;
6930 		}
6931 		*addrp += sizeof(kev32);
6932 		*kevp = (struct kevent_qos_s){
6933 			.ident  = (uintptr_t)kev32.ident,
6934 			.filter = kev32.filter,
6935 			/* Make sure user doesn't pass in any system flags */
6936 			.flags  = kev32.flags & ~EV_SYSFLAGS,
6937 			.udata  = CAST_USER_ADDR_T(kev32.udata),
6938 			.fflags = kev32.fflags,
6939 			.data   = (intptr_t)kev32.data,
6940 		};
6941 	}
6942 
6943 	return 0;
6944 }
6945 
6946 /*!
6947  * @function kevent_modern_copyin
6948  *
6949  * @brief
6950  * Handles the copyin of a kevent_qos/kevent_id event.
6951  */
6952 static int
kevent_modern_copyin(user_addr_t * addrp,struct kevent_qos_s * kevp)6953 kevent_modern_copyin(user_addr_t *addrp, struct kevent_qos_s *kevp)
6954 {
6955 	int error = copyin(*addrp, (caddr_t)kevp, sizeof(struct kevent_qos_s));
6956 	if (__probable(!error)) {
6957 		/* Make sure user doesn't pass in any system flags */
6958 		*addrp += sizeof(struct kevent_qos_s);
6959 		kevp->flags &= ~EV_SYSFLAGS;
6960 	}
6961 	return error;
6962 }
6963 
6964 /*!
6965  * @function kevent_legacy_copyout
6966  *
6967  * @brief
6968  * Handles the copyout of a kevent/kevent64 event.
6969  */
6970 static int
kevent_legacy_copyout(struct kevent_qos_s * kevp,user_addr_t * addrp,unsigned int flags)6971 kevent_legacy_copyout(struct kevent_qos_s *kevp, user_addr_t *addrp, unsigned int flags)
6972 {
6973 	int advance;
6974 	int error;
6975 
6976 	assert((flags & (KEVENT_FLAG_LEGACY32 | KEVENT_FLAG_LEGACY64)) != 0);
6977 
6978 	/*
6979 	 * fully initialize the differnt output event structure
6980 	 * types from the internal kevent (and some universal
6981 	 * defaults for fields not represented in the internal
6982 	 * form).
6983 	 *
6984 	 * Note: these structures have no padding hence the C99
6985 	 *       initializers below do not leak kernel info.
6986 	 */
6987 	if (flags & KEVENT_FLAG_LEGACY64) {
6988 		struct kevent64_s kev64 = {
6989 			.ident  = kevp->ident,
6990 			.filter = kevp->filter,
6991 			.flags  = kevp->flags,
6992 			.fflags = kevp->fflags,
6993 			.data   = (int64_t)kevp->data,
6994 			.udata  = kevp->udata,
6995 			.ext[0] = kevp->ext[0],
6996 			.ext[1] = kevp->ext[1],
6997 		};
6998 		advance = sizeof(struct kevent64_s);
6999 		error = copyout((caddr_t)&kev64, *addrp, advance);
7000 	} else if (flags & KEVENT_FLAG_PROC64) {
7001 		/*
7002 		 * deal with the special case of a user-supplied
7003 		 * value of (uintptr_t)-1.
7004 		 */
7005 		uint64_t ident = (kevp->ident == (uintptr_t)-1) ?
7006 		    (uint64_t)-1LL : (uint64_t)kevp->ident;
7007 		struct user64_kevent kev64 = {
7008 			.ident  = ident,
7009 			.filter = kevp->filter,
7010 			.flags  = kevp->flags,
7011 			.fflags = kevp->fflags,
7012 			.data   = (int64_t) kevp->data,
7013 			.udata  = (user_addr_t) kevp->udata,
7014 		};
7015 		advance = sizeof(kev64);
7016 		error = copyout((caddr_t)&kev64, *addrp, advance);
7017 	} else {
7018 		struct user32_kevent kev32 = {
7019 			.ident  = (uint32_t)kevp->ident,
7020 			.filter = kevp->filter,
7021 			.flags  = kevp->flags,
7022 			.fflags = kevp->fflags,
7023 			.data   = (int32_t)kevp->data,
7024 			.udata  = (uint32_t)kevp->udata,
7025 		};
7026 		advance = sizeof(kev32);
7027 		error = copyout((caddr_t)&kev32, *addrp, advance);
7028 	}
7029 	if (__probable(!error)) {
7030 		*addrp += advance;
7031 	}
7032 	return error;
7033 }
7034 
7035 /*!
7036  * @function kevent_modern_copyout
7037  *
7038  * @brief
7039  * Handles the copyout of a kevent_qos/kevent_id event.
7040  */
7041 OS_ALWAYS_INLINE
7042 static inline int
kevent_modern_copyout(struct kevent_qos_s * kevp,user_addr_t * addrp)7043 kevent_modern_copyout(struct kevent_qos_s *kevp, user_addr_t *addrp)
7044 {
7045 	int error = copyout((caddr_t)kevp, *addrp, sizeof(struct kevent_qos_s));
7046 	if (__probable(!error)) {
7047 		*addrp += sizeof(struct kevent_qos_s);
7048 	}
7049 	return error;
7050 }
7051 
7052 #pragma mark kevent core implementation
7053 
7054 /*!
7055  * @function kevent_callback_inline
7056  *
7057  * @brief
7058  * Callback for each individual event
7059  *
7060  * @discussion
7061  * This is meant to be inlined in kevent_modern_callback and
7062  * kevent_legacy_callback.
7063  */
7064 OS_ALWAYS_INLINE
7065 static inline int
kevent_callback_inline(struct kevent_qos_s * kevp,kevent_ctx_t kectx,bool legacy)7066 kevent_callback_inline(struct kevent_qos_s *kevp, kevent_ctx_t kectx, bool legacy)
7067 {
7068 	int error;
7069 
7070 	assert(kectx->kec_process_noutputs < kectx->kec_process_nevents);
7071 
7072 	/*
7073 	 * Copy out the appropriate amount of event data for this user.
7074 	 */
7075 	if (legacy) {
7076 		error = kevent_legacy_copyout(kevp, &kectx->kec_process_eventlist,
7077 		    kectx->kec_process_flags);
7078 	} else {
7079 		error = kevent_modern_copyout(kevp, &kectx->kec_process_eventlist);
7080 	}
7081 
7082 	/*
7083 	 * If there isn't space for additional events, return
7084 	 * a harmless error to stop the processing here
7085 	 */
7086 	if (error == 0 && ++kectx->kec_process_noutputs == kectx->kec_process_nevents) {
7087 		error = EWOULDBLOCK;
7088 	}
7089 	return error;
7090 }
7091 
7092 /*!
7093  * @function kevent_modern_callback
7094  *
7095  * @brief
7096  * Callback for each individual modern event.
7097  *
7098  * @discussion
7099  * This callback handles kevent_qos/kevent_id events.
7100  */
7101 static int
kevent_modern_callback(struct kevent_qos_s * kevp,kevent_ctx_t kectx)7102 kevent_modern_callback(struct kevent_qos_s *kevp, kevent_ctx_t kectx)
7103 {
7104 	return kevent_callback_inline(kevp, kectx, /*legacy*/ false);
7105 }
7106 
7107 /*!
7108  * @function kevent_legacy_callback
7109  *
7110  * @brief
7111  * Callback for each individual legacy event.
7112  *
7113  * @discussion
7114  * This callback handles kevent/kevent64 events.
7115  */
7116 static int
kevent_legacy_callback(struct kevent_qos_s * kevp,kevent_ctx_t kectx)7117 kevent_legacy_callback(struct kevent_qos_s *kevp, kevent_ctx_t kectx)
7118 {
7119 	return kevent_callback_inline(kevp, kectx, /*legacy*/ true);
7120 }
7121 
7122 /*!
7123  * @function kevent_cleanup
7124  *
7125  * @brief
7126  * Handles the cleanup returning from a kevent call.
7127  *
7128  * @discussion
7129  * kevent entry points will take a reference on workloops,
7130  * and a usecount on the fileglob of kqfiles.
7131  *
7132  * This function undoes this on the exit paths of kevents.
7133  *
7134  * @returns
7135  * The error to return to userspace.
7136  */
7137 static int
kevent_cleanup(kqueue_t kqu,int flags,int error,kevent_ctx_t kectx)7138 kevent_cleanup(kqueue_t kqu, int flags, int error, kevent_ctx_t kectx)
7139 {
7140 	// poll should not call any codepath leading to this
7141 	assert((flags & KEVENT_FLAG_POLL) == 0);
7142 
7143 	if (flags & KEVENT_FLAG_WORKLOOP) {
7144 		kqworkloop_release(kqu.kqwl);
7145 	} else if (flags & KEVENT_FLAG_WORKQ) {
7146 		/* nothing held */
7147 	} else {
7148 		fp_drop(kqu.kqf->kqf_p, kectx->kec_fd, kectx->kec_fp, 0);
7149 	}
7150 
7151 	/* don't restart after signals... */
7152 	if (error == ERESTART) {
7153 		error = EINTR;
7154 	} else if (error == 0) {
7155 		/* don't abandon other output just because of residual copyout failures */
7156 		(void)kevent_put_data_size(flags, kectx);
7157 	}
7158 
7159 	if (flags & KEVENT_FLAG_PARKING) {
7160 		thread_t th = current_thread();
7161 		struct uthread *uth = get_bsdthread_info(th);
7162 		if (uth->uu_kqr_bound) {
7163 			thread_unfreeze_base_pri(th);
7164 		}
7165 	}
7166 	return error;
7167 }
7168 
7169 /*!
7170  * @function kqueue_process
7171  *
7172  * @brief
7173  * Process the triggered events in a kqueue.
7174  *
7175  * @discussion
7176  * Walk the queued knotes and validate that they are really still triggered
7177  * events by calling the filter routines (if necessary).
7178  *
7179  * For each event that is still considered triggered, invoke the callback
7180  * routine provided.
7181  *
7182  * caller holds a reference on the kqueue.
7183  * kqueue locked on entry and exit - but may be dropped
7184  * kqueue list locked (held for duration of call)
7185  *
7186  * This is only called by kqueue_scan() so that the compiler can inline it.
7187  *
7188  * @returns
7189  * - 0:            no event was returned, no other error occured
7190  * - EBADF:        the kqueue is being destroyed (KQ_DRAIN is set)
7191  * - EWOULDBLOCK:  (not an error) events have been found and we should return
7192  * - EFAULT:       copyout failed
7193  * - filter specific errors
7194  */
7195 static int
kqueue_process(kqueue_t kqu,int flags,kevent_ctx_t kectx,kevent_callback_t callback)7196 kqueue_process(kqueue_t kqu, int flags, kevent_ctx_t kectx,
7197     kevent_callback_t callback)
7198 {
7199 	workq_threadreq_t kqr = current_uthread()->uu_kqr_bound;
7200 	struct knote *kn;
7201 	int error = 0, rc = 0;
7202 	struct kqtailq *base_queue, *queue;
7203 	uint16_t kq_type = (kqu.kq->kq_state & (KQ_WORKQ | KQ_WORKLOOP));
7204 
7205 	if (kq_type & KQ_WORKQ) {
7206 		rc = kqworkq_begin_processing(kqu.kqwq, kqr, flags);
7207 	} else if (kq_type & KQ_WORKLOOP) {
7208 		rc = kqworkloop_begin_processing(kqu.kqwl, flags);
7209 	} else {
7210 kqfile_retry:
7211 		rc = kqfile_begin_processing(kqu.kqf);
7212 		if (rc == EBADF) {
7213 			return EBADF;
7214 		}
7215 	}
7216 
7217 	if (rc == -1) {
7218 		/* Nothing to process */
7219 		return 0;
7220 	}
7221 
7222 	/*
7223 	 * loop through the enqueued knotes associated with this request,
7224 	 * processing each one. Each request may have several queues
7225 	 * of knotes to process (depending on the type of kqueue) so we
7226 	 * have to loop through all the queues as long as we have additional
7227 	 * space.
7228 	 */
7229 
7230 process_again:
7231 	if (kq_type & KQ_WORKQ) {
7232 		base_queue = queue = &kqu.kqwq->kqwq_queue[kqr->tr_kq_qos_index - 1];
7233 	} else if (kq_type & KQ_WORKLOOP) {
7234 		base_queue = &kqu.kqwl->kqwl_queue[0];
7235 		queue = &kqu.kqwl->kqwl_queue[KQWL_NBUCKETS - 1];
7236 	} else {
7237 		base_queue = queue = &kqu.kqf->kqf_queue;
7238 	}
7239 
7240 	do {
7241 		while ((kn = TAILQ_FIRST(queue)) != NULL) {
7242 			error = knote_process(kn, kectx, callback);
7243 			if (error == EJUSTRETURN) {
7244 				error = 0;
7245 			} else if (__improbable(error)) {
7246 				/* error is EWOULDBLOCK when the out event array is full */
7247 				goto stop_processing;
7248 			}
7249 		}
7250 	} while (queue-- > base_queue);
7251 
7252 	if (kectx->kec_process_noutputs) {
7253 		/* callers will transform this into no error */
7254 		error = EWOULDBLOCK;
7255 	}
7256 
7257 stop_processing:
7258 	/*
7259 	 * If KEVENT_FLAG_PARKING is set, and no kevents have been returned,
7260 	 * we want to unbind the kqrequest from the thread.
7261 	 *
7262 	 * However, because the kq locks are dropped several times during process,
7263 	 * new knotes may have fired again, in which case, we want to fail the end
7264 	 * processing and process again, until it converges.
7265 	 *
7266 	 * If we have an error or returned events, end processing never fails.
7267 	 */
7268 	if (error) {
7269 		flags &= ~KEVENT_FLAG_PARKING;
7270 	}
7271 	if (kq_type & KQ_WORKQ) {
7272 		rc = kqworkq_end_processing(kqu.kqwq, kqr, flags);
7273 	} else if (kq_type & KQ_WORKLOOP) {
7274 		rc = kqworkloop_end_processing(kqu.kqwl, KQ_PROCESSING, flags);
7275 	} else {
7276 		rc = kqfile_end_processing(kqu.kqf);
7277 	}
7278 
7279 	if (__probable(error)) {
7280 		return error;
7281 	}
7282 
7283 	if (__probable(rc >= 0)) {
7284 		assert(rc == 0 || rc == EBADF);
7285 		return rc;
7286 	}
7287 
7288 	if (kq_type & (KQ_WORKQ | KQ_WORKLOOP)) {
7289 		assert(flags & KEVENT_FLAG_PARKING);
7290 		goto process_again;
7291 	} else {
7292 		goto kqfile_retry;
7293 	}
7294 }
7295 
7296 /*!
7297  * @function kqueue_scan_continue
7298  *
7299  * @brief
7300  * The continuation used by kqueue_scan for kevent entry points.
7301  *
7302  * @discussion
7303  * Assumes we inherit a use/ref count on the kq or its fileglob.
7304  *
7305  * This is called by kqueue_scan if neither KEVENT_FLAG_POLL nor
7306  * KEVENT_FLAG_KERNEL was set, and the caller had to wait.
7307  */
7308 OS_NORETURN OS_NOINLINE
7309 static void
kqueue_scan_continue(void * data,wait_result_t wait_result)7310 kqueue_scan_continue(void *data, wait_result_t wait_result)
7311 {
7312 	uthread_t ut = current_uthread();
7313 	kevent_ctx_t kectx = &ut->uu_save.uus_kevent;
7314 	int error = 0, flags = kectx->kec_process_flags;
7315 	struct kqueue *kq = data;
7316 
7317 	/*
7318 	 * only kevent variants call in here, so we know the callback is
7319 	 * kevent_legacy_callback or kevent_modern_callback.
7320 	 */
7321 	assert((flags & (KEVENT_FLAG_POLL | KEVENT_FLAG_KERNEL)) == 0);
7322 
7323 	switch (wait_result) {
7324 	case THREAD_AWAKENED:
7325 		if (__improbable(flags & (KEVENT_FLAG_LEGACY32 | KEVENT_FLAG_LEGACY64))) {
7326 			error = kqueue_scan(kq, flags, kectx, kevent_legacy_callback);
7327 		} else {
7328 			error = kqueue_scan(kq, flags, kectx, kevent_modern_callback);
7329 		}
7330 		break;
7331 	case THREAD_TIMED_OUT:
7332 		error = 0;
7333 		break;
7334 	case THREAD_INTERRUPTED:
7335 		error = EINTR;
7336 		break;
7337 	case THREAD_RESTART:
7338 		error = EBADF;
7339 		break;
7340 	default:
7341 		panic("%s: - invalid wait_result (%d)", __func__, wait_result);
7342 	}
7343 
7344 
7345 	error = kevent_cleanup(kq, flags, error, kectx);
7346 	*(int32_t *)&ut->uu_rval = kectx->kec_process_noutputs;
7347 	unix_syscall_return(error);
7348 }
7349 
7350 /*!
7351  * @function kqueue_scan
7352  *
7353  * @brief
7354  * Scan and wait for events in a kqueue (used by poll & kevent).
7355  *
7356  * @discussion
7357  * Process the triggered events in a kqueue.
7358  *
7359  * If there are no events triggered arrange to wait for them:
7360  * - unless KEVENT_FLAG_IMMEDIATE is set in kectx->kec_process_flags
7361  * - possibly until kectx->kec_deadline expires
7362  *
7363  * When it waits, and that neither KEVENT_FLAG_POLL nor KEVENT_FLAG_KERNEL
7364  * are set, then it will wait in the kqueue_scan_continue continuation.
7365  *
7366  * poll() will block in place, and KEVENT_FLAG_KERNEL calls
7367  * all pass KEVENT_FLAG_IMMEDIATE and will not wait.
7368  *
7369  * @param kqu
7370  * The kqueue being scanned.
7371  *
7372  * @param flags
7373  * The KEVENT_FLAG_* flags for this call.
7374  *
7375  * @param kectx
7376  * The context used for this scan.
7377  * The uthread_t::uu_save.uus_kevent storage is used for this purpose.
7378  *
7379  * @param callback
7380  * The callback to be called on events sucessfully processed.
7381  * (Either kevent_legacy_callback, kevent_modern_callback or poll_callback)
7382  */
7383 int
kqueue_scan(kqueue_t kqu,int flags,kevent_ctx_t kectx,kevent_callback_t callback)7384 kqueue_scan(kqueue_t kqu, int flags, kevent_ctx_t kectx,
7385     kevent_callback_t callback)
7386 {
7387 	int error;
7388 
7389 	for (;;) {
7390 		kqlock(kqu);
7391 		error = kqueue_process(kqu, flags, kectx, callback);
7392 
7393 		/*
7394 		 * If we got an error, events returned (EWOULDBLOCK)
7395 		 * or blocking was disallowed (KEVENT_FLAG_IMMEDIATE),
7396 		 * just return.
7397 		 */
7398 		if (__probable(error || (flags & KEVENT_FLAG_IMMEDIATE))) {
7399 			kqunlock(kqu);
7400 			return error == EWOULDBLOCK ? 0 : error;
7401 		}
7402 
7403 		assert((kqu.kq->kq_state & (KQ_WORKQ | KQ_WORKLOOP)) == 0);
7404 
7405 		kqu.kqf->kqf_state |= KQ_SLEEP;
7406 		assert_wait_deadline(&kqu.kqf->kqf_count, THREAD_ABORTSAFE,
7407 		    kectx->kec_deadline);
7408 		kqunlock(kqu);
7409 
7410 		if (__probable((flags & (KEVENT_FLAG_POLL | KEVENT_FLAG_KERNEL)) == 0)) {
7411 			thread_block_parameter(kqueue_scan_continue, kqu.kqf);
7412 			__builtin_unreachable();
7413 		}
7414 
7415 		wait_result_t wr = thread_block(THREAD_CONTINUE_NULL);
7416 		switch (wr) {
7417 		case THREAD_AWAKENED:
7418 			break;
7419 		case THREAD_TIMED_OUT:
7420 			return 0;
7421 		case THREAD_INTERRUPTED:
7422 			return EINTR;
7423 		case THREAD_RESTART:
7424 			return EBADF;
7425 		default:
7426 			panic("%s: - bad wait_result (%d)", __func__, wr);
7427 		}
7428 	}
7429 }
7430 
7431 /*!
7432  * @function kevent_internal
7433  *
7434  * @brief
7435  * Common kevent code.
7436  *
7437  * @discussion
7438  * Needs to be inlined to specialize for legacy or modern and
7439  * eliminate dead code.
7440  *
7441  * This is the core logic of kevent entry points, that will:
7442  * - register kevents
7443  * - optionally scan the kqueue for events
7444  *
7445  * The caller is giving kevent_internal a reference on the kqueue
7446  * or its fileproc that needs to be cleaned up by kevent_cleanup().
7447  */
7448 OS_ALWAYS_INLINE
7449 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)7450 kevent_internal(kqueue_t kqu,
7451     user_addr_t changelist, int nchanges,
7452     user_addr_t ueventlist, int nevents,
7453     int flags, kevent_ctx_t kectx, int32_t *retval,
7454     bool legacy)
7455 {
7456 	int error = 0, noutputs = 0, register_rc;
7457 
7458 	/* only bound threads can receive events on workloops */
7459 	if (!legacy && (flags & KEVENT_FLAG_WORKLOOP)) {
7460 #if CONFIG_WORKLOOP_DEBUG
7461 		UU_KEVENT_HISTORY_WRITE_ENTRY(current_uthread(), {
7462 			.uu_kqid = kqu.kqwl->kqwl_dynamicid,
7463 			.uu_kq = error ? NULL : kqu.kq,
7464 			.uu_error = error,
7465 			.uu_nchanges = nchanges,
7466 			.uu_nevents = nevents,
7467 			.uu_flags = flags,
7468 		});
7469 #endif // CONFIG_WORKLOOP_DEBUG
7470 
7471 		if (flags & KEVENT_FLAG_KERNEL) {
7472 			/* see kevent_workq_internal */
7473 			error = copyout(&kqu.kqwl->kqwl_dynamicid,
7474 			    ueventlist - sizeof(kqueue_id_t), sizeof(kqueue_id_t));
7475 			kectx->kec_data_resid -= sizeof(kqueue_id_t);
7476 			if (__improbable(error)) {
7477 				goto out;
7478 			}
7479 		}
7480 
7481 		if (kevent_args_requesting_events(flags, nevents)) {
7482 			/*
7483 			 * Disable the R2K notification while doing a register, if the
7484 			 * caller wants events too, we don't want the AST to be set if we
7485 			 * will process these events soon.
7486 			 */
7487 			kqlock(kqu);
7488 			kqu.kq->kq_state &= ~KQ_R2K_ARMED;
7489 			kqunlock(kqu);
7490 			flags |= KEVENT_FLAG_NEEDS_END_PROCESSING;
7491 		}
7492 	}
7493 
7494 	/* register all the change requests the user provided... */
7495 	while (nchanges > 0 && error == 0) {
7496 		struct kevent_qos_s kev;
7497 		struct knote *kn = NULL;
7498 
7499 		if (legacy) {
7500 			error = kevent_legacy_copyin(&changelist, &kev, flags);
7501 		} else {
7502 			error = kevent_modern_copyin(&changelist, &kev);
7503 		}
7504 		if (error) {
7505 			break;
7506 		}
7507 
7508 		register_rc = kevent_register(kqu.kq, &kev, &kn);
7509 		if (__improbable(!legacy && (register_rc & FILTER_REGISTER_WAIT))) {
7510 			thread_t thread = current_thread();
7511 
7512 			kqlock_held(kqu);
7513 
7514 			if (act_clear_astkevent(thread, AST_KEVENT_REDRIVE_THREADREQ)) {
7515 				workq_kern_threadreq_redrive(kqu.kq->kq_p, WORKQ_THREADREQ_NONE);
7516 			}
7517 
7518 			// f_post_register_wait is meant to call a continuation and not to
7519 			// return, which is why we don't support FILTER_REGISTER_WAIT if
7520 			// KEVENT_FLAG_ERROR_EVENTS is not passed, or if the event that
7521 			// waits isn't the last.
7522 			//
7523 			// It is implementable, but not used by any userspace code at the
7524 			// moment, so for now return ENOTSUP if someone tries to do it.
7525 			if (nchanges == 1 && noutputs < nevents &&
7526 			    (flags & KEVENT_FLAG_KERNEL) == 0 &&
7527 			    (flags & KEVENT_FLAG_PARKING) == 0 &&
7528 			    (flags & KEVENT_FLAG_ERROR_EVENTS) &&
7529 			    (flags & KEVENT_FLAG_WORKLOOP)) {
7530 				uthread_t ut = get_bsdthread_info(thread);
7531 
7532 				/*
7533 				 * store the continuation/completion data in the uthread
7534 				 *
7535 				 * Note: the kectx aliases with this,
7536 				 * and is destroyed in the process.
7537 				 */
7538 				ut->uu_save.uus_kevent_register = (struct _kevent_register){
7539 					.kev        = kev,
7540 					.kqwl       = kqu.kqwl,
7541 					.eventout   = noutputs,
7542 					.ueventlist = ueventlist,
7543 				};
7544 				knote_fops(kn)->f_post_register_wait(ut, kn,
7545 				    &ut->uu_save.uus_kevent_register);
7546 				__builtin_unreachable();
7547 			}
7548 			kqunlock(kqu);
7549 
7550 			kev.flags |= EV_ERROR;
7551 			kev.data = ENOTSUP;
7552 		} else {
7553 			assert((register_rc & FILTER_REGISTER_WAIT) == 0);
7554 		}
7555 
7556 		// keep in sync with kevent_register_wait_return()
7557 		if (noutputs < nevents && (kev.flags & (EV_ERROR | EV_RECEIPT))) {
7558 			if ((kev.flags & EV_ERROR) == 0) {
7559 				kev.flags |= EV_ERROR;
7560 				kev.data = 0;
7561 			}
7562 			if (legacy) {
7563 				error = kevent_legacy_copyout(&kev, &ueventlist, flags);
7564 			} else {
7565 				error = kevent_modern_copyout(&kev, &ueventlist);
7566 			}
7567 			if (error == 0) {
7568 				noutputs++;
7569 			}
7570 		} else if (kev.flags & EV_ERROR) {
7571 			error = (int)kev.data;
7572 		}
7573 		nchanges--;
7574 	}
7575 
7576 	if ((flags & KEVENT_FLAG_ERROR_EVENTS) == 0 &&
7577 	    nevents > 0 && noutputs == 0 && error == 0) {
7578 		kectx->kec_process_flags = flags;
7579 		kectx->kec_process_nevents = nevents;
7580 		kectx->kec_process_noutputs = 0;
7581 		kectx->kec_process_eventlist = ueventlist;
7582 
7583 		if (legacy) {
7584 			error = kqueue_scan(kqu.kq, flags, kectx, kevent_legacy_callback);
7585 		} else {
7586 			error = kqueue_scan(kqu.kq, flags, kectx, kevent_modern_callback);
7587 		}
7588 
7589 		noutputs = kectx->kec_process_noutputs;
7590 	} else if (!legacy && (flags & KEVENT_FLAG_NEEDS_END_PROCESSING)) {
7591 		/*
7592 		 * If we didn't through kqworkloop_end_processing(),
7593 		 * we need to do it here.
7594 		 *
7595 		 * kqueue_scan will call kqworkloop_end_processing(),
7596 		 * so we only need to do it if we didn't scan.
7597 		 */
7598 		kqlock(kqu);
7599 		kqworkloop_end_processing(kqu.kqwl, 0, 0);
7600 		kqunlock(kqu);
7601 	}
7602 
7603 	*retval = noutputs;
7604 out:
7605 	return kevent_cleanup(kqu.kq, flags, error, kectx);
7606 }
7607 
7608 #pragma mark modern syscalls: kevent_qos, kevent_id, kevent_workq_internal
7609 
7610 /*!
7611  * @function kevent_modern_internal
7612  *
7613  * @brief
7614  * The backend of the kevent_id and kevent_workq_internal entry points.
7615  *
7616  * @discussion
7617  * Needs to be inline due to the number of arguments.
7618  */
7619 OS_NOINLINE
7620 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)7621 kevent_modern_internal(kqueue_t kqu,
7622     user_addr_t changelist, int nchanges,
7623     user_addr_t ueventlist, int nevents,
7624     int flags, kevent_ctx_t kectx, int32_t *retval)
7625 {
7626 	return kevent_internal(kqu.kq, changelist, nchanges,
7627 	           ueventlist, nevents, flags, kectx, retval, /*legacy*/ false);
7628 }
7629 
7630 /*!
7631  * @function kevent_id
7632  *
7633  * @brief
7634  * The kevent_id() syscall.
7635  */
7636 int
kevent_id(struct proc * p,struct kevent_id_args * uap,int32_t * retval)7637 kevent_id(struct proc *p, struct kevent_id_args *uap, int32_t *retval)
7638 {
7639 	int error, flags = uap->flags & KEVENT_FLAG_USER;
7640 	uthread_t uth = current_uthread();
7641 	workq_threadreq_t kqr = uth->uu_kqr_bound;
7642 	kevent_ctx_t kectx = &uth->uu_save.uus_kevent;
7643 	kqueue_t kqu;
7644 
7645 	flags = kevent_adjust_flags_for_proc(p, flags);
7646 	flags |= KEVENT_FLAG_DYNAMIC_KQUEUE;
7647 
7648 	if (__improbable((flags & (KEVENT_FLAG_WORKQ | KEVENT_FLAG_WORKLOOP)) !=
7649 	    KEVENT_FLAG_WORKLOOP)) {
7650 		return EINVAL;
7651 	}
7652 
7653 	error = kevent_get_data_size(flags, uap->data_available, uap->data_out, kectx);
7654 	if (__improbable(error)) {
7655 		return error;
7656 	}
7657 
7658 	kectx->kec_deadline = 0;
7659 	kectx->kec_fp       = NULL;
7660 	kectx->kec_fd       = -1;
7661 	/* the kec_process_* fields are filled if kqueue_scann is called only */
7662 
7663 	/*
7664 	 * Get the kq we are going to be working on
7665 	 * As a fastpath, look at the currently bound workloop.
7666 	 */
7667 	kqu.kqwl = kqr ? kqr_kqworkloop(kqr) : NULL;
7668 	if (kqu.kqwl && kqu.kqwl->kqwl_dynamicid == uap->id) {
7669 		if (__improbable(flags & KEVENT_FLAG_DYNAMIC_KQ_MUST_NOT_EXIST)) {
7670 			return EEXIST;
7671 		}
7672 		kqworkloop_retain(kqu.kqwl);
7673 	} else if (__improbable(kevent_args_requesting_events(flags, uap->nevents))) {
7674 		return EXDEV;
7675 	} else {
7676 		error = kqworkloop_get_or_create(p, uap->id, NULL, flags, &kqu.kqwl);
7677 		if (__improbable(error)) {
7678 			return error;
7679 		}
7680 	}
7681 
7682 	return kevent_modern_internal(kqu, uap->changelist, uap->nchanges,
7683 	           uap->eventlist, uap->nevents, flags, kectx, retval);
7684 }
7685 
7686 /**!
7687  * @function kevent_workq_internal
7688  *
7689  * @discussion
7690  * This function is exported for the sake of the workqueue subsystem.
7691  *
7692  * It is called in two ways:
7693  * - when a thread is about to go to userspace to ask for pending event
7694  * - when a thread is returning from userspace with events back
7695  *
7696  * the workqueue subsystem will only use the following flags:
7697  * - KEVENT_FLAG_STACK_DATA (always)
7698  * - KEVENT_FLAG_IMMEDIATE (always)
7699  * - KEVENT_FLAG_PARKING (depending on whether it is going to or returning from
7700  *   userspace).
7701  *
7702  * It implicitly acts on the bound kqueue, and for the case of workloops
7703  * will copyout the kqueue ID before anything else.
7704  *
7705  *
7706  * Pthread will have setup the various arguments to fit this stack layout:
7707  *
7708  * +-------....----+--------------+-----------+--------------------+
7709  * |  user stack   |  data avail  |  nevents  |   pthread_self()   |
7710  * +-------....----+--------------+-----------+--------------------+
7711  *                 ^              ^
7712  *             data_out       eventlist
7713  *
7714  * When a workloop is used, the workloop ID is copied out right before
7715  * the eventlist and is taken from the data buffer.
7716  *
7717  * @warning
7718  * This function is carefuly tailored to not make any call except the final tail
7719  * call into kevent_modern_internal. (LTO inlines current_uthread()).
7720  *
7721  * This function is performance sensitive due to the workq subsystem.
7722  */
7723 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)7724 kevent_workq_internal(struct proc *p,
7725     user_addr_t changelist, int nchanges,
7726     user_addr_t eventlist, int nevents,
7727     user_addr_t data_out, user_size_t *data_available,
7728     unsigned int flags, int32_t *retval)
7729 {
7730 	uthread_t uth = current_uthread();
7731 	workq_threadreq_t kqr = uth->uu_kqr_bound;
7732 	kevent_ctx_t kectx = &uth->uu_save.uus_kevent;
7733 	kqueue_t kqu;
7734 
7735 	assert(flags == (KEVENT_FLAG_STACK_DATA | KEVENT_FLAG_IMMEDIATE) ||
7736 	    flags == (KEVENT_FLAG_STACK_DATA | KEVENT_FLAG_IMMEDIATE | KEVENT_FLAG_PARKING));
7737 
7738 	kectx->kec_data_out   = data_out;
7739 	kectx->kec_data_avail = (uint64_t)data_available;
7740 	kectx->kec_data_size  = *data_available;
7741 	kectx->kec_data_resid = *data_available;
7742 	kectx->kec_deadline   = 0;
7743 	kectx->kec_fp         = NULL;
7744 	kectx->kec_fd         = -1;
7745 	/* the kec_process_* fields are filled if kqueue_scann is called only */
7746 
7747 	flags = kevent_adjust_flags_for_proc(p, flags);
7748 
7749 	if (kqr->tr_flags & WORKQ_TR_FLAG_WORKLOOP) {
7750 		kqu.kqwl = __container_of(kqr, struct kqworkloop, kqwl_request);
7751 		kqworkloop_retain(kqu.kqwl);
7752 
7753 		flags |= KEVENT_FLAG_WORKLOOP | KEVENT_FLAG_DYNAMIC_KQUEUE |
7754 		    KEVENT_FLAG_KERNEL;
7755 	} else {
7756 		kqu.kqwq = p->p_fd.fd_wqkqueue;
7757 
7758 		flags |= KEVENT_FLAG_WORKQ | KEVENT_FLAG_KERNEL;
7759 	}
7760 
7761 	return kevent_modern_internal(kqu, changelist, nchanges,
7762 	           eventlist, nevents, flags, kectx, retval);
7763 }
7764 
7765 /*!
7766  * @function kevent_qos
7767  *
7768  * @brief
7769  * The kevent_qos() syscall.
7770  */
7771 int
kevent_qos(struct proc * p,struct kevent_qos_args * uap,int32_t * retval)7772 kevent_qos(struct proc *p, struct kevent_qos_args *uap, int32_t *retval)
7773 {
7774 	uthread_t uth = current_uthread();
7775 	kevent_ctx_t kectx = &uth->uu_save.uus_kevent;
7776 	int error, flags = uap->flags & KEVENT_FLAG_USER;
7777 	struct kqueue *kq;
7778 
7779 	if (__improbable(flags & KEVENT_ID_FLAG_USER)) {
7780 		return EINVAL;
7781 	}
7782 
7783 	flags = kevent_adjust_flags_for_proc(p, flags);
7784 
7785 	error = kevent_get_data_size(flags, uap->data_available, uap->data_out, kectx);
7786 	if (__improbable(error)) {
7787 		return error;
7788 	}
7789 
7790 	kectx->kec_deadline = 0;
7791 	kectx->kec_fp       = NULL;
7792 	kectx->kec_fd       = uap->fd;
7793 	/* the kec_process_* fields are filled if kqueue_scann is called only */
7794 
7795 	/* get the kq we are going to be working on */
7796 	if (__probable(flags & KEVENT_FLAG_WORKQ)) {
7797 		error = kevent_get_kqwq(p, flags, uap->nevents, &kq);
7798 	} else {
7799 		error = kevent_get_kqfile(p, uap->fd, flags, &kectx->kec_fp, &kq);
7800 	}
7801 	if (__improbable(error)) {
7802 		return error;
7803 	}
7804 
7805 	return kevent_modern_internal(kq, uap->changelist, uap->nchanges,
7806 	           uap->eventlist, uap->nevents, flags, kectx, retval);
7807 }
7808 
7809 #pragma mark legacy syscalls: kevent, kevent64
7810 
7811 /*!
7812  * @function kevent_legacy_get_deadline
7813  *
7814  * @brief
7815  * Compute the deadline for the legacy kevent syscalls.
7816  *
7817  * @discussion
7818  * This is not necessary if KEVENT_FLAG_IMMEDIATE is specified,
7819  * as this takes precedence over the deadline.
7820  *
7821  * This function will fail if utimeout is USER_ADDR_NULL
7822  * (the caller should check).
7823  */
7824 static int
kevent_legacy_get_deadline(int flags,user_addr_t utimeout,uint64_t * deadline)7825 kevent_legacy_get_deadline(int flags, user_addr_t utimeout, uint64_t *deadline)
7826 {
7827 	struct timespec ts;
7828 
7829 	if (flags & KEVENT_FLAG_PROC64) {
7830 		struct user64_timespec ts64;
7831 		int error = copyin(utimeout, &ts64, sizeof(ts64));
7832 		if (__improbable(error)) {
7833 			return error;
7834 		}
7835 		ts.tv_sec = (unsigned long)ts64.tv_sec;
7836 		ts.tv_nsec = (long)ts64.tv_nsec;
7837 	} else {
7838 		struct user32_timespec ts32;
7839 		int error = copyin(utimeout, &ts32, sizeof(ts32));
7840 		if (__improbable(error)) {
7841 			return error;
7842 		}
7843 		ts.tv_sec = ts32.tv_sec;
7844 		ts.tv_nsec = ts32.tv_nsec;
7845 	}
7846 	if (!timespec_is_valid(&ts)) {
7847 		return EINVAL;
7848 	}
7849 
7850 	clock_absolutetime_interval_to_deadline(tstoabstime(&ts), deadline);
7851 	return 0;
7852 }
7853 
7854 /*!
7855  * @function kevent_legacy_internal
7856  *
7857  * @brief
7858  * The core implementation for kevent and kevent64
7859  */
7860 OS_NOINLINE
7861 static int
kevent_legacy_internal(struct proc * p,struct kevent64_args * uap,int32_t * retval,int flags)7862 kevent_legacy_internal(struct proc *p, struct kevent64_args *uap,
7863     int32_t *retval, int flags)
7864 {
7865 	uthread_t uth = current_uthread();
7866 	kevent_ctx_t kectx = &uth->uu_save.uus_kevent;
7867 	struct kqueue *kq;
7868 	int error;
7869 
7870 	if (__improbable(uap->flags & KEVENT_ID_FLAG_USER)) {
7871 		return EINVAL;
7872 	}
7873 
7874 	flags = kevent_adjust_flags_for_proc(p, flags);
7875 
7876 	kectx->kec_data_out   = 0;
7877 	kectx->kec_data_avail = 0;
7878 	kectx->kec_data_size  = 0;
7879 	kectx->kec_data_resid = 0;
7880 	kectx->kec_deadline   = 0;
7881 	kectx->kec_fp         = NULL;
7882 	kectx->kec_fd         = uap->fd;
7883 	/* the kec_process_* fields are filled if kqueue_scann is called only */
7884 
7885 	/* convert timeout to absolute - if we have one (and not immediate) */
7886 	if (__improbable(uap->timeout && !(flags & KEVENT_FLAG_IMMEDIATE))) {
7887 		error = kevent_legacy_get_deadline(flags, uap->timeout,
7888 		    &kectx->kec_deadline);
7889 		if (__improbable(error)) {
7890 			return error;
7891 		}
7892 	}
7893 
7894 	/* get the kq we are going to be working on */
7895 	if (flags & KEVENT_FLAG_WORKQ) {
7896 		error = kevent_get_kqwq(p, flags, uap->nevents, &kq);
7897 	} else {
7898 		error = kevent_get_kqfile(p, uap->fd, flags, &kectx->kec_fp, &kq);
7899 	}
7900 	if (__improbable(error)) {
7901 		return error;
7902 	}
7903 
7904 	return kevent_internal(kq, uap->changelist, uap->nchanges,
7905 	           uap->eventlist, uap->nevents, flags, kectx, retval,
7906 	           /*legacy*/ true);
7907 }
7908 
7909 /*!
7910  * @function kevent
7911  *
7912  * @brief
7913  * The legacy kevent() syscall.
7914  */
7915 int
kevent(struct proc * p,struct kevent_args * uap,int32_t * retval)7916 kevent(struct proc *p, struct kevent_args *uap, int32_t *retval)
7917 {
7918 	struct kevent64_args args = {
7919 		.fd         = uap->fd,
7920 		.changelist = uap->changelist,
7921 		.nchanges   = uap->nchanges,
7922 		.eventlist  = uap->eventlist,
7923 		.nevents    = uap->nevents,
7924 		.timeout    = uap->timeout,
7925 	};
7926 
7927 	return kevent_legacy_internal(p, &args, retval, KEVENT_FLAG_LEGACY32);
7928 }
7929 
7930 /*!
7931  * @function kevent64
7932  *
7933  * @brief
7934  * The legacy kevent64() syscall.
7935  */
7936 int
kevent64(struct proc * p,struct kevent64_args * uap,int32_t * retval)7937 kevent64(struct proc *p, struct kevent64_args *uap, int32_t *retval)
7938 {
7939 	int flags = (uap->flags & KEVENT_FLAG_USER) | KEVENT_FLAG_LEGACY64;
7940 	return kevent_legacy_internal(p, uap, retval, flags);
7941 }
7942 
7943 #pragma mark - socket interface
7944 
7945 #if SOCKETS
7946 #include <sys/param.h>
7947 #include <sys/socket.h>
7948 #include <sys/protosw.h>
7949 #include <sys/domain.h>
7950 #include <sys/mbuf.h>
7951 #include <sys/kern_event.h>
7952 #include <sys/malloc.h>
7953 #include <sys/sys_domain.h>
7954 #include <sys/syslog.h>
7955 
7956 #ifndef ROUNDUP64
7957 #define ROUNDUP64(x) P2ROUNDUP((x), sizeof (u_int64_t))
7958 #endif
7959 
7960 #ifndef ADVANCE64
7961 #define ADVANCE64(p, n) (void*)((char *)(p) + ROUNDUP64(n))
7962 #endif
7963 
7964 static LCK_GRP_DECLARE(kev_lck_grp, "Kernel Event Protocol");
7965 static LCK_RW_DECLARE(kev_rwlock, &kev_lck_grp);
7966 
7967 static int kev_attach(struct socket *so, int proto, struct proc *p);
7968 static int kev_detach(struct socket *so);
7969 static int kev_control(struct socket *so, u_long cmd, caddr_t data,
7970     struct ifnet *ifp, struct proc *p);
7971 static lck_mtx_t * event_getlock(struct socket *, int);
7972 static int event_lock(struct socket *, int, void *);
7973 static int event_unlock(struct socket *, int, void *);
7974 
7975 static int event_sofreelastref(struct socket *);
7976 static void kev_delete(struct kern_event_pcb *);
7977 
7978 static struct pr_usrreqs event_usrreqs = {
7979 	.pru_attach =           kev_attach,
7980 	.pru_control =          kev_control,
7981 	.pru_detach =           kev_detach,
7982 	.pru_soreceive =        soreceive,
7983 };
7984 
7985 static struct protosw eventsw[] = {
7986 	{
7987 		.pr_type =              SOCK_RAW,
7988 		.pr_protocol =          SYSPROTO_EVENT,
7989 		.pr_flags =             PR_ATOMIC,
7990 		.pr_usrreqs =           &event_usrreqs,
7991 		.pr_lock =              event_lock,
7992 		.pr_unlock =            event_unlock,
7993 		.pr_getlock =           event_getlock,
7994 	}
7995 };
7996 
7997 __private_extern__ int kevt_getstat SYSCTL_HANDLER_ARGS;
7998 __private_extern__ int kevt_pcblist SYSCTL_HANDLER_ARGS;
7999 
8000 SYSCTL_NODE(_net_systm, OID_AUTO, kevt,
8001     CTLFLAG_RW | CTLFLAG_LOCKED, 0, "Kernel event family");
8002 
8003 struct kevtstat kevtstat;
8004 SYSCTL_PROC(_net_systm_kevt, OID_AUTO, stats,
8005     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
8006     kevt_getstat, "S,kevtstat", "");
8007 
8008 SYSCTL_PROC(_net_systm_kevt, OID_AUTO, pcblist,
8009     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
8010     kevt_pcblist, "S,xkevtpcb", "");
8011 
8012 static lck_mtx_t *
event_getlock(struct socket * so,int flags)8013 event_getlock(struct socket *so, int flags)
8014 {
8015 #pragma unused(flags)
8016 	struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *)so->so_pcb;
8017 
8018 	if (so->so_pcb != NULL) {
8019 		if (so->so_usecount < 0) {
8020 			panic("%s: so=%p usecount=%d lrh= %s", __func__,
8021 			    so, so->so_usecount, solockhistory_nr(so));
8022 		}
8023 		/* NOTREACHED */
8024 	} else {
8025 		panic("%s: so=%p NULL NO so_pcb %s", __func__,
8026 		    so, solockhistory_nr(so));
8027 		/* NOTREACHED */
8028 	}
8029 	return &ev_pcb->evp_mtx;
8030 }
8031 
8032 static int
event_lock(struct socket * so,int refcount,void * lr)8033 event_lock(struct socket *so, int refcount, void *lr)
8034 {
8035 	void *lr_saved;
8036 
8037 	if (lr == NULL) {
8038 		lr_saved = __builtin_return_address(0);
8039 	} else {
8040 		lr_saved = lr;
8041 	}
8042 
8043 	if (so->so_pcb != NULL) {
8044 		lck_mtx_lock(&((struct kern_event_pcb *)so->so_pcb)->evp_mtx);
8045 	} else {
8046 		panic("%s: so=%p NO PCB! lr=%p lrh= %s", __func__,
8047 		    so, lr_saved, solockhistory_nr(so));
8048 		/* NOTREACHED */
8049 	}
8050 
8051 	if (so->so_usecount < 0) {
8052 		panic("%s: so=%p so_pcb=%p lr=%p ref=%d lrh= %s", __func__,
8053 		    so, so->so_pcb, lr_saved, so->so_usecount,
8054 		    solockhistory_nr(so));
8055 		/* NOTREACHED */
8056 	}
8057 
8058 	if (refcount) {
8059 		so->so_usecount++;
8060 	}
8061 
8062 	so->lock_lr[so->next_lock_lr] = lr_saved;
8063 	so->next_lock_lr = (so->next_lock_lr + 1) % SO_LCKDBG_MAX;
8064 	return 0;
8065 }
8066 
8067 static int
event_unlock(struct socket * so,int refcount,void * lr)8068 event_unlock(struct socket *so, int refcount, void *lr)
8069 {
8070 	void *lr_saved;
8071 	lck_mtx_t *mutex_held;
8072 
8073 	if (lr == NULL) {
8074 		lr_saved = __builtin_return_address(0);
8075 	} else {
8076 		lr_saved = lr;
8077 	}
8078 
8079 	if (refcount) {
8080 		so->so_usecount--;
8081 	}
8082 	if (so->so_usecount < 0) {
8083 		panic("%s: so=%p usecount=%d lrh= %s", __func__,
8084 		    so, so->so_usecount, solockhistory_nr(so));
8085 		/* NOTREACHED */
8086 	}
8087 	if (so->so_pcb == NULL) {
8088 		panic("%s: so=%p NO PCB usecount=%d lr=%p lrh= %s", __func__,
8089 		    so, so->so_usecount, (void *)lr_saved,
8090 		    solockhistory_nr(so));
8091 		/* NOTREACHED */
8092 	}
8093 	mutex_held = (&((struct kern_event_pcb *)so->so_pcb)->evp_mtx);
8094 
8095 	LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
8096 	so->unlock_lr[so->next_unlock_lr] = lr_saved;
8097 	so->next_unlock_lr = (so->next_unlock_lr + 1) % SO_LCKDBG_MAX;
8098 
8099 	if (so->so_usecount == 0) {
8100 		VERIFY(so->so_flags & SOF_PCBCLEARING);
8101 		event_sofreelastref(so);
8102 	} else {
8103 		lck_mtx_unlock(mutex_held);
8104 	}
8105 
8106 	return 0;
8107 }
8108 
8109 static int
event_sofreelastref(struct socket * so)8110 event_sofreelastref(struct socket *so)
8111 {
8112 	struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *)so->so_pcb;
8113 
8114 	LCK_MTX_ASSERT(&(ev_pcb->evp_mtx), LCK_MTX_ASSERT_OWNED);
8115 
8116 	so->so_pcb = NULL;
8117 
8118 	/*
8119 	 * Disable upcall in the event another thread is in kev_post_msg()
8120 	 * appending record to the receive socket buffer, since sbwakeup()
8121 	 * may release the socket lock otherwise.
8122 	 */
8123 	so->so_rcv.sb_flags &= ~SB_UPCALL;
8124 	so->so_snd.sb_flags &= ~SB_UPCALL;
8125 	so->so_event = sonullevent;
8126 	lck_mtx_unlock(&(ev_pcb->evp_mtx));
8127 
8128 	LCK_MTX_ASSERT(&(ev_pcb->evp_mtx), LCK_MTX_ASSERT_NOTOWNED);
8129 	lck_rw_lock_exclusive(&kev_rwlock);
8130 	LIST_REMOVE(ev_pcb, evp_link);
8131 	kevtstat.kes_pcbcount--;
8132 	kevtstat.kes_gencnt++;
8133 	lck_rw_done(&kev_rwlock);
8134 	kev_delete(ev_pcb);
8135 
8136 	sofreelastref(so, 1);
8137 	return 0;
8138 }
8139 
8140 static int event_proto_count = (sizeof(eventsw) / sizeof(struct protosw));
8141 
8142 static
8143 struct kern_event_head kern_event_head;
8144 
8145 static u_int32_t static_event_id = 0;
8146 
8147 static ZONE_DEFINE(ev_pcb_zone, "kerneventpcb",
8148     sizeof(struct kern_event_pcb), ZC_ZFREE_CLEARMEM);
8149 
8150 /*
8151  * Install the protosw's for the NKE manager.  Invoked at extension load time
8152  */
8153 void
kern_event_init(struct domain * dp)8154 kern_event_init(struct domain *dp)
8155 {
8156 	struct protosw *pr;
8157 	int i;
8158 
8159 	VERIFY(!(dp->dom_flags & DOM_INITIALIZED));
8160 	VERIFY(dp == systemdomain);
8161 
8162 	for (i = 0, pr = &eventsw[0]; i < event_proto_count; i++, pr++) {
8163 		net_add_proto(pr, dp, 1);
8164 	}
8165 }
8166 
8167 static int
kev_attach(struct socket * so,__unused int proto,__unused struct proc * p)8168 kev_attach(struct socket *so, __unused int proto, __unused struct proc *p)
8169 {
8170 	int error = 0;
8171 	struct kern_event_pcb *ev_pcb;
8172 
8173 	error = soreserve(so, KEV_SNDSPACE, KEV_RECVSPACE);
8174 	if (error != 0) {
8175 		return error;
8176 	}
8177 
8178 	ev_pcb = zalloc_flags(ev_pcb_zone, Z_WAITOK | Z_ZERO);
8179 	lck_mtx_init(&ev_pcb->evp_mtx, &kev_lck_grp, LCK_ATTR_NULL);
8180 
8181 	ev_pcb->evp_socket = so;
8182 	ev_pcb->evp_vendor_code_filter = 0xffffffff;
8183 
8184 	so->so_pcb = (caddr_t) ev_pcb;
8185 	lck_rw_lock_exclusive(&kev_rwlock);
8186 	LIST_INSERT_HEAD(&kern_event_head, ev_pcb, evp_link);
8187 	kevtstat.kes_pcbcount++;
8188 	kevtstat.kes_gencnt++;
8189 	lck_rw_done(&kev_rwlock);
8190 
8191 	return error;
8192 }
8193 
8194 static void
kev_delete(struct kern_event_pcb * ev_pcb)8195 kev_delete(struct kern_event_pcb *ev_pcb)
8196 {
8197 	VERIFY(ev_pcb != NULL);
8198 	lck_mtx_destroy(&ev_pcb->evp_mtx, &kev_lck_grp);
8199 	zfree(ev_pcb_zone, ev_pcb);
8200 }
8201 
8202 static int
kev_detach(struct socket * so)8203 kev_detach(struct socket *so)
8204 {
8205 	struct kern_event_pcb *ev_pcb = (struct kern_event_pcb *) so->so_pcb;
8206 
8207 	if (ev_pcb != NULL) {
8208 		soisdisconnected(so);
8209 		so->so_flags |= SOF_PCBCLEARING;
8210 	}
8211 
8212 	return 0;
8213 }
8214 
8215 /*
8216  * For now, kev_vendor_code and mbuf_tags use the same
8217  * mechanism.
8218  */
8219 errno_t
kev_vendor_code_find(const char * string,u_int32_t * out_vendor_code)8220 kev_vendor_code_find(
8221 	const char      *string,
8222 	u_int32_t       *out_vendor_code)
8223 {
8224 	if (strlen(string) >= KEV_VENDOR_CODE_MAX_STR_LEN) {
8225 		return EINVAL;
8226 	}
8227 	return net_str_id_find_internal(string, out_vendor_code,
8228 	           NSI_VENDOR_CODE, 1);
8229 }
8230 
8231 errno_t
kev_msg_post(struct kev_msg * event_msg)8232 kev_msg_post(struct kev_msg *event_msg)
8233 {
8234 	mbuf_tag_id_t min_vendor, max_vendor;
8235 
8236 	net_str_id_first_last(&min_vendor, &max_vendor, NSI_VENDOR_CODE);
8237 
8238 	if (event_msg == NULL) {
8239 		return EINVAL;
8240 	}
8241 
8242 	/*
8243 	 * Limit third parties to posting events for registered vendor codes
8244 	 * only
8245 	 */
8246 	if (event_msg->vendor_code < min_vendor ||
8247 	    event_msg->vendor_code > max_vendor) {
8248 		os_atomic_inc(&kevtstat.kes_badvendor, relaxed);
8249 		return EINVAL;
8250 	}
8251 	return kev_post_msg(event_msg);
8252 }
8253 
8254 static int
kev_post_msg_internal(struct kev_msg * event_msg,int wait)8255 kev_post_msg_internal(struct kev_msg *event_msg, int wait)
8256 {
8257 	struct mbuf *m, *m2;
8258 	struct kern_event_pcb *ev_pcb;
8259 	struct kern_event_msg *ev;
8260 	char *tmp;
8261 	u_int32_t total_size;
8262 	int i;
8263 
8264 #if SKYWALK && defined(XNU_TARGET_OS_OSX)
8265 	/*
8266 	 * Special hook for ALF state updates
8267 	 */
8268 	if (event_msg->vendor_code == KEV_VENDOR_APPLE &&
8269 	    event_msg->kev_class == KEV_NKE_CLASS &&
8270 	    event_msg->kev_subclass == KEV_NKE_ALF_SUBCLASS &&
8271 	    event_msg->event_code == KEV_NKE_ALF_STATE_CHANGED) {
8272 #if (DEBUG || DEVELOPMENT)
8273 		os_log_info(OS_LOG_DEFAULT, "KEV_NKE_ALF_STATE_CHANGED posted");
8274 #endif /* DEBUG || DEVELOPMENT */
8275 		net_filter_event_mark(NET_FILTER_EVENT_ALF,
8276 		    net_check_compatible_alf());
8277 	}
8278 #endif /* SKYWALK && XNU_TARGET_OS_OSX */
8279 
8280 	/* Verify the message is small enough to fit in one mbuf w/o cluster */
8281 	total_size = KEV_MSG_HEADER_SIZE;
8282 
8283 	for (i = 0; i < 5; i++) {
8284 		if (event_msg->dv[i].data_length == 0) {
8285 			break;
8286 		}
8287 		total_size += event_msg->dv[i].data_length;
8288 	}
8289 
8290 	if (total_size > MLEN) {
8291 		os_atomic_inc(&kevtstat.kes_toobig, relaxed);
8292 		return EMSGSIZE;
8293 	}
8294 
8295 	m = m_get(wait, MT_DATA);
8296 	if (m == 0) {
8297 		os_atomic_inc(&kevtstat.kes_nomem, relaxed);
8298 		return ENOMEM;
8299 	}
8300 	ev = mtod(m, struct kern_event_msg *);
8301 	total_size = KEV_MSG_HEADER_SIZE;
8302 
8303 	tmp = (char *) &ev->event_data[0];
8304 	for (i = 0; i < 5; i++) {
8305 		if (event_msg->dv[i].data_length == 0) {
8306 			break;
8307 		}
8308 
8309 		total_size += event_msg->dv[i].data_length;
8310 		bcopy(event_msg->dv[i].data_ptr, tmp,
8311 		    event_msg->dv[i].data_length);
8312 		tmp += event_msg->dv[i].data_length;
8313 	}
8314 
8315 	ev->id = ++static_event_id;
8316 	ev->total_size   = total_size;
8317 	ev->vendor_code  = event_msg->vendor_code;
8318 	ev->kev_class    = event_msg->kev_class;
8319 	ev->kev_subclass = event_msg->kev_subclass;
8320 	ev->event_code   = event_msg->event_code;
8321 
8322 	m->m_len = total_size;
8323 	lck_rw_lock_shared(&kev_rwlock);
8324 	for (ev_pcb = LIST_FIRST(&kern_event_head);
8325 	    ev_pcb;
8326 	    ev_pcb = LIST_NEXT(ev_pcb, evp_link)) {
8327 		lck_mtx_lock(&ev_pcb->evp_mtx);
8328 		if (ev_pcb->evp_socket->so_pcb == NULL) {
8329 			lck_mtx_unlock(&ev_pcb->evp_mtx);
8330 			continue;
8331 		}
8332 		if (ev_pcb->evp_vendor_code_filter != KEV_ANY_VENDOR) {
8333 			if (ev_pcb->evp_vendor_code_filter != ev->vendor_code) {
8334 				lck_mtx_unlock(&ev_pcb->evp_mtx);
8335 				continue;
8336 			}
8337 
8338 			if (ev_pcb->evp_class_filter != KEV_ANY_CLASS) {
8339 				if (ev_pcb->evp_class_filter != ev->kev_class) {
8340 					lck_mtx_unlock(&ev_pcb->evp_mtx);
8341 					continue;
8342 				}
8343 
8344 				if ((ev_pcb->evp_subclass_filter !=
8345 				    KEV_ANY_SUBCLASS) &&
8346 				    (ev_pcb->evp_subclass_filter !=
8347 				    ev->kev_subclass)) {
8348 					lck_mtx_unlock(&ev_pcb->evp_mtx);
8349 					continue;
8350 				}
8351 			}
8352 		}
8353 
8354 		m2 = m_copym(m, 0, m->m_len, wait);
8355 		if (m2 == 0) {
8356 			os_atomic_inc(&kevtstat.kes_nomem, relaxed);
8357 			m_free(m);
8358 			lck_mtx_unlock(&ev_pcb->evp_mtx);
8359 			lck_rw_done(&kev_rwlock);
8360 			return ENOMEM;
8361 		}
8362 		if (sbappendrecord(&ev_pcb->evp_socket->so_rcv, m2)) {
8363 			/*
8364 			 * We use "m" for the socket stats as it would be
8365 			 * unsafe to use "m2"
8366 			 */
8367 			so_inc_recv_data_stat(ev_pcb->evp_socket,
8368 			    1, m->m_len, MBUF_TC_BE);
8369 
8370 			sorwakeup(ev_pcb->evp_socket);
8371 			os_atomic_inc(&kevtstat.kes_posted, relaxed);
8372 		} else {
8373 			os_atomic_inc(&kevtstat.kes_fullsock, relaxed);
8374 		}
8375 		lck_mtx_unlock(&ev_pcb->evp_mtx);
8376 	}
8377 	m_free(m);
8378 	lck_rw_done(&kev_rwlock);
8379 
8380 	return 0;
8381 }
8382 
8383 int
kev_post_msg(struct kev_msg * event_msg)8384 kev_post_msg(struct kev_msg *event_msg)
8385 {
8386 	return kev_post_msg_internal(event_msg, M_WAIT);
8387 }
8388 
8389 int
kev_post_msg_nowait(struct kev_msg * event_msg)8390 kev_post_msg_nowait(struct kev_msg *event_msg)
8391 {
8392 	return kev_post_msg_internal(event_msg, M_NOWAIT);
8393 }
8394 
8395 static int
kev_control(struct socket * so,u_long cmd,caddr_t data,__unused struct ifnet * ifp,__unused struct proc * p)8396 kev_control(struct socket *so,
8397     u_long cmd,
8398     caddr_t data,
8399     __unused struct ifnet *ifp,
8400     __unused struct proc *p)
8401 {
8402 	struct kev_request *kev_req = (struct kev_request *) data;
8403 	struct kern_event_pcb  *ev_pcb;
8404 	struct kev_vendor_code *kev_vendor;
8405 	u_int32_t  *id_value = (u_int32_t *) data;
8406 
8407 	switch (cmd) {
8408 	case SIOCGKEVID:
8409 		*id_value = static_event_id;
8410 		break;
8411 	case SIOCSKEVFILT:
8412 		ev_pcb = (struct kern_event_pcb *) so->so_pcb;
8413 		ev_pcb->evp_vendor_code_filter = kev_req->vendor_code;
8414 		ev_pcb->evp_class_filter = kev_req->kev_class;
8415 		ev_pcb->evp_subclass_filter  = kev_req->kev_subclass;
8416 		break;
8417 	case SIOCGKEVFILT:
8418 		ev_pcb = (struct kern_event_pcb *) so->so_pcb;
8419 		kev_req->vendor_code = ev_pcb->evp_vendor_code_filter;
8420 		kev_req->kev_class   = ev_pcb->evp_class_filter;
8421 		kev_req->kev_subclass = ev_pcb->evp_subclass_filter;
8422 		break;
8423 	case SIOCGKEVVENDOR:
8424 		kev_vendor = (struct kev_vendor_code *)data;
8425 		/* Make sure string is NULL terminated */
8426 		kev_vendor->vendor_string[KEV_VENDOR_CODE_MAX_STR_LEN - 1] = 0;
8427 		return net_str_id_find_internal(kev_vendor->vendor_string,
8428 		           &kev_vendor->vendor_code, NSI_VENDOR_CODE, 0);
8429 	default:
8430 		return ENOTSUP;
8431 	}
8432 
8433 	return 0;
8434 }
8435 
8436 int
8437 kevt_getstat SYSCTL_HANDLER_ARGS
8438 {
8439 #pragma unused(oidp, arg1, arg2)
8440 	int error = 0;
8441 
8442 	lck_rw_lock_shared(&kev_rwlock);
8443 
8444 	if (req->newptr != USER_ADDR_NULL) {
8445 		error = EPERM;
8446 		goto done;
8447 	}
8448 	if (req->oldptr == USER_ADDR_NULL) {
8449 		req->oldidx = sizeof(struct kevtstat);
8450 		goto done;
8451 	}
8452 
8453 	error = SYSCTL_OUT(req, &kevtstat,
8454 	    MIN(sizeof(struct kevtstat), req->oldlen));
8455 done:
8456 	lck_rw_done(&kev_rwlock);
8457 
8458 	return error;
8459 }
8460 
8461 __private_extern__ int
8462 kevt_pcblist SYSCTL_HANDLER_ARGS
8463 {
8464 #pragma unused(oidp, arg1, arg2)
8465 	int error = 0;
8466 	uint64_t n, i;
8467 	struct xsystmgen xsg;
8468 	void *buf = NULL;
8469 	size_t item_size = ROUNDUP64(sizeof(struct xkevtpcb)) +
8470 	    ROUNDUP64(sizeof(struct xsocket_n)) +
8471 	    2 * ROUNDUP64(sizeof(struct xsockbuf_n)) +
8472 	    ROUNDUP64(sizeof(struct xsockstat_n));
8473 	struct kern_event_pcb  *ev_pcb;
8474 
8475 	buf = kalloc_data(item_size, Z_WAITOK | Z_ZERO);
8476 	if (buf == NULL) {
8477 		return ENOMEM;
8478 	}
8479 
8480 	lck_rw_lock_shared(&kev_rwlock);
8481 
8482 	n = kevtstat.kes_pcbcount;
8483 
8484 	if (req->oldptr == USER_ADDR_NULL) {
8485 		req->oldidx = (size_t) ((n + n / 8) * item_size);
8486 		goto done;
8487 	}
8488 	if (req->newptr != USER_ADDR_NULL) {
8489 		error = EPERM;
8490 		goto done;
8491 	}
8492 	bzero(&xsg, sizeof(xsg));
8493 	xsg.xg_len = sizeof(xsg);
8494 	xsg.xg_count = n;
8495 	xsg.xg_gen = kevtstat.kes_gencnt;
8496 	xsg.xg_sogen = so_gencnt;
8497 	error = SYSCTL_OUT(req, &xsg, sizeof(xsg));
8498 	if (error) {
8499 		goto done;
8500 	}
8501 	/*
8502 	 * We are done if there is no pcb
8503 	 */
8504 	if (n == 0) {
8505 		goto done;
8506 	}
8507 
8508 	i = 0;
8509 	for (i = 0, ev_pcb = LIST_FIRST(&kern_event_head);
8510 	    i < n && ev_pcb != NULL;
8511 	    i++, ev_pcb = LIST_NEXT(ev_pcb, evp_link)) {
8512 		struct xkevtpcb *xk = (struct xkevtpcb *)buf;
8513 		struct xsocket_n *xso = (struct xsocket_n *)
8514 		    ADVANCE64(xk, sizeof(*xk));
8515 		struct xsockbuf_n *xsbrcv = (struct xsockbuf_n *)
8516 		    ADVANCE64(xso, sizeof(*xso));
8517 		struct xsockbuf_n *xsbsnd = (struct xsockbuf_n *)
8518 		    ADVANCE64(xsbrcv, sizeof(*xsbrcv));
8519 		struct xsockstat_n *xsostats = (struct xsockstat_n *)
8520 		    ADVANCE64(xsbsnd, sizeof(*xsbsnd));
8521 
8522 		bzero(buf, item_size);
8523 
8524 		lck_mtx_lock(&ev_pcb->evp_mtx);
8525 
8526 		xk->kep_len = sizeof(struct xkevtpcb);
8527 		xk->kep_kind = XSO_EVT;
8528 		xk->kep_evtpcb = (uint64_t)VM_KERNEL_ADDRPERM(ev_pcb);
8529 		xk->kep_vendor_code_filter = ev_pcb->evp_vendor_code_filter;
8530 		xk->kep_class_filter = ev_pcb->evp_class_filter;
8531 		xk->kep_subclass_filter = ev_pcb->evp_subclass_filter;
8532 
8533 		sotoxsocket_n(ev_pcb->evp_socket, xso);
8534 		sbtoxsockbuf_n(ev_pcb->evp_socket ?
8535 		    &ev_pcb->evp_socket->so_rcv : NULL, xsbrcv);
8536 		sbtoxsockbuf_n(ev_pcb->evp_socket ?
8537 		    &ev_pcb->evp_socket->so_snd : NULL, xsbsnd);
8538 		sbtoxsockstat_n(ev_pcb->evp_socket, xsostats);
8539 
8540 		lck_mtx_unlock(&ev_pcb->evp_mtx);
8541 
8542 		error = SYSCTL_OUT(req, buf, item_size);
8543 	}
8544 
8545 	if (error == 0) {
8546 		/*
8547 		 * Give the user an updated idea of our state.
8548 		 * If the generation differs from what we told
8549 		 * her before, she knows that something happened
8550 		 * while we were processing this request, and it
8551 		 * might be necessary to retry.
8552 		 */
8553 		bzero(&xsg, sizeof(xsg));
8554 		xsg.xg_len = sizeof(xsg);
8555 		xsg.xg_count = n;
8556 		xsg.xg_gen = kevtstat.kes_gencnt;
8557 		xsg.xg_sogen = so_gencnt;
8558 		error = SYSCTL_OUT(req, &xsg, sizeof(xsg));
8559 		if (error) {
8560 			goto done;
8561 		}
8562 	}
8563 
8564 done:
8565 	lck_rw_done(&kev_rwlock);
8566 
8567 	kfree_data(buf, item_size);
8568 	return error;
8569 }
8570 
8571 #endif /* SOCKETS */
8572 
8573 
8574 int
fill_kqueueinfo(kqueue_t kqu,struct kqueue_info * kinfo)8575 fill_kqueueinfo(kqueue_t kqu, struct kqueue_info * kinfo)
8576 {
8577 	struct vinfo_stat * st;
8578 
8579 	st = &kinfo->kq_stat;
8580 
8581 	st->vst_size = kqu.kq->kq_count;
8582 	if (kqu.kq->kq_state & KQ_KEV_QOS) {
8583 		st->vst_blksize = sizeof(struct kevent_qos_s);
8584 	} else if (kqu.kq->kq_state & KQ_KEV64) {
8585 		st->vst_blksize = sizeof(struct kevent64_s);
8586 	} else {
8587 		st->vst_blksize = sizeof(struct kevent);
8588 	}
8589 	st->vst_mode = S_IFIFO;
8590 	st->vst_ino = (kqu.kq->kq_state & KQ_DYNAMIC) ?
8591 	    kqu.kqwl->kqwl_dynamicid : 0;
8592 
8593 	/* flags exported to libproc as PROC_KQUEUE_* (sys/proc_info.h) */
8594 #define PROC_KQUEUE_MASK (KQ_SLEEP|KQ_KEV32|KQ_KEV64|KQ_KEV_QOS|KQ_WORKQ|KQ_WORKLOOP)
8595 	static_assert(PROC_KQUEUE_SLEEP == KQ_SLEEP);
8596 	static_assert(PROC_KQUEUE_32 == KQ_KEV32);
8597 	static_assert(PROC_KQUEUE_64 == KQ_KEV64);
8598 	static_assert(PROC_KQUEUE_QOS == KQ_KEV_QOS);
8599 	static_assert(PROC_KQUEUE_WORKQ == KQ_WORKQ);
8600 	static_assert(PROC_KQUEUE_WORKLOOP == KQ_WORKLOOP);
8601 	kinfo->kq_state = kqu.kq->kq_state & PROC_KQUEUE_MASK;
8602 	if ((kqu.kq->kq_state & (KQ_WORKLOOP | KQ_WORKQ)) == 0) {
8603 		if (kqu.kqf->kqf_sel.si_flags & SI_RECORDED) {
8604 			kinfo->kq_state |= PROC_KQUEUE_SELECT;
8605 		}
8606 	}
8607 
8608 	return 0;
8609 }
8610 
8611 static int
fill_kqueue_dyninfo(struct kqworkloop * kqwl,struct kqueue_dyninfo * kqdi)8612 fill_kqueue_dyninfo(struct kqworkloop *kqwl, struct kqueue_dyninfo *kqdi)
8613 {
8614 	workq_threadreq_t kqr = &kqwl->kqwl_request;
8615 	workq_threadreq_param_t trp = {};
8616 	int err;
8617 
8618 	if ((kqwl->kqwl_state & KQ_WORKLOOP) == 0) {
8619 		return EINVAL;
8620 	}
8621 
8622 	if ((err = fill_kqueueinfo(&kqwl->kqwl_kqueue, &kqdi->kqdi_info))) {
8623 		return err;
8624 	}
8625 
8626 	kqlock(kqwl);
8627 
8628 	kqdi->kqdi_servicer = thread_tid(kqr_thread(kqr));
8629 	kqdi->kqdi_owner = thread_tid(kqwl->kqwl_owner);
8630 	kqdi->kqdi_request_state = kqr->tr_state;
8631 	kqdi->kqdi_async_qos = kqr->tr_kq_qos_index;
8632 	kqdi->kqdi_events_qos = kqr->tr_kq_override_index;
8633 	kqdi->kqdi_sync_waiters = 0;
8634 	kqdi->kqdi_sync_waiter_qos = 0;
8635 
8636 	trp.trp_value = kqwl->kqwl_params;
8637 	if (trp.trp_flags & TRP_PRIORITY) {
8638 		kqdi->kqdi_pri = trp.trp_pri;
8639 	} else {
8640 		kqdi->kqdi_pri = 0;
8641 	}
8642 
8643 	if (trp.trp_flags & TRP_POLICY) {
8644 		kqdi->kqdi_pol = trp.trp_pol;
8645 	} else {
8646 		kqdi->kqdi_pol = 0;
8647 	}
8648 
8649 	if (trp.trp_flags & TRP_CPUPERCENT) {
8650 		kqdi->kqdi_cpupercent = trp.trp_cpupercent;
8651 	} else {
8652 		kqdi->kqdi_cpupercent = 0;
8653 	}
8654 
8655 	kqunlock(kqwl);
8656 
8657 	return 0;
8658 }
8659 
8660 
8661 static unsigned long
kevent_extinfo_emit(struct kqueue * kq,struct knote * kn,struct kevent_extinfo * buf,unsigned long buflen,unsigned long nknotes)8662 kevent_extinfo_emit(struct kqueue *kq, struct knote *kn, struct kevent_extinfo *buf,
8663     unsigned long buflen, unsigned long nknotes)
8664 {
8665 	for (; kn; kn = SLIST_NEXT(kn, kn_link)) {
8666 		if (kq == knote_get_kq(kn)) {
8667 			if (nknotes < buflen) {
8668 				struct kevent_extinfo *info = &buf[nknotes];
8669 
8670 				kqlock(kq);
8671 
8672 				info->kqext_kev         = *(struct kevent_qos_s *)&kn->kn_kevent;
8673 				if (knote_has_qos(kn)) {
8674 					info->kqext_kev.qos =
8675 					    _pthread_priority_thread_qos_fast(kn->kn_qos);
8676 				} else {
8677 					info->kqext_kev.qos = kn->kn_qos_override;
8678 				}
8679 				info->kqext_kev.filter |= 0xff00; /* sign extend filter */
8680 				info->kqext_kev.xflags  = 0; /* this is where sfflags lives */
8681 				info->kqext_kev.data    = 0; /* this is where sdata lives */
8682 				info->kqext_sdata       = kn->kn_sdata;
8683 				info->kqext_status      = kn->kn_status;
8684 				info->kqext_sfflags     = kn->kn_sfflags;
8685 
8686 				kqunlock(kq);
8687 			}
8688 
8689 			/* we return total number of knotes, which may be more than requested */
8690 			nknotes++;
8691 		}
8692 	}
8693 
8694 	return nknotes;
8695 }
8696 
8697 int
kevent_copyout_proc_dynkqids(void * proc,user_addr_t ubuf,uint32_t ubufsize,int32_t * nkqueues_out)8698 kevent_copyout_proc_dynkqids(void *proc, user_addr_t ubuf, uint32_t ubufsize,
8699     int32_t *nkqueues_out)
8700 {
8701 	proc_t p = (proc_t)proc;
8702 	struct filedesc *fdp = &p->p_fd;
8703 	unsigned int nkqueues = 0;
8704 	unsigned long ubuflen = ubufsize / sizeof(kqueue_id_t);
8705 	size_t buflen, bufsize;
8706 	kqueue_id_t *kq_ids = NULL;
8707 	int err = 0;
8708 
8709 	assert(p != NULL);
8710 
8711 	if (ubuf == USER_ADDR_NULL && ubufsize != 0) {
8712 		err = EINVAL;
8713 		goto out;
8714 	}
8715 
8716 	buflen = MIN(ubuflen, PROC_PIDDYNKQUEUES_MAX);
8717 
8718 	if (ubuflen != 0) {
8719 		if (os_mul_overflow(sizeof(kqueue_id_t), buflen, &bufsize)) {
8720 			err = ERANGE;
8721 			goto out;
8722 		}
8723 		kq_ids = (kqueue_id_t *)kalloc_data(bufsize, Z_WAITOK | Z_ZERO);
8724 		if (!kq_ids) {
8725 			err = ENOMEM;
8726 			goto out;
8727 		}
8728 	}
8729 
8730 	kqhash_lock(fdp);
8731 
8732 	if (fdp->fd_kqhashmask > 0) {
8733 		for (uint32_t i = 0; i < fdp->fd_kqhashmask + 1; i++) {
8734 			struct kqworkloop *kqwl;
8735 
8736 			LIST_FOREACH(kqwl, &fdp->fd_kqhash[i], kqwl_hashlink) {
8737 				/* report the number of kqueues, even if they don't all fit */
8738 				if (nkqueues < buflen) {
8739 					kq_ids[nkqueues] = kqwl->kqwl_dynamicid;
8740 				}
8741 				nkqueues++;
8742 			}
8743 		}
8744 	}
8745 
8746 	kqhash_unlock(fdp);
8747 
8748 	if (kq_ids) {
8749 		size_t copysize;
8750 		if (os_mul_overflow(sizeof(kqueue_id_t), MIN(buflen, nkqueues), &copysize)) {
8751 			err = ERANGE;
8752 			goto out;
8753 		}
8754 
8755 		assert(ubufsize >= copysize);
8756 		err = copyout(kq_ids, ubuf, copysize);
8757 	}
8758 
8759 out:
8760 	if (kq_ids) {
8761 		kfree_data(kq_ids, bufsize);
8762 	}
8763 
8764 	if (!err) {
8765 		*nkqueues_out = (int)min(nkqueues, PROC_PIDDYNKQUEUES_MAX);
8766 	}
8767 	return err;
8768 }
8769 
8770 int
kevent_copyout_dynkqinfo(void * proc,kqueue_id_t kq_id,user_addr_t ubuf,uint32_t ubufsize,int32_t * size_out)8771 kevent_copyout_dynkqinfo(void *proc, kqueue_id_t kq_id, user_addr_t ubuf,
8772     uint32_t ubufsize, int32_t *size_out)
8773 {
8774 	proc_t p = (proc_t)proc;
8775 	struct kqworkloop *kqwl;
8776 	int err = 0;
8777 	struct kqueue_dyninfo kqdi = { };
8778 
8779 	assert(p != NULL);
8780 
8781 	if (ubufsize < sizeof(struct kqueue_info)) {
8782 		return ENOBUFS;
8783 	}
8784 
8785 	kqwl = kqworkloop_hash_lookup_and_retain(&p->p_fd, kq_id);
8786 	if (!kqwl) {
8787 		return ESRCH;
8788 	}
8789 
8790 	/*
8791 	 * backward compatibility: allow the argument to this call to only be
8792 	 * a struct kqueue_info
8793 	 */
8794 	if (ubufsize >= sizeof(struct kqueue_dyninfo)) {
8795 		ubufsize = sizeof(struct kqueue_dyninfo);
8796 		err = fill_kqueue_dyninfo(kqwl, &kqdi);
8797 	} else {
8798 		ubufsize = sizeof(struct kqueue_info);
8799 		err = fill_kqueueinfo(&kqwl->kqwl_kqueue, &kqdi.kqdi_info);
8800 	}
8801 	if (err == 0 && (err = copyout(&kqdi, ubuf, ubufsize)) == 0) {
8802 		*size_out = ubufsize;
8803 	}
8804 	kqworkloop_release(kqwl);
8805 	return err;
8806 }
8807 
8808 int
kevent_copyout_dynkqextinfo(void * proc,kqueue_id_t kq_id,user_addr_t ubuf,uint32_t ubufsize,int32_t * nknotes_out)8809 kevent_copyout_dynkqextinfo(void *proc, kqueue_id_t kq_id, user_addr_t ubuf,
8810     uint32_t ubufsize, int32_t *nknotes_out)
8811 {
8812 	proc_t p = (proc_t)proc;
8813 	struct kqworkloop *kqwl;
8814 	int err;
8815 
8816 	kqwl = kqworkloop_hash_lookup_and_retain(&p->p_fd, kq_id);
8817 	if (!kqwl) {
8818 		return ESRCH;
8819 	}
8820 
8821 	err = pid_kqueue_extinfo(p, &kqwl->kqwl_kqueue, ubuf, ubufsize, nknotes_out);
8822 	kqworkloop_release(kqwl);
8823 	return err;
8824 }
8825 
8826 int
pid_kqueue_extinfo(proc_t p,struct kqueue * kq,user_addr_t ubuf,uint32_t bufsize,int32_t * retval)8827 pid_kqueue_extinfo(proc_t p, struct kqueue *kq, user_addr_t ubuf,
8828     uint32_t bufsize, int32_t *retval)
8829 {
8830 	struct knote *kn;
8831 	int i;
8832 	int err = 0;
8833 	struct filedesc *fdp = &p->p_fd;
8834 	unsigned long nknotes = 0;
8835 	unsigned long buflen = bufsize / sizeof(struct kevent_extinfo);
8836 	struct kevent_extinfo *kqext = NULL;
8837 
8838 	/* arbitrary upper limit to cap kernel memory usage, copyout size, etc. */
8839 	buflen = MIN(buflen, PROC_PIDFDKQUEUE_KNOTES_MAX);
8840 
8841 	kqext = (struct kevent_extinfo *)kalloc_data(buflen * sizeof(struct kevent_extinfo), Z_WAITOK | Z_ZERO);
8842 	if (kqext == NULL) {
8843 		err = ENOMEM;
8844 		goto out;
8845 	}
8846 
8847 	proc_fdlock(p);
8848 	for (i = 0; i < fdp->fd_knlistsize; i++) {
8849 		kn = SLIST_FIRST(&fdp->fd_knlist[i]);
8850 		nknotes = kevent_extinfo_emit(kq, kn, kqext, buflen, nknotes);
8851 	}
8852 	proc_fdunlock(p);
8853 
8854 	if (fdp->fd_knhashmask != 0) {
8855 		for (i = 0; i < (int)fdp->fd_knhashmask + 1; i++) {
8856 			knhash_lock(fdp);
8857 			kn = SLIST_FIRST(&fdp->fd_knhash[i]);
8858 			nknotes = kevent_extinfo_emit(kq, kn, kqext, buflen, nknotes);
8859 			knhash_unlock(fdp);
8860 		}
8861 	}
8862 
8863 	assert(bufsize >= sizeof(struct kevent_extinfo) * MIN(buflen, nknotes));
8864 	err = copyout(kqext, ubuf, sizeof(struct kevent_extinfo) * MIN(buflen, nknotes));
8865 
8866 out:
8867 	kfree_data(kqext, buflen * sizeof(struct kevent_extinfo));
8868 
8869 	if (!err) {
8870 		*retval = (int32_t)MIN(nknotes, PROC_PIDFDKQUEUE_KNOTES_MAX);
8871 	}
8872 	return err;
8873 }
8874 
8875 static unsigned int
klist_copy_udata(struct klist * list,uint64_t * buf,unsigned int buflen,unsigned int nknotes)8876 klist_copy_udata(struct klist *list, uint64_t *buf,
8877     unsigned int buflen, unsigned int nknotes)
8878 {
8879 	struct knote *kn;
8880 	SLIST_FOREACH(kn, list, kn_link) {
8881 		if (nknotes < buflen) {
8882 			/*
8883 			 * kevent_register will always set kn_udata atomically
8884 			 * so that we don't have to take any kqlock here.
8885 			 */
8886 			buf[nknotes] = os_atomic_load_wide(&kn->kn_udata, relaxed);
8887 		}
8888 		/* we return total number of knotes, which may be more than requested */
8889 		nknotes++;
8890 	}
8891 
8892 	return nknotes;
8893 }
8894 
8895 int
kevent_proc_copy_uptrs(void * proc,uint64_t * buf,uint32_t bufsize)8896 kevent_proc_copy_uptrs(void *proc, uint64_t *buf, uint32_t bufsize)
8897 {
8898 	proc_t p = (proc_t)proc;
8899 	struct filedesc *fdp = &p->p_fd;
8900 	unsigned int nuptrs = 0;
8901 	unsigned int buflen = bufsize / sizeof(uint64_t);
8902 	struct kqworkloop *kqwl;
8903 
8904 	if (buflen > 0) {
8905 		assert(buf != NULL);
8906 	}
8907 
8908 	proc_fdlock(p);
8909 	for (int i = 0; i < fdp->fd_knlistsize; i++) {
8910 		nuptrs = klist_copy_udata(&fdp->fd_knlist[i], buf, buflen, nuptrs);
8911 	}
8912 	proc_fdunlock(p);
8913 
8914 	knhash_lock(fdp);
8915 	if (fdp->fd_knhashmask != 0) {
8916 		for (size_t i = 0; i < fdp->fd_knhashmask + 1; i++) {
8917 			nuptrs = klist_copy_udata(&fdp->fd_knhash[i], buf, buflen, nuptrs);
8918 		}
8919 	}
8920 	knhash_unlock(fdp);
8921 
8922 	kqhash_lock(fdp);
8923 	if (fdp->fd_kqhashmask != 0) {
8924 		for (size_t i = 0; i < fdp->fd_kqhashmask + 1; i++) {
8925 			LIST_FOREACH(kqwl, &fdp->fd_kqhash[i], kqwl_hashlink) {
8926 				if (nuptrs < buflen) {
8927 					buf[nuptrs] = kqwl->kqwl_dynamicid;
8928 				}
8929 				nuptrs++;
8930 			}
8931 		}
8932 	}
8933 	kqhash_unlock(fdp);
8934 
8935 	return (int)nuptrs;
8936 }
8937 
8938 static void
kevent_set_return_to_kernel_user_tsd(proc_t p,thread_t thread)8939 kevent_set_return_to_kernel_user_tsd(proc_t p, thread_t thread)
8940 {
8941 	uint64_t ast_addr;
8942 	bool proc_is_64bit = !!(p->p_flag & P_LP64);
8943 	size_t user_addr_size = proc_is_64bit ? 8 : 4;
8944 	uint32_t ast_flags32 = 0;
8945 	uint64_t ast_flags64 = 0;
8946 	struct uthread *ut = get_bsdthread_info(thread);
8947 
8948 	if (ut->uu_kqr_bound != NULL) {
8949 		ast_flags64 |= R2K_WORKLOOP_PENDING_EVENTS;
8950 	}
8951 
8952 	if (ast_flags64 == 0) {
8953 		return;
8954 	}
8955 
8956 	if (!(p->p_flag & P_LP64)) {
8957 		ast_flags32 = (uint32_t)ast_flags64;
8958 		assert(ast_flags64 < 0x100000000ull);
8959 	}
8960 
8961 	ast_addr = thread_rettokern_addr(thread);
8962 	if (ast_addr == 0) {
8963 		return;
8964 	}
8965 
8966 	if (copyout((proc_is_64bit ? (void *)&ast_flags64 : (void *)&ast_flags32),
8967 	    (user_addr_t)ast_addr,
8968 	    user_addr_size) != 0) {
8969 		printf("pid %d (tid:%llu): copyout of return_to_kernel ast flags failed with "
8970 		    "ast_addr = %llu\n", proc_getpid(p), thread_tid(current_thread()), ast_addr);
8971 	}
8972 }
8973 
8974 /*
8975  * Semantics of writing to TSD value:
8976  *
8977  * 1. It is written to by the kernel and cleared by userspace.
8978  * 2. When the userspace code clears the TSD field, it takes responsibility for
8979  * taking action on the quantum expiry action conveyed by kernel.
8980  * 3. The TSD value is always cleared upon entry into userspace and upon exit of
8981  * userspace back to kernel to make sure that it is never leaked across thread
8982  * requests.
8983  */
8984 void
kevent_set_workq_quantum_expiry_user_tsd(proc_t p,thread_t thread,uint64_t flags)8985 kevent_set_workq_quantum_expiry_user_tsd(proc_t p, thread_t thread,
8986     uint64_t flags)
8987 {
8988 	uint64_t ast_addr;
8989 	bool proc_is_64bit = !!(p->p_flag & P_LP64);
8990 	uint32_t ast_flags32 = 0;
8991 	uint64_t ast_flags64 = flags;
8992 
8993 	if (ast_flags64 == 0) {
8994 		return;
8995 	}
8996 
8997 	if (!(p->p_flag & P_LP64)) {
8998 		ast_flags32 = (uint32_t)ast_flags64;
8999 		assert(ast_flags64 < 0x100000000ull);
9000 	}
9001 
9002 	ast_addr = thread_wqquantum_addr(thread);
9003 	assert(ast_addr != 0);
9004 
9005 	if (proc_is_64bit) {
9006 		if (copyout_atomic64(ast_flags64, (user_addr_t) ast_addr)) {
9007 #if DEBUG || DEVELOPMENT
9008 			printf("pid %d (tid:%llu): copyout of workq quantum ast flags failed with "
9009 			    "ast_addr = %llu\n", proc_getpid(p), thread_tid(thread), ast_addr);
9010 #endif
9011 		}
9012 	} else {
9013 		if (copyout_atomic32(ast_flags32, (user_addr_t) ast_addr)) {
9014 #if DEBUG || DEVELOPMENT
9015 			printf("pid %d (tid:%llu): copyout of workq quantum ast flags failed with "
9016 			    "ast_addr = %llu\n", proc_getpid(p), thread_tid(thread), ast_addr);
9017 #endif
9018 		}
9019 	}
9020 }
9021 
9022 void
kevent_ast(thread_t thread,uint16_t bits)9023 kevent_ast(thread_t thread, uint16_t bits)
9024 {
9025 	proc_t p = current_proc();
9026 
9027 
9028 	if (bits & AST_KEVENT_REDRIVE_THREADREQ) {
9029 		workq_kern_threadreq_redrive(p, WORKQ_THREADREQ_CAN_CREATE_THREADS);
9030 	}
9031 	if (bits & AST_KEVENT_RETURN_TO_KERNEL) {
9032 		kevent_set_return_to_kernel_user_tsd(p, thread);
9033 	}
9034 
9035 	if (bits & AST_KEVENT_WORKQ_QUANTUM_EXPIRED) {
9036 		workq_kern_quantum_expiry_reevaluate(p, thread);
9037 	}
9038 }
9039 
9040 #if DEVELOPMENT || DEBUG
9041 
9042 #define KEVENT_SYSCTL_BOUND_ID 1
9043 
9044 static int
9045 kevent_sysctl SYSCTL_HANDLER_ARGS
9046 {
9047 #pragma unused(oidp, arg2)
9048 	uintptr_t type = (uintptr_t)arg1;
9049 	uint64_t bound_id = 0;
9050 
9051 	if (type != KEVENT_SYSCTL_BOUND_ID) {
9052 		return EINVAL;
9053 	}
9054 
9055 	if (req->newptr) {
9056 		return EINVAL;
9057 	}
9058 
9059 	struct uthread *ut = current_uthread();
9060 	if (!ut) {
9061 		return EFAULT;
9062 	}
9063 
9064 	workq_threadreq_t kqr = ut->uu_kqr_bound;
9065 	if (kqr) {
9066 		if (kqr->tr_flags & WORKQ_TR_FLAG_WORKLOOP) {
9067 			bound_id = kqr_kqworkloop(kqr)->kqwl_dynamicid;
9068 		} else {
9069 			bound_id = -1;
9070 		}
9071 	}
9072 
9073 	return sysctl_io_number(req, bound_id, sizeof(bound_id), NULL, NULL);
9074 }
9075 
9076 SYSCTL_NODE(_kern, OID_AUTO, kevent, CTLFLAG_RW | CTLFLAG_LOCKED, 0,
9077     "kevent information");
9078 
9079 SYSCTL_PROC(_kern_kevent, OID_AUTO, bound_id,
9080     CTLTYPE_QUAD | CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_MASKED,
9081     (void *)KEVENT_SYSCTL_BOUND_ID,
9082     sizeof(kqueue_id_t), kevent_sysctl, "Q",
9083     "get the ID of the bound kqueue");
9084 
9085 #endif /* DEVELOPMENT || DEBUG */
9086