Home | History | Annotate | Line # | Download | only in kern
kern_event.c revision 1.30
      1 /*	$NetBSD: kern_event.c,v 1.30 2006/07/23 22:06:11 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon (at) FreeBSD.org>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  *
     28  * $FreeBSD: src/sys/kern/kern_event.c,v 1.27 2001/07/05 17:10:44 rwatson Exp $
     29  */
     30 
     31 #include <sys/cdefs.h>
     32 __KERNEL_RCSID(0, "$NetBSD: kern_event.c,v 1.30 2006/07/23 22:06:11 ad Exp $");
     33 
     34 #include <sys/param.h>
     35 #include <sys/systm.h>
     36 #include <sys/kernel.h>
     37 #include <sys/proc.h>
     38 #include <sys/malloc.h>
     39 #include <sys/unistd.h>
     40 #include <sys/file.h>
     41 #include <sys/fcntl.h>
     42 #include <sys/select.h>
     43 #include <sys/queue.h>
     44 #include <sys/event.h>
     45 #include <sys/eventvar.h>
     46 #include <sys/poll.h>
     47 #include <sys/pool.h>
     48 #include <sys/protosw.h>
     49 #include <sys/socket.h>
     50 #include <sys/socketvar.h>
     51 #include <sys/stat.h>
     52 #include <sys/uio.h>
     53 #include <sys/mount.h>
     54 #include <sys/filedesc.h>
     55 #include <sys/sa.h>
     56 #include <sys/syscallargs.h>
     57 #include <sys/kauth.h>
     58 
     59 static void	kqueue_wakeup(struct kqueue *kq);
     60 
     61 static int	kqueue_scan(struct file *, size_t, struct kevent *,
     62     const struct timespec *, struct lwp *, register_t *,
     63     const struct kevent_ops *);
     64 static int	kqueue_read(struct file *fp, off_t *offset, struct uio *uio,
     65 		    kauth_cred_t cred, int flags);
     66 static int	kqueue_write(struct file *fp, off_t *offset, struct uio *uio,
     67 		    kauth_cred_t cred, int flags);
     68 static int	kqueue_ioctl(struct file *fp, u_long com, void *data,
     69 		    struct lwp *l);
     70 static int	kqueue_fcntl(struct file *fp, u_int com, void *data,
     71 		    struct lwp *l);
     72 static int	kqueue_poll(struct file *fp, int events, struct lwp *l);
     73 static int	kqueue_kqfilter(struct file *fp, struct knote *kn);
     74 static int	kqueue_stat(struct file *fp, struct stat *sp, struct lwp *l);
     75 static int	kqueue_close(struct file *fp, struct lwp *l);
     76 
     77 static const struct fileops kqueueops = {
     78 	kqueue_read, kqueue_write, kqueue_ioctl, kqueue_fcntl, kqueue_poll,
     79 	kqueue_stat, kqueue_close, kqueue_kqfilter
     80 };
     81 
     82 static void	knote_attach(struct knote *kn, struct filedesc *fdp);
     83 static void	knote_drop(struct knote *kn, struct lwp *l,
     84 		    struct filedesc *fdp);
     85 static void	knote_enqueue(struct knote *kn);
     86 static void	knote_dequeue(struct knote *kn);
     87 
     88 static void	filt_kqdetach(struct knote *kn);
     89 static int	filt_kqueue(struct knote *kn, long hint);
     90 static int	filt_procattach(struct knote *kn);
     91 static void	filt_procdetach(struct knote *kn);
     92 static int	filt_proc(struct knote *kn, long hint);
     93 static int	filt_fileattach(struct knote *kn);
     94 static void	filt_timerexpire(void *knx);
     95 static int	filt_timerattach(struct knote *kn);
     96 static void	filt_timerdetach(struct knote *kn);
     97 static int	filt_timer(struct knote *kn, long hint);
     98 
     99 static const struct filterops kqread_filtops =
    100 	{ 1, NULL, filt_kqdetach, filt_kqueue };
    101 static const struct filterops proc_filtops =
    102 	{ 0, filt_procattach, filt_procdetach, filt_proc };
    103 static const struct filterops file_filtops =
    104 	{ 1, filt_fileattach, NULL, NULL };
    105 static const struct filterops timer_filtops =
    106 	{ 0, filt_timerattach, filt_timerdetach, filt_timer };
    107 
    108 static POOL_INIT(kqueue_pool, sizeof(struct kqueue), 0, 0, 0, "kqueuepl", NULL);
    109 static POOL_INIT(knote_pool, sizeof(struct knote), 0, 0, 0, "knotepl", NULL);
    110 static int	kq_ncallouts = 0;
    111 static int	kq_calloutmax = (4 * 1024);
    112 
    113 MALLOC_DEFINE(M_KEVENT, "kevent", "kevents/knotes");
    114 
    115 #define	KNOTE_ACTIVATE(kn)						\
    116 do {									\
    117 	kn->kn_status |= KN_ACTIVE;					\
    118 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
    119 		knote_enqueue(kn);					\
    120 } while(0)
    121 
    122 #define	KN_HASHSIZE		64		/* XXX should be tunable */
    123 #define	KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
    124 
    125 extern const struct filterops sig_filtops;
    126 
    127 /*
    128  * Table for for all system-defined filters.
    129  * These should be listed in the numeric order of the EVFILT_* defines.
    130  * If filtops is NULL, the filter isn't implemented in NetBSD.
    131  * End of list is when name is NULL.
    132  */
    133 struct kfilter {
    134 	const char	 *name;		/* name of filter */
    135 	uint32_t	  filter;	/* id of filter */
    136 	const struct filterops *filtops;/* operations for filter */
    137 };
    138 
    139 		/* System defined filters */
    140 static const struct kfilter sys_kfilters[] = {
    141 	{ "EVFILT_READ",	EVFILT_READ,	&file_filtops },
    142 	{ "EVFILT_WRITE",	EVFILT_WRITE,	&file_filtops },
    143 	{ "EVFILT_AIO",		EVFILT_AIO,	NULL },
    144 	{ "EVFILT_VNODE",	EVFILT_VNODE,	&file_filtops },
    145 	{ "EVFILT_PROC",	EVFILT_PROC,	&proc_filtops },
    146 	{ "EVFILT_SIGNAL",	EVFILT_SIGNAL,	&sig_filtops },
    147 	{ "EVFILT_TIMER",	EVFILT_TIMER,	&timer_filtops },
    148 	{ NULL,			0,		NULL },	/* end of list */
    149 };
    150 
    151 		/* User defined kfilters */
    152 static struct kfilter	*user_kfilters;		/* array */
    153 static int		user_kfilterc;		/* current offset */
    154 static int		user_kfiltermaxc;	/* max size so far */
    155 
    156 /*
    157  * Find kfilter entry by name, or NULL if not found.
    158  */
    159 static const struct kfilter *
    160 kfilter_byname_sys(const char *name)
    161 {
    162 	int i;
    163 
    164 	for (i = 0; sys_kfilters[i].name != NULL; i++) {
    165 		if (strcmp(name, sys_kfilters[i].name) == 0)
    166 			return (&sys_kfilters[i]);
    167 	}
    168 	return (NULL);
    169 }
    170 
    171 static struct kfilter *
    172 kfilter_byname_user(const char *name)
    173 {
    174 	int i;
    175 
    176 	/* user_kfilters[] could be NULL if no filters were registered */
    177 	if (!user_kfilters)
    178 		return (NULL);
    179 
    180 	for (i = 0; user_kfilters[i].name != NULL; i++) {
    181 		if (user_kfilters[i].name != '\0' &&
    182 		    strcmp(name, user_kfilters[i].name) == 0)
    183 			return (&user_kfilters[i]);
    184 	}
    185 	return (NULL);
    186 }
    187 
    188 static const struct kfilter *
    189 kfilter_byname(const char *name)
    190 {
    191 	const struct kfilter *kfilter;
    192 
    193 	if ((kfilter = kfilter_byname_sys(name)) != NULL)
    194 		return (kfilter);
    195 
    196 	return (kfilter_byname_user(name));
    197 }
    198 
    199 /*
    200  * Find kfilter entry by filter id, or NULL if not found.
    201  * Assumes entries are indexed in filter id order, for speed.
    202  */
    203 static const struct kfilter *
    204 kfilter_byfilter(uint32_t filter)
    205 {
    206 	const struct kfilter *kfilter;
    207 
    208 	if (filter < EVFILT_SYSCOUNT)	/* it's a system filter */
    209 		kfilter = &sys_kfilters[filter];
    210 	else if (user_kfilters != NULL &&
    211 	    filter < EVFILT_SYSCOUNT + user_kfilterc)
    212 					/* it's a user filter */
    213 		kfilter = &user_kfilters[filter - EVFILT_SYSCOUNT];
    214 	else
    215 		return (NULL);		/* out of range */
    216 	KASSERT(kfilter->filter == filter);	/* sanity check! */
    217 	return (kfilter);
    218 }
    219 
    220 /*
    221  * Register a new kfilter. Stores the entry in user_kfilters.
    222  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    223  * If retfilter != NULL, the new filterid is returned in it.
    224  */
    225 int
    226 kfilter_register(const char *name, const struct filterops *filtops,
    227     int *retfilter)
    228 {
    229 	struct kfilter *kfilter;
    230 	void *space;
    231 	int len;
    232 
    233 	if (name == NULL || name[0] == '\0' || filtops == NULL)
    234 		return (EINVAL);	/* invalid args */
    235 	if (kfilter_byname(name) != NULL)
    236 		return (EEXIST);	/* already exists */
    237 	if (user_kfilterc > 0xffffffff - EVFILT_SYSCOUNT)
    238 		return (EINVAL);	/* too many */
    239 
    240 	/* check if need to grow user_kfilters */
    241 	if (user_kfilterc + 1 > user_kfiltermaxc) {
    242 		/*
    243 		 * Grow in KFILTER_EXTENT chunks. Use malloc(9), because we
    244 		 * want to traverse user_kfilters as an array.
    245 		 */
    246 		user_kfiltermaxc += KFILTER_EXTENT;
    247 		kfilter = malloc(user_kfiltermaxc * sizeof(struct filter *),
    248 		    M_KEVENT, M_WAITOK);
    249 
    250 		/* copy existing user_kfilters */
    251 		if (user_kfilters != NULL)
    252 			memcpy((caddr_t)kfilter, (caddr_t)user_kfilters,
    253 			    user_kfilterc * sizeof(struct kfilter *));
    254 					/* zero new sections */
    255 		memset((caddr_t)kfilter +
    256 		    user_kfilterc * sizeof(struct kfilter *), 0,
    257 		    (user_kfiltermaxc - user_kfilterc) *
    258 		    sizeof(struct kfilter *));
    259 					/* switch to new kfilter */
    260 		if (user_kfilters != NULL)
    261 			free(user_kfilters, M_KEVENT);
    262 		user_kfilters = kfilter;
    263 	}
    264 	len = strlen(name) + 1;		/* copy name */
    265 	space = malloc(len, M_KEVENT, M_WAITOK);
    266 	memcpy(space, name, len);
    267 	user_kfilters[user_kfilterc].name = space;
    268 
    269 	user_kfilters[user_kfilterc].filter = user_kfilterc + EVFILT_SYSCOUNT;
    270 
    271 	len = sizeof(struct filterops);	/* copy filtops */
    272 	space = malloc(len, M_KEVENT, M_WAITOK);
    273 	memcpy(space, filtops, len);
    274 	user_kfilters[user_kfilterc].filtops = space;
    275 
    276 	if (retfilter != NULL)
    277 		*retfilter = user_kfilters[user_kfilterc].filter;
    278 	user_kfilterc++;		/* finally, increment count */
    279 	return (0);
    280 }
    281 
    282 /*
    283  * Unregister a kfilter previously registered with kfilter_register.
    284  * This retains the filter id, but clears the name and frees filtops (filter
    285  * operations), so that the number isn't reused during a boot.
    286  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    287  */
    288 int
    289 kfilter_unregister(const char *name)
    290 {
    291 	struct kfilter *kfilter;
    292 
    293 	if (name == NULL || name[0] == '\0')
    294 		return (EINVAL);	/* invalid name */
    295 
    296 	if (kfilter_byname_sys(name) != NULL)
    297 		return (EINVAL);	/* can't detach system filters */
    298 
    299 	kfilter = kfilter_byname_user(name);
    300 	if (kfilter == NULL)		/* not found */
    301 		return (ENOENT);
    302 
    303 	if (kfilter->name[0] != '\0') {
    304 		/* XXXUNCONST Cast away const (but we know it's safe. */
    305 		free(__UNCONST(kfilter->name), M_KEVENT);
    306 		kfilter->name = "";	/* mark as `not implemented' */
    307 	}
    308 	if (kfilter->filtops != NULL) {
    309 		/* XXXUNCONST Cast away const (but we know it's safe. */
    310 		free(__UNCONST(kfilter->filtops), M_KEVENT);
    311 		kfilter->filtops = NULL; /* mark as `not implemented' */
    312 	}
    313 	return (0);
    314 }
    315 
    316 
    317 /*
    318  * Filter attach method for EVFILT_READ and EVFILT_WRITE on normal file
    319  * descriptors. Calls struct fileops kqfilter method for given file descriptor.
    320  */
    321 static int
    322 filt_fileattach(struct knote *kn)
    323 {
    324 	struct file *fp;
    325 
    326 	fp = kn->kn_fp;
    327 	return ((*fp->f_ops->fo_kqfilter)(fp, kn));
    328 }
    329 
    330 /*
    331  * Filter detach method for EVFILT_READ on kqueue descriptor.
    332  */
    333 static void
    334 filt_kqdetach(struct knote *kn)
    335 {
    336 	struct kqueue *kq;
    337 
    338 	kq = (struct kqueue *)kn->kn_fp->f_data;
    339 	SLIST_REMOVE(&kq->kq_sel.sel_klist, kn, knote, kn_selnext);
    340 }
    341 
    342 /*
    343  * Filter event method for EVFILT_READ on kqueue descriptor.
    344  */
    345 /*ARGSUSED*/
    346 static int
    347 filt_kqueue(struct knote *kn, long hint)
    348 {
    349 	struct kqueue *kq;
    350 
    351 	kq = (struct kqueue *)kn->kn_fp->f_data;
    352 	kn->kn_data = kq->kq_count;
    353 	return (kn->kn_data > 0);
    354 }
    355 
    356 /*
    357  * Filter attach method for EVFILT_PROC.
    358  */
    359 static int
    360 filt_procattach(struct knote *kn)
    361 {
    362 	struct proc *p, *curp;
    363 	struct lwp *curl;
    364 
    365 	curl = curlwp;
    366 	curp = curl->l_proc;
    367 
    368 	p = pfind(kn->kn_id);
    369 	if (p == NULL)
    370 		return (ESRCH);
    371 
    372 	/*
    373 	 * Fail if it's not owned by you, or the last exec gave us
    374 	 * setuid/setgid privs (unless you're root).
    375 	 */
    376 	if ((kauth_cred_getuid(p->p_cred) != kauth_cred_getuid(curl->l_cred) ||
    377 	    (p->p_flag & P_SUGID)) && kauth_authorize_generic(curl->l_cred,
    378 	    KAUTH_GENERIC_ISSUSER, &curl->l_acflag) != 0)
    379 		return (EACCES);
    380 
    381 	kn->kn_ptr.p_proc = p;
    382 	kn->kn_flags |= EV_CLEAR;	/* automatically set */
    383 
    384 	/*
    385 	 * internal flag indicating registration done by kernel
    386 	 */
    387 	if (kn->kn_flags & EV_FLAG1) {
    388 		kn->kn_data = kn->kn_sdata;	/* ppid */
    389 		kn->kn_fflags = NOTE_CHILD;
    390 		kn->kn_flags &= ~EV_FLAG1;
    391 	}
    392 
    393 	/* XXXSMP lock the process? */
    394 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
    395 
    396 	return (0);
    397 }
    398 
    399 /*
    400  * Filter detach method for EVFILT_PROC.
    401  *
    402  * The knote may be attached to a different process, which may exit,
    403  * leaving nothing for the knote to be attached to.  So when the process
    404  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
    405  * it will be deleted when read out.  However, as part of the knote deletion,
    406  * this routine is called, so a check is needed to avoid actually performing
    407  * a detach, because the original process might not exist any more.
    408  */
    409 static void
    410 filt_procdetach(struct knote *kn)
    411 {
    412 	struct proc *p;
    413 
    414 	if (kn->kn_status & KN_DETACHED)
    415 		return;
    416 
    417 	p = kn->kn_ptr.p_proc;
    418 	KASSERT(p->p_stat == SZOMB || pfind(kn->kn_id) == p);
    419 
    420 	/* XXXSMP lock the process? */
    421 	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
    422 }
    423 
    424 /*
    425  * Filter event method for EVFILT_PROC.
    426  */
    427 static int
    428 filt_proc(struct knote *kn, long hint)
    429 {
    430 	u_int event;
    431 
    432 	/*
    433 	 * mask off extra data
    434 	 */
    435 	event = (u_int)hint & NOTE_PCTRLMASK;
    436 
    437 	/*
    438 	 * if the user is interested in this event, record it.
    439 	 */
    440 	if (kn->kn_sfflags & event)
    441 		kn->kn_fflags |= event;
    442 
    443 	/*
    444 	 * process is gone, so flag the event as finished.
    445 	 */
    446 	if (event == NOTE_EXIT) {
    447 		/*
    448 		 * Detach the knote from watched process and mark
    449 		 * it as such. We can't leave this to kqueue_scan(),
    450 		 * since the process might not exist by then. And we
    451 		 * have to do this now, since psignal KNOTE() is called
    452 		 * also for zombies and we might end up reading freed
    453 		 * memory if the kevent would already be picked up
    454 		 * and knote g/c'ed.
    455 		 */
    456 		kn->kn_fop->f_detach(kn);
    457 		kn->kn_status |= KN_DETACHED;
    458 
    459 		/* Mark as ONESHOT, so that the knote it g/c'ed when read */
    460 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
    461 		return (1);
    462 	}
    463 
    464 	/*
    465 	 * process forked, and user wants to track the new process,
    466 	 * so attach a new knote to it, and immediately report an
    467 	 * event with the parent's pid.
    468 	 */
    469 	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
    470 		struct kevent kev;
    471 		int error;
    472 
    473 		/*
    474 		 * register knote with new process.
    475 		 */
    476 		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
    477 		kev.filter = kn->kn_filter;
    478 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
    479 		kev.fflags = kn->kn_sfflags;
    480 		kev.data = kn->kn_id;			/* parent */
    481 		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
    482 		error = kqueue_register(kn->kn_kq, &kev, NULL);
    483 		if (error)
    484 			kn->kn_fflags |= NOTE_TRACKERR;
    485 	}
    486 
    487 	return (kn->kn_fflags != 0);
    488 }
    489 
    490 static void
    491 filt_timerexpire(void *knx)
    492 {
    493 	struct knote *kn = knx;
    494 	int tticks;
    495 
    496 	kn->kn_data++;
    497 	KNOTE_ACTIVATE(kn);
    498 
    499 	if ((kn->kn_flags & EV_ONESHOT) == 0) {
    500 		tticks = mstohz(kn->kn_sdata);
    501 		callout_schedule((struct callout *)kn->kn_hook, tticks);
    502 	}
    503 }
    504 
    505 /*
    506  * data contains amount of time to sleep, in milliseconds
    507  */
    508 static int
    509 filt_timerattach(struct knote *kn)
    510 {
    511 	struct callout *calloutp;
    512 	int tticks;
    513 
    514 	if (kq_ncallouts >= kq_calloutmax)
    515 		return (ENOMEM);
    516 	kq_ncallouts++;
    517 
    518 	tticks = mstohz(kn->kn_sdata);
    519 
    520 	/* if the supplied value is under our resolution, use 1 tick */
    521 	if (tticks == 0) {
    522 		if (kn->kn_sdata == 0)
    523 			return (EINVAL);
    524 		tticks = 1;
    525 	}
    526 
    527 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
    528 	MALLOC(calloutp, struct callout *, sizeof(*calloutp),
    529 	    M_KEVENT, 0);
    530 	callout_init(calloutp);
    531 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
    532 	kn->kn_hook = calloutp;
    533 
    534 	return (0);
    535 }
    536 
    537 static void
    538 filt_timerdetach(struct knote *kn)
    539 {
    540 	struct callout *calloutp;
    541 
    542 	calloutp = (struct callout *)kn->kn_hook;
    543 	callout_stop(calloutp);
    544 	FREE(calloutp, M_KEVENT);
    545 	kq_ncallouts--;
    546 }
    547 
    548 static int
    549 filt_timer(struct knote *kn, long hint)
    550 {
    551 	return (kn->kn_data != 0);
    552 }
    553 
    554 /*
    555  * filt_seltrue:
    556  *
    557  *	This filter "event" routine simulates seltrue().
    558  */
    559 int
    560 filt_seltrue(struct knote *kn, long hint)
    561 {
    562 
    563 	/*
    564 	 * We don't know how much data can be read/written,
    565 	 * but we know that it *can* be.  This is about as
    566 	 * good as select/poll does as well.
    567 	 */
    568 	kn->kn_data = 0;
    569 	return (1);
    570 }
    571 
    572 /*
    573  * This provides full kqfilter entry for device switch tables, which
    574  * has same effect as filter using filt_seltrue() as filter method.
    575  */
    576 static void
    577 filt_seltruedetach(struct knote *kn)
    578 {
    579 	/* Nothing to do */
    580 }
    581 
    582 static const struct filterops seltrue_filtops =
    583 	{ 1, NULL, filt_seltruedetach, filt_seltrue };
    584 
    585 int
    586 seltrue_kqfilter(dev_t dev, struct knote *kn)
    587 {
    588 	switch (kn->kn_filter) {
    589 	case EVFILT_READ:
    590 	case EVFILT_WRITE:
    591 		kn->kn_fop = &seltrue_filtops;
    592 		break;
    593 	default:
    594 		return (1);
    595 	}
    596 
    597 	/* Nothing more to do */
    598 	return (0);
    599 }
    600 
    601 /*
    602  * kqueue(2) system call.
    603  */
    604 int
    605 sys_kqueue(struct lwp *l, void *v, register_t *retval)
    606 {
    607 	struct filedesc	*fdp;
    608 	struct kqueue	*kq;
    609 	struct file	*fp;
    610 	int		fd, error;
    611 
    612 	fdp = l->l_proc->p_fd;
    613 	error = falloc(l, &fp, &fd);	/* setup a new file descriptor */
    614 	if (error)
    615 		return (error);
    616 	fp->f_flag = FREAD | FWRITE;
    617 	fp->f_type = DTYPE_KQUEUE;
    618 	fp->f_ops = &kqueueops;
    619 	kq = pool_get(&kqueue_pool, PR_WAITOK);
    620 	memset((char *)kq, 0, sizeof(struct kqueue));
    621 	simple_lock_init(&kq->kq_lock);
    622 	TAILQ_INIT(&kq->kq_head);
    623 	fp->f_data = (caddr_t)kq;	/* store the kqueue with the fp */
    624 	*retval = fd;
    625 	if (fdp->fd_knlistsize < 0)
    626 		fdp->fd_knlistsize = 0;	/* this process has a kq */
    627 	kq->kq_fdp = fdp;
    628 	FILE_SET_MATURE(fp);
    629 	FILE_UNUSE(fp, l);		/* falloc() does FILE_USE() */
    630 	return (error);
    631 }
    632 
    633 /*
    634  * kevent(2) system call.
    635  */
    636 static int
    637 kevent_fetch_changes(void *private, const struct kevent *changelist,
    638     struct kevent *changes, size_t index, int n)
    639 {
    640 	return copyin(changelist + index, changes, n * sizeof(*changes));
    641 }
    642 
    643 static int
    644 kevent_put_events(void *private, struct kevent *events,
    645     struct kevent *eventlist, size_t index, int n)
    646 {
    647 	return copyout(events, eventlist + index, n * sizeof(*events));
    648 }
    649 
    650 static const struct kevent_ops kevent_native_ops = {
    651 	keo_private: NULL,
    652 	keo_fetch_timeout: copyin,
    653 	keo_fetch_changes: kevent_fetch_changes,
    654 	keo_put_events: kevent_put_events,
    655 };
    656 
    657 int
    658 sys_kevent(struct lwp *l, void *v, register_t *retval)
    659 {
    660 	struct sys_kevent_args /* {
    661 		syscallarg(int) fd;
    662 		syscallarg(const struct kevent *) changelist;
    663 		syscallarg(size_t) nchanges;
    664 		syscallarg(struct kevent *) eventlist;
    665 		syscallarg(size_t) nevents;
    666 		syscallarg(const struct timespec *) timeout;
    667 	} */ *uap = v;
    668 
    669 	return kevent1(l, retval, SCARG(uap, fd), SCARG(uap, changelist),
    670 	    SCARG(uap, nchanges), SCARG(uap, eventlist), SCARG(uap, nevents),
    671 	    SCARG(uap, timeout), &kevent_native_ops);
    672 }
    673 
    674 int
    675 kevent1(struct lwp *l, register_t *retval, int fd,
    676     const struct kevent *changelist, size_t nchanges, struct kevent *eventlist,
    677     size_t nevents, const struct timespec *timeout,
    678     const struct kevent_ops *keops)
    679 {
    680 	struct kevent	*kevp;
    681 	struct kqueue	*kq;
    682 	struct file	*fp;
    683 	struct timespec	ts;
    684 	struct proc	*p;
    685 	size_t		i, n, ichange;
    686 	int		nerrors, error;
    687 
    688 	p = l->l_proc;
    689 	/* check that we're dealing with a kq */
    690 	fp = fd_getfile(p->p_fd, fd);
    691 	if (fp == NULL)
    692 		return (EBADF);
    693 
    694 	if (fp->f_type != DTYPE_KQUEUE) {
    695 		simple_unlock(&fp->f_slock);
    696 		return (EBADF);
    697 	}
    698 
    699 	FILE_USE(fp);
    700 
    701 	if (timeout != NULL) {
    702 		error = (*keops->keo_fetch_timeout)(timeout, &ts, sizeof(ts));
    703 		if (error)
    704 			goto done;
    705 		timeout = &ts;
    706 	}
    707 
    708 	kq = (struct kqueue *)fp->f_data;
    709 	nerrors = 0;
    710 	ichange = 0;
    711 
    712 	/* traverse list of events to register */
    713 	while (nchanges > 0) {
    714 		/* copyin a maximum of KQ_EVENTS at each pass */
    715 		n = MIN(nchanges, KQ_NEVENTS);
    716 		error = (*keops->keo_fetch_changes)(keops->keo_private,
    717 		    changelist, kq->kq_kev, ichange, n);
    718 		if (error)
    719 			goto done;
    720 		for (i = 0; i < n; i++) {
    721 			kevp = &kq->kq_kev[i];
    722 			kevp->flags &= ~EV_SYSFLAGS;
    723 			/* register each knote */
    724 			error = kqueue_register(kq, kevp, l);
    725 			if (error) {
    726 				if (nevents != 0) {
    727 					kevp->flags = EV_ERROR;
    728 					kevp->data = error;
    729 					error = (*keops->keo_put_events)
    730 					    (keops->keo_private, kevp,
    731 					    eventlist, nerrors, 1);
    732 					if (error)
    733 						goto done;
    734 					nevents--;
    735 					nerrors++;
    736 				} else {
    737 					goto done;
    738 				}
    739 			}
    740 		}
    741 		nchanges -= n;	/* update the results */
    742 		ichange += n;
    743 	}
    744 	if (nerrors) {
    745 		*retval = nerrors;
    746 		error = 0;
    747 		goto done;
    748 	}
    749 
    750 	/* actually scan through the events */
    751 	error = kqueue_scan(fp, nevents, eventlist, timeout, l, retval, keops);
    752  done:
    753 	FILE_UNUSE(fp, l);
    754 	return (error);
    755 }
    756 
    757 /*
    758  * Register a given kevent kev onto the kqueue
    759  */
    760 int
    761 kqueue_register(struct kqueue *kq, struct kevent *kev, struct lwp *l)
    762 {
    763 	const struct kfilter *kfilter;
    764 	struct filedesc	*fdp;
    765 	struct file	*fp;
    766 	struct knote	*kn;
    767 	int		s, error;
    768 
    769 	fdp = kq->kq_fdp;
    770 	fp = NULL;
    771 	kn = NULL;
    772 	error = 0;
    773 	kfilter = kfilter_byfilter(kev->filter);
    774 	if (kfilter == NULL || kfilter->filtops == NULL) {
    775 		/* filter not found nor implemented */
    776 		return (EINVAL);
    777 	}
    778 
    779 	/* search if knote already exists */
    780 	if (kfilter->filtops->f_isfd) {
    781 		/* monitoring a file descriptor */
    782 		if ((fp = fd_getfile(fdp, kev->ident)) == NULL)
    783 			return (EBADF);	/* validate descriptor */
    784 		FILE_USE(fp);
    785 
    786 		if (kev->ident < fdp->fd_knlistsize) {
    787 			SLIST_FOREACH(kn, &fdp->fd_knlist[kev->ident], kn_link)
    788 				if (kq == kn->kn_kq &&
    789 				    kev->filter == kn->kn_filter)
    790 					break;
    791 		}
    792 	} else {
    793 		/*
    794 		 * not monitoring a file descriptor, so
    795 		 * lookup knotes in internal hash table
    796 		 */
    797 		if (fdp->fd_knhashmask != 0) {
    798 			struct klist *list;
    799 
    800 			list = &fdp->fd_knhash[
    801 			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
    802 			SLIST_FOREACH(kn, list, kn_link)
    803 				if (kev->ident == kn->kn_id &&
    804 				    kq == kn->kn_kq &&
    805 				    kev->filter == kn->kn_filter)
    806 					break;
    807 		}
    808 	}
    809 
    810 	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
    811 		error = ENOENT;		/* filter not found */
    812 		goto done;
    813 	}
    814 
    815 	/*
    816 	 * kn now contains the matching knote, or NULL if no match
    817 	 */
    818 	if (kev->flags & EV_ADD) {
    819 		/* add knote */
    820 
    821 		if (kn == NULL) {
    822 			/* create new knote */
    823 			kn = pool_get(&knote_pool, PR_WAITOK);
    824 			if (kn == NULL) {
    825 				error = ENOMEM;
    826 				goto done;
    827 			}
    828 			kn->kn_fp = fp;
    829 			kn->kn_kq = kq;
    830 			kn->kn_fop = kfilter->filtops;
    831 
    832 			/*
    833 			 * apply reference count to knote structure, and
    834 			 * do not release it at the end of this routine.
    835 			 */
    836 			fp = NULL;
    837 
    838 			kn->kn_sfflags = kev->fflags;
    839 			kn->kn_sdata = kev->data;
    840 			kev->fflags = 0;
    841 			kev->data = 0;
    842 			kn->kn_kevent = *kev;
    843 
    844 			knote_attach(kn, fdp);
    845 			if ((error = kfilter->filtops->f_attach(kn)) != 0) {
    846 				knote_drop(kn, l, fdp);
    847 				goto done;
    848 			}
    849 		} else {
    850 			/* modify existing knote */
    851 
    852 			/*
    853 			 * The user may change some filter values after the
    854 			 * initial EV_ADD, but doing so will not reset any
    855 			 * filter which have already been triggered.
    856 			 */
    857 			kn->kn_sfflags = kev->fflags;
    858 			kn->kn_sdata = kev->data;
    859 			kn->kn_kevent.udata = kev->udata;
    860 		}
    861 
    862 		s = splsched();
    863 		if (kn->kn_fop->f_event(kn, 0))
    864 			KNOTE_ACTIVATE(kn);
    865 		splx(s);
    866 
    867 	} else if (kev->flags & EV_DELETE) {	/* delete knote */
    868 		kn->kn_fop->f_detach(kn);
    869 		knote_drop(kn, l, fdp);
    870 		goto done;
    871 	}
    872 
    873 	/* disable knote */
    874 	if ((kev->flags & EV_DISABLE) &&
    875 	    ((kn->kn_status & KN_DISABLED) == 0)) {
    876 		s = splsched();
    877 		kn->kn_status |= KN_DISABLED;
    878 		splx(s);
    879 	}
    880 
    881 	/* enable knote */
    882 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
    883 		s = splsched();
    884 		kn->kn_status &= ~KN_DISABLED;
    885 		if ((kn->kn_status & KN_ACTIVE) &&
    886 		    ((kn->kn_status & KN_QUEUED) == 0))
    887 			knote_enqueue(kn);
    888 		splx(s);
    889 	}
    890 
    891  done:
    892 	if (fp != NULL)
    893 		FILE_UNUSE(fp, l);
    894 	return (error);
    895 }
    896 
    897 /*
    898  * Scan through the list of events on fp (for a maximum of maxevents),
    899  * returning the results in to ulistp. Timeout is determined by tsp; if
    900  * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
    901  * as appropriate.
    902  */
    903 static int
    904 kqueue_scan(struct file *fp, size_t maxevents, struct kevent *ulistp,
    905     const struct timespec *tsp, struct lwp *l, register_t *retval,
    906     const struct kevent_ops *keops)
    907 {
    908 	struct proc	*p = l->l_proc;
    909 	struct kqueue	*kq;
    910 	struct kevent	*kevp;
    911 	struct timeval	atv, sleeptv;
    912 	struct knote	*kn, *marker=NULL;
    913 	size_t		count, nkev, nevents;
    914 	int		s, timeout, error;
    915 
    916 	kq = (struct kqueue *)fp->f_data;
    917 	count = maxevents;
    918 	nkev = nevents = error = 0;
    919 	if (count == 0)
    920 		goto done;
    921 
    922 	if (tsp) {				/* timeout supplied */
    923 		TIMESPEC_TO_TIMEVAL(&atv, tsp);
    924 		if (inittimeleft(&atv, &sleeptv) == -1) {
    925 			error = EINVAL;
    926 			goto done;
    927 		}
    928 		timeout = tvtohz(&atv);
    929 		if (timeout <= 0)
    930 			timeout = -1;           /* do poll */
    931 	} else {
    932 		/* no timeout, wait forever */
    933 		timeout = 0;
    934 	}
    935 
    936 	MALLOC(marker, struct knote *, sizeof(*marker), M_KEVENT, M_WAITOK);
    937 	memset(marker, 0, sizeof(*marker));
    938 
    939 	goto start;
    940 
    941  retry:
    942 	if (tsp && (timeout = gettimeleft(&atv, &sleeptv)) <= 0) {
    943 		goto done;
    944 	}
    945 
    946  start:
    947 	kevp = kq->kq_kev;
    948 	s = splsched();
    949 	simple_lock(&kq->kq_lock);
    950 	if (kq->kq_count == 0) {
    951 		if (timeout < 0) {
    952 			error = EWOULDBLOCK;
    953 			simple_unlock(&kq->kq_lock);
    954 		} else {
    955 			kq->kq_state |= KQ_SLEEP;
    956 			error = ltsleep(kq, PSOCK | PCATCH | PNORELOCK,
    957 					"kqread", timeout, &kq->kq_lock);
    958 		}
    959 		splx(s);
    960 		if (error == 0)
    961 			goto retry;
    962 		/* don't restart after signals... */
    963 		if (error == ERESTART)
    964 			error = EINTR;
    965 		else if (error == EWOULDBLOCK)
    966 			error = 0;
    967 		goto done;
    968 	}
    969 
    970 	/* mark end of knote list */
    971 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
    972 	simple_unlock(&kq->kq_lock);
    973 
    974 	while (count) {				/* while user wants data ... */
    975 		simple_lock(&kq->kq_lock);
    976 		kn = TAILQ_FIRST(&kq->kq_head);	/* get next knote */
    977 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
    978 		if (kn == marker) {		/* if it's our marker, stop */
    979 			/* What if it's some else's marker? */
    980 			simple_unlock(&kq->kq_lock);
    981 			splx(s);
    982 			if (count == maxevents)
    983 				goto retry;
    984 			goto done;
    985 		}
    986 		kq->kq_count--;
    987 		simple_unlock(&kq->kq_lock);
    988 
    989 		if (kn->kn_status & KN_DISABLED) {
    990 			/* don't want disabled events */
    991 			kn->kn_status &= ~KN_QUEUED;
    992 			continue;
    993 		}
    994 		if ((kn->kn_flags & EV_ONESHOT) == 0 &&
    995 		    kn->kn_fop->f_event(kn, 0) == 0) {
    996 			/*
    997 			 * non-ONESHOT event that hasn't
    998 			 * triggered again, so de-queue.
    999 			 */
   1000 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
   1001 			continue;
   1002 		}
   1003 		*kevp = kn->kn_kevent;
   1004 		kevp++;
   1005 		nkev++;
   1006 		if (kn->kn_flags & EV_ONESHOT) {
   1007 			/* delete ONESHOT events after retrieval */
   1008 			kn->kn_status &= ~KN_QUEUED;
   1009 			splx(s);
   1010 			kn->kn_fop->f_detach(kn);
   1011 			knote_drop(kn, l, p->p_fd);
   1012 			s = splsched();
   1013 		} else if (kn->kn_flags & EV_CLEAR) {
   1014 			/* clear state after retrieval */
   1015 			kn->kn_data = 0;
   1016 			kn->kn_fflags = 0;
   1017 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
   1018 		} else {
   1019 			/* add event back on list */
   1020 			simple_lock(&kq->kq_lock);
   1021 			TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1022 			kq->kq_count++;
   1023 			simple_unlock(&kq->kq_lock);
   1024 		}
   1025 		count--;
   1026 		if (nkev == KQ_NEVENTS) {
   1027 			/* do copyouts in KQ_NEVENTS chunks */
   1028 			splx(s);
   1029 			error = (*keops->keo_put_events)(keops->keo_private,
   1030 			    &kq->kq_kev[0], ulistp, nevents, nkev);
   1031 			nevents += nkev;
   1032 			nkev = 0;
   1033 			kevp = kq->kq_kev;
   1034 			s = splsched();
   1035 			if (error)
   1036 				break;
   1037 		}
   1038 	}
   1039 
   1040 	/* remove marker */
   1041 	simple_lock(&kq->kq_lock);
   1042 	TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
   1043 	simple_unlock(&kq->kq_lock);
   1044 	splx(s);
   1045  done:
   1046 	if (marker)
   1047 		FREE(marker, M_KEVENT);
   1048 
   1049 	if (nkev != 0)
   1050 		/* copyout remaining events */
   1051 		error = (*keops->keo_put_events)(keops->keo_private,
   1052 		    &kq->kq_kev[0], ulistp, nevents, nkev);
   1053 	*retval = maxevents - count;
   1054 
   1055 	return (error);
   1056 }
   1057 
   1058 /*
   1059  * struct fileops read method for a kqueue descriptor.
   1060  * Not implemented.
   1061  * XXX: This could be expanded to call kqueue_scan, if desired.
   1062  */
   1063 /*ARGSUSED*/
   1064 static int
   1065 kqueue_read(struct file *fp, off_t *offset, struct uio *uio,
   1066 	kauth_cred_t cred, int flags)
   1067 {
   1068 
   1069 	return (ENXIO);
   1070 }
   1071 
   1072 /*
   1073  * struct fileops write method for a kqueue descriptor.
   1074  * Not implemented.
   1075  */
   1076 /*ARGSUSED*/
   1077 static int
   1078 kqueue_write(struct file *fp, off_t *offset, struct uio *uio,
   1079 	kauth_cred_t cred, int flags)
   1080 {
   1081 
   1082 	return (ENXIO);
   1083 }
   1084 
   1085 /*
   1086  * struct fileops ioctl method for a kqueue descriptor.
   1087  *
   1088  * Two ioctls are currently supported. They both use struct kfilter_mapping:
   1089  *	KFILTER_BYNAME		find name for filter, and return result in
   1090  *				name, which is of size len.
   1091  *	KFILTER_BYFILTER	find filter for name. len is ignored.
   1092  */
   1093 /*ARGSUSED*/
   1094 static int
   1095 kqueue_ioctl(struct file *fp, u_long com, void *data, struct lwp *l)
   1096 {
   1097 	struct kfilter_mapping	*km;
   1098 	const struct kfilter	*kfilter;
   1099 	char			*name;
   1100 	int			error;
   1101 
   1102 	km = (struct kfilter_mapping *)data;
   1103 	error = 0;
   1104 
   1105 	switch (com) {
   1106 	case KFILTER_BYFILTER:	/* convert filter -> name */
   1107 		kfilter = kfilter_byfilter(km->filter);
   1108 		if (kfilter != NULL)
   1109 			error = copyoutstr(kfilter->name, km->name, km->len,
   1110 			    NULL);
   1111 		else
   1112 			error = ENOENT;
   1113 		break;
   1114 
   1115 	case KFILTER_BYNAME:	/* convert name -> filter */
   1116 		MALLOC(name, char *, KFILTER_MAXNAME, M_KEVENT, M_WAITOK);
   1117 		error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
   1118 		if (error) {
   1119 			FREE(name, M_KEVENT);
   1120 			break;
   1121 		}
   1122 		kfilter = kfilter_byname(name);
   1123 		if (kfilter != NULL)
   1124 			km->filter = kfilter->filter;
   1125 		else
   1126 			error = ENOENT;
   1127 		FREE(name, M_KEVENT);
   1128 		break;
   1129 
   1130 	default:
   1131 		error = ENOTTY;
   1132 
   1133 	}
   1134 	return (error);
   1135 }
   1136 
   1137 /*
   1138  * struct fileops fcntl method for a kqueue descriptor.
   1139  * Not implemented.
   1140  */
   1141 /*ARGSUSED*/
   1142 static int
   1143 kqueue_fcntl(struct file *fp, u_int com, void *data, struct lwp *l)
   1144 {
   1145 
   1146 	return (ENOTTY);
   1147 }
   1148 
   1149 /*
   1150  * struct fileops poll method for a kqueue descriptor.
   1151  * Determine if kqueue has events pending.
   1152  */
   1153 static int
   1154 kqueue_poll(struct file *fp, int events, struct lwp *l)
   1155 {
   1156 	struct kqueue	*kq;
   1157 	int		revents;
   1158 
   1159 	kq = (struct kqueue *)fp->f_data;
   1160 	revents = 0;
   1161 	if (events & (POLLIN | POLLRDNORM)) {
   1162 		if (kq->kq_count) {
   1163 			revents |= events & (POLLIN | POLLRDNORM);
   1164 		} else {
   1165 			selrecord(l, &kq->kq_sel);
   1166 		}
   1167 	}
   1168 	return (revents);
   1169 }
   1170 
   1171 /*
   1172  * struct fileops stat method for a kqueue descriptor.
   1173  * Returns dummy info, with st_size being number of events pending.
   1174  */
   1175 static int
   1176 kqueue_stat(struct file *fp, struct stat *st, struct lwp *l)
   1177 {
   1178 	struct kqueue	*kq;
   1179 
   1180 	kq = (struct kqueue *)fp->f_data;
   1181 	memset((void *)st, 0, sizeof(*st));
   1182 	st->st_size = kq->kq_count;
   1183 	st->st_blksize = sizeof(struct kevent);
   1184 	st->st_mode = S_IFIFO;
   1185 	return (0);
   1186 }
   1187 
   1188 /*
   1189  * struct fileops close method for a kqueue descriptor.
   1190  * Cleans up kqueue.
   1191  */
   1192 static int
   1193 kqueue_close(struct file *fp, struct lwp *l)
   1194 {
   1195 	struct proc	*p = l->l_proc;
   1196 	struct kqueue	*kq;
   1197 	struct filedesc	*fdp;
   1198 	struct knote	**knp, *kn, *kn0;
   1199 	int		i;
   1200 
   1201 	kq = (struct kqueue *)fp->f_data;
   1202 	fdp = p->p_fd;
   1203 	for (i = 0; i < fdp->fd_knlistsize; i++) {
   1204 		knp = &SLIST_FIRST(&fdp->fd_knlist[i]);
   1205 		kn = *knp;
   1206 		while (kn != NULL) {
   1207 			kn0 = SLIST_NEXT(kn, kn_link);
   1208 			if (kq == kn->kn_kq) {
   1209 				kn->kn_fop->f_detach(kn);
   1210 				FILE_UNUSE(kn->kn_fp, l);
   1211 				pool_put(&knote_pool, kn);
   1212 				*knp = kn0;
   1213 			} else {
   1214 				knp = &SLIST_NEXT(kn, kn_link);
   1215 			}
   1216 			kn = kn0;
   1217 		}
   1218 	}
   1219 	if (fdp->fd_knhashmask != 0) {
   1220 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
   1221 			knp = &SLIST_FIRST(&fdp->fd_knhash[i]);
   1222 			kn = *knp;
   1223 			while (kn != NULL) {
   1224 				kn0 = SLIST_NEXT(kn, kn_link);
   1225 				if (kq == kn->kn_kq) {
   1226 					kn->kn_fop->f_detach(kn);
   1227 					/* XXX non-fd release of kn->kn_ptr */
   1228 					pool_put(&knote_pool, kn);
   1229 					*knp = kn0;
   1230 				} else {
   1231 					knp = &SLIST_NEXT(kn, kn_link);
   1232 				}
   1233 				kn = kn0;
   1234 			}
   1235 		}
   1236 	}
   1237 	pool_put(&kqueue_pool, kq);
   1238 	fp->f_data = NULL;
   1239 
   1240 	return (0);
   1241 }
   1242 
   1243 /*
   1244  * wakeup a kqueue
   1245  */
   1246 static void
   1247 kqueue_wakeup(struct kqueue *kq)
   1248 {
   1249 	int s;
   1250 
   1251 	s = splsched();
   1252 	simple_lock(&kq->kq_lock);
   1253 	if (kq->kq_state & KQ_SLEEP) {		/* if currently sleeping ...  */
   1254 		kq->kq_state &= ~KQ_SLEEP;
   1255 		wakeup(kq);			/* ... wakeup */
   1256 	}
   1257 
   1258 	/* Notify select/poll and kevent. */
   1259 	selnotify(&kq->kq_sel, 0);
   1260 	simple_unlock(&kq->kq_lock);
   1261 	splx(s);
   1262 }
   1263 
   1264 /*
   1265  * struct fileops kqfilter method for a kqueue descriptor.
   1266  * Event triggered when monitored kqueue changes.
   1267  */
   1268 /*ARGSUSED*/
   1269 static int
   1270 kqueue_kqfilter(struct file *fp, struct knote *kn)
   1271 {
   1272 	struct kqueue *kq;
   1273 
   1274 	KASSERT(fp == kn->kn_fp);
   1275 	kq = (struct kqueue *)kn->kn_fp->f_data;
   1276 	if (kn->kn_filter != EVFILT_READ)
   1277 		return (1);
   1278 	kn->kn_fop = &kqread_filtops;
   1279 	SLIST_INSERT_HEAD(&kq->kq_sel.sel_klist, kn, kn_selnext);
   1280 	return (0);
   1281 }
   1282 
   1283 
   1284 /*
   1285  * Walk down a list of knotes, activating them if their event has triggered.
   1286  */
   1287 void
   1288 knote(struct klist *list, long hint)
   1289 {
   1290 	struct knote *kn;
   1291 
   1292 	SLIST_FOREACH(kn, list, kn_selnext)
   1293 		if (kn->kn_fop->f_event(kn, hint))
   1294 			KNOTE_ACTIVATE(kn);
   1295 }
   1296 
   1297 /*
   1298  * Remove all knotes from a specified klist
   1299  */
   1300 void
   1301 knote_remove(struct lwp *l, struct klist *list)
   1302 {
   1303 	struct knote *kn;
   1304 
   1305 	while ((kn = SLIST_FIRST(list)) != NULL) {
   1306 		kn->kn_fop->f_detach(kn);
   1307 		knote_drop(kn, l, l->l_proc->p_fd);
   1308 	}
   1309 }
   1310 
   1311 /*
   1312  * Remove all knotes referencing a specified fd
   1313  */
   1314 void
   1315 knote_fdclose(struct lwp *l, int fd)
   1316 {
   1317 	struct filedesc	*fdp;
   1318 	struct klist	*list;
   1319 
   1320 	fdp = l->l_proc->p_fd;
   1321 	list = &fdp->fd_knlist[fd];
   1322 	knote_remove(l, list);
   1323 }
   1324 
   1325 /*
   1326  * Attach a new knote to a file descriptor
   1327  */
   1328 static void
   1329 knote_attach(struct knote *kn, struct filedesc *fdp)
   1330 {
   1331 	struct klist	*list;
   1332 	int		size;
   1333 
   1334 	if (! kn->kn_fop->f_isfd) {
   1335 		/* if knote is not on an fd, store on internal hash table */
   1336 		if (fdp->fd_knhashmask == 0)
   1337 			fdp->fd_knhash = hashinit(KN_HASHSIZE, HASH_LIST,
   1338 			    M_KEVENT, M_WAITOK, &fdp->fd_knhashmask);
   1339 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
   1340 		goto done;
   1341 	}
   1342 
   1343 	/*
   1344 	 * otherwise, knote is on an fd.
   1345 	 * knotes are stored in fd_knlist indexed by kn->kn_id.
   1346 	 */
   1347 	if (fdp->fd_knlistsize <= kn->kn_id) {
   1348 		/* expand list, it's too small */
   1349 		size = fdp->fd_knlistsize;
   1350 		while (size <= kn->kn_id) {
   1351 			/* grow in KQ_EXTENT chunks */
   1352 			size += KQ_EXTENT;
   1353 		}
   1354 		list = malloc(size * sizeof(struct klist *), M_KEVENT,M_WAITOK);
   1355 		if (fdp->fd_knlist) {
   1356 			/* copy existing knlist */
   1357 			memcpy((caddr_t)list, (caddr_t)fdp->fd_knlist,
   1358 			    fdp->fd_knlistsize * sizeof(struct klist *));
   1359 		}
   1360 		/*
   1361 		 * Zero new memory. Stylistically, SLIST_INIT() should be
   1362 		 * used here, but that does same thing as the memset() anyway.
   1363 		 */
   1364 		memset(&list[fdp->fd_knlistsize], 0,
   1365 		    (size - fdp->fd_knlistsize) * sizeof(struct klist *));
   1366 
   1367 		/* switch to new knlist */
   1368 		if (fdp->fd_knlist != NULL)
   1369 			free(fdp->fd_knlist, M_KEVENT);
   1370 		fdp->fd_knlistsize = size;
   1371 		fdp->fd_knlist = list;
   1372 	}
   1373 
   1374 	/* get list head for this fd */
   1375 	list = &fdp->fd_knlist[kn->kn_id];
   1376  done:
   1377 	/* add new knote */
   1378 	SLIST_INSERT_HEAD(list, kn, kn_link);
   1379 	kn->kn_status = 0;
   1380 }
   1381 
   1382 /*
   1383  * Drop knote.
   1384  * Should be called at spl == 0, since we don't want to hold spl
   1385  * while calling FILE_UNUSE and free.
   1386  */
   1387 static void
   1388 knote_drop(struct knote *kn, struct lwp *l, struct filedesc *fdp)
   1389 {
   1390 	struct klist	*list;
   1391 
   1392 	if (kn->kn_fop->f_isfd)
   1393 		list = &fdp->fd_knlist[kn->kn_id];
   1394 	else
   1395 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
   1396 
   1397 	SLIST_REMOVE(list, kn, knote, kn_link);
   1398 	if (kn->kn_status & KN_QUEUED)
   1399 		knote_dequeue(kn);
   1400 	if (kn->kn_fop->f_isfd)
   1401 		FILE_UNUSE(kn->kn_fp, l);
   1402 	pool_put(&knote_pool, kn);
   1403 }
   1404 
   1405 
   1406 /*
   1407  * Queue new event for knote.
   1408  */
   1409 static void
   1410 knote_enqueue(struct knote *kn)
   1411 {
   1412 	struct kqueue	*kq;
   1413 	int		s;
   1414 
   1415 	kq = kn->kn_kq;
   1416 	KASSERT((kn->kn_status & KN_QUEUED) == 0);
   1417 
   1418 	s = splsched();
   1419 	simple_lock(&kq->kq_lock);
   1420 	TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1421 	kn->kn_status |= KN_QUEUED;
   1422 	kq->kq_count++;
   1423 	simple_unlock(&kq->kq_lock);
   1424 	splx(s);
   1425 	kqueue_wakeup(kq);
   1426 }
   1427 
   1428 /*
   1429  * Dequeue event for knote.
   1430  */
   1431 static void
   1432 knote_dequeue(struct knote *kn)
   1433 {
   1434 	struct kqueue	*kq;
   1435 	int		s;
   1436 
   1437 	KASSERT(kn->kn_status & KN_QUEUED);
   1438 	kq = kn->kn_kq;
   1439 
   1440 	s = splsched();
   1441 	simple_lock(&kq->kq_lock);
   1442 	TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   1443 	kn->kn_status &= ~KN_QUEUED;
   1444 	kq->kq_count--;
   1445 	simple_unlock(&kq->kq_lock);
   1446 	splx(s);
   1447 }
   1448