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