xref: /freebsd/sys/kern/kern_event.c (revision c1eb4109f3b1d90a9c1538179ea6a52a191899b2)
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 /*
979  * Performs a kevent() call on a temporarily created kqueue. This can be
980  * used to perform one-shot polling, similar to poll() and select().
981  */
982 int
983 kern_kevent_anonymous(struct thread *td, int nevents,
984     struct kevent_copyops *k_ops)
985 {
986 	struct kqueue kq = {};
987 	int error;
988 
989 	kqueue_init(&kq);
990 	kq.kq_refcnt = 1;
991 	error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
992 	kqueue_drain(&kq, td);
993 	kqueue_destroy(&kq);
994 	return (error);
995 }
996 
997 int
998 kqueue_add_filteropts(int filt, struct filterops *filtops)
999 {
1000 	int error;
1001 
1002 	error = 0;
1003 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1004 		printf(
1005 "trying to add a filterop that is out of range: %d is beyond %d\n",
1006 		    ~filt, EVFILT_SYSCOUNT);
1007 		return EINVAL;
1008 	}
1009 	mtx_lock(&filterops_lock);
1010 	if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1011 	    sysfilt_ops[~filt].for_fop != NULL)
1012 		error = EEXIST;
1013 	else {
1014 		sysfilt_ops[~filt].for_fop = filtops;
1015 		sysfilt_ops[~filt].for_refcnt = 0;
1016 	}
1017 	mtx_unlock(&filterops_lock);
1018 
1019 	return (error);
1020 }
1021 
1022 int
1023 kqueue_del_filteropts(int filt)
1024 {
1025 	int error;
1026 
1027 	error = 0;
1028 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1029 		return EINVAL;
1030 
1031 	mtx_lock(&filterops_lock);
1032 	if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1033 	    sysfilt_ops[~filt].for_fop == NULL)
1034 		error = EINVAL;
1035 	else if (sysfilt_ops[~filt].for_refcnt != 0)
1036 		error = EBUSY;
1037 	else {
1038 		sysfilt_ops[~filt].for_fop = &null_filtops;
1039 		sysfilt_ops[~filt].for_refcnt = 0;
1040 	}
1041 	mtx_unlock(&filterops_lock);
1042 
1043 	return error;
1044 }
1045 
1046 static struct filterops *
1047 kqueue_fo_find(int filt)
1048 {
1049 
1050 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1051 		return NULL;
1052 
1053 	if (sysfilt_ops[~filt].for_nolock)
1054 		return sysfilt_ops[~filt].for_fop;
1055 
1056 	mtx_lock(&filterops_lock);
1057 	sysfilt_ops[~filt].for_refcnt++;
1058 	if (sysfilt_ops[~filt].for_fop == NULL)
1059 		sysfilt_ops[~filt].for_fop = &null_filtops;
1060 	mtx_unlock(&filterops_lock);
1061 
1062 	return sysfilt_ops[~filt].for_fop;
1063 }
1064 
1065 static void
1066 kqueue_fo_release(int filt)
1067 {
1068 
1069 	if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1070 		return;
1071 
1072 	if (sysfilt_ops[~filt].for_nolock)
1073 		return;
1074 
1075 	mtx_lock(&filterops_lock);
1076 	KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1077 	    ("filter object refcount not valid on release"));
1078 	sysfilt_ops[~filt].for_refcnt--;
1079 	mtx_unlock(&filterops_lock);
1080 }
1081 
1082 /*
1083  * A ref to kq (obtained via kqueue_acquire) must be held.  waitok will
1084  * influence if memory allocation should wait.  Make sure it is 0 if you
1085  * hold any mutexes.
1086  */
1087 static int
1088 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1089 {
1090 	struct filterops *fops;
1091 	struct file *fp;
1092 	struct knote *kn, *tkn;
1093 	cap_rights_t rights;
1094 	int error, filt, event;
1095 	int haskqglobal, filedesc_unlock;
1096 
1097 	fp = NULL;
1098 	kn = NULL;
1099 	error = 0;
1100 	haskqglobal = 0;
1101 	filedesc_unlock = 0;
1102 
1103 	filt = kev->filter;
1104 	fops = kqueue_fo_find(filt);
1105 	if (fops == NULL)
1106 		return EINVAL;
1107 
1108 	if (kev->flags & EV_ADD) {
1109 		/*
1110 		 * Prevent waiting with locks.  Non-sleepable
1111 		 * allocation failures are handled in the loop, only
1112 		 * if the spare knote appears to be actually required.
1113 		 */
1114 		tkn = knote_alloc(waitok);
1115 	} else {
1116 		tkn = NULL;
1117 	}
1118 
1119 findkn:
1120 	if (fops->f_isfd) {
1121 		KASSERT(td != NULL, ("td is NULL"));
1122 		error = fget(td, kev->ident,
1123 		    cap_rights_init(&rights, CAP_EVENT), &fp);
1124 		if (error)
1125 			goto done;
1126 
1127 		if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1128 		    kev->ident, 0) != 0) {
1129 			/* try again */
1130 			fdrop(fp, td);
1131 			fp = NULL;
1132 			error = kqueue_expand(kq, fops, kev->ident, waitok);
1133 			if (error)
1134 				goto done;
1135 			goto findkn;
1136 		}
1137 
1138 		if (fp->f_type == DTYPE_KQUEUE) {
1139 			/*
1140 			 * if we add some inteligence about what we are doing,
1141 			 * we should be able to support events on ourselves.
1142 			 * We need to know when we are doing this to prevent
1143 			 * getting both the knlist lock and the kq lock since
1144 			 * they are the same thing.
1145 			 */
1146 			if (fp->f_data == kq) {
1147 				error = EINVAL;
1148 				goto done;
1149 			}
1150 
1151 			/*
1152 			 * Pre-lock the filedesc before the global
1153 			 * lock mutex, see the comment in
1154 			 * kqueue_close().
1155 			 */
1156 			FILEDESC_XLOCK(td->td_proc->p_fd);
1157 			filedesc_unlock = 1;
1158 			KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1159 		}
1160 
1161 		KQ_LOCK(kq);
1162 		if (kev->ident < kq->kq_knlistsize) {
1163 			SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1164 				if (kev->filter == kn->kn_filter)
1165 					break;
1166 		}
1167 	} else {
1168 		if ((kev->flags & EV_ADD) == EV_ADD)
1169 			kqueue_expand(kq, fops, kev->ident, waitok);
1170 
1171 		KQ_LOCK(kq);
1172 		if (kq->kq_knhashmask != 0) {
1173 			struct klist *list;
1174 
1175 			list = &kq->kq_knhash[
1176 			    KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1177 			SLIST_FOREACH(kn, list, kn_link)
1178 				if (kev->ident == kn->kn_id &&
1179 				    kev->filter == kn->kn_filter)
1180 					break;
1181 		}
1182 	}
1183 
1184 	/* knote is in the process of changing, wait for it to stablize. */
1185 	if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1186 		KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1187 		if (filedesc_unlock) {
1188 			FILEDESC_XUNLOCK(td->td_proc->p_fd);
1189 			filedesc_unlock = 0;
1190 		}
1191 		kq->kq_state |= KQ_FLUXWAIT;
1192 		msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1193 		if (fp != NULL) {
1194 			fdrop(fp, td);
1195 			fp = NULL;
1196 		}
1197 		goto findkn;
1198 	}
1199 
1200 	/*
1201 	 * kn now contains the matching knote, or NULL if no match
1202 	 */
1203 	if (kn == NULL) {
1204 		if (kev->flags & EV_ADD) {
1205 			kn = tkn;
1206 			tkn = NULL;
1207 			if (kn == NULL) {
1208 				KQ_UNLOCK(kq);
1209 				error = ENOMEM;
1210 				goto done;
1211 			}
1212 			kn->kn_fp = fp;
1213 			kn->kn_kq = kq;
1214 			kn->kn_fop = fops;
1215 			/*
1216 			 * apply reference counts to knote structure, and
1217 			 * do not release it at the end of this routine.
1218 			 */
1219 			fops = NULL;
1220 			fp = NULL;
1221 
1222 			kn->kn_sfflags = kev->fflags;
1223 			kn->kn_sdata = kev->data;
1224 			kev->fflags = 0;
1225 			kev->data = 0;
1226 			kn->kn_kevent = *kev;
1227 			kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1228 			    EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1229 			kn->kn_status = KN_INFLUX|KN_DETACHED;
1230 
1231 			error = knote_attach(kn, kq);
1232 			KQ_UNLOCK(kq);
1233 			if (error != 0) {
1234 				tkn = kn;
1235 				goto done;
1236 			}
1237 
1238 			if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1239 				knote_drop(kn, td);
1240 				goto done;
1241 			}
1242 			KN_LIST_LOCK(kn);
1243 			goto done_ev_add;
1244 		} else {
1245 			/* No matching knote and the EV_ADD flag is not set. */
1246 			KQ_UNLOCK(kq);
1247 			error = ENOENT;
1248 			goto done;
1249 		}
1250 	}
1251 
1252 	if (kev->flags & EV_DELETE) {
1253 		kn->kn_status |= KN_INFLUX;
1254 		KQ_UNLOCK(kq);
1255 		if (!(kn->kn_status & KN_DETACHED))
1256 			kn->kn_fop->f_detach(kn);
1257 		knote_drop(kn, td);
1258 		goto done;
1259 	}
1260 
1261 	if (kev->flags & EV_FORCEONESHOT) {
1262 		kn->kn_flags |= EV_ONESHOT;
1263 		KNOTE_ACTIVATE(kn, 1);
1264 	}
1265 
1266 	/*
1267 	 * The user may change some filter values after the initial EV_ADD,
1268 	 * but doing so will not reset any filter which has already been
1269 	 * triggered.
1270 	 */
1271 	kn->kn_status |= KN_INFLUX | KN_SCAN;
1272 	KQ_UNLOCK(kq);
1273 	KN_LIST_LOCK(kn);
1274 	kn->kn_kevent.udata = kev->udata;
1275 	if (!fops->f_isfd && fops->f_touch != NULL) {
1276 		fops->f_touch(kn, kev, EVENT_REGISTER);
1277 	} else {
1278 		kn->kn_sfflags = kev->fflags;
1279 		kn->kn_sdata = kev->data;
1280 	}
1281 
1282 	/*
1283 	 * We can get here with kn->kn_knlist == NULL.  This can happen when
1284 	 * the initial attach event decides that the event is "completed"
1285 	 * already.  i.e. filt_procattach is called on a zombie process.  It
1286 	 * will call filt_proc which will remove it from the list, and NULL
1287 	 * kn_knlist.
1288 	 */
1289 done_ev_add:
1290 	if ((kev->flags & EV_DISABLE) &&
1291 	    ((kn->kn_status & KN_DISABLED) == 0)) {
1292 		kn->kn_status |= KN_DISABLED;
1293 	}
1294 
1295 	if ((kn->kn_status & KN_DISABLED) == 0)
1296 		event = kn->kn_fop->f_event(kn, 0);
1297 	else
1298 		event = 0;
1299 	KQ_LOCK(kq);
1300 	if (event)
1301 		KNOTE_ACTIVATE(kn, 1);
1302 	kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1303 	KN_LIST_UNLOCK(kn);
1304 
1305 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1306 		kn->kn_status &= ~KN_DISABLED;
1307 		if ((kn->kn_status & KN_ACTIVE) &&
1308 		    ((kn->kn_status & KN_QUEUED) == 0))
1309 			knote_enqueue(kn);
1310 	}
1311 	KQ_UNLOCK_FLUX(kq);
1312 
1313 done:
1314 	KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1315 	if (filedesc_unlock)
1316 		FILEDESC_XUNLOCK(td->td_proc->p_fd);
1317 	if (fp != NULL)
1318 		fdrop(fp, td);
1319 	knote_free(tkn);
1320 	if (fops != NULL)
1321 		kqueue_fo_release(filt);
1322 	return (error);
1323 }
1324 
1325 static int
1326 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1327 {
1328 	int error;
1329 	struct kqueue *kq;
1330 
1331 	error = 0;
1332 
1333 	kq = fp->f_data;
1334 	if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1335 		return (EBADF);
1336 	*kqp = kq;
1337 	KQ_LOCK(kq);
1338 	if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1339 		KQ_UNLOCK(kq);
1340 		return (EBADF);
1341 	}
1342 	kq->kq_refcnt++;
1343 	KQ_UNLOCK(kq);
1344 
1345 	return error;
1346 }
1347 
1348 static void
1349 kqueue_release(struct kqueue *kq, int locked)
1350 {
1351 	if (locked)
1352 		KQ_OWNED(kq);
1353 	else
1354 		KQ_LOCK(kq);
1355 	kq->kq_refcnt--;
1356 	if (kq->kq_refcnt == 1)
1357 		wakeup(&kq->kq_refcnt);
1358 	if (!locked)
1359 		KQ_UNLOCK(kq);
1360 }
1361 
1362 static void
1363 kqueue_schedtask(struct kqueue *kq)
1364 {
1365 
1366 	KQ_OWNED(kq);
1367 	KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1368 	    ("scheduling kqueue task while draining"));
1369 
1370 	if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1371 		taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1372 		kq->kq_state |= KQ_TASKSCHED;
1373 	}
1374 }
1375 
1376 /*
1377  * Expand the kq to make sure we have storage for fops/ident pair.
1378  *
1379  * Return 0 on success (or no work necessary), return errno on failure.
1380  *
1381  * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1382  * If kqueue_register is called from a non-fd context, there usually/should
1383  * be no locks held.
1384  */
1385 static int
1386 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1387 	int waitok)
1388 {
1389 	struct klist *list, *tmp_knhash, *to_free;
1390 	u_long tmp_knhashmask;
1391 	int size;
1392 	int fd;
1393 	int mflag = waitok ? M_WAITOK : M_NOWAIT;
1394 
1395 	KQ_NOTOWNED(kq);
1396 
1397 	to_free = NULL;
1398 	if (fops->f_isfd) {
1399 		fd = ident;
1400 		if (kq->kq_knlistsize <= fd) {
1401 			size = kq->kq_knlistsize;
1402 			while (size <= fd)
1403 				size += KQEXTENT;
1404 			list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1405 			if (list == NULL)
1406 				return ENOMEM;
1407 			KQ_LOCK(kq);
1408 			if (kq->kq_knlistsize > fd) {
1409 				to_free = list;
1410 				list = NULL;
1411 			} else {
1412 				if (kq->kq_knlist != NULL) {
1413 					bcopy(kq->kq_knlist, list,
1414 					    kq->kq_knlistsize * sizeof(*list));
1415 					to_free = kq->kq_knlist;
1416 					kq->kq_knlist = NULL;
1417 				}
1418 				bzero((caddr_t)list +
1419 				    kq->kq_knlistsize * sizeof(*list),
1420 				    (size - kq->kq_knlistsize) * sizeof(*list));
1421 				kq->kq_knlistsize = size;
1422 				kq->kq_knlist = list;
1423 			}
1424 			KQ_UNLOCK(kq);
1425 		}
1426 	} else {
1427 		if (kq->kq_knhashmask == 0) {
1428 			tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1429 			    &tmp_knhashmask);
1430 			if (tmp_knhash == NULL)
1431 				return ENOMEM;
1432 			KQ_LOCK(kq);
1433 			if (kq->kq_knhashmask == 0) {
1434 				kq->kq_knhash = tmp_knhash;
1435 				kq->kq_knhashmask = tmp_knhashmask;
1436 			} else {
1437 				to_free = tmp_knhash;
1438 			}
1439 			KQ_UNLOCK(kq);
1440 		}
1441 	}
1442 	free(to_free, M_KQUEUE);
1443 
1444 	KQ_NOTOWNED(kq);
1445 	return 0;
1446 }
1447 
1448 static void
1449 kqueue_task(void *arg, int pending)
1450 {
1451 	struct kqueue *kq;
1452 	int haskqglobal;
1453 
1454 	haskqglobal = 0;
1455 	kq = arg;
1456 
1457 	KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1458 	KQ_LOCK(kq);
1459 
1460 	KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1461 
1462 	kq->kq_state &= ~KQ_TASKSCHED;
1463 	if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1464 		wakeup(&kq->kq_state);
1465 	}
1466 	KQ_UNLOCK(kq);
1467 	KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1468 }
1469 
1470 /*
1471  * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1472  * We treat KN_MARKER knotes as if they are INFLUX.
1473  */
1474 static int
1475 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1476     const struct timespec *tsp, struct kevent *keva, struct thread *td)
1477 {
1478 	struct kevent *kevp;
1479 	struct knote *kn, *marker;
1480 	sbintime_t asbt, rsbt;
1481 	int count, error, haskqglobal, influx, nkev, touch;
1482 
1483 	count = maxevents;
1484 	nkev = 0;
1485 	error = 0;
1486 	haskqglobal = 0;
1487 
1488 	if (maxevents == 0)
1489 		goto done_nl;
1490 
1491 	rsbt = 0;
1492 	if (tsp != NULL) {
1493 		if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1494 		    tsp->tv_nsec >= 1000000000) {
1495 			error = EINVAL;
1496 			goto done_nl;
1497 		}
1498 		if (timespecisset(tsp)) {
1499 			if (tsp->tv_sec <= INT32_MAX) {
1500 				rsbt = tstosbt(*tsp);
1501 				if (TIMESEL(&asbt, rsbt))
1502 					asbt += tc_tick_sbt;
1503 				if (asbt <= SBT_MAX - rsbt)
1504 					asbt += rsbt;
1505 				else
1506 					asbt = 0;
1507 				rsbt >>= tc_precexp;
1508 			} else
1509 				asbt = 0;
1510 		} else
1511 			asbt = -1;
1512 	} else
1513 		asbt = 0;
1514 	marker = knote_alloc(1);
1515 	marker->kn_status = KN_MARKER;
1516 	KQ_LOCK(kq);
1517 
1518 retry:
1519 	kevp = keva;
1520 	if (kq->kq_count == 0) {
1521 		if (asbt == -1) {
1522 			error = EWOULDBLOCK;
1523 		} else {
1524 			kq->kq_state |= KQ_SLEEP;
1525 			error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1526 			    "kqread", asbt, rsbt, C_ABSOLUTE);
1527 		}
1528 		if (error == 0)
1529 			goto retry;
1530 		/* don't restart after signals... */
1531 		if (error == ERESTART)
1532 			error = EINTR;
1533 		else if (error == EWOULDBLOCK)
1534 			error = 0;
1535 		goto done;
1536 	}
1537 
1538 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1539 	influx = 0;
1540 	while (count) {
1541 		KQ_OWNED(kq);
1542 		kn = TAILQ_FIRST(&kq->kq_head);
1543 
1544 		if ((kn->kn_status == KN_MARKER && kn != marker) ||
1545 		    (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1546 			if (influx) {
1547 				influx = 0;
1548 				KQ_FLUX_WAKEUP(kq);
1549 			}
1550 			kq->kq_state |= KQ_FLUXWAIT;
1551 			error = msleep(kq, &kq->kq_lock, PSOCK,
1552 			    "kqflxwt", 0);
1553 			continue;
1554 		}
1555 
1556 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1557 		if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1558 			kn->kn_status &= ~KN_QUEUED;
1559 			kq->kq_count--;
1560 			continue;
1561 		}
1562 		if (kn == marker) {
1563 			KQ_FLUX_WAKEUP(kq);
1564 			if (count == maxevents)
1565 				goto retry;
1566 			goto done;
1567 		}
1568 		KASSERT((kn->kn_status & KN_INFLUX) == 0,
1569 		    ("KN_INFLUX set when not suppose to be"));
1570 
1571 		if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1572 			kn->kn_status &= ~KN_QUEUED;
1573 			kn->kn_status |= KN_INFLUX;
1574 			kq->kq_count--;
1575 			KQ_UNLOCK(kq);
1576 			/*
1577 			 * We don't need to lock the list since we've marked
1578 			 * it _INFLUX.
1579 			 */
1580 			if (!(kn->kn_status & KN_DETACHED))
1581 				kn->kn_fop->f_detach(kn);
1582 			knote_drop(kn, td);
1583 			KQ_LOCK(kq);
1584 			continue;
1585 		} else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1586 			kn->kn_status &= ~KN_QUEUED;
1587 			kn->kn_status |= KN_INFLUX;
1588 			kq->kq_count--;
1589 			KQ_UNLOCK(kq);
1590 			/*
1591 			 * We don't need to lock the list since we've marked
1592 			 * it _INFLUX.
1593 			 */
1594 			*kevp = kn->kn_kevent;
1595 			if (!(kn->kn_status & KN_DETACHED))
1596 				kn->kn_fop->f_detach(kn);
1597 			knote_drop(kn, td);
1598 			KQ_LOCK(kq);
1599 			kn = NULL;
1600 		} else {
1601 			kn->kn_status |= KN_INFLUX | KN_SCAN;
1602 			KQ_UNLOCK(kq);
1603 			if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1604 				KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1605 			KN_LIST_LOCK(kn);
1606 			if (kn->kn_fop->f_event(kn, 0) == 0) {
1607 				KQ_LOCK(kq);
1608 				KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1609 				kn->kn_status &=
1610 				    ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1611 				    KN_SCAN);
1612 				kq->kq_count--;
1613 				KN_LIST_UNLOCK(kn);
1614 				influx = 1;
1615 				continue;
1616 			}
1617 			touch = (!kn->kn_fop->f_isfd &&
1618 			    kn->kn_fop->f_touch != NULL);
1619 			if (touch)
1620 				kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1621 			else
1622 				*kevp = kn->kn_kevent;
1623 			KQ_LOCK(kq);
1624 			KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1625 			if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1626 				/*
1627 				 * Manually clear knotes who weren't
1628 				 * 'touch'ed.
1629 				 */
1630 				if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1631 					kn->kn_data = 0;
1632 					kn->kn_fflags = 0;
1633 				}
1634 				if (kn->kn_flags & EV_DISPATCH)
1635 					kn->kn_status |= KN_DISABLED;
1636 				kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1637 				kq->kq_count--;
1638 			} else
1639 				TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1640 
1641 			kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1642 			KN_LIST_UNLOCK(kn);
1643 			influx = 1;
1644 		}
1645 
1646 		/* we are returning a copy to the user */
1647 		kevp++;
1648 		nkev++;
1649 		count--;
1650 
1651 		if (nkev == KQ_NEVENTS) {
1652 			influx = 0;
1653 			KQ_UNLOCK_FLUX(kq);
1654 			error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1655 			nkev = 0;
1656 			kevp = keva;
1657 			KQ_LOCK(kq);
1658 			if (error)
1659 				break;
1660 		}
1661 	}
1662 	TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1663 done:
1664 	KQ_OWNED(kq);
1665 	KQ_UNLOCK_FLUX(kq);
1666 	knote_free(marker);
1667 done_nl:
1668 	KQ_NOTOWNED(kq);
1669 	if (nkev != 0)
1670 		error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1671 	td->td_retval[0] = maxevents - count;
1672 	return (error);
1673 }
1674 
1675 /*ARGSUSED*/
1676 static int
1677 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1678 	struct ucred *active_cred, struct thread *td)
1679 {
1680 	/*
1681 	 * Enabling sigio causes two major problems:
1682 	 * 1) infinite recursion:
1683 	 * Synopsys: kevent is being used to track signals and have FIOASYNC
1684 	 * set.  On receipt of a signal this will cause a kqueue to recurse
1685 	 * into itself over and over.  Sending the sigio causes the kqueue
1686 	 * to become ready, which in turn posts sigio again, forever.
1687 	 * Solution: this can be solved by setting a flag in the kqueue that
1688 	 * we have a SIGIO in progress.
1689 	 * 2) locking problems:
1690 	 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1691 	 * us above the proc and pgrp locks.
1692 	 * Solution: Post a signal using an async mechanism, being sure to
1693 	 * record a generation count in the delivery so that we do not deliver
1694 	 * a signal to the wrong process.
1695 	 *
1696 	 * Note, these two mechanisms are somewhat mutually exclusive!
1697 	 */
1698 #if 0
1699 	struct kqueue *kq;
1700 
1701 	kq = fp->f_data;
1702 	switch (cmd) {
1703 	case FIOASYNC:
1704 		if (*(int *)data) {
1705 			kq->kq_state |= KQ_ASYNC;
1706 		} else {
1707 			kq->kq_state &= ~KQ_ASYNC;
1708 		}
1709 		return (0);
1710 
1711 	case FIOSETOWN:
1712 		return (fsetown(*(int *)data, &kq->kq_sigio));
1713 
1714 	case FIOGETOWN:
1715 		*(int *)data = fgetown(&kq->kq_sigio);
1716 		return (0);
1717 	}
1718 #endif
1719 
1720 	return (ENOTTY);
1721 }
1722 
1723 /*ARGSUSED*/
1724 static int
1725 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1726 	struct thread *td)
1727 {
1728 	struct kqueue *kq;
1729 	int revents = 0;
1730 	int error;
1731 
1732 	if ((error = kqueue_acquire(fp, &kq)))
1733 		return POLLERR;
1734 
1735 	KQ_LOCK(kq);
1736 	if (events & (POLLIN | POLLRDNORM)) {
1737 		if (kq->kq_count) {
1738 			revents |= events & (POLLIN | POLLRDNORM);
1739 		} else {
1740 			selrecord(td, &kq->kq_sel);
1741 			if (SEL_WAITING(&kq->kq_sel))
1742 				kq->kq_state |= KQ_SEL;
1743 		}
1744 	}
1745 	kqueue_release(kq, 1);
1746 	KQ_UNLOCK(kq);
1747 	return (revents);
1748 }
1749 
1750 /*ARGSUSED*/
1751 static int
1752 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1753 	struct thread *td)
1754 {
1755 
1756 	bzero((void *)st, sizeof *st);
1757 	/*
1758 	 * We no longer return kq_count because the unlocked value is useless.
1759 	 * If you spent all this time getting the count, why not spend your
1760 	 * syscall better by calling kevent?
1761 	 *
1762 	 * XXX - This is needed for libc_r.
1763 	 */
1764 	st->st_mode = S_IFIFO;
1765 	return (0);
1766 }
1767 
1768 static void
1769 kqueue_drain(struct kqueue *kq, struct thread *td)
1770 {
1771 	struct knote *kn;
1772 	int i;
1773 
1774 	KQ_LOCK(kq);
1775 
1776 	KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1777 	    ("kqueue already closing"));
1778 	kq->kq_state |= KQ_CLOSING;
1779 	if (kq->kq_refcnt > 1)
1780 		msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1781 
1782 	KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1783 
1784 	KASSERT(knlist_empty(&kq->kq_sel.si_note),
1785 	    ("kqueue's knlist not empty"));
1786 
1787 	for (i = 0; i < kq->kq_knlistsize; i++) {
1788 		while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1789 			if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1790 				kq->kq_state |= KQ_FLUXWAIT;
1791 				msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1792 				continue;
1793 			}
1794 			kn->kn_status |= KN_INFLUX;
1795 			KQ_UNLOCK(kq);
1796 			if (!(kn->kn_status & KN_DETACHED))
1797 				kn->kn_fop->f_detach(kn);
1798 			knote_drop(kn, td);
1799 			KQ_LOCK(kq);
1800 		}
1801 	}
1802 	if (kq->kq_knhashmask != 0) {
1803 		for (i = 0; i <= kq->kq_knhashmask; i++) {
1804 			while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1805 				if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1806 					kq->kq_state |= KQ_FLUXWAIT;
1807 					msleep(kq, &kq->kq_lock, PSOCK,
1808 					       "kqclo2", 0);
1809 					continue;
1810 				}
1811 				kn->kn_status |= KN_INFLUX;
1812 				KQ_UNLOCK(kq);
1813 				if (!(kn->kn_status & KN_DETACHED))
1814 					kn->kn_fop->f_detach(kn);
1815 				knote_drop(kn, td);
1816 				KQ_LOCK(kq);
1817 			}
1818 		}
1819 	}
1820 
1821 	if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1822 		kq->kq_state |= KQ_TASKDRAIN;
1823 		msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1824 	}
1825 
1826 	if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1827 		selwakeuppri(&kq->kq_sel, PSOCK);
1828 		if (!SEL_WAITING(&kq->kq_sel))
1829 			kq->kq_state &= ~KQ_SEL;
1830 	}
1831 
1832 	KQ_UNLOCK(kq);
1833 }
1834 
1835 static void
1836 kqueue_destroy(struct kqueue *kq)
1837 {
1838 
1839 	KASSERT(kq->kq_fdp == NULL,
1840 	    ("kqueue still attached to a file descriptor"));
1841 	seldrain(&kq->kq_sel);
1842 	knlist_destroy(&kq->kq_sel.si_note);
1843 	mtx_destroy(&kq->kq_lock);
1844 
1845 	if (kq->kq_knhash != NULL)
1846 		free(kq->kq_knhash, M_KQUEUE);
1847 	if (kq->kq_knlist != NULL)
1848 		free(kq->kq_knlist, M_KQUEUE);
1849 
1850 	funsetown(&kq->kq_sigio);
1851 }
1852 
1853 /*ARGSUSED*/
1854 static int
1855 kqueue_close(struct file *fp, struct thread *td)
1856 {
1857 	struct kqueue *kq = fp->f_data;
1858 	struct filedesc *fdp;
1859 	int error;
1860 	int filedesc_unlock;
1861 
1862 	if ((error = kqueue_acquire(fp, &kq)))
1863 		return error;
1864 	kqueue_drain(kq, td);
1865 
1866 	/*
1867 	 * We could be called due to the knote_drop() doing fdrop(),
1868 	 * called from kqueue_register().  In this case the global
1869 	 * lock is owned, and filedesc sx is locked before, to not
1870 	 * take the sleepable lock after non-sleepable.
1871 	 */
1872 	fdp = kq->kq_fdp;
1873 	kq->kq_fdp = NULL;
1874 	if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1875 		FILEDESC_XLOCK(fdp);
1876 		filedesc_unlock = 1;
1877 	} else
1878 		filedesc_unlock = 0;
1879 	TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1880 	if (filedesc_unlock)
1881 		FILEDESC_XUNLOCK(fdp);
1882 
1883 	kqueue_destroy(kq);
1884 	chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1885 	crfree(kq->kq_cred);
1886 	free(kq, M_KQUEUE);
1887 	fp->f_data = NULL;
1888 
1889 	return (0);
1890 }
1891 
1892 static int
1893 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1894 {
1895 
1896 	kif->kf_type = KF_TYPE_KQUEUE;
1897 	return (0);
1898 }
1899 
1900 static void
1901 kqueue_wakeup(struct kqueue *kq)
1902 {
1903 	KQ_OWNED(kq);
1904 
1905 	if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1906 		kq->kq_state &= ~KQ_SLEEP;
1907 		wakeup(kq);
1908 	}
1909 	if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1910 		selwakeuppri(&kq->kq_sel, PSOCK);
1911 		if (!SEL_WAITING(&kq->kq_sel))
1912 			kq->kq_state &= ~KQ_SEL;
1913 	}
1914 	if (!knlist_empty(&kq->kq_sel.si_note))
1915 		kqueue_schedtask(kq);
1916 	if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1917 		pgsigio(&kq->kq_sigio, SIGIO, 0);
1918 	}
1919 }
1920 
1921 /*
1922  * Walk down a list of knotes, activating them if their event has triggered.
1923  *
1924  * There is a possibility to optimize in the case of one kq watching another.
1925  * Instead of scheduling a task to wake it up, you could pass enough state
1926  * down the chain to make up the parent kqueue.  Make this code functional
1927  * first.
1928  */
1929 void
1930 knote(struct knlist *list, long hint, int lockflags)
1931 {
1932 	struct kqueue *kq;
1933 	struct knote *kn, *tkn;
1934 	int error;
1935 
1936 	if (list == NULL)
1937 		return;
1938 
1939 	KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1940 
1941 	if ((lockflags & KNF_LISTLOCKED) == 0)
1942 		list->kl_lock(list->kl_lockarg);
1943 
1944 	/*
1945 	 * If we unlock the list lock (and set KN_INFLUX), we can
1946 	 * eliminate the kqueue scheduling, but this will introduce
1947 	 * four lock/unlock's for each knote to test.  Also, marker
1948 	 * would be needed to keep iteration position, since filters
1949 	 * or other threads could remove events.
1950 	 */
1951 	SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
1952 		kq = kn->kn_kq;
1953 		KQ_LOCK(kq);
1954 		if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1955 			/*
1956 			 * Do not process the influx notes, except for
1957 			 * the influx coming from the kq unlock in the
1958 			 * kqueue_scan().  In the later case, we do
1959 			 * not interfere with the scan, since the code
1960 			 * fragment in kqueue_scan() locks the knlist,
1961 			 * and cannot proceed until we finished.
1962 			 */
1963 			KQ_UNLOCK(kq);
1964 		} else if ((lockflags & KNF_NOKQLOCK) != 0) {
1965 			kn->kn_status |= KN_INFLUX;
1966 			KQ_UNLOCK(kq);
1967 			error = kn->kn_fop->f_event(kn, hint);
1968 			KQ_LOCK(kq);
1969 			kn->kn_status &= ~KN_INFLUX;
1970 			if (error)
1971 				KNOTE_ACTIVATE(kn, 1);
1972 			KQ_UNLOCK_FLUX(kq);
1973 		} else {
1974 			kn->kn_status |= KN_HASKQLOCK;
1975 			if (kn->kn_fop->f_event(kn, hint))
1976 				KNOTE_ACTIVATE(kn, 1);
1977 			kn->kn_status &= ~KN_HASKQLOCK;
1978 			KQ_UNLOCK(kq);
1979 		}
1980 	}
1981 	if ((lockflags & KNF_LISTLOCKED) == 0)
1982 		list->kl_unlock(list->kl_lockarg);
1983 }
1984 
1985 /*
1986  * add a knote to a knlist
1987  */
1988 void
1989 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1990 {
1991 	KNL_ASSERT_LOCK(knl, islocked);
1992 	KQ_NOTOWNED(kn->kn_kq);
1993 	KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1994 	    (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1995 	if (!islocked)
1996 		knl->kl_lock(knl->kl_lockarg);
1997 	SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1998 	if (!islocked)
1999 		knl->kl_unlock(knl->kl_lockarg);
2000 	KQ_LOCK(kn->kn_kq);
2001 	kn->kn_knlist = knl;
2002 	kn->kn_status &= ~KN_DETACHED;
2003 	KQ_UNLOCK(kn->kn_kq);
2004 }
2005 
2006 static void
2007 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
2008 {
2009 	KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2010 	KNL_ASSERT_LOCK(knl, knlislocked);
2011 	mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2012 	if (!kqislocked)
2013 		KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2014     ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2015 	if (!knlislocked)
2016 		knl->kl_lock(knl->kl_lockarg);
2017 	SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2018 	kn->kn_knlist = NULL;
2019 	if (!knlislocked)
2020 		knl->kl_unlock(knl->kl_lockarg);
2021 	if (!kqislocked)
2022 		KQ_LOCK(kn->kn_kq);
2023 	kn->kn_status |= KN_DETACHED;
2024 	if (!kqislocked)
2025 		KQ_UNLOCK(kn->kn_kq);
2026 }
2027 
2028 /*
2029  * remove knote from the specified knlist
2030  */
2031 void
2032 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2033 {
2034 
2035 	knlist_remove_kq(knl, kn, islocked, 0);
2036 }
2037 
2038 /*
2039  * remove knote from the specified knlist while in f_event handler.
2040  */
2041 void
2042 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
2043 {
2044 
2045 	knlist_remove_kq(knl, kn, 1,
2046 	    (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
2047 }
2048 
2049 int
2050 knlist_empty(struct knlist *knl)
2051 {
2052 
2053 	KNL_ASSERT_LOCKED(knl);
2054 	return SLIST_EMPTY(&knl->kl_list);
2055 }
2056 
2057 static struct mtx	knlist_lock;
2058 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2059 	MTX_DEF);
2060 static void knlist_mtx_lock(void *arg);
2061 static void knlist_mtx_unlock(void *arg);
2062 
2063 static void
2064 knlist_mtx_lock(void *arg)
2065 {
2066 
2067 	mtx_lock((struct mtx *)arg);
2068 }
2069 
2070 static void
2071 knlist_mtx_unlock(void *arg)
2072 {
2073 
2074 	mtx_unlock((struct mtx *)arg);
2075 }
2076 
2077 static void
2078 knlist_mtx_assert_locked(void *arg)
2079 {
2080 
2081 	mtx_assert((struct mtx *)arg, MA_OWNED);
2082 }
2083 
2084 static void
2085 knlist_mtx_assert_unlocked(void *arg)
2086 {
2087 
2088 	mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2089 }
2090 
2091 static void
2092 knlist_rw_rlock(void *arg)
2093 {
2094 
2095 	rw_rlock((struct rwlock *)arg);
2096 }
2097 
2098 static void
2099 knlist_rw_runlock(void *arg)
2100 {
2101 
2102 	rw_runlock((struct rwlock *)arg);
2103 }
2104 
2105 static void
2106 knlist_rw_assert_locked(void *arg)
2107 {
2108 
2109 	rw_assert((struct rwlock *)arg, RA_LOCKED);
2110 }
2111 
2112 static void
2113 knlist_rw_assert_unlocked(void *arg)
2114 {
2115 
2116 	rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2117 }
2118 
2119 void
2120 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2121     void (*kl_unlock)(void *),
2122     void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2123 {
2124 
2125 	if (lock == NULL)
2126 		knl->kl_lockarg = &knlist_lock;
2127 	else
2128 		knl->kl_lockarg = lock;
2129 
2130 	if (kl_lock == NULL)
2131 		knl->kl_lock = knlist_mtx_lock;
2132 	else
2133 		knl->kl_lock = kl_lock;
2134 	if (kl_unlock == NULL)
2135 		knl->kl_unlock = knlist_mtx_unlock;
2136 	else
2137 		knl->kl_unlock = kl_unlock;
2138 	if (kl_assert_locked == NULL)
2139 		knl->kl_assert_locked = knlist_mtx_assert_locked;
2140 	else
2141 		knl->kl_assert_locked = kl_assert_locked;
2142 	if (kl_assert_unlocked == NULL)
2143 		knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2144 	else
2145 		knl->kl_assert_unlocked = kl_assert_unlocked;
2146 
2147 	SLIST_INIT(&knl->kl_list);
2148 }
2149 
2150 void
2151 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2152 {
2153 
2154 	knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2155 }
2156 
2157 void
2158 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2159 {
2160 
2161 	knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2162 	    knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2163 }
2164 
2165 void
2166 knlist_destroy(struct knlist *knl)
2167 {
2168 
2169 #ifdef INVARIANTS
2170 	/*
2171 	 * if we run across this error, we need to find the offending
2172 	 * driver and have it call knlist_clear or knlist_delete.
2173 	 */
2174 	if (!SLIST_EMPTY(&knl->kl_list))
2175 		printf("WARNING: destroying knlist w/ knotes on it!\n");
2176 #endif
2177 
2178 	knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2179 	SLIST_INIT(&knl->kl_list);
2180 }
2181 
2182 /*
2183  * Even if we are locked, we may need to drop the lock to allow any influx
2184  * knotes time to "settle".
2185  */
2186 void
2187 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2188 {
2189 	struct knote *kn, *kn2;
2190 	struct kqueue *kq;
2191 
2192 	if (islocked)
2193 		KNL_ASSERT_LOCKED(knl);
2194 	else {
2195 		KNL_ASSERT_UNLOCKED(knl);
2196 again:		/* need to reacquire lock since we have dropped it */
2197 		knl->kl_lock(knl->kl_lockarg);
2198 	}
2199 
2200 	SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2201 		kq = kn->kn_kq;
2202 		KQ_LOCK(kq);
2203 		if ((kn->kn_status & KN_INFLUX)) {
2204 			KQ_UNLOCK(kq);
2205 			continue;
2206 		}
2207 		knlist_remove_kq(knl, kn, 1, 1);
2208 		if (killkn) {
2209 			kn->kn_status |= KN_INFLUX | KN_DETACHED;
2210 			KQ_UNLOCK(kq);
2211 			knote_drop(kn, td);
2212 		} else {
2213 			/* Make sure cleared knotes disappear soon */
2214 			kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2215 			KQ_UNLOCK(kq);
2216 		}
2217 		kq = NULL;
2218 	}
2219 
2220 	if (!SLIST_EMPTY(&knl->kl_list)) {
2221 		/* there are still KN_INFLUX remaining */
2222 		kn = SLIST_FIRST(&knl->kl_list);
2223 		kq = kn->kn_kq;
2224 		KQ_LOCK(kq);
2225 		KASSERT(kn->kn_status & KN_INFLUX,
2226 		    ("knote removed w/o list lock"));
2227 		knl->kl_unlock(knl->kl_lockarg);
2228 		kq->kq_state |= KQ_FLUXWAIT;
2229 		msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2230 		kq = NULL;
2231 		goto again;
2232 	}
2233 
2234 	if (islocked)
2235 		KNL_ASSERT_LOCKED(knl);
2236 	else {
2237 		knl->kl_unlock(knl->kl_lockarg);
2238 		KNL_ASSERT_UNLOCKED(knl);
2239 	}
2240 }
2241 
2242 /*
2243  * Remove all knotes referencing a specified fd must be called with FILEDESC
2244  * lock.  This prevents a race where a new fd comes along and occupies the
2245  * entry and we attach a knote to the fd.
2246  */
2247 void
2248 knote_fdclose(struct thread *td, int fd)
2249 {
2250 	struct filedesc *fdp = td->td_proc->p_fd;
2251 	struct kqueue *kq;
2252 	struct knote *kn;
2253 	int influx;
2254 
2255 	FILEDESC_XLOCK_ASSERT(fdp);
2256 
2257 	/*
2258 	 * We shouldn't have to worry about new kevents appearing on fd
2259 	 * since filedesc is locked.
2260 	 */
2261 	TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2262 		KQ_LOCK(kq);
2263 
2264 again:
2265 		influx = 0;
2266 		while (kq->kq_knlistsize > fd &&
2267 		    (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2268 			if (kn->kn_status & KN_INFLUX) {
2269 				/* someone else might be waiting on our knote */
2270 				if (influx)
2271 					wakeup(kq);
2272 				kq->kq_state |= KQ_FLUXWAIT;
2273 				msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2274 				goto again;
2275 			}
2276 			kn->kn_status |= KN_INFLUX;
2277 			KQ_UNLOCK(kq);
2278 			if (!(kn->kn_status & KN_DETACHED))
2279 				kn->kn_fop->f_detach(kn);
2280 			knote_drop(kn, td);
2281 			influx = 1;
2282 			KQ_LOCK(kq);
2283 		}
2284 		KQ_UNLOCK_FLUX(kq);
2285 	}
2286 }
2287 
2288 static int
2289 knote_attach(struct knote *kn, struct kqueue *kq)
2290 {
2291 	struct klist *list;
2292 
2293 	KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2294 	KQ_OWNED(kq);
2295 
2296 	if (kn->kn_fop->f_isfd) {
2297 		if (kn->kn_id >= kq->kq_knlistsize)
2298 			return ENOMEM;
2299 		list = &kq->kq_knlist[kn->kn_id];
2300 	} else {
2301 		if (kq->kq_knhash == NULL)
2302 			return ENOMEM;
2303 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2304 	}
2305 
2306 	SLIST_INSERT_HEAD(list, kn, kn_link);
2307 
2308 	return 0;
2309 }
2310 
2311 /*
2312  * knote must already have been detached using the f_detach method.
2313  * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2314  * to prevent other removal.
2315  */
2316 static void
2317 knote_drop(struct knote *kn, struct thread *td)
2318 {
2319 	struct kqueue *kq;
2320 	struct klist *list;
2321 
2322 	kq = kn->kn_kq;
2323 
2324 	KQ_NOTOWNED(kq);
2325 	KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2326 	    ("knote_drop called without KN_INFLUX set in kn_status"));
2327 
2328 	KQ_LOCK(kq);
2329 	if (kn->kn_fop->f_isfd)
2330 		list = &kq->kq_knlist[kn->kn_id];
2331 	else
2332 		list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2333 
2334 	if (!SLIST_EMPTY(list))
2335 		SLIST_REMOVE(list, kn, knote, kn_link);
2336 	if (kn->kn_status & KN_QUEUED)
2337 		knote_dequeue(kn);
2338 	KQ_UNLOCK_FLUX(kq);
2339 
2340 	if (kn->kn_fop->f_isfd) {
2341 		fdrop(kn->kn_fp, td);
2342 		kn->kn_fp = NULL;
2343 	}
2344 	kqueue_fo_release(kn->kn_kevent.filter);
2345 	kn->kn_fop = NULL;
2346 	knote_free(kn);
2347 }
2348 
2349 static void
2350 knote_enqueue(struct knote *kn)
2351 {
2352 	struct kqueue *kq = kn->kn_kq;
2353 
2354 	KQ_OWNED(kn->kn_kq);
2355 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2356 
2357 	TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2358 	kn->kn_status |= KN_QUEUED;
2359 	kq->kq_count++;
2360 	kqueue_wakeup(kq);
2361 }
2362 
2363 static void
2364 knote_dequeue(struct knote *kn)
2365 {
2366 	struct kqueue *kq = kn->kn_kq;
2367 
2368 	KQ_OWNED(kn->kn_kq);
2369 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2370 
2371 	TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2372 	kn->kn_status &= ~KN_QUEUED;
2373 	kq->kq_count--;
2374 }
2375 
2376 static void
2377 knote_init(void)
2378 {
2379 
2380 	knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2381 	    NULL, NULL, UMA_ALIGN_PTR, 0);
2382 }
2383 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2384 
2385 static struct knote *
2386 knote_alloc(int waitok)
2387 {
2388 
2389 	return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2390 	    M_ZERO));
2391 }
2392 
2393 static void
2394 knote_free(struct knote *kn)
2395 {
2396 
2397 	uma_zfree(knote_zone, kn);
2398 }
2399 
2400 /*
2401  * Register the kev w/ the kq specified by fd.
2402  */
2403 int
2404 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2405 {
2406 	struct kqueue *kq;
2407 	struct file *fp;
2408 	cap_rights_t rights;
2409 	int error;
2410 
2411 	error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2412 	if (error != 0)
2413 		return (error);
2414 	if ((error = kqueue_acquire(fp, &kq)) != 0)
2415 		goto noacquire;
2416 
2417 	error = kqueue_register(kq, kev, td, waitok);
2418 
2419 	kqueue_release(kq, 0);
2420 
2421 noacquire:
2422 	fdrop(fp, td);
2423 
2424 	return error;
2425 }
2426