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