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