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