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