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