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