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