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