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