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