xref: /freebsd/sys/kern/kern_event.c (revision fd9e09cb2ab07993e8dc783c802f273329e70bb8)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
5  * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
6  * Copyright (c) 2009 Apple, Inc.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 #include "opt_ktrace.h"
33 #include "opt_kqueue.h"
34 
35 #ifdef COMPAT_FREEBSD11
36 #define	_WANT_FREEBSD11_KEVENT
37 #endif
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/capsicum.h>
42 #include <sys/kernel.h>
43 #include <sys/limits.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/proc.h>
47 #include <sys/malloc.h>
48 #include <sys/unistd.h>
49 #include <sys/file.h>
50 #include <sys/filedesc.h>
51 #include <sys/filio.h>
52 #include <sys/fcntl.h>
53 #include <sys/jail.h>
54 #include <sys/kthread.h>
55 #include <sys/selinfo.h>
56 #include <sys/queue.h>
57 #include <sys/event.h>
58 #include <sys/eventvar.h>
59 #include <sys/poll.h>
60 #include <sys/protosw.h>
61 #include <sys/resourcevar.h>
62 #include <sys/sbuf.h>
63 #include <sys/sigio.h>
64 #include <sys/signalvar.h>
65 #include <sys/socket.h>
66 #include <sys/socketvar.h>
67 #include <sys/stat.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysent.h>
70 #include <sys/sysproto.h>
71 #include <sys/syscallsubr.h>
72 #include <sys/taskqueue.h>
73 #include <sys/uio.h>
74 #include <sys/user.h>
75 #ifdef KTRACE
76 #include <sys/ktrace.h>
77 #endif
78 #include <machine/atomic.h>
79 #ifdef COMPAT_FREEBSD32
80 #include <compat/freebsd32/freebsd32.h>
81 #include <compat/freebsd32/freebsd32_util.h>
82 #endif
83 
84 #include <vm/uma.h>
85 
86 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
87 
88 /*
89  * This lock is used if multiple kq locks are required.  This possibly
90  * should be made into a per proc lock.
91  */
92 static struct mtx	kq_global;
93 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
94 #define KQ_GLOBAL_LOCK(lck, haslck)	do {	\
95 	if (!haslck)				\
96 		mtx_lock(lck);			\
97 	haslck = 1;				\
98 } while (0)
99 #define KQ_GLOBAL_UNLOCK(lck, haslck)	do {	\
100 	if (haslck)				\
101 		mtx_unlock(lck);			\
102 	haslck = 0;				\
103 } while (0)
104 
105 TASKQUEUE_DEFINE_THREAD(kqueue_ctx);
106 
107 static int	kevent_copyout(void *arg, struct kevent *kevp, int count);
108 static int	kevent_copyin(void *arg, struct kevent *kevp, int count);
109 static int	kqueue_register(struct kqueue *kq, struct kevent *kev,
110 		    struct thread *td, int mflag);
111 static int	kqueue_acquire(struct file *fp, struct kqueue **kqp);
112 static void	kqueue_release(struct kqueue *kq, int locked);
113 static void	kqueue_destroy(struct kqueue *kq);
114 static void	kqueue_drain(struct kqueue *kq, struct thread *td);
115 static int	kqueue_expand(struct kqueue *kq, const struct filterops *fops,
116 		    uintptr_t ident, int mflag);
117 static void	kqueue_task(void *arg, int pending);
118 static int	kqueue_scan(struct kqueue *kq, int maxevents,
119 		    struct kevent_copyops *k_ops,
120 		    const struct timespec *timeout,
121 		    struct kevent *keva, struct thread *td);
122 static void 	kqueue_wakeup(struct kqueue *kq);
123 static const struct filterops *kqueue_fo_find(int filt);
124 static void	kqueue_fo_release(int filt);
125 struct g_kevent_args;
126 static int	kern_kevent_generic(struct thread *td,
127 		    struct g_kevent_args *uap,
128 		    struct kevent_copyops *k_ops, const char *struct_name);
129 
130 static fo_ioctl_t	kqueue_ioctl;
131 static fo_poll_t	kqueue_poll;
132 static fo_kqfilter_t	kqueue_kqfilter;
133 static fo_stat_t	kqueue_stat;
134 static fo_close_t	kqueue_close;
135 static fo_fill_kinfo_t	kqueue_fill_kinfo;
136 
137 static const struct fileops kqueueops = {
138 	.fo_read = invfo_rdwr,
139 	.fo_write = invfo_rdwr,
140 	.fo_truncate = invfo_truncate,
141 	.fo_ioctl = kqueue_ioctl,
142 	.fo_poll = kqueue_poll,
143 	.fo_kqfilter = kqueue_kqfilter,
144 	.fo_stat = kqueue_stat,
145 	.fo_close = kqueue_close,
146 	.fo_chmod = invfo_chmod,
147 	.fo_chown = invfo_chown,
148 	.fo_sendfile = invfo_sendfile,
149 	.fo_cmp = file_kcmp_generic,
150 	.fo_fill_kinfo = kqueue_fill_kinfo,
151 };
152 
153 static int 	knote_attach(struct knote *kn, struct kqueue *kq);
154 static void 	knote_drop(struct knote *kn, struct thread *td);
155 static void 	knote_drop_detached(struct knote *kn, struct thread *td);
156 static void 	knote_enqueue(struct knote *kn);
157 static void 	knote_dequeue(struct knote *kn);
158 static void 	knote_init(void);
159 static struct 	knote *knote_alloc(int mflag);
160 static void 	knote_free(struct knote *kn);
161 
162 static void	filt_kqdetach(struct knote *kn);
163 static int	filt_kqueue(struct knote *kn, long hint);
164 static int	filt_procattach(struct knote *kn);
165 static void	filt_procdetach(struct knote *kn);
166 static int	filt_proc(struct knote *kn, long hint);
167 static int	filt_jailattach(struct knote *kn);
168 static void	filt_jaildetach(struct knote *kn);
169 static int	filt_jail(struct knote *kn, long hint);
170 static int	filt_fileattach(struct knote *kn);
171 static void	filt_timerexpire(void *knx);
172 static void	filt_timerexpire_l(struct knote *kn, bool proc_locked);
173 static int	filt_timerattach(struct knote *kn);
174 static void	filt_timerdetach(struct knote *kn);
175 static void	filt_timerstart(struct knote *kn, sbintime_t to);
176 static void	filt_timertouch(struct knote *kn, struct kevent *kev,
177 		    u_long type);
178 static int	filt_timervalidate(struct knote *kn, sbintime_t *to);
179 static int	filt_timer(struct knote *kn, long hint);
180 static int	filt_userattach(struct knote *kn);
181 static void	filt_userdetach(struct knote *kn);
182 static int	filt_user(struct knote *kn, long hint);
183 static void	filt_usertouch(struct knote *kn, struct kevent *kev,
184 		    u_long type);
185 
186 static const struct filterops file_filtops = {
187 	.f_isfd = 1,
188 	.f_attach = filt_fileattach,
189 };
190 static const struct filterops kqread_filtops = {
191 	.f_isfd = 1,
192 	.f_detach = filt_kqdetach,
193 	.f_event = filt_kqueue,
194 };
195 /* XXX - move to kern_proc.c?  */
196 static const struct filterops proc_filtops = {
197 	.f_isfd = 0,
198 	.f_attach = filt_procattach,
199 	.f_detach = filt_procdetach,
200 	.f_event = filt_proc,
201 };
202 static const struct filterops jail_filtops = {
203 	.f_isfd = 0,
204 	.f_attach = filt_jailattach,
205 	.f_detach = filt_jaildetach,
206 	.f_event = filt_jail,
207 };
208 static const struct filterops timer_filtops = {
209 	.f_isfd = 0,
210 	.f_attach = filt_timerattach,
211 	.f_detach = filt_timerdetach,
212 	.f_event = filt_timer,
213 	.f_touch = filt_timertouch,
214 };
215 static const struct filterops user_filtops = {
216 	.f_attach = filt_userattach,
217 	.f_detach = filt_userdetach,
218 	.f_event = filt_user,
219 	.f_touch = filt_usertouch,
220 };
221 
222 static uma_zone_t	knote_zone;
223 static unsigned int __exclusive_cache_line	kq_ncallouts;
224 static unsigned int 	kq_calloutmax = 4 * 1024;
225 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
226     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
227 
228 /* XXX - ensure not influx ? */
229 #define KNOTE_ACTIVATE(kn, islock) do { 				\
230 	if ((islock))							\
231 		mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED);		\
232 	else								\
233 		KQ_LOCK((kn)->kn_kq);					\
234 	(kn)->kn_status |= KN_ACTIVE;					\
235 	if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
236 		knote_enqueue((kn));					\
237 	if (!(islock))							\
238 		KQ_UNLOCK((kn)->kn_kq);					\
239 } while (0)
240 #define KQ_LOCK(kq) do {						\
241 	mtx_lock(&(kq)->kq_lock);					\
242 } while (0)
243 #define KQ_FLUX_WAKEUP(kq) do {						\
244 	if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) {		\
245 		(kq)->kq_state &= ~KQ_FLUXWAIT;				\
246 		wakeup((kq));						\
247 	}								\
248 } while (0)
249 #define KQ_UNLOCK_FLUX(kq) do {						\
250 	KQ_FLUX_WAKEUP(kq);						\
251 	mtx_unlock(&(kq)->kq_lock);					\
252 } while (0)
253 #define KQ_UNLOCK(kq) do {						\
254 	mtx_unlock(&(kq)->kq_lock);					\
255 } while (0)
256 #define KQ_OWNED(kq) do {						\
257 	mtx_assert(&(kq)->kq_lock, MA_OWNED);				\
258 } while (0)
259 #define KQ_NOTOWNED(kq) do {						\
260 	mtx_assert(&(kq)->kq_lock, MA_NOTOWNED);			\
261 } while (0)
262 
263 static struct knlist *
kn_list_lock(struct knote * kn)264 kn_list_lock(struct knote *kn)
265 {
266 	struct knlist *knl;
267 
268 	knl = kn->kn_knlist;
269 	if (knl != NULL)
270 		knl->kl_lock(knl->kl_lockarg);
271 	return (knl);
272 }
273 
274 static void
kn_list_unlock(struct knlist * knl)275 kn_list_unlock(struct knlist *knl)
276 {
277 	bool do_free;
278 
279 	if (knl == NULL)
280 		return;
281 	do_free = knl->kl_autodestroy && knlist_empty(knl);
282 	knl->kl_unlock(knl->kl_lockarg);
283 	if (do_free) {
284 		knlist_destroy(knl);
285 		free(knl, M_KQUEUE);
286 	}
287 }
288 
289 static bool
kn_in_flux(struct knote * kn)290 kn_in_flux(struct knote *kn)
291 {
292 
293 	return (kn->kn_influx > 0);
294 }
295 
296 static void
kn_enter_flux(struct knote * kn)297 kn_enter_flux(struct knote *kn)
298 {
299 
300 	KQ_OWNED(kn->kn_kq);
301 	MPASS(kn->kn_influx < INT_MAX);
302 	kn->kn_influx++;
303 }
304 
305 static bool
kn_leave_flux(struct knote * kn)306 kn_leave_flux(struct knote *kn)
307 {
308 
309 	KQ_OWNED(kn->kn_kq);
310 	MPASS(kn->kn_influx > 0);
311 	kn->kn_influx--;
312 	return (kn->kn_influx == 0);
313 }
314 
315 #define	KNL_ASSERT_LOCK(knl, islocked) do {				\
316 	if (islocked)							\
317 		KNL_ASSERT_LOCKED(knl);				\
318 	else								\
319 		KNL_ASSERT_UNLOCKED(knl);				\
320 } while (0)
321 #ifdef INVARIANTS
322 #define	KNL_ASSERT_LOCKED(knl) do {					\
323 	knl->kl_assert_lock((knl)->kl_lockarg, LA_LOCKED);		\
324 } while (0)
325 #define	KNL_ASSERT_UNLOCKED(knl) do {					\
326 	knl->kl_assert_lock((knl)->kl_lockarg, LA_UNLOCKED);		\
327 } while (0)
328 #else /* !INVARIANTS */
329 #define	KNL_ASSERT_LOCKED(knl) do {} while (0)
330 #define	KNL_ASSERT_UNLOCKED(knl) do {} while (0)
331 #endif /* INVARIANTS */
332 
333 #ifndef	KN_HASHSIZE
334 #define	KN_HASHSIZE		64		/* XXX should be tunable */
335 #endif
336 
337 #define KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
338 
339 static int
filt_nullattach(struct knote * kn)340 filt_nullattach(struct knote *kn)
341 {
342 
343 	return (ENXIO);
344 };
345 
346 static const struct filterops null_filtops = {
347 	.f_isfd = 0,
348 	.f_attach = filt_nullattach,
349 };
350 
351 /* XXX - make SYSINIT to add these, and move into respective modules. */
352 extern const struct filterops sig_filtops;
353 extern const struct filterops fs_filtops;
354 
355 /*
356  * Table for all system-defined filters.
357  */
358 static struct mtx	filterops_lock;
359 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops", MTX_DEF);
360 static struct {
361 	const struct filterops *for_fop;
362 	int for_nolock;
363 	int for_refcnt;
364 } sysfilt_ops[EVFILT_SYSCOUNT] = {
365 	[~EVFILT_READ] = { &file_filtops, 1 },
366 	[~EVFILT_WRITE] = { &file_filtops, 1 },
367 	[~EVFILT_AIO] = { &null_filtops },
368 	[~EVFILT_VNODE] = { &file_filtops, 1 },
369 	[~EVFILT_PROC] = { &proc_filtops, 1 },
370 	[~EVFILT_SIGNAL] = { &sig_filtops, 1 },
371 	[~EVFILT_TIMER] = { &timer_filtops, 1 },
372 	[~EVFILT_PROCDESC] = { &file_filtops, 1 },
373 	[~EVFILT_FS] = { &fs_filtops, 1 },
374 	[~EVFILT_LIO] = { &null_filtops },
375 	[~EVFILT_USER] = { &user_filtops, 1 },
376 	[~EVFILT_SENDFILE] = { &null_filtops },
377 	[~EVFILT_EMPTY] = { &file_filtops, 1 },
378 	[~EVFILT_JAIL] = { &jail_filtops, 1 },
379 };
380 
381 /*
382  * Simple redirection for all cdevsw style objects to call their fo_kqfilter
383  * method.
384  */
385 static int
filt_fileattach(struct knote * kn)386 filt_fileattach(struct knote *kn)
387 {
388 
389 	return (fo_kqfilter(kn->kn_fp, kn));
390 }
391 
392 /*ARGSUSED*/
393 static int
kqueue_kqfilter(struct file * fp,struct knote * kn)394 kqueue_kqfilter(struct file *fp, struct knote *kn)
395 {
396 	struct kqueue *kq = kn->kn_fp->f_data;
397 
398 	if (kn->kn_filter != EVFILT_READ)
399 		return (EINVAL);
400 
401 	kn->kn_status |= KN_KQUEUE;
402 	kn->kn_fop = &kqread_filtops;
403 	knlist_add(&kq->kq_sel.si_note, kn, 0);
404 
405 	return (0);
406 }
407 
408 static void
filt_kqdetach(struct knote * kn)409 filt_kqdetach(struct knote *kn)
410 {
411 	struct kqueue *kq = kn->kn_fp->f_data;
412 
413 	knlist_remove(&kq->kq_sel.si_note, kn, 0);
414 }
415 
416 /*ARGSUSED*/
417 static int
filt_kqueue(struct knote * kn,long hint)418 filt_kqueue(struct knote *kn, long hint)
419 {
420 	struct kqueue *kq = kn->kn_fp->f_data;
421 
422 	kn->kn_data = kq->kq_count;
423 	return (kn->kn_data > 0);
424 }
425 
426 /* XXX - move to kern_proc.c?  */
427 static int
filt_procattach(struct knote * kn)428 filt_procattach(struct knote *kn)
429 {
430 	struct proc *p;
431 	int error;
432 	bool exiting, immediate;
433 
434 	exiting = immediate = false;
435 	if (kn->kn_sfflags & NOTE_EXIT)
436 		p = pfind_any(kn->kn_id);
437 	else
438 		p = pfind(kn->kn_id);
439 	if (p == NULL)
440 		return (ESRCH);
441 	if (p->p_flag & P_WEXIT)
442 		exiting = true;
443 
444 	if ((error = p_cansee(curthread, p))) {
445 		PROC_UNLOCK(p);
446 		return (error);
447 	}
448 
449 	kn->kn_ptr.p_proc = p;
450 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
451 
452 	/*
453 	 * Internal flag indicating registration done by kernel for the
454 	 * purposes of getting a NOTE_CHILD notification.
455 	 */
456 	if (kn->kn_flags & EV_FLAG2) {
457 		kn->kn_flags &= ~EV_FLAG2;
458 		kn->kn_data = kn->kn_sdata;		/* ppid */
459 		kn->kn_fflags = NOTE_CHILD;
460 		kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
461 		immediate = true; /* Force immediate activation of child note. */
462 	}
463 	/*
464 	 * Internal flag indicating registration done by kernel (for other than
465 	 * NOTE_CHILD).
466 	 */
467 	if (kn->kn_flags & EV_FLAG1) {
468 		kn->kn_flags &= ~EV_FLAG1;
469 	}
470 
471 	knlist_add(p->p_klist, kn, 1);
472 
473 	/*
474 	 * Immediately activate any child notes or, in the case of a zombie
475 	 * target process, exit notes.  The latter is necessary to handle the
476 	 * case where the target process, e.g. a child, dies before the kevent
477 	 * is registered.
478 	 */
479 	if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
480 		KNOTE_ACTIVATE(kn, 0);
481 
482 	PROC_UNLOCK(p);
483 
484 	return (0);
485 }
486 
487 /*
488  * The knote may be attached to a different process, which may exit,
489  * leaving nothing for the knote to be attached to.  So when the process
490  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
491  * it will be deleted when read out.  However, as part of the knote deletion,
492  * this routine is called, so a check is needed to avoid actually performing
493  * a detach, because the original process does not exist any more.
494  */
495 /* XXX - move to kern_proc.c?  */
496 static void
filt_procdetach(struct knote * kn)497 filt_procdetach(struct knote *kn)
498 {
499 
500 	knlist_remove(kn->kn_knlist, kn, 0);
501 	kn->kn_ptr.p_proc = NULL;
502 }
503 
504 /* XXX - move to kern_proc.c?  */
505 static int
filt_proc(struct knote * kn,long hint)506 filt_proc(struct knote *kn, long hint)
507 {
508 	struct proc *p;
509 	u_int event;
510 
511 	p = kn->kn_ptr.p_proc;
512 	if (p == NULL) /* already activated, from attach filter */
513 		return (0);
514 
515 	/* Mask off extra data. */
516 	event = (u_int)hint & NOTE_PCTRLMASK;
517 
518 	/* If the user is interested in this event, record it. */
519 	if (kn->kn_sfflags & event)
520 		kn->kn_fflags |= event;
521 
522 	/* Process is gone, so flag the event as finished. */
523 	if (event == NOTE_EXIT) {
524 		kn->kn_flags |= EV_EOF | EV_ONESHOT;
525 		kn->kn_ptr.p_proc = NULL;
526 		if (kn->kn_fflags & NOTE_EXIT)
527 			kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
528 		if (kn->kn_fflags == 0)
529 			kn->kn_flags |= EV_DROP;
530 		return (1);
531 	}
532 
533 	return (kn->kn_fflags != 0);
534 }
535 
536 /*
537  * Called when the process forked. It mostly does the same as the
538  * knote(), activating all knotes registered to be activated when the
539  * process forked. Additionally, for each knote attached to the
540  * parent, check whether user wants to track the new process. If so
541  * attach a new knote to it, and immediately report an event with the
542  * child's pid. This is also called on jail creation, which is treated
543  * the same way by jail events.
544  */
545 void
knote_fork(struct knlist * list,int pid)546 knote_fork(struct knlist *list, int pid)
547 {
548 	struct kqueue *kq;
549 	struct knote *kn;
550 	struct kevent kev;
551 	int error;
552 
553 	MPASS(list != NULL);
554 	KNL_ASSERT_LOCKED(list);
555 	if (SLIST_EMPTY(&list->kl_list))
556 		return;
557 
558 	memset(&kev, 0, sizeof(kev));
559 	SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
560 		kq = kn->kn_kq;
561 		KQ_LOCK(kq);
562 		if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
563 			KQ_UNLOCK(kq);
564 			continue;
565 		}
566 
567 		/*
568 		 * The same as knote(), activate the event.
569 		 */
570 		_Static_assert(NOTE_JAIL_CHILD == NOTE_FORK,
571 		    "NOTE_JAIL_CHILD should be the same as NOTE_FORK");
572 		if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
573 			if (kn->kn_fop->f_event(kn, NOTE_FORK))
574 				KNOTE_ACTIVATE(kn, 1);
575 			KQ_UNLOCK(kq);
576 			continue;
577 		}
578 
579 		/*
580 		 * The NOTE_TRACK case. In addition to the activation
581 		 * of the event, we need to register new events to
582 		 * track the child. Drop the locks in preparation for
583 		 * the call to kqueue_register().
584 		 */
585 		kn_enter_flux(kn);
586 		KQ_UNLOCK(kq);
587 		list->kl_unlock(list->kl_lockarg);
588 
589 		/*
590 		 * Activate existing knote and register tracking knotes with
591 		 * new process.
592 		 *
593 		 * First register a knote to get just the child notice. This
594 		 * must be a separate note from a potential NOTE_EXIT
595 		 * notification since both NOTE_CHILD and NOTE_EXIT are defined
596 		 * to use the data field (in conflicting ways).
597 		 */
598 		kev.ident = pid;
599 		kev.filter = kn->kn_filter;
600 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
601 		    EV_FLAG2;
602 		kev.fflags = kn->kn_sfflags;
603 		kev.data = kn->kn_id;		/* parent */
604 		kev.udata = kn->kn_kevent.udata;/* preserve udata */
605 		error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
606 		if (error)
607 			kn->kn_fflags |= NOTE_TRACKERR;
608 
609 		/*
610 		 * Then register another knote to track other potential events
611 		 * from the new process.
612 		 */
613 		kev.ident = pid;
614 		kev.filter = kn->kn_filter;
615 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
616 		kev.fflags = kn->kn_sfflags;
617 		kev.data = kn->kn_id;		/* parent */
618 		kev.udata = kn->kn_kevent.udata;/* preserve udata */
619 		error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
620 		if (error)
621 			kn->kn_fflags |= NOTE_TRACKERR;
622 		if (kn->kn_fop->f_event(kn, NOTE_FORK))
623 			KNOTE_ACTIVATE(kn, 0);
624 		list->kl_lock(list->kl_lockarg);
625 		KQ_LOCK(kq);
626 		kn_leave_flux(kn);
627 		KQ_UNLOCK_FLUX(kq);
628 	}
629 }
630 
631 int
filt_jailattach(struct knote * kn)632 filt_jailattach(struct knote *kn)
633 {
634 	struct prison *pr;
635 	bool immediate;
636 
637 	immediate = false;
638 	if (kn->kn_id == 0) {
639 		/* Let jid=0 watch the current prison (including prison0). */
640 		pr = curthread->td_ucred->cr_prison;
641 		mtx_lock(&pr->pr_mtx);
642 	} else if (kn->kn_flags & (EV_FLAG1 | EV_FLAG2)) {
643 		/*
644 		 * The kernel registers prisons before they are valid,
645 		 * so prison_find_child will fail.
646 		 */
647 		TAILQ_FOREACH(pr, &allprison, pr_list) {
648 			if (pr->pr_id < kn->kn_id)
649 				continue;
650 			if (pr->pr_id > kn->kn_id) {
651 				pr = NULL;
652 				break;
653 			}
654 			mtx_lock(&pr->pr_mtx);
655 			break;
656 		}
657 		if (pr == NULL)
658 			return (ENOENT);
659 	} else {
660 		sx_slock(&allprison_lock);
661 		pr = prison_find_child(curthread->td_ucred->cr_prison,
662 		    kn->kn_id);
663 		sx_sunlock(&allprison_lock);
664 		if (pr == NULL)
665 			return (ENOENT);
666 		if (!prison_isalive(pr)) {
667 			mtx_unlock(&pr->pr_mtx);
668 			return (ENOENT);
669 		}
670 	}
671 	kn->kn_ptr.p_prison = pr;
672 	kn->kn_flags |= EV_CLEAR;
673 
674 	/*
675 	 * Internal flag indicating registration done by kernel for the
676 	 * purposes of getting a NOTE_CHILD notification.
677 	 */
678 	if (kn->kn_flags & EV_FLAG2) {
679 		kn->kn_flags &= ~EV_FLAG2;
680 		kn->kn_data = kn->kn_sdata;		/* parent id */
681 		kn->kn_fflags = NOTE_CHILD;
682 		kn->kn_sfflags &= ~NOTE_JAIL_CTRLMASK;
683 		immediate = true; /* Force immediate activation of child note. */
684 	}
685 	/*
686 	 * Internal flag indicating registration done by kernel (for other than
687 	 * NOTE_CHILD).
688 	 */
689 	if (kn->kn_flags & EV_FLAG1) {
690 		kn->kn_flags &= ~EV_FLAG1;
691 	}
692 
693 	knlist_add(pr->pr_klist, kn, 1);
694 
695 	/* Immediately activate any child notes. */
696 	if (immediate)
697 		KNOTE_ACTIVATE(kn, 0);
698 
699 	mtx_unlock(&pr->pr_mtx);
700 	return (0);
701 }
702 
703 void
filt_jaildetach(struct knote * kn)704 filt_jaildetach(struct knote *kn)
705 {
706 	if (kn->kn_ptr.p_prison != NULL) {
707 		knlist_remove(kn->kn_knlist, kn, 0);
708 		kn->kn_ptr.p_prison = NULL;
709 	} else
710 		kn->kn_status |= KN_DETACHED;
711 }
712 
713 int
filt_jail(struct knote * kn,long hint)714 filt_jail(struct knote *kn, long hint)
715 {
716 	struct prison *pr;
717 	u_int event;
718 
719 	pr = kn->kn_ptr.p_prison;
720 	if (pr == NULL) /* already activated, from attach filter */
721 		return (0);
722 
723 	/* Mask off extra data. */
724 	event = (u_int)hint & NOTE_JAIL_CTRLMASK;
725 
726 	/* If the user is interested in this event, record it. */
727 	if (kn->kn_sfflags & event)
728 		kn->kn_fflags |= event;
729 
730 	/* Report the attached process id. */
731 	if (event == NOTE_JAIL_ATTACH) {
732 		if (kn->kn_data != 0)
733 			kn->kn_fflags |= NOTE_JAIL_ATTACH_MULTI;
734 		kn->kn_data = hint & NOTE_JAIL_DATAMASK;
735 	}
736 
737 	/* Prison is gone, so flag the event as finished. */
738 	if (event == NOTE_JAIL_REMOVE) {
739 		kn->kn_flags |= EV_EOF | EV_ONESHOT;
740 		kn->kn_ptr.p_prison = NULL;
741 		if (kn->kn_fflags == 0)
742 			kn->kn_flags |= EV_DROP;
743 		return (1);
744 	}
745 
746 	return (kn->kn_fflags != 0);
747 }
748 
749 /*
750  * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
751  * interval timer support code.
752  */
753 
754 #define NOTE_TIMER_PRECMASK						\
755     (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
756 
757 static sbintime_t
timer2sbintime(int64_t data,int flags)758 timer2sbintime(int64_t data, int flags)
759 {
760 	int64_t secs;
761 
762         /*
763          * Macros for converting to the fractional second portion of an
764          * sbintime_t using 64bit multiplication to improve precision.
765          */
766 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
767 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
768 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
769 	switch (flags & NOTE_TIMER_PRECMASK) {
770 	case NOTE_SECONDS:
771 #ifdef __LP64__
772 		if (data > (SBT_MAX / SBT_1S))
773 			return (SBT_MAX);
774 #endif
775 		return ((sbintime_t)data << 32);
776 	case NOTE_MSECONDS: /* FALLTHROUGH */
777 	case 0:
778 		if (data >= 1000) {
779 			secs = data / 1000;
780 #ifdef __LP64__
781 			if (secs > (SBT_MAX / SBT_1S))
782 				return (SBT_MAX);
783 #endif
784 			return (secs << 32 | MS_TO_SBT(data % 1000));
785 		}
786 		return (MS_TO_SBT(data));
787 	case NOTE_USECONDS:
788 		if (data >= 1000000) {
789 			secs = data / 1000000;
790 #ifdef __LP64__
791 			if (secs > (SBT_MAX / SBT_1S))
792 				return (SBT_MAX);
793 #endif
794 			return (secs << 32 | US_TO_SBT(data % 1000000));
795 		}
796 		return (US_TO_SBT(data));
797 	case NOTE_NSECONDS:
798 		if (data >= 1000000000) {
799 			secs = data / 1000000000;
800 #ifdef __LP64__
801 			if (secs > (SBT_MAX / SBT_1S))
802 				return (SBT_MAX);
803 #endif
804 			return (secs << 32 | NS_TO_SBT(data % 1000000000));
805 		}
806 		return (NS_TO_SBT(data));
807 	default:
808 		break;
809 	}
810 	return (-1);
811 }
812 
813 struct kq_timer_cb_data {
814 	struct callout c;
815 	struct proc *p;
816 	struct knote *kn;
817 	int cpuid;
818 	int flags;
819 	TAILQ_ENTRY(kq_timer_cb_data) link;
820 	sbintime_t next;	/* next timer event fires at */
821 	sbintime_t to;		/* precalculated timer period, 0 for abs */
822 };
823 
824 #define	KQ_TIMER_CB_ENQUEUED	0x01
825 
826 static void
kqtimer_sched_callout(struct kq_timer_cb_data * kc)827 kqtimer_sched_callout(struct kq_timer_cb_data *kc)
828 {
829 	callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kc->kn,
830 	    kc->cpuid, C_ABSOLUTE);
831 }
832 
833 void
kqtimer_proc_continue(struct proc * p)834 kqtimer_proc_continue(struct proc *p)
835 {
836 	struct kq_timer_cb_data *kc, *kc1;
837 	struct bintime bt;
838 	sbintime_t now;
839 
840 	PROC_LOCK_ASSERT(p, MA_OWNED);
841 
842 	getboottimebin(&bt);
843 	now = bttosbt(bt);
844 
845 	TAILQ_FOREACH_SAFE(kc, &p->p_kqtim_stop, link, kc1) {
846 		TAILQ_REMOVE(&p->p_kqtim_stop, kc, link);
847 		kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
848 		if (kc->next <= now)
849 			filt_timerexpire_l(kc->kn, true);
850 		else
851 			kqtimer_sched_callout(kc);
852 	}
853 }
854 
855 static void
filt_timerexpire_l(struct knote * kn,bool proc_locked)856 filt_timerexpire_l(struct knote *kn, bool proc_locked)
857 {
858 	struct kq_timer_cb_data *kc;
859 	struct proc *p;
860 	uint64_t delta;
861 	sbintime_t now;
862 
863 	kc = kn->kn_ptr.p_v;
864 
865 	if ((kn->kn_flags & EV_ONESHOT) != 0 || kc->to == 0) {
866 		kn->kn_data++;
867 		KNOTE_ACTIVATE(kn, 0);
868 		return;
869 	}
870 
871 	now = sbinuptime();
872 	if (now >= kc->next) {
873 		delta = (now - kc->next) / kc->to;
874 		if (delta == 0)
875 			delta = 1;
876 		kn->kn_data += delta;
877 		kc->next += delta * kc->to;
878 		if (now >= kc->next)	/* overflow */
879 			kc->next = now + kc->to;
880 		KNOTE_ACTIVATE(kn, 0);	/* XXX - handle locking */
881 	}
882 
883 	/*
884 	 * Initial check for stopped kc->p is racy.  It is fine to
885 	 * miss the set of the stop flags, at worst we would schedule
886 	 * one more callout.  On the other hand, it is not fine to not
887 	 * schedule when we we missed clearing of the flags, we
888 	 * recheck them under the lock and observe consistent state.
889 	 */
890 	p = kc->p;
891 	if (P_SHOULDSTOP(p) || P_KILLED(p)) {
892 		if (!proc_locked)
893 			PROC_LOCK(p);
894 		if (P_SHOULDSTOP(p) || P_KILLED(p)) {
895 			if ((kc->flags & KQ_TIMER_CB_ENQUEUED) == 0) {
896 				kc->flags |= KQ_TIMER_CB_ENQUEUED;
897 				TAILQ_INSERT_TAIL(&p->p_kqtim_stop, kc, link);
898 			}
899 			if (!proc_locked)
900 				PROC_UNLOCK(p);
901 			return;
902 		}
903 		if (!proc_locked)
904 			PROC_UNLOCK(p);
905 	}
906 	kqtimer_sched_callout(kc);
907 }
908 
909 static void
filt_timerexpire(void * knx)910 filt_timerexpire(void *knx)
911 {
912 	filt_timerexpire_l(knx, false);
913 }
914 
915 /*
916  * data contains amount of time to sleep
917  */
918 static int
filt_timervalidate(struct knote * kn,sbintime_t * to)919 filt_timervalidate(struct knote *kn, sbintime_t *to)
920 {
921 	struct bintime bt;
922 	sbintime_t sbt;
923 
924 	if (kn->kn_sdata < 0)
925 		return (EINVAL);
926 	if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
927 		kn->kn_sdata = 1;
928 	/*
929 	 * The only fflags values supported are the timer unit
930 	 * (precision) and the absolute time indicator.
931 	 */
932 	if ((kn->kn_sfflags & ~(NOTE_TIMER_PRECMASK | NOTE_ABSTIME)) != 0)
933 		return (EINVAL);
934 
935 	*to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
936 	if (*to < 0)
937 		return (EINVAL);
938 	if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
939 		getboottimebin(&bt);
940 		sbt = bttosbt(bt);
941 		*to = MAX(0, *to - sbt);
942 	}
943 	return (0);
944 }
945 
946 static int
filt_timerattach(struct knote * kn)947 filt_timerattach(struct knote *kn)
948 {
949 	struct kq_timer_cb_data *kc;
950 	sbintime_t to;
951 	int error;
952 
953 	to = -1;
954 	error = filt_timervalidate(kn, &to);
955 	if (error != 0)
956 		return (error);
957 	KASSERT(to > 0 || (kn->kn_flags & EV_ONESHOT) != 0 ||
958 	    (kn->kn_sfflags & NOTE_ABSTIME) != 0,
959 	    ("%s: periodic timer has a calculated zero timeout", __func__));
960 	KASSERT(to >= 0,
961 	    ("%s: timer has a calculated negative timeout", __func__));
962 
963 	if (atomic_fetchadd_int(&kq_ncallouts, 1) + 1 > kq_calloutmax) {
964 		atomic_subtract_int(&kq_ncallouts, 1);
965 		return (ENOMEM);
966 	}
967 
968 	if ((kn->kn_sfflags & NOTE_ABSTIME) == 0)
969 		kn->kn_flags |= EV_CLEAR;	/* automatically set */
970 	kn->kn_status &= ~KN_DETACHED;		/* knlist_add clears it */
971 	kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
972 	kc->kn = kn;
973 	kc->p = curproc;
974 	kc->cpuid = PCPU_GET(cpuid);
975 	kc->flags = 0;
976 	callout_init(&kc->c, 1);
977 	filt_timerstart(kn, to);
978 
979 	return (0);
980 }
981 
982 static void
filt_timerstart(struct knote * kn,sbintime_t to)983 filt_timerstart(struct knote *kn, sbintime_t to)
984 {
985 	struct kq_timer_cb_data *kc;
986 
987 	kc = kn->kn_ptr.p_v;
988 	if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
989 		kc->next = to;
990 		kc->to = 0;
991 	} else {
992 		kc->next = to + sbinuptime();
993 		kc->to = to;
994 	}
995 	kqtimer_sched_callout(kc);
996 }
997 
998 static void
filt_timerdetach(struct knote * kn)999 filt_timerdetach(struct knote *kn)
1000 {
1001 	struct kq_timer_cb_data *kc;
1002 	unsigned int old __unused;
1003 	bool pending;
1004 
1005 	kc = kn->kn_ptr.p_v;
1006 	do {
1007 		callout_drain(&kc->c);
1008 
1009 		/*
1010 		 * kqtimer_proc_continue() might have rescheduled this callout.
1011 		 * Double-check, using the process mutex as an interlock.
1012 		 */
1013 		PROC_LOCK(kc->p);
1014 		if ((kc->flags & KQ_TIMER_CB_ENQUEUED) != 0) {
1015 			kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
1016 			TAILQ_REMOVE(&kc->p->p_kqtim_stop, kc, link);
1017 		}
1018 		pending = callout_pending(&kc->c);
1019 		PROC_UNLOCK(kc->p);
1020 	} while (pending);
1021 	free(kc, M_KQUEUE);
1022 	old = atomic_fetchadd_int(&kq_ncallouts, -1);
1023 	KASSERT(old > 0, ("Number of callouts cannot become negative"));
1024 	kn->kn_status |= KN_DETACHED;	/* knlist_remove sets it */
1025 }
1026 
1027 static void
filt_timertouch(struct knote * kn,struct kevent * kev,u_long type)1028 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
1029 {
1030 	struct kq_timer_cb_data *kc;
1031 	struct kqueue *kq;
1032 	sbintime_t to;
1033 	int error;
1034 
1035 	switch (type) {
1036 	case EVENT_REGISTER:
1037 		/* Handle re-added timers that update data/fflags */
1038 		if (kev->flags & EV_ADD) {
1039 			kc = kn->kn_ptr.p_v;
1040 
1041 			/* Drain any existing callout. */
1042 			callout_drain(&kc->c);
1043 
1044 			/* Throw away any existing undelivered record
1045 			 * of the timer expiration. This is done under
1046 			 * the presumption that if a process is
1047 			 * re-adding this timer with new parameters,
1048 			 * it is no longer interested in what may have
1049 			 * happened under the old parameters. If it is
1050 			 * interested, it can wait for the expiration,
1051 			 * delete the old timer definition, and then
1052 			 * add the new one.
1053 			 *
1054 			 * This has to be done while the kq is locked:
1055 			 *   - if enqueued, dequeue
1056 			 *   - make it no longer active
1057 			 *   - clear the count of expiration events
1058 			 */
1059 			kq = kn->kn_kq;
1060 			KQ_LOCK(kq);
1061 			if (kn->kn_status & KN_QUEUED)
1062 				knote_dequeue(kn);
1063 
1064 			kn->kn_status &= ~KN_ACTIVE;
1065 			kn->kn_data = 0;
1066 			KQ_UNLOCK(kq);
1067 
1068 			/* Reschedule timer based on new data/fflags */
1069 			kn->kn_sfflags = kev->fflags;
1070 			kn->kn_sdata = kev->data;
1071 			error = filt_timervalidate(kn, &to);
1072 			if (error != 0) {
1073 			  	kn->kn_flags |= EV_ERROR;
1074 				kn->kn_data = error;
1075 			} else
1076 			  	filt_timerstart(kn, to);
1077 		}
1078 		break;
1079 
1080         case EVENT_PROCESS:
1081 		*kev = kn->kn_kevent;
1082 		if (kn->kn_flags & EV_CLEAR) {
1083 			kn->kn_data = 0;
1084 			kn->kn_fflags = 0;
1085 		}
1086 		break;
1087 
1088 	default:
1089 		panic("filt_timertouch() - invalid type (%ld)", type);
1090 		break;
1091 	}
1092 }
1093 
1094 static int
filt_timer(struct knote * kn,long hint)1095 filt_timer(struct knote *kn, long hint)
1096 {
1097 
1098 	return (kn->kn_data != 0);
1099 }
1100 
1101 static int
filt_userattach(struct knote * kn)1102 filt_userattach(struct knote *kn)
1103 {
1104 
1105 	/*
1106 	 * EVFILT_USER knotes are not attached to anything in the kernel.
1107 	 */
1108 	kn->kn_hook = NULL;
1109 	if (kn->kn_fflags & NOTE_TRIGGER)
1110 		kn->kn_hookid = 1;
1111 	else
1112 		kn->kn_hookid = 0;
1113 	return (0);
1114 }
1115 
1116 static void
filt_userdetach(__unused struct knote * kn)1117 filt_userdetach(__unused struct knote *kn)
1118 {
1119 
1120 	/*
1121 	 * EVFILT_USER knotes are not attached to anything in the kernel.
1122 	 */
1123 }
1124 
1125 static int
filt_user(struct knote * kn,__unused long hint)1126 filt_user(struct knote *kn, __unused long hint)
1127 {
1128 
1129 	return (kn->kn_hookid);
1130 }
1131 
1132 static void
filt_usertouch(struct knote * kn,struct kevent * kev,u_long type)1133 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
1134 {
1135 	u_int ffctrl;
1136 
1137 	switch (type) {
1138 	case EVENT_REGISTER:
1139 		if (kev->fflags & NOTE_TRIGGER)
1140 			kn->kn_hookid = 1;
1141 
1142 		ffctrl = kev->fflags & NOTE_FFCTRLMASK;
1143 		kev->fflags &= NOTE_FFLAGSMASK;
1144 		switch (ffctrl) {
1145 		case NOTE_FFNOP:
1146 			break;
1147 
1148 		case NOTE_FFAND:
1149 			kn->kn_sfflags &= kev->fflags;
1150 			break;
1151 
1152 		case NOTE_FFOR:
1153 			kn->kn_sfflags |= kev->fflags;
1154 			break;
1155 
1156 		case NOTE_FFCOPY:
1157 			kn->kn_sfflags = kev->fflags;
1158 			break;
1159 
1160 		default:
1161 			/* XXX Return error? */
1162 			break;
1163 		}
1164 		kn->kn_sdata = kev->data;
1165 		if (kev->flags & EV_CLEAR) {
1166 			kn->kn_hookid = 0;
1167 			kn->kn_data = 0;
1168 			kn->kn_fflags = 0;
1169 		}
1170 		break;
1171 
1172         case EVENT_PROCESS:
1173 		*kev = kn->kn_kevent;
1174 		kev->fflags = kn->kn_sfflags;
1175 		kev->data = kn->kn_sdata;
1176 		if (kn->kn_flags & EV_CLEAR) {
1177 			kn->kn_hookid = 0;
1178 			kn->kn_data = 0;
1179 			kn->kn_fflags = 0;
1180 		}
1181 		break;
1182 
1183 	default:
1184 		panic("filt_usertouch() - invalid type (%ld)", type);
1185 		break;
1186 	}
1187 }
1188 
1189 int
sys_kqueue(struct thread * td,struct kqueue_args * uap)1190 sys_kqueue(struct thread *td, struct kqueue_args *uap)
1191 {
1192 
1193 	return (kern_kqueue(td, 0, NULL));
1194 }
1195 
1196 int
sys_kqueuex(struct thread * td,struct kqueuex_args * uap)1197 sys_kqueuex(struct thread *td, struct kqueuex_args *uap)
1198 {
1199 	int flags;
1200 
1201 	if ((uap->flags & ~(KQUEUE_CLOEXEC)) != 0)
1202 		return (EINVAL);
1203 	flags = 0;
1204 	if ((uap->flags & KQUEUE_CLOEXEC) != 0)
1205 		flags |= O_CLOEXEC;
1206 	return (kern_kqueue(td, flags, NULL));
1207 }
1208 
1209 static void
kqueue_init(struct kqueue * kq)1210 kqueue_init(struct kqueue *kq)
1211 {
1212 
1213 	mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
1214 	TAILQ_INIT(&kq->kq_head);
1215 	knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
1216 	TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
1217 }
1218 
1219 int
kern_kqueue(struct thread * td,int flags,struct filecaps * fcaps)1220 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
1221 {
1222 	struct filedesc *fdp;
1223 	struct kqueue *kq;
1224 	struct file *fp;
1225 	struct ucred *cred;
1226 	int fd, error;
1227 
1228 	fdp = td->td_proc->p_fd;
1229 	cred = td->td_ucred;
1230 	if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
1231 		return (ENOMEM);
1232 
1233 	error = falloc_caps(td, &fp, &fd, flags, fcaps);
1234 	if (error != 0) {
1235 		chgkqcnt(cred->cr_ruidinfo, -1, 0);
1236 		return (error);
1237 	}
1238 
1239 	/* An extra reference on `fp' has been held for us by falloc(). */
1240 	kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
1241 	kqueue_init(kq);
1242 	kq->kq_fdp = fdp;
1243 	kq->kq_cred = crhold(cred);
1244 
1245 	FILEDESC_XLOCK(fdp);
1246 	TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
1247 	FILEDESC_XUNLOCK(fdp);
1248 
1249 	finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
1250 	fdrop(fp, td);
1251 
1252 	td->td_retval[0] = fd;
1253 	return (0);
1254 }
1255 
1256 struct g_kevent_args {
1257 	int	fd;
1258 	const void *changelist;
1259 	int	nchanges;
1260 	void	*eventlist;
1261 	int	nevents;
1262 	const struct timespec *timeout;
1263 };
1264 
1265 int
sys_kevent(struct thread * td,struct kevent_args * uap)1266 sys_kevent(struct thread *td, struct kevent_args *uap)
1267 {
1268 	struct kevent_copyops k_ops = {
1269 		.arg = uap,
1270 		.k_copyout = kevent_copyout,
1271 		.k_copyin = kevent_copyin,
1272 		.kevent_size = sizeof(struct kevent),
1273 	};
1274 	struct g_kevent_args gk_args = {
1275 		.fd = uap->fd,
1276 		.changelist = uap->changelist,
1277 		.nchanges = uap->nchanges,
1278 		.eventlist = uap->eventlist,
1279 		.nevents = uap->nevents,
1280 		.timeout = uap->timeout,
1281 	};
1282 
1283 	return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent"));
1284 }
1285 
1286 static int
kern_kevent_generic(struct thread * td,struct g_kevent_args * uap,struct kevent_copyops * k_ops,const char * struct_name)1287 kern_kevent_generic(struct thread *td, struct g_kevent_args *uap,
1288     struct kevent_copyops *k_ops, const char *struct_name)
1289 {
1290 	struct timespec ts, *tsp;
1291 #ifdef KTRACE
1292 	struct kevent *eventlist = uap->eventlist;
1293 #endif
1294 	int error;
1295 
1296 	if (uap->timeout != NULL) {
1297 		error = copyin(uap->timeout, &ts, sizeof(ts));
1298 		if (error)
1299 			return (error);
1300 		tsp = &ts;
1301 	} else
1302 		tsp = NULL;
1303 
1304 #ifdef KTRACE
1305 	if (KTRPOINT(td, KTR_STRUCT_ARRAY))
1306 		ktrstructarray(struct_name, UIO_USERSPACE, uap->changelist,
1307 		    uap->nchanges, k_ops->kevent_size);
1308 #endif
1309 
1310 	error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1311 	    k_ops, tsp);
1312 
1313 #ifdef KTRACE
1314 	if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1315 		ktrstructarray(struct_name, UIO_USERSPACE, eventlist,
1316 		    td->td_retval[0], k_ops->kevent_size);
1317 #endif
1318 
1319 	return (error);
1320 }
1321 
1322 /*
1323  * Copy 'count' items into the destination list pointed to by uap->eventlist.
1324  */
1325 static int
kevent_copyout(void * arg,struct kevent * kevp,int count)1326 kevent_copyout(void *arg, struct kevent *kevp, int count)
1327 {
1328 	struct kevent_args *uap;
1329 	int error;
1330 
1331 	KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1332 	uap = (struct kevent_args *)arg;
1333 
1334 	error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1335 	if (error == 0)
1336 		uap->eventlist += count;
1337 	return (error);
1338 }
1339 
1340 /*
1341  * Copy 'count' items from the list pointed to by uap->changelist.
1342  */
1343 static int
kevent_copyin(void * arg,struct kevent * kevp,int count)1344 kevent_copyin(void *arg, struct kevent *kevp, int count)
1345 {
1346 	struct kevent_args *uap;
1347 	int error;
1348 
1349 	KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1350 	uap = (struct kevent_args *)arg;
1351 
1352 	error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1353 	if (error == 0)
1354 		uap->changelist += count;
1355 	return (error);
1356 }
1357 
1358 #ifdef COMPAT_FREEBSD11
1359 static int
kevent11_copyout(void * arg,struct kevent * kevp,int count)1360 kevent11_copyout(void *arg, struct kevent *kevp, int count)
1361 {
1362 	struct freebsd11_kevent_args *uap;
1363 	struct freebsd11_kevent kev11;
1364 	int error, i;
1365 
1366 	KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1367 	uap = (struct freebsd11_kevent_args *)arg;
1368 
1369 	for (i = 0; i < count; i++) {
1370 		kev11.ident = kevp->ident;
1371 		kev11.filter = kevp->filter;
1372 		kev11.flags = kevp->flags;
1373 		kev11.fflags = kevp->fflags;
1374 		kev11.data = kevp->data;
1375 		kev11.udata = kevp->udata;
1376 		error = copyout(&kev11, uap->eventlist, sizeof(kev11));
1377 		if (error != 0)
1378 			break;
1379 		uap->eventlist++;
1380 		kevp++;
1381 	}
1382 	return (error);
1383 }
1384 
1385 /*
1386  * Copy 'count' items from the list pointed to by uap->changelist.
1387  */
1388 static int
kevent11_copyin(void * arg,struct kevent * kevp,int count)1389 kevent11_copyin(void *arg, struct kevent *kevp, int count)
1390 {
1391 	struct freebsd11_kevent_args *uap;
1392 	struct freebsd11_kevent kev11;
1393 	int error, i;
1394 
1395 	KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1396 	uap = (struct freebsd11_kevent_args *)arg;
1397 
1398 	for (i = 0; i < count; i++) {
1399 		error = copyin(uap->changelist, &kev11, sizeof(kev11));
1400 		if (error != 0)
1401 			break;
1402 		kevp->ident = kev11.ident;
1403 		kevp->filter = kev11.filter;
1404 		kevp->flags = kev11.flags;
1405 		kevp->fflags = kev11.fflags;
1406 		kevp->data = (uintptr_t)kev11.data;
1407 		kevp->udata = kev11.udata;
1408 		bzero(&kevp->ext, sizeof(kevp->ext));
1409 		uap->changelist++;
1410 		kevp++;
1411 	}
1412 	return (error);
1413 }
1414 
1415 int
freebsd11_kevent(struct thread * td,struct freebsd11_kevent_args * uap)1416 freebsd11_kevent(struct thread *td, struct freebsd11_kevent_args *uap)
1417 {
1418 	struct kevent_copyops k_ops = {
1419 		.arg = uap,
1420 		.k_copyout = kevent11_copyout,
1421 		.k_copyin = kevent11_copyin,
1422 		.kevent_size = sizeof(struct freebsd11_kevent),
1423 	};
1424 	struct g_kevent_args gk_args = {
1425 		.fd = uap->fd,
1426 		.changelist = uap->changelist,
1427 		.nchanges = uap->nchanges,
1428 		.eventlist = uap->eventlist,
1429 		.nevents = uap->nevents,
1430 		.timeout = uap->timeout,
1431 	};
1432 
1433 	return (kern_kevent_generic(td, &gk_args, &k_ops, "freebsd11_kevent"));
1434 }
1435 #endif
1436 
1437 int
kern_kevent(struct thread * td,int fd,int nchanges,int nevents,struct kevent_copyops * k_ops,const struct timespec * timeout)1438 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1439     struct kevent_copyops *k_ops, const struct timespec *timeout)
1440 {
1441 	cap_rights_t rights;
1442 	struct file *fp;
1443 	int error;
1444 
1445 	cap_rights_init_zero(&rights);
1446 	if (nchanges > 0)
1447 		cap_rights_set_one(&rights, CAP_KQUEUE_CHANGE);
1448 	if (nevents > 0)
1449 		cap_rights_set_one(&rights, CAP_KQUEUE_EVENT);
1450 	error = fget(td, fd, &rights, &fp);
1451 	if (error != 0)
1452 		return (error);
1453 
1454 	error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1455 	fdrop(fp, td);
1456 
1457 	return (error);
1458 }
1459 
1460 static int
kqueue_kevent(struct kqueue * kq,struct thread * td,int nchanges,int nevents,struct kevent_copyops * k_ops,const struct timespec * timeout)1461 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1462     struct kevent_copyops *k_ops, const struct timespec *timeout)
1463 {
1464 	struct kevent keva[KQ_NEVENTS];
1465 	struct kevent *kevp, *changes;
1466 	int i, n, nerrors, error;
1467 
1468 	if (nchanges < 0)
1469 		return (EINVAL);
1470 
1471 	nerrors = 0;
1472 	while (nchanges > 0) {
1473 		n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1474 		error = k_ops->k_copyin(k_ops->arg, keva, n);
1475 		if (error)
1476 			return (error);
1477 		changes = keva;
1478 		for (i = 0; i < n; i++) {
1479 			kevp = &changes[i];
1480 			if (!kevp->filter)
1481 				continue;
1482 			kevp->flags &= ~EV_SYSFLAGS;
1483 			error = kqueue_register(kq, kevp, td, M_WAITOK);
1484 			if (error || (kevp->flags & EV_RECEIPT)) {
1485 				if (nevents == 0)
1486 					return (error);
1487 				kevp->flags = EV_ERROR;
1488 				kevp->data = error;
1489 				(void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1490 				nevents--;
1491 				nerrors++;
1492 			}
1493 		}
1494 		nchanges -= n;
1495 	}
1496 	if (nerrors) {
1497 		td->td_retval[0] = nerrors;
1498 		return (0);
1499 	}
1500 
1501 	return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1502 }
1503 
1504 int
kern_kevent_fp(struct thread * td,struct file * fp,int nchanges,int nevents,struct kevent_copyops * k_ops,const struct timespec * timeout)1505 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1506     struct kevent_copyops *k_ops, const struct timespec *timeout)
1507 {
1508 	struct kqueue *kq;
1509 	int error;
1510 
1511 	error = kqueue_acquire(fp, &kq);
1512 	if (error != 0)
1513 		return (error);
1514 	error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1515 	kqueue_release(kq, 0);
1516 	return (error);
1517 }
1518 
1519 /*
1520  * Performs a kevent() call on a temporarily created kqueue. This can be
1521  * used to perform one-shot polling, similar to poll() and select().
1522  */
1523 int
kern_kevent_anonymous(struct thread * td,int nevents,struct kevent_copyops * k_ops)1524 kern_kevent_anonymous(struct thread *td, int nevents,
1525     struct kevent_copyops *k_ops)
1526 {
1527 	struct kqueue kq = {};
1528 	int error;
1529 
1530 	kqueue_init(&kq);
1531 	kq.kq_refcnt = 1;
1532 	error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1533 	kqueue_drain(&kq, td);
1534 	kqueue_destroy(&kq);
1535 	return (error);
1536 }
1537 
1538 int
kqueue_add_filteropts(int filt,const struct filterops * filtops)1539 kqueue_add_filteropts(int filt, const struct filterops *filtops)
1540 {
1541 	int error;
1542 
1543 	error = 0;
1544 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1545 		printf(
1546 "trying to add a filterop that is out of range: %d is beyond %d\n",
1547 		    ~filt, EVFILT_SYSCOUNT);
1548 		return EINVAL;
1549 	}
1550 	mtx_lock(&filterops_lock);
1551 	if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1552 	    sysfilt_ops[~filt].for_fop != NULL)
1553 		error = EEXIST;
1554 	else {
1555 		sysfilt_ops[~filt].for_fop = filtops;
1556 		sysfilt_ops[~filt].for_refcnt = 0;
1557 	}
1558 	mtx_unlock(&filterops_lock);
1559 
1560 	return (error);
1561 }
1562 
1563 int
kqueue_del_filteropts(int filt)1564 kqueue_del_filteropts(int filt)
1565 {
1566 	int error;
1567 
1568 	error = 0;
1569 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1570 		return EINVAL;
1571 
1572 	mtx_lock(&filterops_lock);
1573 	if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1574 	    sysfilt_ops[~filt].for_fop == NULL)
1575 		error = EINVAL;
1576 	else if (sysfilt_ops[~filt].for_refcnt != 0)
1577 		error = EBUSY;
1578 	else {
1579 		sysfilt_ops[~filt].for_fop = &null_filtops;
1580 		sysfilt_ops[~filt].for_refcnt = 0;
1581 	}
1582 	mtx_unlock(&filterops_lock);
1583 
1584 	return error;
1585 }
1586 
1587 static const struct filterops *
kqueue_fo_find(int filt)1588 kqueue_fo_find(int filt)
1589 {
1590 
1591 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1592 		return NULL;
1593 
1594 	if (sysfilt_ops[~filt].for_nolock)
1595 		return sysfilt_ops[~filt].for_fop;
1596 
1597 	mtx_lock(&filterops_lock);
1598 	sysfilt_ops[~filt].for_refcnt++;
1599 	if (sysfilt_ops[~filt].for_fop == NULL)
1600 		sysfilt_ops[~filt].for_fop = &null_filtops;
1601 	mtx_unlock(&filterops_lock);
1602 
1603 	return sysfilt_ops[~filt].for_fop;
1604 }
1605 
1606 static void
kqueue_fo_release(int filt)1607 kqueue_fo_release(int filt)
1608 {
1609 
1610 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1611 		return;
1612 
1613 	if (sysfilt_ops[~filt].for_nolock)
1614 		return;
1615 
1616 	mtx_lock(&filterops_lock);
1617 	KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1618 	    ("filter object refcount not valid on release"));
1619 	sysfilt_ops[~filt].for_refcnt--;
1620 	mtx_unlock(&filterops_lock);
1621 }
1622 
1623 /*
1624  * A ref to kq (obtained via kqueue_acquire) must be held.
1625  */
1626 static int
kqueue_register(struct kqueue * kq,struct kevent * kev,struct thread * td,int mflag)1627 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td,
1628     int mflag)
1629 {
1630 	const struct filterops *fops;
1631 	struct file *fp;
1632 	struct knote *kn, *tkn;
1633 	struct knlist *knl;
1634 	int error, filt, event;
1635 	int haskqglobal, filedesc_unlock;
1636 
1637 	if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1638 		return (EINVAL);
1639 
1640 	fp = NULL;
1641 	kn = NULL;
1642 	knl = NULL;
1643 	error = 0;
1644 	haskqglobal = 0;
1645 	filedesc_unlock = 0;
1646 
1647 	filt = kev->filter;
1648 	fops = kqueue_fo_find(filt);
1649 	if (fops == NULL)
1650 		return EINVAL;
1651 
1652 	if (kev->flags & EV_ADD) {
1653 		/* Reject an invalid flag pair early */
1654 		if (kev->flags & EV_KEEPUDATA) {
1655 			tkn = NULL;
1656 			error = EINVAL;
1657 			goto done;
1658 		}
1659 
1660 		/*
1661 		 * Prevent waiting with locks.  Non-sleepable
1662 		 * allocation failures are handled in the loop, only
1663 		 * if the spare knote appears to be actually required.
1664 		 */
1665 		tkn = knote_alloc(mflag);
1666 	} else {
1667 		tkn = NULL;
1668 	}
1669 
1670 findkn:
1671 	if (fops->f_isfd) {
1672 		KASSERT(td != NULL, ("td is NULL"));
1673 		if (kev->ident > INT_MAX)
1674 			error = EBADF;
1675 		else
1676 			error = fget(td, kev->ident, &cap_event_rights, &fp);
1677 		if (error)
1678 			goto done;
1679 
1680 		if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1681 		    kev->ident, M_NOWAIT) != 0) {
1682 			/* try again */
1683 			fdrop(fp, td);
1684 			fp = NULL;
1685 			error = kqueue_expand(kq, fops, kev->ident, mflag);
1686 			if (error)
1687 				goto done;
1688 			goto findkn;
1689 		}
1690 
1691 		if (fp->f_type == DTYPE_KQUEUE) {
1692 			/*
1693 			 * If we add some intelligence about what we are doing,
1694 			 * we should be able to support events on ourselves.
1695 			 * We need to know when we are doing this to prevent
1696 			 * getting both the knlist lock and the kq lock since
1697 			 * they are the same thing.
1698 			 */
1699 			if (fp->f_data == kq) {
1700 				error = EINVAL;
1701 				goto done;
1702 			}
1703 
1704 			/*
1705 			 * Pre-lock the filedesc before the global
1706 			 * lock mutex, see the comment in
1707 			 * kqueue_close().
1708 			 */
1709 			FILEDESC_XLOCK(td->td_proc->p_fd);
1710 			filedesc_unlock = 1;
1711 			KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1712 		}
1713 
1714 		KQ_LOCK(kq);
1715 		if (kev->ident < kq->kq_knlistsize) {
1716 			SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1717 				if (kev->filter == kn->kn_filter)
1718 					break;
1719 		}
1720 	} else {
1721 		if ((kev->flags & EV_ADD) == EV_ADD) {
1722 			error = kqueue_expand(kq, fops, kev->ident, mflag);
1723 			if (error != 0)
1724 				goto done;
1725 		}
1726 
1727 		KQ_LOCK(kq);
1728 
1729 		/*
1730 		 * If possible, find an existing knote to use for this kevent.
1731 		 */
1732 		if ((kev->filter == EVFILT_PROC || kev->filter == EVFILT_JAIL)
1733 		    && (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1734 			/* This is an internal creation of a process tracking
1735 			 * note. Don't attempt to coalesce this with an
1736 			 * existing note.
1737 			 */
1738 			;
1739 		} else if (kq->kq_knhashmask != 0) {
1740 			struct klist *list;
1741 
1742 			list = &kq->kq_knhash[
1743 			    KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1744 			SLIST_FOREACH(kn, list, kn_link)
1745 				if (kev->ident == kn->kn_id &&
1746 				    kev->filter == kn->kn_filter)
1747 					break;
1748 		}
1749 	}
1750 
1751 	/* knote is in the process of changing, wait for it to stabilize. */
1752 	if (kn != NULL && kn_in_flux(kn)) {
1753 		KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1754 		if (filedesc_unlock) {
1755 			FILEDESC_XUNLOCK(td->td_proc->p_fd);
1756 			filedesc_unlock = 0;
1757 		}
1758 		kq->kq_state |= KQ_FLUXWAIT;
1759 		msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1760 		if (fp != NULL) {
1761 			fdrop(fp, td);
1762 			fp = NULL;
1763 		}
1764 		goto findkn;
1765 	}
1766 
1767 	/*
1768 	 * kn now contains the matching knote, or NULL if no match
1769 	 */
1770 	if (kn == NULL) {
1771 		if (kev->flags & EV_ADD) {
1772 			kn = tkn;
1773 			tkn = NULL;
1774 			if (kn == NULL) {
1775 				KQ_UNLOCK(kq);
1776 				error = ENOMEM;
1777 				goto done;
1778 			}
1779 			kn->kn_fp = fp;
1780 			kn->kn_kq = kq;
1781 			kn->kn_fop = fops;
1782 			/*
1783 			 * apply reference counts to knote structure, and
1784 			 * do not release it at the end of this routine.
1785 			 */
1786 			fops = NULL;
1787 			fp = NULL;
1788 
1789 			kn->kn_sfflags = kev->fflags;
1790 			kn->kn_sdata = kev->data;
1791 			kev->fflags = 0;
1792 			kev->data = 0;
1793 			kn->kn_kevent = *kev;
1794 			kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1795 			    EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1796 			kn->kn_status = KN_DETACHED;
1797 			if ((kev->flags & EV_DISABLE) != 0)
1798 				kn->kn_status |= KN_DISABLED;
1799 			kn_enter_flux(kn);
1800 
1801 			error = knote_attach(kn, kq);
1802 			KQ_UNLOCK(kq);
1803 			if (error != 0) {
1804 				tkn = kn;
1805 				goto done;
1806 			}
1807 
1808 			if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1809 				knote_drop_detached(kn, td);
1810 				goto done;
1811 			}
1812 			knl = kn_list_lock(kn);
1813 			goto done_ev_add;
1814 		} else {
1815 			/* No matching knote and the EV_ADD flag is not set. */
1816 			KQ_UNLOCK(kq);
1817 			error = ENOENT;
1818 			goto done;
1819 		}
1820 	}
1821 
1822 	if (kev->flags & EV_DELETE) {
1823 		kn_enter_flux(kn);
1824 		KQ_UNLOCK(kq);
1825 		knote_drop(kn, td);
1826 		goto done;
1827 	}
1828 
1829 	if (kev->flags & EV_FORCEONESHOT) {
1830 		kn->kn_flags |= EV_ONESHOT;
1831 		KNOTE_ACTIVATE(kn, 1);
1832 	}
1833 
1834 	if ((kev->flags & EV_ENABLE) != 0)
1835 		kn->kn_status &= ~KN_DISABLED;
1836 	else if ((kev->flags & EV_DISABLE) != 0)
1837 		kn->kn_status |= KN_DISABLED;
1838 
1839 	/*
1840 	 * The user may change some filter values after the initial EV_ADD,
1841 	 * but doing so will not reset any filter which has already been
1842 	 * triggered.
1843 	 */
1844 	kn->kn_status |= KN_SCAN;
1845 	kn_enter_flux(kn);
1846 	KQ_UNLOCK(kq);
1847 	knl = kn_list_lock(kn);
1848 	if ((kev->flags & EV_KEEPUDATA) == 0)
1849 		kn->kn_kevent.udata = kev->udata;
1850 	if (!fops->f_isfd && fops->f_touch != NULL) {
1851 		fops->f_touch(kn, kev, EVENT_REGISTER);
1852 	} else {
1853 		kn->kn_sfflags = kev->fflags;
1854 		kn->kn_sdata = kev->data;
1855 	}
1856 
1857 done_ev_add:
1858 	/*
1859 	 * We can get here with kn->kn_knlist == NULL.  This can happen when
1860 	 * the initial attach event decides that the event is "completed"
1861 	 * already, e.g., filt_procattach() is called on a zombie process.  It
1862 	 * will call filt_proc() which will remove it from the list, and NULL
1863 	 * kn_knlist.
1864 	 *
1865 	 * KN_DISABLED will be stable while the knote is in flux, so the
1866 	 * unlocked read will not race with an update.
1867 	 */
1868 	if ((kn->kn_status & KN_DISABLED) == 0)
1869 		event = kn->kn_fop->f_event(kn, 0);
1870 	else
1871 		event = 0;
1872 
1873 	KQ_LOCK(kq);
1874 	if (event)
1875 		kn->kn_status |= KN_ACTIVE;
1876 	if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1877 	    KN_ACTIVE)
1878 		knote_enqueue(kn);
1879 	kn->kn_status &= ~KN_SCAN;
1880 	kn_leave_flux(kn);
1881 	kn_list_unlock(knl);
1882 	KQ_UNLOCK_FLUX(kq);
1883 
1884 done:
1885 	KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1886 	if (filedesc_unlock)
1887 		FILEDESC_XUNLOCK(td->td_proc->p_fd);
1888 	if (fp != NULL)
1889 		fdrop(fp, td);
1890 	knote_free(tkn);
1891 	if (fops != NULL)
1892 		kqueue_fo_release(filt);
1893 	return (error);
1894 }
1895 
1896 static int
kqueue_acquire(struct file * fp,struct kqueue ** kqp)1897 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1898 {
1899 	int error;
1900 	struct kqueue *kq;
1901 
1902 	error = 0;
1903 
1904 	kq = fp->f_data;
1905 	if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1906 		return (EINVAL);
1907 	*kqp = kq;
1908 	KQ_LOCK(kq);
1909 	if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1910 		KQ_UNLOCK(kq);
1911 		return (EBADF);
1912 	}
1913 	kq->kq_refcnt++;
1914 	KQ_UNLOCK(kq);
1915 
1916 	return error;
1917 }
1918 
1919 static void
kqueue_release(struct kqueue * kq,int locked)1920 kqueue_release(struct kqueue *kq, int locked)
1921 {
1922 	if (locked)
1923 		KQ_OWNED(kq);
1924 	else
1925 		KQ_LOCK(kq);
1926 	kq->kq_refcnt--;
1927 	if (kq->kq_refcnt == 1)
1928 		wakeup(&kq->kq_refcnt);
1929 	if (!locked)
1930 		KQ_UNLOCK(kq);
1931 }
1932 
1933 static void
ast_kqueue(struct thread * td,int tda __unused)1934 ast_kqueue(struct thread *td, int tda __unused)
1935 {
1936 	taskqueue_quiesce(taskqueue_kqueue_ctx);
1937 }
1938 
1939 static void
kqueue_schedtask(struct kqueue * kq)1940 kqueue_schedtask(struct kqueue *kq)
1941 {
1942 	KQ_OWNED(kq);
1943 	KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1944 	    ("scheduling kqueue task while draining"));
1945 
1946 	if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1947 		taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1948 		kq->kq_state |= KQ_TASKSCHED;
1949 		ast_sched(curthread, TDA_KQUEUE);
1950 	}
1951 }
1952 
1953 /*
1954  * Expand the kq to make sure we have storage for fops/ident pair.
1955  *
1956  * Return 0 on success (or no work necessary), return errno on failure.
1957  */
1958 static int
kqueue_expand(struct kqueue * kq,const struct filterops * fops,uintptr_t ident,int mflag)1959 kqueue_expand(struct kqueue *kq, const struct filterops *fops, uintptr_t ident,
1960     int mflag)
1961 {
1962 	struct klist *list, *tmp_knhash, *to_free;
1963 	u_long tmp_knhashmask;
1964 	int error, fd, size;
1965 
1966 	KQ_NOTOWNED(kq);
1967 
1968 	error = 0;
1969 	to_free = NULL;
1970 	if (fops->f_isfd) {
1971 		fd = ident;
1972 		if (kq->kq_knlistsize <= fd) {
1973 			size = kq->kq_knlistsize;
1974 			while (size <= fd)
1975 				size += KQEXTENT;
1976 			list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1977 			if (list == NULL)
1978 				return ENOMEM;
1979 			KQ_LOCK(kq);
1980 			if ((kq->kq_state & KQ_CLOSING) != 0) {
1981 				to_free = list;
1982 				error = EBADF;
1983 			} else if (kq->kq_knlistsize > fd) {
1984 				to_free = list;
1985 			} else {
1986 				if (kq->kq_knlist != NULL) {
1987 					bcopy(kq->kq_knlist, list,
1988 					    kq->kq_knlistsize * sizeof(*list));
1989 					to_free = kq->kq_knlist;
1990 					kq->kq_knlist = NULL;
1991 				}
1992 				bzero((caddr_t)list +
1993 				    kq->kq_knlistsize * sizeof(*list),
1994 				    (size - kq->kq_knlistsize) * sizeof(*list));
1995 				kq->kq_knlistsize = size;
1996 				kq->kq_knlist = list;
1997 			}
1998 			KQ_UNLOCK(kq);
1999 		}
2000 	} else {
2001 		if (kq->kq_knhashmask == 0) {
2002 			tmp_knhash = hashinit_flags(KN_HASHSIZE, M_KQUEUE,
2003 			    &tmp_knhashmask, (mflag & M_WAITOK) != 0 ?
2004 			    HASH_WAITOK : HASH_NOWAIT);
2005 			if (tmp_knhash == NULL)
2006 				return (ENOMEM);
2007 			KQ_LOCK(kq);
2008 			if ((kq->kq_state & KQ_CLOSING) != 0) {
2009 				to_free = tmp_knhash;
2010 				error = EBADF;
2011 			} else if (kq->kq_knhashmask == 0) {
2012 				kq->kq_knhash = tmp_knhash;
2013 				kq->kq_knhashmask = tmp_knhashmask;
2014 			} else {
2015 				to_free = tmp_knhash;
2016 			}
2017 			KQ_UNLOCK(kq);
2018 		}
2019 	}
2020 	free(to_free, M_KQUEUE);
2021 
2022 	KQ_NOTOWNED(kq);
2023 	return (error);
2024 }
2025 
2026 static void
kqueue_task(void * arg,int pending)2027 kqueue_task(void *arg, int pending)
2028 {
2029 	struct kqueue *kq;
2030 	int haskqglobal;
2031 
2032 	haskqglobal = 0;
2033 	kq = arg;
2034 
2035 	KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
2036 	KQ_LOCK(kq);
2037 
2038 	KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
2039 
2040 	kq->kq_state &= ~KQ_TASKSCHED;
2041 	if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
2042 		wakeup(&kq->kq_state);
2043 	}
2044 	KQ_UNLOCK(kq);
2045 	KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2046 }
2047 
2048 /*
2049  * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
2050  * We treat KN_MARKER knotes as if they are in flux.
2051  */
2052 static int
kqueue_scan(struct kqueue * kq,int maxevents,struct kevent_copyops * k_ops,const struct timespec * tsp,struct kevent * keva,struct thread * td)2053 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
2054     const struct timespec *tsp, struct kevent *keva, struct thread *td)
2055 {
2056 	struct kevent *kevp;
2057 	struct knote *kn, *marker;
2058 	struct knlist *knl;
2059 	sbintime_t asbt, rsbt;
2060 	int count, error, haskqglobal, influx, nkev, touch;
2061 
2062 	count = maxevents;
2063 	nkev = 0;
2064 	error = 0;
2065 	haskqglobal = 0;
2066 
2067 	if (maxevents == 0)
2068 		goto done_nl;
2069 	if (maxevents < 0) {
2070 		error = EINVAL;
2071 		goto done_nl;
2072 	}
2073 
2074 	rsbt = 0;
2075 	if (tsp != NULL) {
2076 		if (!timespecvalid_interval(tsp)) {
2077 			error = EINVAL;
2078 			goto done_nl;
2079 		}
2080 		if (timespecisset(tsp)) {
2081 			if (tsp->tv_sec <= INT32_MAX) {
2082 				rsbt = tstosbt(*tsp);
2083 				if (TIMESEL(&asbt, rsbt))
2084 					asbt += tc_tick_sbt;
2085 				if (asbt <= SBT_MAX - rsbt)
2086 					asbt += rsbt;
2087 				else
2088 					asbt = 0;
2089 				rsbt >>= tc_precexp;
2090 			} else
2091 				asbt = 0;
2092 		} else
2093 			asbt = -1;
2094 	} else
2095 		asbt = 0;
2096 	marker = knote_alloc(M_WAITOK);
2097 	marker->kn_status = KN_MARKER;
2098 	KQ_LOCK(kq);
2099 
2100 retry:
2101 	kevp = keva;
2102 	if (kq->kq_count == 0) {
2103 		if (asbt == -1) {
2104 			error = EWOULDBLOCK;
2105 		} else {
2106 			kq->kq_state |= KQ_SLEEP;
2107 			error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
2108 			    "kqread", asbt, rsbt, C_ABSOLUTE);
2109 		}
2110 		if (error == 0)
2111 			goto retry;
2112 		/* don't restart after signals... */
2113 		if (error == ERESTART)
2114 			error = EINTR;
2115 		else if (error == EWOULDBLOCK)
2116 			error = 0;
2117 		goto done;
2118 	}
2119 
2120 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
2121 	influx = 0;
2122 	while (count) {
2123 		KQ_OWNED(kq);
2124 		kn = TAILQ_FIRST(&kq->kq_head);
2125 
2126 		if ((kn->kn_status == KN_MARKER && kn != marker) ||
2127 		    kn_in_flux(kn)) {
2128 			if (influx) {
2129 				influx = 0;
2130 				KQ_FLUX_WAKEUP(kq);
2131 			}
2132 			kq->kq_state |= KQ_FLUXWAIT;
2133 			error = msleep(kq, &kq->kq_lock, PSOCK,
2134 			    "kqflxwt", 0);
2135 			continue;
2136 		}
2137 
2138 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2139 		if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
2140 			kn->kn_status &= ~KN_QUEUED;
2141 			kq->kq_count--;
2142 			continue;
2143 		}
2144 		if (kn == marker) {
2145 			KQ_FLUX_WAKEUP(kq);
2146 			if (count == maxevents)
2147 				goto retry;
2148 			goto done;
2149 		}
2150 		KASSERT(!kn_in_flux(kn),
2151 		    ("knote %p is unexpectedly in flux", kn));
2152 
2153 		if ((kn->kn_flags & EV_DROP) == EV_DROP) {
2154 			kn->kn_status &= ~KN_QUEUED;
2155 			kn_enter_flux(kn);
2156 			kq->kq_count--;
2157 			KQ_UNLOCK(kq);
2158 			/*
2159 			 * We don't need to lock the list since we've
2160 			 * marked it as in flux.
2161 			 */
2162 			knote_drop(kn, td);
2163 			KQ_LOCK(kq);
2164 			continue;
2165 		} else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
2166 			kn->kn_status &= ~KN_QUEUED;
2167 			kn_enter_flux(kn);
2168 			kq->kq_count--;
2169 			KQ_UNLOCK(kq);
2170 			/*
2171 			 * We don't need to lock the list since we've
2172 			 * marked the knote as being in flux.
2173 			 */
2174 			*kevp = kn->kn_kevent;
2175 			knote_drop(kn, td);
2176 			KQ_LOCK(kq);
2177 			kn = NULL;
2178 		} else {
2179 			kn->kn_status |= KN_SCAN;
2180 			kn_enter_flux(kn);
2181 			KQ_UNLOCK(kq);
2182 			if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
2183 				KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
2184 			knl = kn_list_lock(kn);
2185 			if (kn->kn_fop->f_event(kn, 0) == 0) {
2186 				KQ_LOCK(kq);
2187 				KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2188 				kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
2189 				    KN_SCAN);
2190 				kn_leave_flux(kn);
2191 				kq->kq_count--;
2192 				kn_list_unlock(knl);
2193 				influx = 1;
2194 				continue;
2195 			}
2196 			touch = (!kn->kn_fop->f_isfd &&
2197 			    kn->kn_fop->f_touch != NULL);
2198 			if (touch)
2199 				kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
2200 			else
2201 				*kevp = kn->kn_kevent;
2202 			KQ_LOCK(kq);
2203 			KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2204 			if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
2205 				/*
2206 				 * Manually clear knotes who weren't
2207 				 * 'touch'ed.
2208 				 */
2209 				if (touch == 0 && kn->kn_flags & EV_CLEAR) {
2210 					kn->kn_data = 0;
2211 					kn->kn_fflags = 0;
2212 				}
2213 				if (kn->kn_flags & EV_DISPATCH)
2214 					kn->kn_status |= KN_DISABLED;
2215 				kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
2216 				kq->kq_count--;
2217 			} else
2218 				TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2219 
2220 			kn->kn_status &= ~KN_SCAN;
2221 			kn_leave_flux(kn);
2222 			kn_list_unlock(knl);
2223 			influx = 1;
2224 		}
2225 
2226 		/* we are returning a copy to the user */
2227 		kevp++;
2228 		nkev++;
2229 		count--;
2230 
2231 		if (nkev == KQ_NEVENTS) {
2232 			influx = 0;
2233 			KQ_UNLOCK_FLUX(kq);
2234 			error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2235 			nkev = 0;
2236 			kevp = keva;
2237 			KQ_LOCK(kq);
2238 			if (error)
2239 				break;
2240 		}
2241 	}
2242 	TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
2243 done:
2244 	KQ_OWNED(kq);
2245 	KQ_UNLOCK_FLUX(kq);
2246 	knote_free(marker);
2247 done_nl:
2248 	KQ_NOTOWNED(kq);
2249 	if (nkev != 0)
2250 		error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2251 	td->td_retval[0] = maxevents - count;
2252 	return (error);
2253 }
2254 
2255 /*ARGSUSED*/
2256 static int
kqueue_ioctl(struct file * fp,u_long cmd,void * data,struct ucred * active_cred,struct thread * td)2257 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
2258 	struct ucred *active_cred, struct thread *td)
2259 {
2260 	/*
2261 	 * Enabling sigio causes two major problems:
2262 	 * 1) infinite recursion:
2263 	 * Synopsys: kevent is being used to track signals and have FIOASYNC
2264 	 * set.  On receipt of a signal this will cause a kqueue to recurse
2265 	 * into itself over and over.  Sending the sigio causes the kqueue
2266 	 * to become ready, which in turn posts sigio again, forever.
2267 	 * Solution: this can be solved by setting a flag in the kqueue that
2268 	 * we have a SIGIO in progress.
2269 	 * 2) locking problems:
2270 	 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
2271 	 * us above the proc and pgrp locks.
2272 	 * Solution: Post a signal using an async mechanism, being sure to
2273 	 * record a generation count in the delivery so that we do not deliver
2274 	 * a signal to the wrong process.
2275 	 *
2276 	 * Note, these two mechanisms are somewhat mutually exclusive!
2277 	 */
2278 #if 0
2279 	struct kqueue *kq;
2280 
2281 	kq = fp->f_data;
2282 	switch (cmd) {
2283 	case FIOASYNC:
2284 		if (*(int *)data) {
2285 			kq->kq_state |= KQ_ASYNC;
2286 		} else {
2287 			kq->kq_state &= ~KQ_ASYNC;
2288 		}
2289 		return (0);
2290 
2291 	case FIOSETOWN:
2292 		return (fsetown(*(int *)data, &kq->kq_sigio));
2293 
2294 	case FIOGETOWN:
2295 		*(int *)data = fgetown(&kq->kq_sigio);
2296 		return (0);
2297 	}
2298 #endif
2299 
2300 	return (ENOTTY);
2301 }
2302 
2303 /*ARGSUSED*/
2304 static int
kqueue_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)2305 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
2306 	struct thread *td)
2307 {
2308 	struct kqueue *kq;
2309 	int revents = 0;
2310 	int error;
2311 
2312 	if ((error = kqueue_acquire(fp, &kq)))
2313 		return POLLERR;
2314 
2315 	KQ_LOCK(kq);
2316 	if (events & (POLLIN | POLLRDNORM)) {
2317 		if (kq->kq_count) {
2318 			revents |= events & (POLLIN | POLLRDNORM);
2319 		} else {
2320 			selrecord(td, &kq->kq_sel);
2321 			if (SEL_WAITING(&kq->kq_sel))
2322 				kq->kq_state |= KQ_SEL;
2323 		}
2324 	}
2325 	kqueue_release(kq, 1);
2326 	KQ_UNLOCK(kq);
2327 	return (revents);
2328 }
2329 
2330 /*ARGSUSED*/
2331 static int
kqueue_stat(struct file * fp,struct stat * st,struct ucred * active_cred)2332 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred)
2333 {
2334 
2335 	bzero((void *)st, sizeof *st);
2336 	/*
2337 	 * We no longer return kq_count because the unlocked value is useless.
2338 	 * If you spent all this time getting the count, why not spend your
2339 	 * syscall better by calling kevent?
2340 	 *
2341 	 * XXX - This is needed for libc_r.
2342 	 */
2343 	st->st_mode = S_IFIFO;
2344 	return (0);
2345 }
2346 
2347 static void
kqueue_drain(struct kqueue * kq,struct thread * td)2348 kqueue_drain(struct kqueue *kq, struct thread *td)
2349 {
2350 	struct knote *kn;
2351 	int i;
2352 
2353 	KQ_LOCK(kq);
2354 
2355 	KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
2356 	    ("kqueue already closing"));
2357 	kq->kq_state |= KQ_CLOSING;
2358 	if (kq->kq_refcnt > 1)
2359 		msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
2360 
2361 	KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
2362 
2363 	KASSERT(knlist_empty(&kq->kq_sel.si_note),
2364 	    ("kqueue's knlist not empty"));
2365 
2366 	for (i = 0; i < kq->kq_knlistsize; i++) {
2367 		while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
2368 			if (kn_in_flux(kn)) {
2369 				kq->kq_state |= KQ_FLUXWAIT;
2370 				msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
2371 				continue;
2372 			}
2373 			kn_enter_flux(kn);
2374 			KQ_UNLOCK(kq);
2375 			knote_drop(kn, td);
2376 			KQ_LOCK(kq);
2377 		}
2378 	}
2379 	if (kq->kq_knhashmask != 0) {
2380 		for (i = 0; i <= kq->kq_knhashmask; i++) {
2381 			while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
2382 				if (kn_in_flux(kn)) {
2383 					kq->kq_state |= KQ_FLUXWAIT;
2384 					msleep(kq, &kq->kq_lock, PSOCK,
2385 					       "kqclo2", 0);
2386 					continue;
2387 				}
2388 				kn_enter_flux(kn);
2389 				KQ_UNLOCK(kq);
2390 				knote_drop(kn, td);
2391 				KQ_LOCK(kq);
2392 			}
2393 		}
2394 	}
2395 
2396 	if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
2397 		kq->kq_state |= KQ_TASKDRAIN;
2398 		msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2399 	}
2400 
2401 	if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2402 		selwakeuppri(&kq->kq_sel, PSOCK);
2403 		if (!SEL_WAITING(&kq->kq_sel))
2404 			kq->kq_state &= ~KQ_SEL;
2405 	}
2406 
2407 	KQ_UNLOCK(kq);
2408 }
2409 
2410 static void
kqueue_destroy(struct kqueue * kq)2411 kqueue_destroy(struct kqueue *kq)
2412 {
2413 
2414 	KASSERT(kq->kq_fdp == NULL,
2415 	    ("kqueue still attached to a file descriptor"));
2416 	seldrain(&kq->kq_sel);
2417 	knlist_destroy(&kq->kq_sel.si_note);
2418 	mtx_destroy(&kq->kq_lock);
2419 
2420 	if (kq->kq_knhash != NULL)
2421 		free(kq->kq_knhash, M_KQUEUE);
2422 	if (kq->kq_knlist != NULL)
2423 		free(kq->kq_knlist, M_KQUEUE);
2424 
2425 	funsetown(&kq->kq_sigio);
2426 }
2427 
2428 /*ARGSUSED*/
2429 static int
kqueue_close(struct file * fp,struct thread * td)2430 kqueue_close(struct file *fp, struct thread *td)
2431 {
2432 	struct kqueue *kq = fp->f_data;
2433 	struct filedesc *fdp;
2434 	int error;
2435 	int filedesc_unlock;
2436 
2437 	if ((error = kqueue_acquire(fp, &kq)))
2438 		return error;
2439 	kqueue_drain(kq, td);
2440 
2441 	/*
2442 	 * We could be called due to the knote_drop() doing fdrop(),
2443 	 * called from kqueue_register().  In this case the global
2444 	 * lock is owned, and filedesc sx is locked before, to not
2445 	 * take the sleepable lock after non-sleepable.
2446 	 */
2447 	fdp = kq->kq_fdp;
2448 	kq->kq_fdp = NULL;
2449 	if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2450 		FILEDESC_XLOCK(fdp);
2451 		filedesc_unlock = 1;
2452 	} else
2453 		filedesc_unlock = 0;
2454 	TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2455 	if (filedesc_unlock)
2456 		FILEDESC_XUNLOCK(fdp);
2457 
2458 	kqueue_destroy(kq);
2459 	chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2460 	crfree(kq->kq_cred);
2461 	free(kq, M_KQUEUE);
2462 	fp->f_data = NULL;
2463 
2464 	return (0);
2465 }
2466 
2467 static int
kqueue_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)2468 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2469 {
2470 	struct kqueue *kq = fp->f_data;
2471 
2472 	kif->kf_type = KF_TYPE_KQUEUE;
2473 	kif->kf_un.kf_kqueue.kf_kqueue_addr = (uintptr_t)kq;
2474 	kif->kf_un.kf_kqueue.kf_kqueue_count = kq->kq_count;
2475 	kif->kf_un.kf_kqueue.kf_kqueue_state = kq->kq_state;
2476 	return (0);
2477 }
2478 
2479 static void
kqueue_wakeup(struct kqueue * kq)2480 kqueue_wakeup(struct kqueue *kq)
2481 {
2482 	KQ_OWNED(kq);
2483 
2484 	if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2485 		kq->kq_state &= ~KQ_SLEEP;
2486 		wakeup(kq);
2487 	}
2488 	if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2489 		selwakeuppri(&kq->kq_sel, PSOCK);
2490 		if (!SEL_WAITING(&kq->kq_sel))
2491 			kq->kq_state &= ~KQ_SEL;
2492 	}
2493 	if (!knlist_empty(&kq->kq_sel.si_note))
2494 		kqueue_schedtask(kq);
2495 	if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2496 		pgsigio(&kq->kq_sigio, SIGIO, 0);
2497 	}
2498 }
2499 
2500 /*
2501  * Walk down a list of knotes, activating them if their event has triggered.
2502  *
2503  * There is a possibility to optimize in the case of one kq watching another.
2504  * Instead of scheduling a task to wake it up, you could pass enough state
2505  * down the chain to make up the parent kqueue.  Make this code functional
2506  * first.
2507  */
2508 void
knote(struct knlist * list,long hint,int lockflags)2509 knote(struct knlist *list, long hint, int lockflags)
2510 {
2511 	struct kqueue *kq;
2512 	struct knote *kn, *tkn;
2513 	int error;
2514 
2515 	if (list == NULL)
2516 		return;
2517 
2518 	KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2519 
2520 	if ((lockflags & KNF_LISTLOCKED) == 0)
2521 		list->kl_lock(list->kl_lockarg);
2522 
2523 	/*
2524 	 * If we unlock the list lock (and enter influx), we can
2525 	 * eliminate the kqueue scheduling, but this will introduce
2526 	 * four lock/unlock's for each knote to test.  Also, marker
2527 	 * would be needed to keep iteration position, since filters
2528 	 * or other threads could remove events.
2529 	 */
2530 	SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2531 		kq = kn->kn_kq;
2532 		KQ_LOCK(kq);
2533 		if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2534 			/*
2535 			 * Do not process the influx notes, except for
2536 			 * the influx coming from the kq unlock in the
2537 			 * kqueue_scan().  In the later case, we do
2538 			 * not interfere with the scan, since the code
2539 			 * fragment in kqueue_scan() locks the knlist,
2540 			 * and cannot proceed until we finished.
2541 			 */
2542 			KQ_UNLOCK(kq);
2543 		} else if ((lockflags & KNF_NOKQLOCK) != 0) {
2544 			kn_enter_flux(kn);
2545 			KQ_UNLOCK(kq);
2546 			error = kn->kn_fop->f_event(kn, hint);
2547 			KQ_LOCK(kq);
2548 			kn_leave_flux(kn);
2549 			if (error)
2550 				KNOTE_ACTIVATE(kn, 1);
2551 			KQ_UNLOCK_FLUX(kq);
2552 		} else {
2553 			if (kn->kn_fop->f_event(kn, hint))
2554 				KNOTE_ACTIVATE(kn, 1);
2555 			KQ_UNLOCK(kq);
2556 		}
2557 	}
2558 	if ((lockflags & KNF_LISTLOCKED) == 0)
2559 		list->kl_unlock(list->kl_lockarg);
2560 }
2561 
2562 /*
2563  * add a knote to a knlist
2564  */
2565 void
knlist_add(struct knlist * knl,struct knote * kn,int islocked)2566 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2567 {
2568 
2569 	KNL_ASSERT_LOCK(knl, islocked);
2570 	KQ_NOTOWNED(kn->kn_kq);
2571 	KASSERT(kn_in_flux(kn), ("knote %p not in flux", kn));
2572 	KASSERT((kn->kn_status & KN_DETACHED) != 0,
2573 	    ("knote %p was not detached", kn));
2574 	if (!islocked)
2575 		knl->kl_lock(knl->kl_lockarg);
2576 	SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2577 	if (!islocked)
2578 		knl->kl_unlock(knl->kl_lockarg);
2579 	KQ_LOCK(kn->kn_kq);
2580 	kn->kn_knlist = knl;
2581 	kn->kn_status &= ~KN_DETACHED;
2582 	KQ_UNLOCK(kn->kn_kq);
2583 }
2584 
2585 static void
knlist_remove_kq(struct knlist * knl,struct knote * kn,int knlislocked,int kqislocked)2586 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2587     int kqislocked)
2588 {
2589 
2590 	KASSERT(!kqislocked || knlislocked, ("kq locked w/o knl locked"));
2591 	KNL_ASSERT_LOCK(knl, knlislocked);
2592 	mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2593 	KASSERT(kqislocked || kn_in_flux(kn), ("knote %p not in flux", kn));
2594 	KASSERT((kn->kn_status & KN_DETACHED) == 0,
2595 	    ("knote %p was already detached", kn));
2596 	if (!knlislocked)
2597 		knl->kl_lock(knl->kl_lockarg);
2598 	SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2599 	kn->kn_knlist = NULL;
2600 	if (!knlislocked)
2601 		kn_list_unlock(knl);
2602 	if (!kqislocked)
2603 		KQ_LOCK(kn->kn_kq);
2604 	kn->kn_status |= KN_DETACHED;
2605 	if (!kqislocked)
2606 		KQ_UNLOCK(kn->kn_kq);
2607 }
2608 
2609 /*
2610  * remove knote from the specified knlist
2611  */
2612 void
knlist_remove(struct knlist * knl,struct knote * kn,int islocked)2613 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2614 {
2615 
2616 	knlist_remove_kq(knl, kn, islocked, 0);
2617 }
2618 
2619 int
knlist_empty(struct knlist * knl)2620 knlist_empty(struct knlist *knl)
2621 {
2622 
2623 	KNL_ASSERT_LOCKED(knl);
2624 	return (SLIST_EMPTY(&knl->kl_list));
2625 }
2626 
2627 static struct mtx knlist_lock;
2628 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2629     MTX_DEF);
2630 static void knlist_mtx_lock(void *arg);
2631 static void knlist_mtx_unlock(void *arg);
2632 
2633 static void
knlist_mtx_lock(void * arg)2634 knlist_mtx_lock(void *arg)
2635 {
2636 
2637 	mtx_lock((struct mtx *)arg);
2638 }
2639 
2640 static void
knlist_mtx_unlock(void * arg)2641 knlist_mtx_unlock(void *arg)
2642 {
2643 
2644 	mtx_unlock((struct mtx *)arg);
2645 }
2646 
2647 static void
knlist_mtx_assert_lock(void * arg,int what)2648 knlist_mtx_assert_lock(void *arg, int what)
2649 {
2650 
2651 	if (what == LA_LOCKED)
2652 		mtx_assert((struct mtx *)arg, MA_OWNED);
2653 	else
2654 		mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2655 }
2656 
2657 void
knlist_init(struct knlist * knl,void * lock,void (* kl_lock)(void *),void (* kl_unlock)(void *),void (* kl_assert_lock)(void *,int))2658 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2659     void (*kl_unlock)(void *),
2660     void (*kl_assert_lock)(void *, int))
2661 {
2662 
2663 	if (lock == NULL)
2664 		knl->kl_lockarg = &knlist_lock;
2665 	else
2666 		knl->kl_lockarg = lock;
2667 
2668 	if (kl_lock == NULL)
2669 		knl->kl_lock = knlist_mtx_lock;
2670 	else
2671 		knl->kl_lock = kl_lock;
2672 	if (kl_unlock == NULL)
2673 		knl->kl_unlock = knlist_mtx_unlock;
2674 	else
2675 		knl->kl_unlock = kl_unlock;
2676 	if (kl_assert_lock == NULL)
2677 		knl->kl_assert_lock = knlist_mtx_assert_lock;
2678 	else
2679 		knl->kl_assert_lock = kl_assert_lock;
2680 
2681 	knl->kl_autodestroy = 0;
2682 	SLIST_INIT(&knl->kl_list);
2683 }
2684 
2685 void
knlist_init_mtx(struct knlist * knl,struct mtx * lock)2686 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2687 {
2688 
2689 	knlist_init(knl, lock, NULL, NULL, NULL);
2690 }
2691 
2692 struct knlist *
knlist_alloc(struct mtx * lock)2693 knlist_alloc(struct mtx *lock)
2694 {
2695 	struct knlist *knl;
2696 
2697 	knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2698 	knlist_init_mtx(knl, lock);
2699 	return (knl);
2700 }
2701 
2702 void
knlist_destroy(struct knlist * knl)2703 knlist_destroy(struct knlist *knl)
2704 {
2705 
2706 	KASSERT(KNLIST_EMPTY(knl),
2707 	    ("destroying knlist %p with knotes on it", knl));
2708 }
2709 
2710 void
knlist_detach(struct knlist * knl)2711 knlist_detach(struct knlist *knl)
2712 {
2713 
2714 	KNL_ASSERT_LOCKED(knl);
2715 	knl->kl_autodestroy = 1;
2716 	if (knlist_empty(knl)) {
2717 		knlist_destroy(knl);
2718 		free(knl, M_KQUEUE);
2719 	}
2720 }
2721 
2722 /*
2723  * Even if we are locked, we may need to drop the lock to allow any influx
2724  * knotes time to "settle".
2725  */
2726 void
knlist_cleardel(struct knlist * knl,struct thread * td,int islocked,int killkn)2727 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2728 {
2729 	struct knote *kn, *kn2;
2730 	struct kqueue *kq;
2731 
2732 	KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2733 	if (islocked)
2734 		KNL_ASSERT_LOCKED(knl);
2735 	else {
2736 		KNL_ASSERT_UNLOCKED(knl);
2737 again:		/* need to reacquire lock since we have dropped it */
2738 		knl->kl_lock(knl->kl_lockarg);
2739 	}
2740 
2741 	SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2742 		kq = kn->kn_kq;
2743 		KQ_LOCK(kq);
2744 		if (kn_in_flux(kn)) {
2745 			KQ_UNLOCK(kq);
2746 			continue;
2747 		}
2748 		knlist_remove_kq(knl, kn, 1, 1);
2749 		if (killkn) {
2750 			kn_enter_flux(kn);
2751 			KQ_UNLOCK(kq);
2752 			knote_drop_detached(kn, td);
2753 		} else {
2754 			/* Make sure cleared knotes disappear soon */
2755 			kn->kn_flags |= EV_EOF | EV_ONESHOT;
2756 			KQ_UNLOCK(kq);
2757 		}
2758 		kq = NULL;
2759 	}
2760 
2761 	if (!SLIST_EMPTY(&knl->kl_list)) {
2762 		/* there are still in flux knotes remaining */
2763 		kn = SLIST_FIRST(&knl->kl_list);
2764 		kq = kn->kn_kq;
2765 		KQ_LOCK(kq);
2766 		KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2767 		knl->kl_unlock(knl->kl_lockarg);
2768 		kq->kq_state |= KQ_FLUXWAIT;
2769 		msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2770 		kq = NULL;
2771 		goto again;
2772 	}
2773 
2774 	if (islocked)
2775 		KNL_ASSERT_LOCKED(knl);
2776 	else {
2777 		knl->kl_unlock(knl->kl_lockarg);
2778 		KNL_ASSERT_UNLOCKED(knl);
2779 	}
2780 }
2781 
2782 /*
2783  * Remove all knotes referencing a specified fd must be called with FILEDESC
2784  * lock.  This prevents a race where a new fd comes along and occupies the
2785  * entry and we attach a knote to the fd.
2786  */
2787 void
knote_fdclose(struct thread * td,int fd)2788 knote_fdclose(struct thread *td, int fd)
2789 {
2790 	struct filedesc *fdp = td->td_proc->p_fd;
2791 	struct kqueue *kq;
2792 	struct knote *kn;
2793 	int influx;
2794 
2795 	FILEDESC_XLOCK_ASSERT(fdp);
2796 
2797 	/*
2798 	 * We shouldn't have to worry about new kevents appearing on fd
2799 	 * since filedesc is locked.
2800 	 */
2801 	TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2802 		KQ_LOCK(kq);
2803 
2804 again:
2805 		influx = 0;
2806 		while (kq->kq_knlistsize > fd &&
2807 		    (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2808 			if (kn_in_flux(kn)) {
2809 				/* someone else might be waiting on our knote */
2810 				if (influx)
2811 					wakeup(kq);
2812 				kq->kq_state |= KQ_FLUXWAIT;
2813 				msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2814 				goto again;
2815 			}
2816 			kn_enter_flux(kn);
2817 			KQ_UNLOCK(kq);
2818 			influx = 1;
2819 			knote_drop(kn, td);
2820 			KQ_LOCK(kq);
2821 		}
2822 		KQ_UNLOCK_FLUX(kq);
2823 	}
2824 }
2825 
2826 static int
knote_attach(struct knote * kn,struct kqueue * kq)2827 knote_attach(struct knote *kn, struct kqueue *kq)
2828 {
2829 	struct klist *list;
2830 
2831 	KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2832 	KQ_OWNED(kq);
2833 
2834 	if ((kq->kq_state & KQ_CLOSING) != 0)
2835 		return (EBADF);
2836 	if (kn->kn_fop->f_isfd) {
2837 		if (kn->kn_id >= kq->kq_knlistsize)
2838 			return (ENOMEM);
2839 		list = &kq->kq_knlist[kn->kn_id];
2840 	} else {
2841 		if (kq->kq_knhash == NULL)
2842 			return (ENOMEM);
2843 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2844 	}
2845 	SLIST_INSERT_HEAD(list, kn, kn_link);
2846 	return (0);
2847 }
2848 
2849 static void
knote_drop(struct knote * kn,struct thread * td)2850 knote_drop(struct knote *kn, struct thread *td)
2851 {
2852 
2853 	if ((kn->kn_status & KN_DETACHED) == 0)
2854 		kn->kn_fop->f_detach(kn);
2855 	knote_drop_detached(kn, td);
2856 }
2857 
2858 static void
knote_drop_detached(struct knote * kn,struct thread * td)2859 knote_drop_detached(struct knote *kn, struct thread *td)
2860 {
2861 	struct kqueue *kq;
2862 	struct klist *list;
2863 
2864 	kq = kn->kn_kq;
2865 
2866 	KASSERT((kn->kn_status & KN_DETACHED) != 0,
2867 	    ("knote %p still attached", kn));
2868 	KQ_NOTOWNED(kq);
2869 
2870 	KQ_LOCK(kq);
2871 	for (;;) {
2872 		KASSERT(kn->kn_influx >= 1,
2873 		    ("knote_drop called on %p with influx %d",
2874 		    kn, kn->kn_influx));
2875 		if (kn->kn_influx == 1)
2876 			break;
2877 		kq->kq_state |= KQ_FLUXWAIT;
2878 		msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2879 	}
2880 
2881 	if (kn->kn_fop->f_isfd)
2882 		list = &kq->kq_knlist[kn->kn_id];
2883 	else
2884 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2885 
2886 	if (!SLIST_EMPTY(list))
2887 		SLIST_REMOVE(list, kn, knote, kn_link);
2888 	if (kn->kn_status & KN_QUEUED)
2889 		knote_dequeue(kn);
2890 	KQ_UNLOCK_FLUX(kq);
2891 
2892 	if (kn->kn_fop->f_isfd) {
2893 		fdrop(kn->kn_fp, td);
2894 		kn->kn_fp = NULL;
2895 	}
2896 	kqueue_fo_release(kn->kn_kevent.filter);
2897 	kn->kn_fop = NULL;
2898 	knote_free(kn);
2899 }
2900 
2901 static void
knote_enqueue(struct knote * kn)2902 knote_enqueue(struct knote *kn)
2903 {
2904 	struct kqueue *kq = kn->kn_kq;
2905 
2906 	KQ_OWNED(kn->kn_kq);
2907 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2908 
2909 	TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2910 	kn->kn_status |= KN_QUEUED;
2911 	kq->kq_count++;
2912 	kqueue_wakeup(kq);
2913 }
2914 
2915 static void
knote_dequeue(struct knote * kn)2916 knote_dequeue(struct knote *kn)
2917 {
2918 	struct kqueue *kq = kn->kn_kq;
2919 
2920 	KQ_OWNED(kn->kn_kq);
2921 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2922 
2923 	TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2924 	kn->kn_status &= ~KN_QUEUED;
2925 	kq->kq_count--;
2926 }
2927 
2928 static void
knote_init(void)2929 knote_init(void)
2930 {
2931 
2932 	knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2933 	    NULL, NULL, UMA_ALIGN_PTR, 0);
2934 	ast_register(TDA_KQUEUE, ASTR_ASTF_REQUIRED, 0, ast_kqueue);
2935 	prison0.pr_klist = knlist_alloc(&prison0.pr_mtx);
2936 }
2937 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2938 
2939 static struct knote *
knote_alloc(int mflag)2940 knote_alloc(int mflag)
2941 {
2942 
2943 	return (uma_zalloc(knote_zone, mflag | M_ZERO));
2944 }
2945 
2946 static void
knote_free(struct knote * kn)2947 knote_free(struct knote *kn)
2948 {
2949 
2950 	uma_zfree(knote_zone, kn);
2951 }
2952 
2953 /*
2954  * Register the kev w/ the kq specified by fd.
2955  */
2956 int
kqfd_register(int fd,struct kevent * kev,struct thread * td,int mflag)2957 kqfd_register(int fd, struct kevent *kev, struct thread *td, int mflag)
2958 {
2959 	struct kqueue *kq;
2960 	struct file *fp;
2961 	cap_rights_t rights;
2962 	int error;
2963 
2964 	error = fget(td, fd, cap_rights_init_one(&rights, CAP_KQUEUE_CHANGE),
2965 	    &fp);
2966 	if (error != 0)
2967 		return (error);
2968 	if ((error = kqueue_acquire(fp, &kq)) != 0)
2969 		goto noacquire;
2970 
2971 	error = kqueue_register(kq, kev, td, mflag);
2972 	kqueue_release(kq, 0);
2973 
2974 noacquire:
2975 	fdrop(fp, td);
2976 	return (error);
2977 }
2978 
2979 struct knote_status_export_bit {
2980 	int kn_status_bit;
2981 	int knt_status_bit;
2982 };
2983 
2984 #define	ST(name) \
2985     { .kn_status_bit = KN_##name, .knt_status_bit = KNOTE_STATUS_##name }
2986 static const struct knote_status_export_bit knote_status_export_bits[] = {
2987 	ST(ACTIVE),
2988 	ST(QUEUED),
2989 	ST(DISABLED),
2990 	ST(DETACHED),
2991 	ST(KQUEUE),
2992 };
2993 #undef ST
2994 
2995 static int
knote_status_export(int kn_status)2996 knote_status_export(int kn_status)
2997 {
2998 	const struct knote_status_export_bit *b;
2999 	unsigned i;
3000 	int res;
3001 
3002 	res = 0;
3003 	for (i = 0; i < nitems(knote_status_export_bits); i++) {
3004 		b = &knote_status_export_bits[i];
3005 		if ((kn_status & b->kn_status_bit) != 0)
3006 			res |= b->knt_status_bit;
3007 	}
3008 	return (res);
3009 }
3010 
3011 static int
kern_proc_kqueue_report_one(struct sbuf * s,struct proc * p,int kq_fd,struct kqueue * kq,struct knote * kn,bool compat32 __unused)3012 kern_proc_kqueue_report_one(struct sbuf *s, struct proc *p,
3013     int kq_fd, struct kqueue *kq, struct knote *kn, bool compat32 __unused)
3014 {
3015 	struct kinfo_knote kin;
3016 #ifdef COMPAT_FREEBSD32
3017 	struct kinfo_knote32 kin32;
3018 #endif
3019 	int error;
3020 
3021 	if (kn->kn_status == KN_MARKER)
3022 		return (0);
3023 
3024 	memset(&kin, 0, sizeof(kin));
3025 	kin.knt_kq_fd = kq_fd;
3026 	memcpy(&kin.knt_event, &kn->kn_kevent, sizeof(struct kevent));
3027 	kin.knt_status = knote_status_export(kn->kn_status);
3028 	kn_enter_flux(kn);
3029 	KQ_UNLOCK_FLUX(kq);
3030 	if (kn->kn_fop->f_userdump != NULL)
3031 		(void)kn->kn_fop->f_userdump(p, kn, &kin);
3032 #ifdef COMPAT_FREEBSD32
3033 	if (compat32) {
3034 		freebsd32_kinfo_knote_to_32(&kin, &kin32);
3035 		error = sbuf_bcat(s, &kin32, sizeof(kin32));
3036 	} else
3037 #endif
3038 		error = sbuf_bcat(s, &kin, sizeof(kin));
3039 	KQ_LOCK(kq);
3040 	kn_leave_flux(kn);
3041 	return (error);
3042 }
3043 
3044 static int
kern_proc_kqueue_report(struct sbuf * s,struct proc * p,int kq_fd,struct kqueue * kq,bool compat32)3045 kern_proc_kqueue_report(struct sbuf *s, struct proc *p, int kq_fd,
3046     struct kqueue *kq, bool compat32)
3047 {
3048 	struct knote *kn;
3049 	int error, i;
3050 
3051 	error = 0;
3052 	KQ_LOCK(kq);
3053 	for (i = 0; i < kq->kq_knlistsize; i++) {
3054 		SLIST_FOREACH(kn, &kq->kq_knlist[i], kn_link) {
3055 			error = kern_proc_kqueue_report_one(s, p, kq_fd,
3056 			    kq, kn, compat32);
3057 			if (error != 0)
3058 				goto out;
3059 		}
3060 	}
3061 	if (kq->kq_knhashmask == 0)
3062 		goto out;
3063 	for (i = 0; i <= kq->kq_knhashmask; i++) {
3064 		SLIST_FOREACH(kn, &kq->kq_knhash[i], kn_link) {
3065 			error = kern_proc_kqueue_report_one(s, p, kq_fd,
3066 			    kq, kn, compat32);
3067 			if (error != 0)
3068 				goto out;
3069 		}
3070 	}
3071 out:
3072 	KQ_UNLOCK_FLUX(kq);
3073 	return (error);
3074 }
3075 
3076 struct kern_proc_kqueues_out1_cb_args {
3077 	struct sbuf *s;
3078 	bool compat32;
3079 };
3080 
3081 static int
kern_proc_kqueues_out1_cb(struct proc * p,int fd,struct file * fp,void * arg)3082 kern_proc_kqueues_out1_cb(struct proc *p, int fd, struct file *fp, void *arg)
3083 {
3084 	struct kqueue *kq;
3085 	struct kern_proc_kqueues_out1_cb_args *a;
3086 
3087 	if (fp->f_type != DTYPE_KQUEUE)
3088 		return (0);
3089 	a = arg;
3090 	kq = fp->f_data;
3091 	return (kern_proc_kqueue_report(a->s, p, fd, kq, a->compat32));
3092 }
3093 
3094 static int
kern_proc_kqueues_out1(struct thread * td,struct proc * p,struct sbuf * s,bool compat32)3095 kern_proc_kqueues_out1(struct thread *td, struct proc *p, struct sbuf *s,
3096     bool compat32)
3097 {
3098 	struct kern_proc_kqueues_out1_cb_args a;
3099 
3100 	a.s = s;
3101 	a.compat32 = compat32;
3102 	return (fget_remote_foreach(td, p, kern_proc_kqueues_out1_cb, &a));
3103 }
3104 
3105 int
kern_proc_kqueues_out(struct proc * p,struct sbuf * sb,size_t maxlen,bool compat32)3106 kern_proc_kqueues_out(struct proc *p, struct sbuf *sb, size_t maxlen,
3107     bool compat32)
3108 {
3109 	struct sbuf *s, sm;
3110 	size_t sb_len;
3111 	int error;
3112 
3113 	if (maxlen == -1 || maxlen == 0)
3114 		sb_len = 128;
3115 	else
3116 		sb_len = maxlen;
3117 	s = sbuf_new(&sm, NULL, sb_len, maxlen == -1 ? SBUF_AUTOEXTEND :
3118 	    SBUF_FIXEDLEN);
3119 	error = kern_proc_kqueues_out1(curthread, p, s, compat32);
3120 	sbuf_finish(s);
3121 	if (error == 0) {
3122 		sbuf_bcat(sb, sbuf_data(s), MIN(sbuf_len(s), maxlen == -1 ?
3123 		    SIZE_T_MAX : maxlen));
3124 	}
3125 	sbuf_delete(s);
3126 	return (error);
3127 }
3128 
3129 static int
sysctl_kern_proc_kqueue_one(struct thread * td,struct sbuf * s,struct proc * p,int kq_fd,bool compat32)3130 sysctl_kern_proc_kqueue_one(struct thread *td, struct sbuf *s, struct proc *p,
3131     int kq_fd, bool compat32)
3132 {
3133 	struct file *fp;
3134 	struct kqueue *kq;
3135 	int error;
3136 
3137 	error = fget_remote(td, p, kq_fd, &fp);
3138 	if (error == 0) {
3139 		if (fp->f_type != DTYPE_KQUEUE) {
3140 			error = EINVAL;
3141 		} else {
3142 			kq = fp->f_data;
3143 			error = kern_proc_kqueue_report(s, p, kq_fd, kq,
3144 			    compat32);
3145 		}
3146 		fdrop(fp, td);
3147 	}
3148 	return (error);
3149 }
3150 
3151 static int
sysctl_kern_proc_kqueue(SYSCTL_HANDLER_ARGS)3152 sysctl_kern_proc_kqueue(SYSCTL_HANDLER_ARGS)
3153 {
3154 	struct thread *td;
3155 	struct proc *p;
3156 	struct sbuf *s, sm;
3157 	int error, error1, *name;
3158 	bool compat32;
3159 
3160 	name = (int *)arg1;
3161 	if ((u_int)arg2 > 2 || (u_int)arg2 == 0)
3162 		return (EINVAL);
3163 
3164 	error = pget((pid_t)name[0], PGET_HOLD | PGET_CANDEBUG, &p);
3165 	if (error != 0)
3166 		return (error);
3167 
3168 	td = curthread;
3169 #ifdef FREEBSD_COMPAT32
3170 	compat32 = SV_CURPROC_FLAG(SV_ILP32);
3171 #else
3172 	compat32 = false;
3173 #endif
3174 
3175 	s = sbuf_new_for_sysctl(&sm, NULL, 0, req);
3176 	if (s == NULL) {
3177 		error = ENOMEM;
3178 		goto out;
3179 	}
3180 	sbuf_clear_flags(s, SBUF_INCLUDENUL);
3181 
3182 	if ((u_int)arg2 == 1) {
3183 		error = kern_proc_kqueues_out1(td, p, s, compat32);
3184 	} else {
3185 		error = sysctl_kern_proc_kqueue_one(td, s, p,
3186 		    name[1] /* kq_fd */, compat32);
3187 	}
3188 
3189 	error1 = sbuf_finish(s);
3190 	if (error == 0)
3191 		error = error1;
3192 	sbuf_delete(s);
3193 
3194 out:
3195 	PRELE(p);
3196 	return (error);
3197 }
3198 
3199 static SYSCTL_NODE(_kern_proc, KERN_PROC_KQUEUE, kq,
3200     CTLFLAG_RD | CTLFLAG_MPSAFE,
3201     sysctl_kern_proc_kqueue, "KQueue events");
3202