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