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