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