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