Home | History | Annotate | Line # | Download | only in kern
kern_event.c revision 1.23.2.11
      1 /*	$NetBSD: kern_event.c,v 1.23.2.11 2008/03/24 09:39:01 yamt Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the NetBSD
     18  *	Foundation, Inc. and its contributors.
     19  * 4. Neither the name of The NetBSD Foundation nor the names of its
     20  *    contributors may be used to endorse or promote products derived
     21  *    from this software without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     24  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     26  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     27  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     33  * POSSIBILITY OF SUCH DAMAGE.
     34  */
     35 
     36 /*-
     37  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon (at) FreeBSD.org>
     38  * All rights reserved.
     39  *
     40  * Redistribution and use in source and binary forms, with or without
     41  * modification, are permitted provided that the following conditions
     42  * are met:
     43  * 1. Redistributions of source code must retain the above copyright
     44  *    notice, this list of conditions and the following disclaimer.
     45  * 2. Redistributions in binary form must reproduce the above copyright
     46  *    notice, this list of conditions and the following disclaimer in the
     47  *    documentation and/or other materials provided with the distribution.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     59  * SUCH DAMAGE.
     60  *
     61  * FreeBSD: src/sys/kern/kern_event.c,v 1.27 2001/07/05 17:10:44 rwatson Exp
     62  */
     63 
     64 #include <sys/cdefs.h>
     65 __KERNEL_RCSID(0, "$NetBSD: kern_event.c,v 1.23.2.11 2008/03/24 09:39:01 yamt Exp $");
     66 
     67 #include <sys/param.h>
     68 #include <sys/systm.h>
     69 #include <sys/kernel.h>
     70 #include <sys/proc.h>
     71 #include <sys/file.h>
     72 #include <sys/select.h>
     73 #include <sys/queue.h>
     74 #include <sys/event.h>
     75 #include <sys/eventvar.h>
     76 #include <sys/poll.h>
     77 #include <sys/malloc.h>		/* for hashinit */
     78 #include <sys/kmem.h>
     79 #include <sys/stat.h>
     80 #include <sys/filedesc.h>
     81 #include <sys/syscallargs.h>
     82 #include <sys/kauth.h>
     83 #include <sys/conf.h>
     84 #include <sys/atomic.h>
     85 
     86 static int	kqueue_scan(file_t *, size_t, struct kevent *,
     87 			    const struct timespec *, register_t *,
     88 			    const struct kevent_ops *, struct kevent *,
     89 			    size_t);
     90 static int	kqueue_ioctl(file_t *, u_long, void *);
     91 static int	kqueue_fcntl(file_t *, u_int, void *);
     92 static int	kqueue_poll(file_t *, int);
     93 static int	kqueue_kqfilter(file_t *, struct knote *);
     94 static int	kqueue_stat(file_t *, struct stat *);
     95 static int	kqueue_close(file_t *);
     96 static int	kqueue_register(struct kqueue *, struct kevent *);
     97 static void	kqueue_doclose(struct kqueue *, struct klist *, int);
     98 
     99 static void	knote_detach(struct knote *, filedesc_t *fdp, bool);
    100 static void	knote_enqueue(struct knote *);
    101 static void	knote_dequeue(struct knote *);
    102 static void	knote_activate(struct knote *);
    103 
    104 static void	filt_kqdetach(struct knote *);
    105 static int	filt_kqueue(struct knote *, long hint);
    106 static int	filt_procattach(struct knote *);
    107 static void	filt_procdetach(struct knote *);
    108 static int	filt_proc(struct knote *, long hint);
    109 static int	filt_fileattach(struct knote *);
    110 static void	filt_timerexpire(void *x);
    111 static int	filt_timerattach(struct knote *);
    112 static void	filt_timerdetach(struct knote *);
    113 static int	filt_timer(struct knote *, long hint);
    114 
    115 static const struct fileops kqueueops = {
    116 	(void *)enxio, (void *)enxio, kqueue_ioctl, kqueue_fcntl, kqueue_poll,
    117 	kqueue_stat, kqueue_close, kqueue_kqfilter
    118 };
    119 
    120 static const struct filterops kqread_filtops =
    121 	{ 1, NULL, filt_kqdetach, filt_kqueue };
    122 static const struct filterops proc_filtops =
    123 	{ 0, filt_procattach, filt_procdetach, filt_proc };
    124 static const struct filterops file_filtops =
    125 	{ 1, filt_fileattach, NULL, NULL };
    126 static const struct filterops timer_filtops =
    127 	{ 0, filt_timerattach, filt_timerdetach, filt_timer };
    128 
    129 static u_int	kq_ncallouts = 0;
    130 static int	kq_calloutmax = (4 * 1024);
    131 
    132 MALLOC_DEFINE(M_KEVENT, "kevent", "kevents/knotes");	/* for hashinit */
    133 
    134 #define	KN_HASHSIZE		64		/* XXX should be tunable */
    135 #define	KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
    136 
    137 extern const struct filterops sig_filtops;
    138 
    139 /*
    140  * Table for for all system-defined filters.
    141  * These should be listed in the numeric order of the EVFILT_* defines.
    142  * If filtops is NULL, the filter isn't implemented in NetBSD.
    143  * End of list is when name is NULL.
    144  *
    145  * Note that 'refcnt' is meaningless for built-in filters.
    146  */
    147 struct kfilter {
    148 	const char	*name;		/* name of filter */
    149 	uint32_t	filter;		/* id of filter */
    150 	unsigned	refcnt;		/* reference count */
    151 	const struct filterops *filtops;/* operations for filter */
    152 	size_t		namelen;	/* length of name string */
    153 };
    154 
    155 /* System defined filters */
    156 static struct kfilter sys_kfilters[] = {
    157 	{ "EVFILT_READ",	EVFILT_READ,	0, &file_filtops, 0 },
    158 	{ "EVFILT_WRITE",	EVFILT_WRITE,	0, &file_filtops, 0, },
    159 	{ "EVFILT_AIO",		EVFILT_AIO,	0, NULL, 0 },
    160 	{ "EVFILT_VNODE",	EVFILT_VNODE,	0, &file_filtops, 0 },
    161 	{ "EVFILT_PROC",	EVFILT_PROC,	0, &proc_filtops, 0 },
    162 	{ "EVFILT_SIGNAL",	EVFILT_SIGNAL,	0, &sig_filtops, 0 },
    163 	{ "EVFILT_TIMER",	EVFILT_TIMER,	0, &timer_filtops, 0 },
    164 	{ NULL,			0,		0, NULL, 0 },
    165 };
    166 
    167 /* User defined kfilters */
    168 static struct kfilter	*user_kfilters;		/* array */
    169 static int		user_kfilterc;		/* current offset */
    170 static int		user_kfiltermaxc;	/* max size so far */
    171 static size_t		user_kfiltersz;		/* size of allocated memory */
    172 
    173 /* Locks */
    174 static krwlock_t	kqueue_filter_lock;	/* lock on filter lists */
    175 static kmutex_t		kqueue_misc_lock;	/* miscellaneous */
    176 
    177 /*
    178  * Initialize the kqueue subsystem.
    179  */
    180 void
    181 kqueue_init(void)
    182 {
    183 
    184 	rw_init(&kqueue_filter_lock);
    185 	mutex_init(&kqueue_misc_lock, MUTEX_DEFAULT, IPL_NONE);
    186 }
    187 
    188 /*
    189  * Find kfilter entry by name, or NULL if not found.
    190  */
    191 static struct kfilter *
    192 kfilter_byname_sys(const char *name)
    193 {
    194 	int i;
    195 
    196 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    197 
    198 	for (i = 0; sys_kfilters[i].name != NULL; i++) {
    199 		if (strcmp(name, sys_kfilters[i].name) == 0)
    200 			return &sys_kfilters[i];
    201 	}
    202 	return NULL;
    203 }
    204 
    205 static struct kfilter *
    206 kfilter_byname_user(const char *name)
    207 {
    208 	int i;
    209 
    210 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    211 
    212 	/* user filter slots have a NULL name if previously deregistered */
    213 	for (i = 0; i < user_kfilterc ; i++) {
    214 		if (user_kfilters[i].name != NULL &&
    215 		    strcmp(name, user_kfilters[i].name) == 0)
    216 			return &user_kfilters[i];
    217 	}
    218 	return NULL;
    219 }
    220 
    221 static struct kfilter *
    222 kfilter_byname(const char *name)
    223 {
    224 	struct kfilter *kfilter;
    225 
    226 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    227 
    228 	if ((kfilter = kfilter_byname_sys(name)) != NULL)
    229 		return kfilter;
    230 
    231 	return kfilter_byname_user(name);
    232 }
    233 
    234 /*
    235  * Find kfilter entry by filter id, or NULL if not found.
    236  * Assumes entries are indexed in filter id order, for speed.
    237  */
    238 static struct kfilter *
    239 kfilter_byfilter(uint32_t filter)
    240 {
    241 	struct kfilter *kfilter;
    242 
    243 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    244 
    245 	if (filter < EVFILT_SYSCOUNT)	/* it's a system filter */
    246 		kfilter = &sys_kfilters[filter];
    247 	else if (user_kfilters != NULL &&
    248 	    filter < EVFILT_SYSCOUNT + user_kfilterc)
    249 					/* it's a user filter */
    250 		kfilter = &user_kfilters[filter - EVFILT_SYSCOUNT];
    251 	else
    252 		return (NULL);		/* out of range */
    253 	KASSERT(kfilter->filter == filter);	/* sanity check! */
    254 	return (kfilter);
    255 }
    256 
    257 /*
    258  * Register a new kfilter. Stores the entry in user_kfilters.
    259  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    260  * If retfilter != NULL, the new filterid is returned in it.
    261  */
    262 int
    263 kfilter_register(const char *name, const struct filterops *filtops,
    264 		 int *retfilter)
    265 {
    266 	struct kfilter *kfilter;
    267 	size_t len;
    268 	int i;
    269 
    270 	if (name == NULL || name[0] == '\0' || filtops == NULL)
    271 		return (EINVAL);	/* invalid args */
    272 
    273 	rw_enter(&kqueue_filter_lock, RW_WRITER);
    274 	if (kfilter_byname(name) != NULL) {
    275 		rw_exit(&kqueue_filter_lock);
    276 		return (EEXIST);	/* already exists */
    277 	}
    278 	if (user_kfilterc > 0xffffffff - EVFILT_SYSCOUNT) {
    279 		rw_exit(&kqueue_filter_lock);
    280 		return (EINVAL);	/* too many */
    281 	}
    282 
    283 	for (i = 0; i < user_kfilterc; i++) {
    284 		kfilter = &user_kfilters[i];
    285 		if (kfilter->name == NULL) {
    286 			/* Previously deregistered slot.  Reuse. */
    287 			goto reuse;
    288 		}
    289 	}
    290 
    291 	/* check if need to grow user_kfilters */
    292 	if (user_kfilterc + 1 > user_kfiltermaxc) {
    293 		/* Grow in KFILTER_EXTENT chunks. */
    294 		user_kfiltermaxc += KFILTER_EXTENT;
    295 		len = user_kfiltermaxc * sizeof(struct filter *);
    296 		kfilter = kmem_alloc(len, KM_SLEEP);
    297 		memset((char *)kfilter + user_kfiltersz, 0, len - user_kfiltersz);
    298 		if (user_kfilters != NULL) {
    299 			memcpy(kfilter, user_kfilters, user_kfiltersz);
    300 			kmem_free(user_kfilters, user_kfiltersz);
    301 		}
    302 		user_kfiltersz = len;
    303 		user_kfilters = kfilter;
    304 	}
    305 	/* Adding new slot */
    306 	kfilter = &user_kfilters[user_kfilterc++];
    307 reuse:
    308 	kfilter->namelen = strlen(name) + 1;
    309 	kfilter->name = kmem_alloc(kfilter->namelen, KM_SLEEP);
    310 	memcpy(__UNCONST(kfilter->name), name, kfilter->namelen);
    311 
    312 	kfilter->filter = (kfilter - user_kfilters) + EVFILT_SYSCOUNT;
    313 
    314 	kfilter->filtops = kmem_alloc(sizeof(*filtops), KM_SLEEP);
    315 	memcpy(__UNCONST(kfilter->filtops), filtops, sizeof(*filtops));
    316 
    317 	if (retfilter != NULL)
    318 		*retfilter = kfilter->filter;
    319 	rw_exit(&kqueue_filter_lock);
    320 
    321 	return (0);
    322 }
    323 
    324 /*
    325  * Unregister a kfilter previously registered with kfilter_register.
    326  * This retains the filter id, but clears the name and frees filtops (filter
    327  * operations), so that the number isn't reused during a boot.
    328  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    329  */
    330 int
    331 kfilter_unregister(const char *name)
    332 {
    333 	struct kfilter *kfilter;
    334 
    335 	if (name == NULL || name[0] == '\0')
    336 		return (EINVAL);	/* invalid name */
    337 
    338 	rw_enter(&kqueue_filter_lock, RW_WRITER);
    339 	if (kfilter_byname_sys(name) != NULL) {
    340 		rw_exit(&kqueue_filter_lock);
    341 		return (EINVAL);	/* can't detach system filters */
    342 	}
    343 
    344 	kfilter = kfilter_byname_user(name);
    345 	if (kfilter == NULL) {
    346 		rw_exit(&kqueue_filter_lock);
    347 		return (ENOENT);
    348 	}
    349 	if (kfilter->refcnt != 0) {
    350 		rw_exit(&kqueue_filter_lock);
    351 		return (EBUSY);
    352 	}
    353 
    354 	/* Cast away const (but we know it's safe. */
    355 	kmem_free(__UNCONST(kfilter->name), kfilter->namelen);
    356 	kfilter->name = NULL;	/* mark as `not implemented' */
    357 
    358 	if (kfilter->filtops != NULL) {
    359 		/* Cast away const (but we know it's safe. */
    360 		kmem_free(__UNCONST(kfilter->filtops),
    361 		    sizeof(*kfilter->filtops));
    362 		kfilter->filtops = NULL; /* mark as `not implemented' */
    363 	}
    364 	rw_exit(&kqueue_filter_lock);
    365 
    366 	return (0);
    367 }
    368 
    369 
    370 /*
    371  * Filter attach method for EVFILT_READ and EVFILT_WRITE on normal file
    372  * descriptors. Calls fileops kqfilter method for given file descriptor.
    373  */
    374 static int
    375 filt_fileattach(struct knote *kn)
    376 {
    377 	file_t *fp;
    378 
    379 	fp = kn->kn_obj;
    380 
    381 	return (*fp->f_ops->fo_kqfilter)(fp, kn);
    382 }
    383 
    384 /*
    385  * Filter detach method for EVFILT_READ on kqueue descriptor.
    386  */
    387 static void
    388 filt_kqdetach(struct knote *kn)
    389 {
    390 	struct kqueue *kq;
    391 
    392 	kq = ((file_t *)kn->kn_obj)->f_data;
    393 
    394 	mutex_spin_enter(&kq->kq_lock);
    395 	SLIST_REMOVE(&kq->kq_sel.sel_klist, kn, knote, kn_selnext);
    396 	mutex_spin_exit(&kq->kq_lock);
    397 }
    398 
    399 /*
    400  * Filter event method for EVFILT_READ on kqueue descriptor.
    401  */
    402 /*ARGSUSED*/
    403 static int
    404 filt_kqueue(struct knote *kn, long hint)
    405 {
    406 	struct kqueue *kq;
    407 	int rv;
    408 
    409 	kq = ((file_t *)kn->kn_obj)->f_data;
    410 
    411 	if (hint != NOTE_SUBMIT)
    412 		mutex_spin_enter(&kq->kq_lock);
    413 	kn->kn_data = kq->kq_count;
    414 	rv = (kn->kn_data > 0);
    415 	if (hint != NOTE_SUBMIT)
    416 		mutex_spin_exit(&kq->kq_lock);
    417 
    418 	return rv;
    419 }
    420 
    421 /*
    422  * Filter attach method for EVFILT_PROC.
    423  */
    424 static int
    425 filt_procattach(struct knote *kn)
    426 {
    427 	struct proc *p, *curp;
    428 	struct lwp *curl;
    429 
    430 	curl = curlwp;
    431 	curp = curl->l_proc;
    432 
    433 	mutex_enter(&proclist_lock);
    434 	p = p_find(kn->kn_id, PFIND_LOCKED);
    435 	if (p == NULL) {
    436 		mutex_exit(&proclist_lock);
    437 		return ESRCH;
    438 	}
    439 
    440 	/*
    441 	 * Fail if it's not owned by you, or the last exec gave us
    442 	 * setuid/setgid privs (unless you're root).
    443 	 */
    444 	mutex_enter(&p->p_mutex);
    445 	mutex_exit(&proclist_lock);
    446 	if (kauth_authorize_process(curl->l_cred, KAUTH_PROCESS_KEVENT_FILTER,
    447 	    p, NULL, NULL, NULL) != 0) {
    448 	    	mutex_exit(&p->p_mutex);
    449 		return EACCES;
    450 	}
    451 
    452 	kn->kn_obj = p;
    453 	kn->kn_flags |= EV_CLEAR;	/* automatically set */
    454 
    455 	/*
    456 	 * internal flag indicating registration done by kernel
    457 	 */
    458 	if (kn->kn_flags & EV_FLAG1) {
    459 		kn->kn_data = kn->kn_sdata;	/* ppid */
    460 		kn->kn_fflags = NOTE_CHILD;
    461 		kn->kn_flags &= ~EV_FLAG1;
    462 	}
    463 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
    464     	mutex_exit(&p->p_mutex);
    465 
    466 	return 0;
    467 }
    468 
    469 /*
    470  * Filter detach method for EVFILT_PROC.
    471  *
    472  * The knote may be attached to a different process, which may exit,
    473  * leaving nothing for the knote to be attached to.  So when the process
    474  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
    475  * it will be deleted when read out.  However, as part of the knote deletion,
    476  * this routine is called, so a check is needed to avoid actually performing
    477  * a detach, because the original process might not exist any more.
    478  */
    479 static void
    480 filt_procdetach(struct knote *kn)
    481 {
    482 	struct proc *p;
    483 
    484 	if (kn->kn_status & KN_DETACHED)
    485 		return;
    486 
    487 	p = kn->kn_obj;
    488 
    489 	mutex_enter(&p->p_mutex);
    490 	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
    491 	mutex_exit(&p->p_mutex);
    492 }
    493 
    494 /*
    495  * Filter event method for EVFILT_PROC.
    496  */
    497 static int
    498 filt_proc(struct knote *kn, long hint)
    499 {
    500 	u_int event, fflag;
    501 	struct kevent kev;
    502 	struct kqueue *kq;
    503 	int error;
    504 
    505 	event = (u_int)hint & NOTE_PCTRLMASK;
    506 	kq = kn->kn_kq;
    507 	fflag = 0;
    508 
    509 	/* If the user is interested in this event, record it. */
    510 	if (kn->kn_sfflags & event)
    511 		fflag |= event;
    512 
    513 	if (event == NOTE_EXIT) {
    514 		/*
    515 		 * Process is gone, so flag the event as finished.
    516 		 *
    517 		 * Detach the knote from watched process and mark
    518 		 * it as such. We can't leave this to kqueue_scan(),
    519 		 * since the process might not exist by then. And we
    520 		 * have to do this now, since psignal KNOTE() is called
    521 		 * also for zombies and we might end up reading freed
    522 		 * memory if the kevent would already be picked up
    523 		 * and knote g/c'ed.
    524 		 */
    525 		filt_procdetach(kn);
    526 
    527 		mutex_spin_enter(&kq->kq_lock);
    528 		kn->kn_status |= KN_DETACHED;
    529 		/* Mark as ONESHOT, so that the knote it g/c'ed when read */
    530 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
    531 		kn->kn_fflags |= fflag;
    532 		mutex_spin_exit(&kq->kq_lock);
    533 
    534 		return 1;
    535 	}
    536 
    537 	mutex_spin_enter(&kq->kq_lock);
    538 	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
    539 		/*
    540 		 * Process forked, and user wants to track the new process,
    541 		 * so attach a new knote to it, and immediately report an
    542 		 * event with the parent's pid.  Register knote with new
    543 		 * process.
    544 		 */
    545 		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
    546 		kev.filter = kn->kn_filter;
    547 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
    548 		kev.fflags = kn->kn_sfflags;
    549 		kev.data = kn->kn_id;			/* parent */
    550 		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
    551 		mutex_spin_exit(&kq->kq_lock);
    552 		error = kqueue_register(kq, &kev);
    553 		mutex_spin_enter(&kq->kq_lock);
    554 		if (error != 0)
    555 			kn->kn_fflags |= NOTE_TRACKERR;
    556 	}
    557 	kn->kn_fflags |= fflag;
    558 	fflag = kn->kn_fflags;
    559 	mutex_spin_exit(&kq->kq_lock);
    560 
    561 	return fflag != 0;
    562 }
    563 
    564 static void
    565 filt_timerexpire(void *knx)
    566 {
    567 	struct knote *kn = knx;
    568 	int tticks;
    569 
    570 	mutex_enter(&kqueue_misc_lock);
    571 	kn->kn_data++;
    572 	knote_activate(kn);
    573 	if ((kn->kn_flags & EV_ONESHOT) == 0) {
    574 		tticks = mstohz(kn->kn_sdata);
    575 		callout_schedule((callout_t *)kn->kn_hook, tticks);
    576 	}
    577 	mutex_exit(&kqueue_misc_lock);
    578 }
    579 
    580 /*
    581  * data contains amount of time to sleep, in milliseconds
    582  */
    583 static int
    584 filt_timerattach(struct knote *kn)
    585 {
    586 	callout_t *calloutp;
    587 	struct kqueue *kq;
    588 	int tticks;
    589 
    590 	tticks = mstohz(kn->kn_sdata);
    591 
    592 	/* if the supplied value is under our resolution, use 1 tick */
    593 	if (tticks == 0) {
    594 		if (kn->kn_sdata == 0)
    595 			return EINVAL;
    596 		tticks = 1;
    597 	}
    598 
    599 	if (atomic_inc_uint_nv(&kq_ncallouts) >= kq_calloutmax ||
    600 	    (calloutp = kmem_alloc(sizeof(*calloutp), KM_NOSLEEP)) == NULL) {
    601 		atomic_dec_uint(&kq_ncallouts);
    602 		return ENOMEM;
    603 	}
    604 	callout_init(calloutp, 0);
    605 
    606 	kq = kn->kn_kq;
    607 	mutex_spin_enter(&kq->kq_lock);
    608 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
    609 	kn->kn_hook = calloutp;
    610 	mutex_spin_exit(&kq->kq_lock);
    611 
    612 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
    613 
    614 	return (0);
    615 }
    616 
    617 static void
    618 filt_timerdetach(struct knote *kn)
    619 {
    620 	callout_t *calloutp;
    621 
    622 	calloutp = (callout_t *)kn->kn_hook;
    623 	callout_stop(calloutp);
    624 	callout_destroy(calloutp);
    625 	kmem_free(calloutp, sizeof(*calloutp));
    626 	atomic_dec_uint(&kq_ncallouts);
    627 }
    628 
    629 static int
    630 filt_timer(struct knote *kn, long hint)
    631 {
    632 	int rv;
    633 
    634 	mutex_enter(&kqueue_misc_lock);
    635 	rv = (kn->kn_data != 0);
    636 	mutex_exit(&kqueue_misc_lock);
    637 
    638 	return rv;
    639 }
    640 
    641 /*
    642  * filt_seltrue:
    643  *
    644  *	This filter "event" routine simulates seltrue().
    645  */
    646 int
    647 filt_seltrue(struct knote *kn, long hint)
    648 {
    649 
    650 	/*
    651 	 * We don't know how much data can be read/written,
    652 	 * but we know that it *can* be.  This is about as
    653 	 * good as select/poll does as well.
    654 	 */
    655 	kn->kn_data = 0;
    656 	return (1);
    657 }
    658 
    659 /*
    660  * This provides full kqfilter entry for device switch tables, which
    661  * has same effect as filter using filt_seltrue() as filter method.
    662  */
    663 static void
    664 filt_seltruedetach(struct knote *kn)
    665 {
    666 	/* Nothing to do */
    667 }
    668 
    669 const struct filterops seltrue_filtops =
    670 	{ 1, NULL, filt_seltruedetach, filt_seltrue };
    671 
    672 int
    673 seltrue_kqfilter(dev_t dev, struct knote *kn)
    674 {
    675 	switch (kn->kn_filter) {
    676 	case EVFILT_READ:
    677 	case EVFILT_WRITE:
    678 		kn->kn_fop = &seltrue_filtops;
    679 		break;
    680 	default:
    681 		return (EINVAL);
    682 	}
    683 
    684 	/* Nothing more to do */
    685 	return (0);
    686 }
    687 
    688 /*
    689  * kqueue(2) system call.
    690  */
    691 int
    692 sys_kqueue(struct lwp *l, const void *v, register_t *retval)
    693 {
    694 	struct kqueue *kq;
    695 	file_t *fp;
    696 	int fd, error;
    697 
    698 	if ((error = fd_allocfile(&fp, &fd)) != 0)
    699 		return error;
    700 	fp->f_flag = FREAD | FWRITE;
    701 	fp->f_type = DTYPE_KQUEUE;
    702 	fp->f_ops = &kqueueops;
    703 	kq = kmem_zalloc(sizeof(*kq), KM_SLEEP);
    704 	mutex_init(&kq->kq_lock, MUTEX_DEFAULT, IPL_SCHED);
    705 	cv_init(&kq->kq_cv, "kqueue");
    706 	selinit(&kq->kq_sel);
    707 	TAILQ_INIT(&kq->kq_head);
    708 	fp->f_data = kq;
    709 	*retval = fd;
    710 	kq->kq_fdp = curlwp->l_fd;
    711 	fd_affix(curproc, fp, fd);
    712 	return error;
    713 }
    714 
    715 /*
    716  * kevent(2) system call.
    717  */
    718 static int
    719 kevent_fetch_changes(void *private, const struct kevent *changelist,
    720 		     struct kevent *changes, size_t index, int n)
    721 {
    722 
    723 	return copyin(changelist + index, changes, n * sizeof(*changes));
    724 }
    725 
    726 static int
    727 kevent_put_events(void *private, struct kevent *events,
    728 		  struct kevent *eventlist, size_t index, int n)
    729 {
    730 
    731 	return copyout(events, eventlist + index, n * sizeof(*events));
    732 }
    733 
    734 static const struct kevent_ops kevent_native_ops = {
    735 	keo_private: NULL,
    736 	keo_fetch_timeout: copyin,
    737 	keo_fetch_changes: kevent_fetch_changes,
    738 	keo_put_events: kevent_put_events,
    739 };
    740 
    741 int
    742 sys_kevent(struct lwp *l, const struct sys_kevent_args *uap, 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, M_KEVENT, M_WAITOK,
    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 timeval	atv, sleeptv;
   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 		TIMESPEC_TO_TIMEVAL(&atv, tsp);
   1094 		if (inittimeleft(&atv, &sleeptv) == -1) {
   1095 			*retval = maxevents;
   1096 			return EINVAL;
   1097 		}
   1098 		timeout = tvtohz(&atv);
   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(&atv, &sleeptv)) > 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(&atv,
   1139 					    &sleeptv)) <= 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 				if (rv == 0) {
   1161 					/*
   1162 					 * non-ONESHOT event that hasn't
   1163 					 * triggered again, so de-queue.
   1164 					 */
   1165 					mutex_spin_enter(&kq->kq_lock);
   1166 					kn->kn_status &= ~KN_ACTIVE;
   1167 					continue;
   1168 				}
   1169 				mutex_spin_enter(&kq->kq_lock);
   1170 			}
   1171 			*kevp++ = kn->kn_kevent;
   1172 			nkev++;
   1173 			if (kn->kn_flags & EV_ONESHOT) {
   1174 				/* delete ONESHOT events after retrieval */
   1175 				mutex_spin_exit(&kq->kq_lock);
   1176 				mutex_enter(&fdp->fd_lock);
   1177 				knote_detach(kn, fdp, true);
   1178 				mutex_spin_enter(&kq->kq_lock);
   1179 			} else if (kn->kn_flags & EV_CLEAR) {
   1180 				/* clear state after retrieval */
   1181 				kn->kn_data = 0;
   1182 				kn->kn_fflags = 0;
   1183 				kn->kn_status &= ~KN_ACTIVE;
   1184 			} else {
   1185 				/* add event back on list */
   1186 				kq_check(kq);
   1187 				TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1188 				kq->kq_count++;
   1189 				kn->kn_status |= KN_QUEUED;
   1190 				kq_check(kq);
   1191 			}
   1192 			if (nkev == kevcnt) {
   1193 				/* do copyouts in kevcnt chunks */
   1194 				mutex_spin_exit(&kq->kq_lock);
   1195 				error = (*keops->keo_put_events)
   1196 				    (keops->keo_private,
   1197 				    kevbuf, ulistp, nevents, nkev);
   1198 				mutex_spin_enter(&kq->kq_lock);
   1199 				nevents += nkev;
   1200 				nkev = 0;
   1201 				kevp = kevbuf;
   1202 			}
   1203 			count--;
   1204 			if (error != 0 || count == 0) {
   1205 				/* remove marker */
   1206 				TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
   1207 				break;
   1208 			}
   1209 		}
   1210 	}
   1211  done:
   1212  	mutex_spin_exit(&kq->kq_lock);
   1213 	if (marker != NULL)
   1214 		kmem_free(marker, sizeof(*marker));
   1215 	if (nkev != 0) {
   1216 		/* copyout remaining events */
   1217 		error = (*keops->keo_put_events)(keops->keo_private,
   1218 		    kevbuf, ulistp, nevents, nkev);
   1219 	}
   1220 	*retval = maxevents - count;
   1221 
   1222 	return error;
   1223 }
   1224 
   1225 /*
   1226  * fileops ioctl method for a kqueue descriptor.
   1227  *
   1228  * Two ioctls are currently supported. They both use struct kfilter_mapping:
   1229  *	KFILTER_BYNAME		find name for filter, and return result in
   1230  *				name, which is of size len.
   1231  *	KFILTER_BYFILTER	find filter for name. len is ignored.
   1232  */
   1233 /*ARGSUSED*/
   1234 static int
   1235 kqueue_ioctl(file_t *fp, u_long com, void *data)
   1236 {
   1237 	struct kfilter_mapping	*km;
   1238 	const struct kfilter	*kfilter;
   1239 	char			*name;
   1240 	int			error;
   1241 
   1242 	km = data;
   1243 	error = 0;
   1244 	name = kmem_alloc(KFILTER_MAXNAME, KM_SLEEP);
   1245 
   1246 	switch (com) {
   1247 	case KFILTER_BYFILTER:	/* convert filter -> name */
   1248 		rw_enter(&kqueue_filter_lock, RW_READER);
   1249 		kfilter = kfilter_byfilter(km->filter);
   1250 		if (kfilter != NULL) {
   1251 			strlcpy(name, kfilter->name, KFILTER_MAXNAME);
   1252 			rw_exit(&kqueue_filter_lock);
   1253 			error = copyoutstr(name, km->name, km->len, NULL);
   1254 		} else {
   1255 			rw_exit(&kqueue_filter_lock);
   1256 			error = ENOENT;
   1257 		}
   1258 		break;
   1259 
   1260 	case KFILTER_BYNAME:	/* convert name -> filter */
   1261 		error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
   1262 		if (error) {
   1263 			break;
   1264 		}
   1265 		rw_enter(&kqueue_filter_lock, RW_READER);
   1266 		kfilter = kfilter_byname(name);
   1267 		if (kfilter != NULL)
   1268 			km->filter = kfilter->filter;
   1269 		else
   1270 			error = ENOENT;
   1271 		rw_exit(&kqueue_filter_lock);
   1272 		break;
   1273 
   1274 	default:
   1275 		error = ENOTTY;
   1276 		break;
   1277 
   1278 	}
   1279 	kmem_free(name, KFILTER_MAXNAME);
   1280 	return (error);
   1281 }
   1282 
   1283 /*
   1284  * fileops fcntl method for a kqueue descriptor.
   1285  */
   1286 static int
   1287 kqueue_fcntl(file_t *fp, u_int com, void *data)
   1288 {
   1289 
   1290 	return (ENOTTY);
   1291 }
   1292 
   1293 /*
   1294  * fileops poll method for a kqueue descriptor.
   1295  * Determine if kqueue has events pending.
   1296  */
   1297 static int
   1298 kqueue_poll(file_t *fp, int events)
   1299 {
   1300 	struct kqueue	*kq;
   1301 	int		revents;
   1302 
   1303 	kq = fp->f_data;
   1304 
   1305 	revents = 0;
   1306 	if (events & (POLLIN | POLLRDNORM)) {
   1307 		mutex_spin_enter(&kq->kq_lock);
   1308 		if (kq->kq_count != 0) {
   1309 			revents |= events & (POLLIN | POLLRDNORM);
   1310 		} else {
   1311 			selrecord(curlwp, &kq->kq_sel);
   1312 		}
   1313 		kq_check(kq);
   1314 		mutex_spin_exit(&kq->kq_lock);
   1315 	}
   1316 
   1317 	return revents;
   1318 }
   1319 
   1320 /*
   1321  * fileops stat method for a kqueue descriptor.
   1322  * Returns dummy info, with st_size being number of events pending.
   1323  */
   1324 static int
   1325 kqueue_stat(file_t *fp, struct stat *st)
   1326 {
   1327 	struct kqueue *kq;
   1328 
   1329 	kq = fp->f_data;
   1330 
   1331 	memset(st, 0, sizeof(*st));
   1332 	st->st_size = kq->kq_count;
   1333 	st->st_blksize = sizeof(struct kevent);
   1334 	st->st_mode = S_IFIFO;
   1335 
   1336 	return 0;
   1337 }
   1338 
   1339 static void
   1340 kqueue_doclose(struct kqueue *kq, struct klist *list, int fd)
   1341 {
   1342 	struct knote *kn;
   1343 	filedesc_t *fdp;
   1344 
   1345 	fdp = kq->kq_fdp;
   1346 
   1347 	KASSERT(mutex_owned(&fdp->fd_lock));
   1348 
   1349 	for (kn = SLIST_FIRST(list); kn != NULL;) {
   1350 		if (kq != kn->kn_kq) {
   1351 			kn = SLIST_NEXT(kn, kn_link);
   1352 			continue;
   1353 		}
   1354 		knote_detach(kn, fdp, true);
   1355 		mutex_enter(&fdp->fd_lock);
   1356 		kn = SLIST_FIRST(list);
   1357 	}
   1358 }
   1359 
   1360 
   1361 /*
   1362  * fileops close method for a kqueue descriptor.
   1363  */
   1364 static int
   1365 kqueue_close(file_t *fp)
   1366 {
   1367 	struct kqueue *kq;
   1368 	filedesc_t *fdp;
   1369 	fdfile_t *ff;
   1370 	int i;
   1371 
   1372 	kq = fp->f_data;
   1373 	fdp = curlwp->l_fd;
   1374 
   1375 	mutex_enter(&fdp->fd_lock);
   1376 	for (i = 0; i <= fdp->fd_lastkqfile; i++) {
   1377 		if ((ff = fdp->fd_ofiles[i]) == NULL)
   1378 			continue;
   1379 		kqueue_doclose(kq, (struct klist *)&ff->ff_knlist, i);
   1380 	}
   1381 	if (fdp->fd_knhashmask != 0) {
   1382 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
   1383 			kqueue_doclose(kq, &fdp->fd_knhash[i], -1);
   1384 		}
   1385 	}
   1386 	mutex_exit(&fdp->fd_lock);
   1387 
   1388 	KASSERT(kq->kq_count == 0);
   1389 	mutex_destroy(&kq->kq_lock);
   1390 	cv_destroy(&kq->kq_cv);
   1391 	seldestroy(&kq->kq_sel);
   1392 	kmem_free(kq, sizeof(*kq));
   1393 	fp->f_data = NULL;
   1394 
   1395 	return (0);
   1396 }
   1397 
   1398 /*
   1399  * struct fileops kqfilter method for a kqueue descriptor.
   1400  * Event triggered when monitored kqueue changes.
   1401  */
   1402 static int
   1403 kqueue_kqfilter(file_t *fp, struct knote *kn)
   1404 {
   1405 	struct kqueue *kq;
   1406 	filedesc_t *fdp;
   1407 
   1408 	kq = ((file_t *)kn->kn_obj)->f_data;
   1409 
   1410 	KASSERT(fp == kn->kn_obj);
   1411 
   1412 	if (kn->kn_filter != EVFILT_READ)
   1413 		return 1;
   1414 
   1415 	kn->kn_fop = &kqread_filtops;
   1416 	fdp = curlwp->l_fd;
   1417 	mutex_enter(&kq->kq_lock);
   1418 	SLIST_INSERT_HEAD(&kq->kq_sel.sel_klist, kn, kn_selnext);
   1419 	mutex_exit(&kq->kq_lock);
   1420 
   1421 	return 0;
   1422 }
   1423 
   1424 
   1425 /*
   1426  * Walk down a list of knotes, activating them if their event has
   1427  * triggered.  The caller's object lock (e.g. device driver lock)
   1428  * must be held.
   1429  */
   1430 void
   1431 knote(struct klist *list, long hint)
   1432 {
   1433 	struct knote *kn;
   1434 
   1435 	SLIST_FOREACH(kn, list, kn_selnext) {
   1436 		if ((*kn->kn_fop->f_event)(kn, hint))
   1437 			knote_activate(kn);
   1438 	}
   1439 }
   1440 
   1441 /*
   1442  * Remove all knotes referencing a specified fd
   1443  */
   1444 void
   1445 knote_fdclose(int fd)
   1446 {
   1447 	struct klist *list;
   1448 	struct knote *kn;
   1449 	filedesc_t *fdp;
   1450 
   1451 	fdp = curlwp->l_fd;
   1452 	list = (struct klist *)&fdp->fd_ofiles[fd]->ff_knlist;
   1453 	mutex_enter(&fdp->fd_lock);
   1454 	while ((kn = SLIST_FIRST(list)) != NULL) {
   1455 		knote_detach(kn, fdp, true);
   1456 		mutex_enter(&fdp->fd_lock);
   1457 	}
   1458 	mutex_exit(&fdp->fd_lock);
   1459 }
   1460 
   1461 /*
   1462  * Drop knote.  Called with fdp->fd_lock held, and will drop before
   1463  * returning.
   1464  */
   1465 static void
   1466 knote_detach(struct knote *kn, filedesc_t *fdp, bool dofop)
   1467 {
   1468 	struct klist *list;
   1469 
   1470 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1471 	KASSERT(mutex_owned(&fdp->fd_lock));
   1472 
   1473 	if (dofop) {
   1474 		KERNEL_LOCK(1, NULL);		/* XXXSMP */
   1475 		(*kn->kn_fop->f_detach)(kn);
   1476 		KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
   1477 	}
   1478 
   1479 	if (kn->kn_fop->f_isfd)
   1480 		list = (struct klist *)&fdp->fd_ofiles[kn->kn_id]->ff_knlist;
   1481 	else
   1482 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
   1483 
   1484 	SLIST_REMOVE(list, kn, knote, kn_link);
   1485 	knote_dequeue(kn);
   1486 	mutex_exit(&fdp->fd_lock);
   1487 	if (kn->kn_fop->f_isfd)
   1488 		fd_putfile(kn->kn_id);
   1489 	atomic_dec_uint(&kn->kn_kfilter->refcnt);
   1490 	kmem_free(kn, sizeof(*kn));
   1491 }
   1492 
   1493 /*
   1494  * Queue new event for knote.
   1495  */
   1496 static void
   1497 knote_enqueue(struct knote *kn)
   1498 {
   1499 	struct kqueue *kq;
   1500 
   1501 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1502 
   1503 	kq = kn->kn_kq;
   1504 
   1505 	mutex_spin_enter(&kq->kq_lock);
   1506 	if ((kn->kn_status & KN_DISABLED) != 0) {
   1507 		kn->kn_status &= ~KN_DISABLED;
   1508 	}
   1509 	if ((kn->kn_status & (KN_ACTIVE | KN_QUEUED)) == KN_ACTIVE) {
   1510 		kq_check(kq);
   1511 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1512 		kn->kn_status |= KN_QUEUED;
   1513 		kq->kq_count++;
   1514 		kq_check(kq);
   1515 		cv_broadcast(&kq->kq_cv);
   1516 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   1517 	}
   1518 	mutex_spin_exit(&kq->kq_lock);
   1519 }
   1520 
   1521 /*
   1522  * Dequeue event for knote.
   1523  */
   1524 static void
   1525 knote_dequeue(struct knote *kn)
   1526 {
   1527 	struct kqueue *kq;
   1528 
   1529 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1530 
   1531 	kq = kn->kn_kq;
   1532 
   1533 	mutex_spin_enter(&kq->kq_lock);
   1534 	if ((kn->kn_status & KN_QUEUED) != 0) {
   1535 		kq_check(kq);
   1536 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   1537 		kn->kn_status &= ~KN_QUEUED;
   1538 		kq->kq_count--;
   1539 		kq_check(kq);
   1540 	}
   1541 	mutex_spin_exit(&kq->kq_lock);
   1542 }
   1543 
   1544 /*
   1545  * Queue new event for knote.
   1546  */
   1547 static void
   1548 knote_activate(struct knote *kn)
   1549 {
   1550 	struct kqueue *kq;
   1551 
   1552 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1553 
   1554 	kq = kn->kn_kq;
   1555 
   1556 	mutex_spin_enter(&kq->kq_lock);
   1557 	kn->kn_status |= KN_ACTIVE;
   1558 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) {
   1559 		kq_check(kq);
   1560 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1561 		kn->kn_status |= KN_QUEUED;
   1562 		kq->kq_count++;
   1563 		kq_check(kq);
   1564 		cv_broadcast(&kq->kq_cv);
   1565 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   1566 	}
   1567 	mutex_spin_exit(&kq->kq_lock);
   1568 }
   1569