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