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