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