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