Home | History | Annotate | Line # | Download | only in kern
kern_event.c revision 1.125
      1 /*	$NetBSD: kern_event.c,v 1.125 2021/09/26 23:34:46 thorpej 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  * Copyright (c) 2009 Apple, Inc
     35  * All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  *
     46  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     47  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     49  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     50  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     51  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     52  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     53  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     54  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     55  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     56  * SUCH DAMAGE.
     57  *
     58  * FreeBSD: src/sys/kern/kern_event.c,v 1.27 2001/07/05 17:10:44 rwatson Exp
     59  */
     60 
     61 #include <sys/cdefs.h>
     62 __KERNEL_RCSID(0, "$NetBSD: kern_event.c,v 1.125 2021/09/26 23:34:46 thorpej Exp $");
     63 
     64 #include <sys/param.h>
     65 #include <sys/systm.h>
     66 #include <sys/kernel.h>
     67 #include <sys/wait.h>
     68 #include <sys/proc.h>
     69 #include <sys/file.h>
     70 #include <sys/select.h>
     71 #include <sys/queue.h>
     72 #include <sys/event.h>
     73 #include <sys/eventvar.h>
     74 #include <sys/poll.h>
     75 #include <sys/kmem.h>
     76 #include <sys/stat.h>
     77 #include <sys/filedesc.h>
     78 #include <sys/syscallargs.h>
     79 #include <sys/kauth.h>
     80 #include <sys/conf.h>
     81 #include <sys/atomic.h>
     82 
     83 static int	kqueue_scan(file_t *, size_t, struct kevent *,
     84 			    const struct timespec *, register_t *,
     85 			    const struct kevent_ops *, struct kevent *,
     86 			    size_t);
     87 static int	kqueue_ioctl(file_t *, u_long, void *);
     88 static int	kqueue_fcntl(file_t *, u_int, void *);
     89 static int	kqueue_poll(file_t *, int);
     90 static int	kqueue_kqfilter(file_t *, struct knote *);
     91 static int	kqueue_stat(file_t *, struct stat *);
     92 static int	kqueue_close(file_t *);
     93 static void	kqueue_restart(file_t *);
     94 static int	kqueue_register(struct kqueue *, struct kevent *);
     95 static void	kqueue_doclose(struct kqueue *, struct klist *, int);
     96 
     97 static void	knote_detach(struct knote *, filedesc_t *fdp, bool);
     98 static void	knote_enqueue(struct knote *);
     99 static void	knote_activate(struct knote *);
    100 
    101 static void	filt_kqdetach(struct knote *);
    102 static int	filt_kqueue(struct knote *, long hint);
    103 static int	filt_procattach(struct knote *);
    104 static void	filt_procdetach(struct knote *);
    105 static int	filt_proc(struct knote *, long hint);
    106 static int	filt_fileattach(struct knote *);
    107 static void	filt_timerexpire(void *x);
    108 static int	filt_timerattach(struct knote *);
    109 static void	filt_timerdetach(struct knote *);
    110 static int	filt_timer(struct knote *, long hint);
    111 static int	filt_userattach(struct knote *);
    112 static void	filt_userdetach(struct knote *);
    113 static int	filt_user(struct knote *, long hint);
    114 static void	filt_usertouch(struct knote *, struct kevent *, long type);
    115 
    116 static const struct fileops kqueueops = {
    117 	.fo_name = "kqueue",
    118 	.fo_read = (void *)enxio,
    119 	.fo_write = (void *)enxio,
    120 	.fo_ioctl = kqueue_ioctl,
    121 	.fo_fcntl = kqueue_fcntl,
    122 	.fo_poll = kqueue_poll,
    123 	.fo_stat = kqueue_stat,
    124 	.fo_close = kqueue_close,
    125 	.fo_kqfilter = kqueue_kqfilter,
    126 	.fo_restart = kqueue_restart,
    127 };
    128 
    129 static const struct filterops kqread_filtops = {
    130 	.f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
    131 	.f_attach = NULL,
    132 	.f_detach = filt_kqdetach,
    133 	.f_event = filt_kqueue,
    134 };
    135 
    136 static const struct filterops proc_filtops = {
    137 	.f_flags = 0,
    138 	.f_attach = filt_procattach,
    139 	.f_detach = filt_procdetach,
    140 	.f_event = filt_proc,
    141 };
    142 
    143 /*
    144  * file_filtops is not marked MPSAFE because it's going to call
    145  * fileops::fo_kqfilter(), which might not be.  That function,
    146  * however, will override the knote's filterops, and thus will
    147  * inherit the MPSAFE-ness of the back-end at that time.
    148  */
    149 static const struct filterops file_filtops = {
    150 	.f_flags = FILTEROP_ISFD,
    151 	.f_attach = filt_fileattach,
    152 	.f_detach = NULL,
    153 	.f_event = NULL,
    154 };
    155 
    156 static const struct filterops timer_filtops = {
    157 	.f_flags = FILTEROP_MPSAFE,
    158 	.f_attach = filt_timerattach,
    159 	.f_detach = filt_timerdetach,
    160 	.f_event = filt_timer,
    161 };
    162 
    163 static const struct filterops user_filtops = {
    164 	.f_flags = FILTEROP_MPSAFE,
    165 	.f_attach = filt_userattach,
    166 	.f_detach = filt_userdetach,
    167 	.f_event = filt_user,
    168 	.f_touch = filt_usertouch,
    169 };
    170 
    171 static u_int	kq_ncallouts = 0;
    172 static int	kq_calloutmax = (4 * 1024);
    173 
    174 #define	KN_HASHSIZE		64		/* XXX should be tunable */
    175 #define	KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
    176 
    177 extern const struct filterops fs_filtops;	/* vfs_syscalls.c */
    178 extern const struct filterops sig_filtops;	/* kern_sig.c */
    179 
    180 #define KQ_FLUX_WAKEUP(kq)	cv_broadcast(&kq->kq_cv)
    181 
    182 /*
    183  * Table for for all system-defined filters.
    184  * These should be listed in the numeric order of the EVFILT_* defines.
    185  * If filtops is NULL, the filter isn't implemented in NetBSD.
    186  * End of list is when name is NULL.
    187  *
    188  * Note that 'refcnt' is meaningless for built-in filters.
    189  */
    190 struct kfilter {
    191 	const char	*name;		/* name of filter */
    192 	uint32_t	filter;		/* id of filter */
    193 	unsigned	refcnt;		/* reference count */
    194 	const struct filterops *filtops;/* operations for filter */
    195 	size_t		namelen;	/* length of name string */
    196 };
    197 
    198 /* System defined filters */
    199 static struct kfilter sys_kfilters[] = {
    200 	{ "EVFILT_READ",	EVFILT_READ,	0, &file_filtops, 0 },
    201 	{ "EVFILT_WRITE",	EVFILT_WRITE,	0, &file_filtops, 0, },
    202 	{ "EVFILT_AIO",		EVFILT_AIO,	0, NULL, 0 },
    203 	{ "EVFILT_VNODE",	EVFILT_VNODE,	0, &file_filtops, 0 },
    204 	{ "EVFILT_PROC",	EVFILT_PROC,	0, &proc_filtops, 0 },
    205 	{ "EVFILT_SIGNAL",	EVFILT_SIGNAL,	0, &sig_filtops, 0 },
    206 	{ "EVFILT_TIMER",	EVFILT_TIMER,	0, &timer_filtops, 0 },
    207 	{ "EVFILT_FS",		EVFILT_FS,	0, &fs_filtops, 0 },
    208 	{ "EVFILT_USER",	EVFILT_USER,	0, &user_filtops, 0 },
    209 	{ NULL,			0,		0, NULL, 0 },
    210 };
    211 
    212 /* User defined kfilters */
    213 static struct kfilter	*user_kfilters;		/* array */
    214 static int		user_kfilterc;		/* current offset */
    215 static int		user_kfiltermaxc;	/* max size so far */
    216 static size_t		user_kfiltersz;		/* size of allocated memory */
    217 
    218 /*
    219  * Global Locks.
    220  *
    221  * Lock order:
    222  *
    223  *	kqueue_filter_lock
    224  *	-> kn_kq->kq_fdp->fd_lock
    225  *	-> object lock (e.g., device driver lock, &c.)
    226  *	-> kn_kq->kq_lock
    227  *
    228  * Locking rules:
    229  *
    230  *	f_attach: fdp->fd_lock, KERNEL_LOCK
    231  *	f_detach: fdp->fd_lock, KERNEL_LOCK
    232  *	f_event(!NOTE_SUBMIT) via kevent: fdp->fd_lock, _no_ object lock
    233  *	f_event via knote: whatever caller guarantees
    234  *		Typically,	f_event(NOTE_SUBMIT) via knote: object lock
    235  *				f_event(!NOTE_SUBMIT) via knote: nothing,
    236  *					acquires/releases object lock inside.
    237  */
    238 static krwlock_t	kqueue_filter_lock;	/* lock on filter lists */
    239 static kmutex_t		kqueue_timer_lock;	/* for EVFILT_TIMER */
    240 
    241 static int
    242 filter_attach(struct knote *kn)
    243 {
    244 	int rv;
    245 
    246 	KASSERT(kn->kn_fop != NULL);
    247 	KASSERT(kn->kn_fop->f_attach != NULL);
    248 
    249 	/*
    250 	 * N.B. that kn->kn_fop may change as the result of calling
    251 	 * f_attach().
    252 	 */
    253 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
    254 		rv = kn->kn_fop->f_attach(kn);
    255 	} else {
    256 		KERNEL_LOCK(1, NULL);
    257 		rv = kn->kn_fop->f_attach(kn);
    258 		KERNEL_UNLOCK_ONE(NULL);
    259 	}
    260 
    261 	return rv;
    262 }
    263 
    264 static void
    265 filter_detach(struct knote *kn)
    266 {
    267 	KASSERT(kn->kn_fop != NULL);
    268 	KASSERT(kn->kn_fop->f_detach != NULL);
    269 
    270 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
    271 		kn->kn_fop->f_detach(kn);
    272 	} else {
    273 		KERNEL_LOCK(1, NULL);
    274 		kn->kn_fop->f_detach(kn);
    275 		KERNEL_UNLOCK_ONE(NULL);
    276 	}
    277 }
    278 
    279 static int
    280 filter_event(struct knote *kn, long hint)
    281 {
    282 	int rv;
    283 
    284 	KASSERT(kn->kn_fop != NULL);
    285 	KASSERT(kn->kn_fop->f_event != NULL);
    286 
    287 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
    288 		rv = kn->kn_fop->f_event(kn, hint);
    289 	} else {
    290 		KERNEL_LOCK(1, NULL);
    291 		rv = kn->kn_fop->f_event(kn, hint);
    292 		KERNEL_UNLOCK_ONE(NULL);
    293 	}
    294 
    295 	return rv;
    296 }
    297 
    298 static void
    299 filter_touch(struct knote *kn, struct kevent *kev, long type)
    300 {
    301 	kn->kn_fop->f_touch(kn, kev, type);
    302 }
    303 
    304 static kauth_listener_t	kqueue_listener;
    305 
    306 static int
    307 kqueue_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    308     void *arg0, void *arg1, void *arg2, void *arg3)
    309 {
    310 	struct proc *p;
    311 	int result;
    312 
    313 	result = KAUTH_RESULT_DEFER;
    314 	p = arg0;
    315 
    316 	if (action != KAUTH_PROCESS_KEVENT_FILTER)
    317 		return result;
    318 
    319 	if ((kauth_cred_getuid(p->p_cred) != kauth_cred_getuid(cred) ||
    320 	    ISSET(p->p_flag, PK_SUGID)))
    321 		return result;
    322 
    323 	result = KAUTH_RESULT_ALLOW;
    324 
    325 	return result;
    326 }
    327 
    328 /*
    329  * Initialize the kqueue subsystem.
    330  */
    331 void
    332 kqueue_init(void)
    333 {
    334 
    335 	rw_init(&kqueue_filter_lock);
    336 	mutex_init(&kqueue_timer_lock, MUTEX_DEFAULT, IPL_SOFTCLOCK);
    337 
    338 	kqueue_listener = kauth_listen_scope(KAUTH_SCOPE_PROCESS,
    339 	    kqueue_listener_cb, NULL);
    340 }
    341 
    342 /*
    343  * Find kfilter entry by name, or NULL if not found.
    344  */
    345 static struct kfilter *
    346 kfilter_byname_sys(const char *name)
    347 {
    348 	int i;
    349 
    350 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    351 
    352 	for (i = 0; sys_kfilters[i].name != NULL; i++) {
    353 		if (strcmp(name, sys_kfilters[i].name) == 0)
    354 			return &sys_kfilters[i];
    355 	}
    356 	return NULL;
    357 }
    358 
    359 static struct kfilter *
    360 kfilter_byname_user(const char *name)
    361 {
    362 	int i;
    363 
    364 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    365 
    366 	/* user filter slots have a NULL name if previously deregistered */
    367 	for (i = 0; i < user_kfilterc ; i++) {
    368 		if (user_kfilters[i].name != NULL &&
    369 		    strcmp(name, user_kfilters[i].name) == 0)
    370 			return &user_kfilters[i];
    371 	}
    372 	return NULL;
    373 }
    374 
    375 static struct kfilter *
    376 kfilter_byname(const char *name)
    377 {
    378 	struct kfilter *kfilter;
    379 
    380 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    381 
    382 	if ((kfilter = kfilter_byname_sys(name)) != NULL)
    383 		return kfilter;
    384 
    385 	return kfilter_byname_user(name);
    386 }
    387 
    388 /*
    389  * Find kfilter entry by filter id, or NULL if not found.
    390  * Assumes entries are indexed in filter id order, for speed.
    391  */
    392 static struct kfilter *
    393 kfilter_byfilter(uint32_t filter)
    394 {
    395 	struct kfilter *kfilter;
    396 
    397 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    398 
    399 	if (filter < EVFILT_SYSCOUNT)	/* it's a system filter */
    400 		kfilter = &sys_kfilters[filter];
    401 	else if (user_kfilters != NULL &&
    402 	    filter < EVFILT_SYSCOUNT + user_kfilterc)
    403 					/* it's a user filter */
    404 		kfilter = &user_kfilters[filter - EVFILT_SYSCOUNT];
    405 	else
    406 		return (NULL);		/* out of range */
    407 	KASSERT(kfilter->filter == filter);	/* sanity check! */
    408 	return (kfilter);
    409 }
    410 
    411 /*
    412  * Register a new kfilter. Stores the entry in user_kfilters.
    413  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    414  * If retfilter != NULL, the new filterid is returned in it.
    415  */
    416 int
    417 kfilter_register(const char *name, const struct filterops *filtops,
    418 		 int *retfilter)
    419 {
    420 	struct kfilter *kfilter;
    421 	size_t len;
    422 	int i;
    423 
    424 	if (name == NULL || name[0] == '\0' || filtops == NULL)
    425 		return (EINVAL);	/* invalid args */
    426 
    427 	rw_enter(&kqueue_filter_lock, RW_WRITER);
    428 	if (kfilter_byname(name) != NULL) {
    429 		rw_exit(&kqueue_filter_lock);
    430 		return (EEXIST);	/* already exists */
    431 	}
    432 	if (user_kfilterc > 0xffffffff - EVFILT_SYSCOUNT) {
    433 		rw_exit(&kqueue_filter_lock);
    434 		return (EINVAL);	/* too many */
    435 	}
    436 
    437 	for (i = 0; i < user_kfilterc; i++) {
    438 		kfilter = &user_kfilters[i];
    439 		if (kfilter->name == NULL) {
    440 			/* Previously deregistered slot.  Reuse. */
    441 			goto reuse;
    442 		}
    443 	}
    444 
    445 	/* check if need to grow user_kfilters */
    446 	if (user_kfilterc + 1 > user_kfiltermaxc) {
    447 		/* Grow in KFILTER_EXTENT chunks. */
    448 		user_kfiltermaxc += KFILTER_EXTENT;
    449 		len = user_kfiltermaxc * sizeof(*kfilter);
    450 		kfilter = kmem_alloc(len, KM_SLEEP);
    451 		memset((char *)kfilter + user_kfiltersz, 0, len - user_kfiltersz);
    452 		if (user_kfilters != NULL) {
    453 			memcpy(kfilter, user_kfilters, user_kfiltersz);
    454 			kmem_free(user_kfilters, user_kfiltersz);
    455 		}
    456 		user_kfiltersz = len;
    457 		user_kfilters = kfilter;
    458 	}
    459 	/* Adding new slot */
    460 	kfilter = &user_kfilters[user_kfilterc++];
    461 reuse:
    462 	kfilter->name = kmem_strdupsize(name, &kfilter->namelen, KM_SLEEP);
    463 
    464 	kfilter->filter = (kfilter - user_kfilters) + EVFILT_SYSCOUNT;
    465 
    466 	kfilter->filtops = kmem_alloc(sizeof(*filtops), KM_SLEEP);
    467 	memcpy(__UNCONST(kfilter->filtops), filtops, sizeof(*filtops));
    468 
    469 	if (retfilter != NULL)
    470 		*retfilter = kfilter->filter;
    471 	rw_exit(&kqueue_filter_lock);
    472 
    473 	return (0);
    474 }
    475 
    476 /*
    477  * Unregister a kfilter previously registered with kfilter_register.
    478  * This retains the filter id, but clears the name and frees filtops (filter
    479  * operations), so that the number isn't reused during a boot.
    480  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    481  */
    482 int
    483 kfilter_unregister(const char *name)
    484 {
    485 	struct kfilter *kfilter;
    486 
    487 	if (name == NULL || name[0] == '\0')
    488 		return (EINVAL);	/* invalid name */
    489 
    490 	rw_enter(&kqueue_filter_lock, RW_WRITER);
    491 	if (kfilter_byname_sys(name) != NULL) {
    492 		rw_exit(&kqueue_filter_lock);
    493 		return (EINVAL);	/* can't detach system filters */
    494 	}
    495 
    496 	kfilter = kfilter_byname_user(name);
    497 	if (kfilter == NULL) {
    498 		rw_exit(&kqueue_filter_lock);
    499 		return (ENOENT);
    500 	}
    501 	if (kfilter->refcnt != 0) {
    502 		rw_exit(&kqueue_filter_lock);
    503 		return (EBUSY);
    504 	}
    505 
    506 	/* Cast away const (but we know it's safe. */
    507 	kmem_free(__UNCONST(kfilter->name), kfilter->namelen);
    508 	kfilter->name = NULL;	/* mark as `not implemented' */
    509 
    510 	if (kfilter->filtops != NULL) {
    511 		/* Cast away const (but we know it's safe. */
    512 		kmem_free(__UNCONST(kfilter->filtops),
    513 		    sizeof(*kfilter->filtops));
    514 		kfilter->filtops = NULL; /* mark as `not implemented' */
    515 	}
    516 	rw_exit(&kqueue_filter_lock);
    517 
    518 	return (0);
    519 }
    520 
    521 
    522 /*
    523  * Filter attach method for EVFILT_READ and EVFILT_WRITE on normal file
    524  * descriptors. Calls fileops kqfilter method for given file descriptor.
    525  */
    526 static int
    527 filt_fileattach(struct knote *kn)
    528 {
    529 	file_t *fp;
    530 
    531 	fp = kn->kn_obj;
    532 
    533 	return (*fp->f_ops->fo_kqfilter)(fp, kn);
    534 }
    535 
    536 /*
    537  * Filter detach method for EVFILT_READ on kqueue descriptor.
    538  */
    539 static void
    540 filt_kqdetach(struct knote *kn)
    541 {
    542 	struct kqueue *kq;
    543 
    544 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
    545 
    546 	mutex_spin_enter(&kq->kq_lock);
    547 	selremove_knote(&kq->kq_sel, kn);
    548 	mutex_spin_exit(&kq->kq_lock);
    549 }
    550 
    551 /*
    552  * Filter event method for EVFILT_READ on kqueue descriptor.
    553  */
    554 /*ARGSUSED*/
    555 static int
    556 filt_kqueue(struct knote *kn, long hint)
    557 {
    558 	struct kqueue *kq;
    559 	int rv;
    560 
    561 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
    562 
    563 	if (hint != NOTE_SUBMIT)
    564 		mutex_spin_enter(&kq->kq_lock);
    565 	kn->kn_data = KQ_COUNT(kq);
    566 	rv = (kn->kn_data > 0);
    567 	if (hint != NOTE_SUBMIT)
    568 		mutex_spin_exit(&kq->kq_lock);
    569 
    570 	return rv;
    571 }
    572 
    573 /*
    574  * Filter attach method for EVFILT_PROC.
    575  */
    576 static int
    577 filt_procattach(struct knote *kn)
    578 {
    579 	struct proc *p;
    580 	struct lwp *curl;
    581 
    582 	curl = curlwp;
    583 
    584 	mutex_enter(&proc_lock);
    585 	if (kn->kn_flags & EV_FLAG1) {
    586 		/*
    587 		 * NOTE_TRACK attaches to the child process too early
    588 		 * for proc_find, so do a raw look up and check the state
    589 		 * explicitly.
    590 		 */
    591 		p = proc_find_raw(kn->kn_id);
    592 		if (p != NULL && p->p_stat != SIDL)
    593 			p = NULL;
    594 	} else {
    595 		p = proc_find(kn->kn_id);
    596 	}
    597 
    598 	if (p == NULL) {
    599 		mutex_exit(&proc_lock);
    600 		return ESRCH;
    601 	}
    602 
    603 	/*
    604 	 * Fail if it's not owned by you, or the last exec gave us
    605 	 * setuid/setgid privs (unless you're root).
    606 	 */
    607 	mutex_enter(p->p_lock);
    608 	mutex_exit(&proc_lock);
    609 	if (kauth_authorize_process(curl->l_cred,
    610 	    KAUTH_PROCESS_KEVENT_FILTER, p, NULL, NULL, NULL) != 0) {
    611 	    	mutex_exit(p->p_lock);
    612 		return EACCES;
    613 	}
    614 
    615 	kn->kn_obj = p;
    616 	kn->kn_flags |= EV_CLEAR;	/* automatically set */
    617 
    618 	/*
    619 	 * internal flag indicating registration done by kernel
    620 	 */
    621 	if (kn->kn_flags & EV_FLAG1) {
    622 		kn->kn_data = kn->kn_sdata;	/* ppid */
    623 		kn->kn_fflags = NOTE_CHILD;
    624 		kn->kn_flags &= ~EV_FLAG1;
    625 	}
    626 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
    627     	mutex_exit(p->p_lock);
    628 
    629 	return 0;
    630 }
    631 
    632 /*
    633  * Filter detach method for EVFILT_PROC.
    634  *
    635  * The knote may be attached to a different process, which may exit,
    636  * leaving nothing for the knote to be attached to.  So when the process
    637  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
    638  * it will be deleted when read out.  However, as part of the knote deletion,
    639  * this routine is called, so a check is needed to avoid actually performing
    640  * a detach, because the original process might not exist any more.
    641  */
    642 static void
    643 filt_procdetach(struct knote *kn)
    644 {
    645 	struct proc *p;
    646 
    647 	if (kn->kn_status & KN_DETACHED)
    648 		return;
    649 
    650 	p = kn->kn_obj;
    651 
    652 	mutex_enter(p->p_lock);
    653 	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
    654 	mutex_exit(p->p_lock);
    655 }
    656 
    657 /*
    658  * Filter event method for EVFILT_PROC.
    659  */
    660 static int
    661 filt_proc(struct knote *kn, long hint)
    662 {
    663 	u_int event, fflag;
    664 	struct kevent kev;
    665 	struct kqueue *kq;
    666 	int error;
    667 
    668 	event = (u_int)hint & NOTE_PCTRLMASK;
    669 	kq = kn->kn_kq;
    670 	fflag = 0;
    671 
    672 	/* If the user is interested in this event, record it. */
    673 	if (kn->kn_sfflags & event)
    674 		fflag |= event;
    675 
    676 	if (event == NOTE_EXIT) {
    677 		struct proc *p = kn->kn_obj;
    678 
    679 		if (p != NULL)
    680 			kn->kn_data = P_WAITSTATUS(p);
    681 		/*
    682 		 * Process is gone, so flag the event as finished.
    683 		 *
    684 		 * Detach the knote from watched process and mark
    685 		 * it as such. We can't leave this to kqueue_scan(),
    686 		 * since the process might not exist by then. And we
    687 		 * have to do this now, since psignal KNOTE() is called
    688 		 * also for zombies and we might end up reading freed
    689 		 * memory if the kevent would already be picked up
    690 		 * and knote g/c'ed.
    691 		 */
    692 		filt_procdetach(kn);
    693 
    694 		mutex_spin_enter(&kq->kq_lock);
    695 		kn->kn_status |= KN_DETACHED;
    696 		/* Mark as ONESHOT, so that the knote it g/c'ed when read */
    697 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
    698 		kn->kn_fflags |= fflag;
    699 		mutex_spin_exit(&kq->kq_lock);
    700 
    701 		return 1;
    702 	}
    703 
    704 	mutex_spin_enter(&kq->kq_lock);
    705 	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
    706 		/*
    707 		 * Process forked, and user wants to track the new process,
    708 		 * so attach a new knote to it, and immediately report an
    709 		 * event with the parent's pid.  Register knote with new
    710 		 * process.
    711 		 */
    712 		memset(&kev, 0, sizeof(kev));
    713 		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
    714 		kev.filter = kn->kn_filter;
    715 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
    716 		kev.fflags = kn->kn_sfflags;
    717 		kev.data = kn->kn_id;			/* parent */
    718 		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
    719 		mutex_spin_exit(&kq->kq_lock);
    720 		error = kqueue_register(kq, &kev);
    721 		mutex_spin_enter(&kq->kq_lock);
    722 		if (error != 0)
    723 			kn->kn_fflags |= NOTE_TRACKERR;
    724 	}
    725 	kn->kn_fflags |= fflag;
    726 	fflag = kn->kn_fflags;
    727 	mutex_spin_exit(&kq->kq_lock);
    728 
    729 	return fflag != 0;
    730 }
    731 
    732 static void
    733 filt_timerexpire(void *knx)
    734 {
    735 	struct knote *kn = knx;
    736 	int tticks;
    737 
    738 	mutex_enter(&kqueue_timer_lock);
    739 	kn->kn_data++;
    740 	knote_activate(kn);
    741 	if ((kn->kn_flags & EV_ONESHOT) == 0) {
    742 		tticks = mstohz(kn->kn_sdata);
    743 		if (tticks <= 0)
    744 			tticks = 1;
    745 		callout_schedule((callout_t *)kn->kn_hook, tticks);
    746 	}
    747 	mutex_exit(&kqueue_timer_lock);
    748 }
    749 
    750 /*
    751  * data contains amount of time to sleep, in milliseconds
    752  */
    753 static int
    754 filt_timerattach(struct knote *kn)
    755 {
    756 	callout_t *calloutp;
    757 	struct kqueue *kq;
    758 	int tticks;
    759 
    760 	tticks = mstohz(kn->kn_sdata);
    761 
    762 	/* if the supplied value is under our resolution, use 1 tick */
    763 	if (tticks == 0) {
    764 		if (kn->kn_sdata == 0)
    765 			return EINVAL;
    766 		tticks = 1;
    767 	}
    768 
    769 	if (atomic_inc_uint_nv(&kq_ncallouts) >= kq_calloutmax ||
    770 	    (calloutp = kmem_alloc(sizeof(*calloutp), KM_NOSLEEP)) == NULL) {
    771 		atomic_dec_uint(&kq_ncallouts);
    772 		return ENOMEM;
    773 	}
    774 	callout_init(calloutp, CALLOUT_MPSAFE);
    775 
    776 	kq = kn->kn_kq;
    777 	mutex_spin_enter(&kq->kq_lock);
    778 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
    779 	kn->kn_hook = calloutp;
    780 	mutex_spin_exit(&kq->kq_lock);
    781 
    782 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
    783 
    784 	return (0);
    785 }
    786 
    787 static void
    788 filt_timerdetach(struct knote *kn)
    789 {
    790 	callout_t *calloutp;
    791 	struct kqueue *kq = kn->kn_kq;
    792 
    793 	/*
    794 	 * We don't need to hold the kqueue_timer_lock here; even
    795 	 * if filt_timerexpire() misses our setting of EV_ONESHOT,
    796 	 * we are guaranteed that the callout will no longer be
    797 	 * scheduled even if we attempted to halt it after it already
    798 	 * started running, even if it rescheduled itself.
    799 	 */
    800 
    801 	mutex_spin_enter(&kq->kq_lock);
    802 	/* prevent rescheduling when we expire */
    803 	kn->kn_flags |= EV_ONESHOT;
    804 	mutex_spin_exit(&kq->kq_lock);
    805 
    806 	calloutp = (callout_t *)kn->kn_hook;
    807 
    808 	/*
    809 	 * Attempt to stop the callout.  This will block if it's
    810 	 * already running.
    811 	 */
    812 	callout_halt(calloutp, NULL);
    813 
    814 	callout_destroy(calloutp);
    815 	kmem_free(calloutp, sizeof(*calloutp));
    816 	atomic_dec_uint(&kq_ncallouts);
    817 }
    818 
    819 static int
    820 filt_timer(struct knote *kn, long hint)
    821 {
    822 	int rv;
    823 
    824 	mutex_enter(&kqueue_timer_lock);
    825 	rv = (kn->kn_data != 0);
    826 	mutex_exit(&kqueue_timer_lock);
    827 
    828 	return rv;
    829 }
    830 
    831 static int
    832 filt_userattach(struct knote *kn)
    833 {
    834 	struct kqueue *kq = kn->kn_kq;
    835 
    836 	/*
    837 	 * EVFILT_USER knotes are not attached to anything in the kernel.
    838 	 */
    839 	mutex_spin_enter(&kq->kq_lock);
    840 	kn->kn_hook = NULL;
    841 	if (kn->kn_fflags & NOTE_TRIGGER)
    842 		kn->kn_hookid = 1;
    843 	else
    844 		kn->kn_hookid = 0;
    845 	mutex_spin_exit(&kq->kq_lock);
    846 	return (0);
    847 }
    848 
    849 static void
    850 filt_userdetach(struct knote *kn)
    851 {
    852 
    853 	/*
    854 	 * EVFILT_USER knotes are not attached to anything in the kernel.
    855 	 */
    856 }
    857 
    858 static int
    859 filt_user(struct knote *kn, long hint)
    860 {
    861 	struct kqueue *kq = kn->kn_kq;
    862 	int hookid;
    863 
    864 	mutex_spin_enter(&kq->kq_lock);
    865 	hookid = kn->kn_hookid;
    866 	mutex_spin_exit(&kq->kq_lock);
    867 
    868 	return hookid;
    869 }
    870 
    871 static void
    872 filt_usertouch(struct knote *kn, struct kevent *kev, long type)
    873 {
    874 	int ffctrl;
    875 
    876 	KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
    877 
    878 	switch (type) {
    879 	case EVENT_REGISTER:
    880 		if (kev->fflags & NOTE_TRIGGER)
    881 			kn->kn_hookid = 1;
    882 
    883 		ffctrl = kev->fflags & NOTE_FFCTRLMASK;
    884 		kev->fflags &= NOTE_FFLAGSMASK;
    885 		switch (ffctrl) {
    886 		case NOTE_FFNOP:
    887 			break;
    888 
    889 		case NOTE_FFAND:
    890 			kn->kn_sfflags &= kev->fflags;
    891 			break;
    892 
    893 		case NOTE_FFOR:
    894 			kn->kn_sfflags |= kev->fflags;
    895 			break;
    896 
    897 		case NOTE_FFCOPY:
    898 			kn->kn_sfflags = kev->fflags;
    899 			break;
    900 
    901 		default:
    902 			/* XXX Return error? */
    903 			break;
    904 		}
    905 		kn->kn_sdata = kev->data;
    906 		if (kev->flags & EV_CLEAR) {
    907 			kn->kn_hookid = 0;
    908 			kn->kn_data = 0;
    909 			kn->kn_fflags = 0;
    910 		}
    911 		break;
    912 
    913 	case EVENT_PROCESS:
    914 		*kev = kn->kn_kevent;
    915 		kev->fflags = kn->kn_sfflags;
    916 		kev->data = kn->kn_sdata;
    917 		if (kn->kn_flags & EV_CLEAR) {
    918 			kn->kn_hookid = 0;
    919 			kn->kn_data = 0;
    920 			kn->kn_fflags = 0;
    921 		}
    922 		break;
    923 
    924 	default:
    925 		panic("filt_usertouch() - invalid type (%ld)", type);
    926 		break;
    927 	}
    928 }
    929 
    930 /*
    931  * filt_seltrue:
    932  *
    933  *	This filter "event" routine simulates seltrue().
    934  */
    935 int
    936 filt_seltrue(struct knote *kn, long hint)
    937 {
    938 
    939 	/*
    940 	 * We don't know how much data can be read/written,
    941 	 * but we know that it *can* be.  This is about as
    942 	 * good as select/poll does as well.
    943 	 */
    944 	kn->kn_data = 0;
    945 	return (1);
    946 }
    947 
    948 /*
    949  * This provides full kqfilter entry for device switch tables, which
    950  * has same effect as filter using filt_seltrue() as filter method.
    951  */
    952 static void
    953 filt_seltruedetach(struct knote *kn)
    954 {
    955 	/* Nothing to do */
    956 }
    957 
    958 const struct filterops seltrue_filtops = {
    959 	.f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
    960 	.f_attach = NULL,
    961 	.f_detach = filt_seltruedetach,
    962 	.f_event = filt_seltrue,
    963 };
    964 
    965 int
    966 seltrue_kqfilter(dev_t dev, struct knote *kn)
    967 {
    968 	switch (kn->kn_filter) {
    969 	case EVFILT_READ:
    970 	case EVFILT_WRITE:
    971 		kn->kn_fop = &seltrue_filtops;
    972 		break;
    973 	default:
    974 		return (EINVAL);
    975 	}
    976 
    977 	/* Nothing more to do */
    978 	return (0);
    979 }
    980 
    981 /*
    982  * kqueue(2) system call.
    983  */
    984 static int
    985 kqueue1(struct lwp *l, int flags, register_t *retval)
    986 {
    987 	struct kqueue *kq;
    988 	file_t *fp;
    989 	int fd, error;
    990 
    991 	if ((error = fd_allocfile(&fp, &fd)) != 0)
    992 		return error;
    993 	fp->f_flag = FREAD | FWRITE | (flags & (FNONBLOCK|FNOSIGPIPE));
    994 	fp->f_type = DTYPE_KQUEUE;
    995 	fp->f_ops = &kqueueops;
    996 	kq = kmem_zalloc(sizeof(*kq), KM_SLEEP);
    997 	mutex_init(&kq->kq_lock, MUTEX_DEFAULT, IPL_SCHED);
    998 	cv_init(&kq->kq_cv, "kqueue");
    999 	selinit(&kq->kq_sel);
   1000 	TAILQ_INIT(&kq->kq_head);
   1001 	fp->f_kqueue = kq;
   1002 	*retval = fd;
   1003 	kq->kq_fdp = curlwp->l_fd;
   1004 	fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0);
   1005 	fd_affix(curproc, fp, fd);
   1006 	return error;
   1007 }
   1008 
   1009 /*
   1010  * kqueue(2) system call.
   1011  */
   1012 int
   1013 sys_kqueue(struct lwp *l, const void *v, register_t *retval)
   1014 {
   1015 	return kqueue1(l, 0, retval);
   1016 }
   1017 
   1018 int
   1019 sys_kqueue1(struct lwp *l, const struct sys_kqueue1_args *uap,
   1020     register_t *retval)
   1021 {
   1022 	/* {
   1023 		syscallarg(int) flags;
   1024 	} */
   1025 	return kqueue1(l, SCARG(uap, flags), retval);
   1026 }
   1027 
   1028 /*
   1029  * kevent(2) system call.
   1030  */
   1031 int
   1032 kevent_fetch_changes(void *ctx, const struct kevent *changelist,
   1033     struct kevent *changes, size_t index, int n)
   1034 {
   1035 
   1036 	return copyin(changelist + index, changes, n * sizeof(*changes));
   1037 }
   1038 
   1039 int
   1040 kevent_put_events(void *ctx, struct kevent *events,
   1041     struct kevent *eventlist, size_t index, int n)
   1042 {
   1043 
   1044 	return copyout(events, eventlist + index, n * sizeof(*events));
   1045 }
   1046 
   1047 static const struct kevent_ops kevent_native_ops = {
   1048 	.keo_private = NULL,
   1049 	.keo_fetch_timeout = copyin,
   1050 	.keo_fetch_changes = kevent_fetch_changes,
   1051 	.keo_put_events = kevent_put_events,
   1052 };
   1053 
   1054 int
   1055 sys___kevent50(struct lwp *l, const struct sys___kevent50_args *uap,
   1056     register_t *retval)
   1057 {
   1058 	/* {
   1059 		syscallarg(int) fd;
   1060 		syscallarg(const struct kevent *) changelist;
   1061 		syscallarg(size_t) nchanges;
   1062 		syscallarg(struct kevent *) eventlist;
   1063 		syscallarg(size_t) nevents;
   1064 		syscallarg(const struct timespec *) timeout;
   1065 	} */
   1066 
   1067 	return kevent1(retval, SCARG(uap, fd), SCARG(uap, changelist),
   1068 	    SCARG(uap, nchanges), SCARG(uap, eventlist), SCARG(uap, nevents),
   1069 	    SCARG(uap, timeout), &kevent_native_ops);
   1070 }
   1071 
   1072 int
   1073 kevent1(register_t *retval, int fd,
   1074 	const struct kevent *changelist, size_t nchanges,
   1075 	struct kevent *eventlist, size_t nevents,
   1076 	const struct timespec *timeout,
   1077 	const struct kevent_ops *keops)
   1078 {
   1079 	struct kevent *kevp;
   1080 	struct kqueue *kq;
   1081 	struct timespec	ts;
   1082 	size_t i, n, ichange;
   1083 	int nerrors, error;
   1084 	struct kevent kevbuf[KQ_NEVENTS];	/* approx 300 bytes on 64-bit */
   1085 	file_t *fp;
   1086 
   1087 	/* check that we're dealing with a kq */
   1088 	fp = fd_getfile(fd);
   1089 	if (fp == NULL)
   1090 		return (EBADF);
   1091 
   1092 	if (fp->f_type != DTYPE_KQUEUE) {
   1093 		fd_putfile(fd);
   1094 		return (EBADF);
   1095 	}
   1096 
   1097 	if (timeout != NULL) {
   1098 		error = (*keops->keo_fetch_timeout)(timeout, &ts, sizeof(ts));
   1099 		if (error)
   1100 			goto done;
   1101 		timeout = &ts;
   1102 	}
   1103 
   1104 	kq = fp->f_kqueue;
   1105 	nerrors = 0;
   1106 	ichange = 0;
   1107 
   1108 	/* traverse list of events to register */
   1109 	while (nchanges > 0) {
   1110 		n = MIN(nchanges, __arraycount(kevbuf));
   1111 		error = (*keops->keo_fetch_changes)(keops->keo_private,
   1112 		    changelist, kevbuf, ichange, n);
   1113 		if (error)
   1114 			goto done;
   1115 		for (i = 0; i < n; i++) {
   1116 			kevp = &kevbuf[i];
   1117 			kevp->flags &= ~EV_SYSFLAGS;
   1118 			/* register each knote */
   1119 			error = kqueue_register(kq, kevp);
   1120 			if (!error && !(kevp->flags & EV_RECEIPT))
   1121 				continue;
   1122 			if (nevents == 0)
   1123 				goto done;
   1124 			kevp->flags = EV_ERROR;
   1125 			kevp->data = error;
   1126 			error = (*keops->keo_put_events)
   1127 				(keops->keo_private, kevp,
   1128 				 eventlist, nerrors, 1);
   1129 			if (error)
   1130 				goto done;
   1131 			nevents--;
   1132 			nerrors++;
   1133 		}
   1134 		nchanges -= n;	/* update the results */
   1135 		ichange += n;
   1136 	}
   1137 	if (nerrors) {
   1138 		*retval = nerrors;
   1139 		error = 0;
   1140 		goto done;
   1141 	}
   1142 
   1143 	/* actually scan through the events */
   1144 	error = kqueue_scan(fp, nevents, eventlist, timeout, retval, keops,
   1145 	    kevbuf, __arraycount(kevbuf));
   1146  done:
   1147 	fd_putfile(fd);
   1148 	return (error);
   1149 }
   1150 
   1151 /*
   1152  * Register a given kevent kev onto the kqueue
   1153  */
   1154 static int
   1155 kqueue_register(struct kqueue *kq, struct kevent *kev)
   1156 {
   1157 	struct kfilter *kfilter;
   1158 	filedesc_t *fdp;
   1159 	file_t *fp;
   1160 	fdfile_t *ff;
   1161 	struct knote *kn, *newkn;
   1162 	struct klist *list;
   1163 	int error, fd, rv;
   1164 
   1165 	fdp = kq->kq_fdp;
   1166 	fp = NULL;
   1167 	kn = NULL;
   1168 	error = 0;
   1169 	fd = 0;
   1170 
   1171 	newkn = kmem_zalloc(sizeof(*newkn), KM_SLEEP);
   1172 
   1173 	rw_enter(&kqueue_filter_lock, RW_READER);
   1174 	kfilter = kfilter_byfilter(kev->filter);
   1175 	if (kfilter == NULL || kfilter->filtops == NULL) {
   1176 		/* filter not found nor implemented */
   1177 		rw_exit(&kqueue_filter_lock);
   1178 		kmem_free(newkn, sizeof(*newkn));
   1179 		return (EINVAL);
   1180 	}
   1181 
   1182 	/* search if knote already exists */
   1183 	if (kfilter->filtops->f_flags & FILTEROP_ISFD) {
   1184 		/* monitoring a file descriptor */
   1185 		/* validate descriptor */
   1186 		if (kev->ident > INT_MAX
   1187 		    || (fp = fd_getfile(fd = kev->ident)) == NULL) {
   1188 			rw_exit(&kqueue_filter_lock);
   1189 			kmem_free(newkn, sizeof(*newkn));
   1190 			return EBADF;
   1191 		}
   1192 		mutex_enter(&fdp->fd_lock);
   1193 		ff = fdp->fd_dt->dt_ff[fd];
   1194 		if (ff->ff_refcnt & FR_CLOSING) {
   1195 			error = EBADF;
   1196 			goto doneunlock;
   1197 		}
   1198 		if (fd <= fdp->fd_lastkqfile) {
   1199 			SLIST_FOREACH(kn, &ff->ff_knlist, kn_link) {
   1200 				if (kq == kn->kn_kq &&
   1201 				    kev->filter == kn->kn_filter)
   1202 					break;
   1203 			}
   1204 		}
   1205 	} else {
   1206 		/*
   1207 		 * not monitoring a file descriptor, so
   1208 		 * lookup knotes in internal hash table
   1209 		 */
   1210 		mutex_enter(&fdp->fd_lock);
   1211 		if (fdp->fd_knhashmask != 0) {
   1212 			list = &fdp->fd_knhash[
   1213 			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
   1214 			SLIST_FOREACH(kn, list, kn_link) {
   1215 				if (kev->ident == kn->kn_id &&
   1216 				    kq == kn->kn_kq &&
   1217 				    kev->filter == kn->kn_filter)
   1218 					break;
   1219 			}
   1220 		}
   1221 	}
   1222 
   1223 	/*
   1224 	 * kn now contains the matching knote, or NULL if no match
   1225 	 */
   1226 	if (kn == NULL) {
   1227 		if (kev->flags & EV_ADD) {
   1228 			/* create new knote */
   1229 			kn = newkn;
   1230 			newkn = NULL;
   1231 			kn->kn_obj = fp;
   1232 			kn->kn_id = kev->ident;
   1233 			kn->kn_kq = kq;
   1234 			kn->kn_fop = kfilter->filtops;
   1235 			kn->kn_kfilter = kfilter;
   1236 			kn->kn_sfflags = kev->fflags;
   1237 			kn->kn_sdata = kev->data;
   1238 			kev->fflags = 0;
   1239 			kev->data = 0;
   1240 			kn->kn_kevent = *kev;
   1241 
   1242 			KASSERT(kn->kn_fop != NULL);
   1243 			/*
   1244 			 * apply reference count to knote structure, and
   1245 			 * do not release it at the end of this routine.
   1246 			 */
   1247 			fp = NULL;
   1248 
   1249 			if (!(kn->kn_fop->f_flags & FILTEROP_ISFD)) {
   1250 				/*
   1251 				 * If knote is not on an fd, store on
   1252 				 * internal hash table.
   1253 				 */
   1254 				if (fdp->fd_knhashmask == 0) {
   1255 					/* XXXAD can block with fd_lock held */
   1256 					fdp->fd_knhash = hashinit(KN_HASHSIZE,
   1257 					    HASH_LIST, true,
   1258 					    &fdp->fd_knhashmask);
   1259 				}
   1260 				list = &fdp->fd_knhash[KN_HASH(kn->kn_id,
   1261 				    fdp->fd_knhashmask)];
   1262 			} else {
   1263 				/* Otherwise, knote is on an fd. */
   1264 				list = (struct klist *)
   1265 				    &fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
   1266 				if ((int)kn->kn_id > fdp->fd_lastkqfile)
   1267 					fdp->fd_lastkqfile = kn->kn_id;
   1268 			}
   1269 			SLIST_INSERT_HEAD(list, kn, kn_link);
   1270 
   1271 			/*
   1272 			 * N.B. kn->kn_fop may change as the result
   1273 			 * of filter_attach()!
   1274 			 */
   1275 			error = filter_attach(kn);
   1276 			if (error != 0) {
   1277 #ifdef DEBUG
   1278 				struct proc *p = curlwp->l_proc;
   1279 				const file_t *ft = kn->kn_obj;
   1280 				printf("%s: %s[%d]: event type %d not "
   1281 				    "supported for file type %d/%s "
   1282 				    "(error %d)\n", __func__,
   1283 				    p->p_comm, p->p_pid,
   1284 				    kn->kn_filter, ft ? ft->f_type : -1,
   1285 				    ft ? ft->f_ops->fo_name : "?", error);
   1286 #endif
   1287 
   1288 				/* knote_detach() drops fdp->fd_lock */
   1289 				knote_detach(kn, fdp, false);
   1290 				goto done;
   1291 			}
   1292 			atomic_inc_uint(&kfilter->refcnt);
   1293 			goto done_ev_add;
   1294 		} else {
   1295 			/* No matching knote and the EV_ADD flag is not set. */
   1296 			error = ENOENT;
   1297 			goto doneunlock;
   1298 		}
   1299 	}
   1300 
   1301 	if (kev->flags & EV_DELETE) {
   1302 		/* knote_detach() drops fdp->fd_lock */
   1303 		knote_detach(kn, fdp, true);
   1304 		goto done;
   1305 	}
   1306 
   1307 	/*
   1308 	 * The user may change some filter values after the
   1309 	 * initial EV_ADD, but doing so will not reset any
   1310 	 * filter which have already been triggered.
   1311 	 */
   1312 	kn->kn_kevent.udata = kev->udata;
   1313 	KASSERT(kn->kn_fop != NULL);
   1314 	if (!(kn->kn_fop->f_flags & FILTEROP_ISFD) &&
   1315 	    kn->kn_fop->f_touch != NULL) {
   1316 		mutex_spin_enter(&kq->kq_lock);
   1317 		filter_touch(kn, kev, EVENT_REGISTER);
   1318 		mutex_spin_exit(&kq->kq_lock);
   1319 	} else {
   1320 		kn->kn_sfflags = kev->fflags;
   1321 		kn->kn_sdata = kev->data;
   1322 	}
   1323 
   1324 	/*
   1325 	 * We can get here if we are trying to attach
   1326 	 * an event to a file descriptor that does not
   1327 	 * support events, and the attach routine is
   1328 	 * broken and does not return an error.
   1329 	 */
   1330 done_ev_add:
   1331 	rv = filter_event(kn, 0);
   1332 	if (rv)
   1333 		knote_activate(kn);
   1334 
   1335 	/* disable knote */
   1336 	if ((kev->flags & EV_DISABLE)) {
   1337 		mutex_spin_enter(&kq->kq_lock);
   1338 		if ((kn->kn_status & KN_DISABLED) == 0)
   1339 			kn->kn_status |= KN_DISABLED;
   1340 		mutex_spin_exit(&kq->kq_lock);
   1341 	}
   1342 
   1343 	/* enable knote */
   1344 	if ((kev->flags & EV_ENABLE)) {
   1345 		knote_enqueue(kn);
   1346 	}
   1347 doneunlock:
   1348 	mutex_exit(&fdp->fd_lock);
   1349  done:
   1350 	rw_exit(&kqueue_filter_lock);
   1351 	if (newkn != NULL)
   1352 		kmem_free(newkn, sizeof(*newkn));
   1353 	if (fp != NULL)
   1354 		fd_putfile(fd);
   1355 	return (error);
   1356 }
   1357 
   1358 #if defined(DEBUG)
   1359 #define KN_FMT(buf, kn) \
   1360     (snprintb((buf), sizeof(buf), __KN_FLAG_BITS, (kn)->kn_status), buf)
   1361 
   1362 static void
   1363 kqueue_check(const char *func, size_t line, const struct kqueue *kq)
   1364 {
   1365 	const struct knote *kn;
   1366 	u_int count;
   1367 	int nmarker;
   1368 	char buf[128];
   1369 
   1370 	KASSERT(mutex_owned(&kq->kq_lock));
   1371 	KASSERT(KQ_COUNT(kq) < UINT_MAX / 2);
   1372 
   1373 	count = 0;
   1374 	nmarker = 0;
   1375 	TAILQ_FOREACH(kn, &kq->kq_head, kn_tqe) {
   1376 		if ((kn->kn_status & (KN_MARKER | KN_QUEUED)) == 0) {
   1377 			panic("%s,%zu: kq=%p kn=%p !(MARKER|QUEUED) %s",
   1378 			    func, line, kq, kn, KN_FMT(buf, kn));
   1379 		}
   1380 		if ((kn->kn_status & KN_MARKER) == 0) {
   1381 			if (kn->kn_kq != kq) {
   1382 				panic("%s,%zu: kq=%p kn(%p) != kn->kq(%p): %s",
   1383 				    func, line, kq, kn, kn->kn_kq,
   1384 				    KN_FMT(buf, kn));
   1385 			}
   1386 			if ((kn->kn_status & KN_ACTIVE) == 0) {
   1387 				panic("%s,%zu: kq=%p kn=%p: !ACTIVE %s",
   1388 				    func, line, kq, kn, KN_FMT(buf, kn));
   1389 			}
   1390 			count++;
   1391 			if (count > KQ_COUNT(kq)) {
   1392 				panic("%s,%zu: kq=%p kq->kq_count(%d) != "
   1393 				    "count(%d), nmarker=%d",
   1394 		    		    func, line, kq, KQ_COUNT(kq), count,
   1395 				    nmarker);
   1396 			}
   1397 		} else {
   1398 			nmarker++;
   1399 		}
   1400 	}
   1401 }
   1402 #define kq_check(a) kqueue_check(__func__, __LINE__, (a))
   1403 #else /* defined(DEBUG) */
   1404 #define	kq_check(a)	/* nothing */
   1405 #endif /* defined(DEBUG) */
   1406 
   1407 static void
   1408 kqueue_restart(file_t *fp)
   1409 {
   1410 	struct kqueue *kq = fp->f_kqueue;
   1411 	KASSERT(kq != NULL);
   1412 
   1413 	mutex_spin_enter(&kq->kq_lock);
   1414 	kq->kq_count |= KQ_RESTART;
   1415 	cv_broadcast(&kq->kq_cv);
   1416 	mutex_spin_exit(&kq->kq_lock);
   1417 }
   1418 
   1419 /*
   1420  * Scan through the list of events on fp (for a maximum of maxevents),
   1421  * returning the results in to ulistp. Timeout is determined by tsp; if
   1422  * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
   1423  * as appropriate.
   1424  */
   1425 static int
   1426 kqueue_scan(file_t *fp, size_t maxevents, struct kevent *ulistp,
   1427 	    const struct timespec *tsp, register_t *retval,
   1428 	    const struct kevent_ops *keops, struct kevent *kevbuf,
   1429 	    size_t kevcnt)
   1430 {
   1431 	struct kqueue	*kq;
   1432 	struct kevent	*kevp;
   1433 	struct timespec	ats, sleepts;
   1434 	struct knote	*kn, *marker, morker;
   1435 	size_t		count, nkev, nevents;
   1436 	int		timeout, error, touch, rv, influx;
   1437 	filedesc_t	*fdp;
   1438 
   1439 	fdp = curlwp->l_fd;
   1440 	kq = fp->f_kqueue;
   1441 	count = maxevents;
   1442 	nkev = nevents = error = 0;
   1443 	if (count == 0) {
   1444 		*retval = 0;
   1445 		return 0;
   1446 	}
   1447 
   1448 	if (tsp) {				/* timeout supplied */
   1449 		ats = *tsp;
   1450 		if (inittimeleft(&ats, &sleepts) == -1) {
   1451 			*retval = maxevents;
   1452 			return EINVAL;
   1453 		}
   1454 		timeout = tstohz(&ats);
   1455 		if (timeout <= 0)
   1456 			timeout = -1;           /* do poll */
   1457 	} else {
   1458 		/* no timeout, wait forever */
   1459 		timeout = 0;
   1460 	}
   1461 
   1462 	memset(&morker, 0, sizeof(morker));
   1463 	marker = &morker;
   1464 	marker->kn_status = KN_MARKER;
   1465 	mutex_spin_enter(&kq->kq_lock);
   1466  retry:
   1467 	kevp = kevbuf;
   1468 	if (KQ_COUNT(kq) == 0) {
   1469 		if (timeout >= 0) {
   1470 			error = cv_timedwait_sig(&kq->kq_cv,
   1471 			    &kq->kq_lock, timeout);
   1472 			if (error == 0) {
   1473 				if (KQ_COUNT(kq) == 0 &&
   1474 				    (kq->kq_count & KQ_RESTART)) {
   1475 					/* return to clear file reference */
   1476 					error = ERESTART;
   1477 				} else if (tsp == NULL || (timeout =
   1478 				    gettimeleft(&ats, &sleepts)) > 0) {
   1479 					goto retry;
   1480 				}
   1481 			} else {
   1482 				/* don't restart after signals... */
   1483 				if (error == ERESTART)
   1484 					error = EINTR;
   1485 				if (error == EWOULDBLOCK)
   1486 					error = 0;
   1487 			}
   1488 		}
   1489 		mutex_spin_exit(&kq->kq_lock);
   1490 		goto done;
   1491 	}
   1492 
   1493 	/* mark end of knote list */
   1494 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
   1495 	influx = 0;
   1496 
   1497 	/*
   1498 	 * Acquire the fdp->fd_lock interlock to avoid races with
   1499 	 * file creation/destruction from other threads.
   1500 	 */
   1501 relock:
   1502 	mutex_spin_exit(&kq->kq_lock);
   1503 	mutex_enter(&fdp->fd_lock);
   1504 	mutex_spin_enter(&kq->kq_lock);
   1505 
   1506 	while (count != 0) {
   1507 		kn = TAILQ_FIRST(&kq->kq_head);	/* get next knote */
   1508 
   1509 		if ((kn->kn_status & KN_MARKER) != 0 && kn != marker) {
   1510 			if (influx) {
   1511 				influx = 0;
   1512 				KQ_FLUX_WAKEUP(kq);
   1513 			}
   1514 			mutex_exit(&fdp->fd_lock);
   1515 			(void)cv_wait(&kq->kq_cv, &kq->kq_lock);
   1516 			goto relock;
   1517 		}
   1518 
   1519 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   1520 		if (kn == marker) {
   1521 			/* it's our marker, stop */
   1522 			KQ_FLUX_WAKEUP(kq);
   1523 			if (count == maxevents) {
   1524 				mutex_exit(&fdp->fd_lock);
   1525 				goto retry;
   1526 			}
   1527 			break;
   1528 		}
   1529 		KASSERT((kn->kn_status & KN_BUSY) == 0);
   1530 
   1531 		kq_check(kq);
   1532 		kn->kn_status &= ~KN_QUEUED;
   1533 		kn->kn_status |= KN_BUSY;
   1534 		kq_check(kq);
   1535 		if (kn->kn_status & KN_DISABLED) {
   1536 			kn->kn_status &= ~KN_BUSY;
   1537 			kq->kq_count--;
   1538 			/* don't want disabled events */
   1539 			continue;
   1540 		}
   1541 		if ((kn->kn_flags & EV_ONESHOT) == 0) {
   1542 			mutex_spin_exit(&kq->kq_lock);
   1543 			KASSERT(mutex_owned(&fdp->fd_lock));
   1544 			rv = filter_event(kn, 0);
   1545 			mutex_spin_enter(&kq->kq_lock);
   1546 			/* Re-poll if note was re-enqueued. */
   1547 			if ((kn->kn_status & KN_QUEUED) != 0) {
   1548 				kn->kn_status &= ~KN_BUSY;
   1549 				/* Re-enqueue raised kq_count, lower it again */
   1550 				kq->kq_count--;
   1551 				influx = 1;
   1552 				continue;
   1553 			}
   1554 			if (rv == 0) {
   1555 				/*
   1556 				 * non-ONESHOT event that hasn't
   1557 				 * triggered again, so de-queue.
   1558 				 */
   1559 				kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
   1560 				kq->kq_count--;
   1561 				influx = 1;
   1562 				continue;
   1563 			}
   1564 		}
   1565 		KASSERT(kn->kn_fop != NULL);
   1566 		touch = (!(kn->kn_fop->f_flags & FILTEROP_ISFD) &&
   1567 				kn->kn_fop->f_touch != NULL);
   1568 		/* XXXAD should be got from f_event if !oneshot. */
   1569 		if (touch) {
   1570 			filter_touch(kn, kevp, EVENT_PROCESS);
   1571 		} else {
   1572 			*kevp = kn->kn_kevent;
   1573 		}
   1574 		kevp++;
   1575 		nkev++;
   1576 		influx = 1;
   1577 		if (kn->kn_flags & EV_ONESHOT) {
   1578 			/* delete ONESHOT events after retrieval */
   1579 			kn->kn_status &= ~KN_BUSY;
   1580 			kq->kq_count--;
   1581 			mutex_spin_exit(&kq->kq_lock);
   1582 			knote_detach(kn, fdp, true);
   1583 			mutex_enter(&fdp->fd_lock);
   1584 			mutex_spin_enter(&kq->kq_lock);
   1585 		} else if (kn->kn_flags & EV_CLEAR) {
   1586 			/* clear state after retrieval */
   1587 			kn->kn_data = 0;
   1588 			kn->kn_fflags = 0;
   1589 			/*
   1590 			 * Manually clear knotes who weren't
   1591 			 * 'touch'ed.
   1592 			 */
   1593 			if (touch == 0) {
   1594 				kn->kn_data = 0;
   1595 				kn->kn_fflags = 0;
   1596 			}
   1597 			kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
   1598 			kq->kq_count--;
   1599 		} else if (kn->kn_flags & EV_DISPATCH) {
   1600 			kn->kn_status |= KN_DISABLED;
   1601 			kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
   1602 			kq->kq_count--;
   1603 		} else {
   1604 			/* add event back on list */
   1605 			kq_check(kq);
   1606 			kn->kn_status |= KN_QUEUED;
   1607 			kn->kn_status &= ~KN_BUSY;
   1608 			TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1609 			kq_check(kq);
   1610 		}
   1611 
   1612 		if (nkev == kevcnt) {
   1613 			/* do copyouts in kevcnt chunks */
   1614 			influx = 0;
   1615 			KQ_FLUX_WAKEUP(kq);
   1616 			mutex_spin_exit(&kq->kq_lock);
   1617 			mutex_exit(&fdp->fd_lock);
   1618 			error = (*keops->keo_put_events)
   1619 			    (keops->keo_private,
   1620 			    kevbuf, ulistp, nevents, nkev);
   1621 			mutex_enter(&fdp->fd_lock);
   1622 			mutex_spin_enter(&kq->kq_lock);
   1623 			nevents += nkev;
   1624 			nkev = 0;
   1625 			kevp = kevbuf;
   1626 		}
   1627 		count--;
   1628 		if (error != 0 || count == 0) {
   1629 			/* remove marker */
   1630 			TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
   1631 			break;
   1632 		}
   1633 	}
   1634 	KQ_FLUX_WAKEUP(kq);
   1635 	mutex_spin_exit(&kq->kq_lock);
   1636 	mutex_exit(&fdp->fd_lock);
   1637 
   1638 done:
   1639 	if (nkev != 0) {
   1640 		/* copyout remaining events */
   1641 		error = (*keops->keo_put_events)(keops->keo_private,
   1642 		    kevbuf, ulistp, nevents, nkev);
   1643 	}
   1644 	*retval = maxevents - count;
   1645 
   1646 	return error;
   1647 }
   1648 
   1649 /*
   1650  * fileops ioctl method for a kqueue descriptor.
   1651  *
   1652  * Two ioctls are currently supported. They both use struct kfilter_mapping:
   1653  *	KFILTER_BYNAME		find name for filter, and return result in
   1654  *				name, which is of size len.
   1655  *	KFILTER_BYFILTER	find filter for name. len is ignored.
   1656  */
   1657 /*ARGSUSED*/
   1658 static int
   1659 kqueue_ioctl(file_t *fp, u_long com, void *data)
   1660 {
   1661 	struct kfilter_mapping	*km;
   1662 	const struct kfilter	*kfilter;
   1663 	char			*name;
   1664 	int			error;
   1665 
   1666 	km = data;
   1667 	error = 0;
   1668 	name = kmem_alloc(KFILTER_MAXNAME, KM_SLEEP);
   1669 
   1670 	switch (com) {
   1671 	case KFILTER_BYFILTER:	/* convert filter -> name */
   1672 		rw_enter(&kqueue_filter_lock, RW_READER);
   1673 		kfilter = kfilter_byfilter(km->filter);
   1674 		if (kfilter != NULL) {
   1675 			strlcpy(name, kfilter->name, KFILTER_MAXNAME);
   1676 			rw_exit(&kqueue_filter_lock);
   1677 			error = copyoutstr(name, km->name, km->len, NULL);
   1678 		} else {
   1679 			rw_exit(&kqueue_filter_lock);
   1680 			error = ENOENT;
   1681 		}
   1682 		break;
   1683 
   1684 	case KFILTER_BYNAME:	/* convert name -> filter */
   1685 		error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
   1686 		if (error) {
   1687 			break;
   1688 		}
   1689 		rw_enter(&kqueue_filter_lock, RW_READER);
   1690 		kfilter = kfilter_byname(name);
   1691 		if (kfilter != NULL)
   1692 			km->filter = kfilter->filter;
   1693 		else
   1694 			error = ENOENT;
   1695 		rw_exit(&kqueue_filter_lock);
   1696 		break;
   1697 
   1698 	default:
   1699 		error = ENOTTY;
   1700 		break;
   1701 
   1702 	}
   1703 	kmem_free(name, KFILTER_MAXNAME);
   1704 	return (error);
   1705 }
   1706 
   1707 /*
   1708  * fileops fcntl method for a kqueue descriptor.
   1709  */
   1710 static int
   1711 kqueue_fcntl(file_t *fp, u_int com, void *data)
   1712 {
   1713 
   1714 	return (ENOTTY);
   1715 }
   1716 
   1717 /*
   1718  * fileops poll method for a kqueue descriptor.
   1719  * Determine if kqueue has events pending.
   1720  */
   1721 static int
   1722 kqueue_poll(file_t *fp, int events)
   1723 {
   1724 	struct kqueue	*kq;
   1725 	int		revents;
   1726 
   1727 	kq = fp->f_kqueue;
   1728 
   1729 	revents = 0;
   1730 	if (events & (POLLIN | POLLRDNORM)) {
   1731 		mutex_spin_enter(&kq->kq_lock);
   1732 		if (KQ_COUNT(kq) != 0) {
   1733 			revents |= events & (POLLIN | POLLRDNORM);
   1734 		} else {
   1735 			selrecord(curlwp, &kq->kq_sel);
   1736 		}
   1737 		kq_check(kq);
   1738 		mutex_spin_exit(&kq->kq_lock);
   1739 	}
   1740 
   1741 	return revents;
   1742 }
   1743 
   1744 /*
   1745  * fileops stat method for a kqueue descriptor.
   1746  * Returns dummy info, with st_size being number of events pending.
   1747  */
   1748 static int
   1749 kqueue_stat(file_t *fp, struct stat *st)
   1750 {
   1751 	struct kqueue *kq;
   1752 
   1753 	kq = fp->f_kqueue;
   1754 
   1755 	memset(st, 0, sizeof(*st));
   1756 	st->st_size = KQ_COUNT(kq);
   1757 	st->st_blksize = sizeof(struct kevent);
   1758 	st->st_mode = S_IFIFO;
   1759 
   1760 	return 0;
   1761 }
   1762 
   1763 static void
   1764 kqueue_doclose(struct kqueue *kq, struct klist *list, int fd)
   1765 {
   1766 	struct knote *kn;
   1767 	filedesc_t *fdp;
   1768 
   1769 	fdp = kq->kq_fdp;
   1770 
   1771 	KASSERT(mutex_owned(&fdp->fd_lock));
   1772 
   1773 	for (kn = SLIST_FIRST(list); kn != NULL;) {
   1774 		if (kq != kn->kn_kq) {
   1775 			kn = SLIST_NEXT(kn, kn_link);
   1776 			continue;
   1777 		}
   1778 		knote_detach(kn, fdp, true);
   1779 		mutex_enter(&fdp->fd_lock);
   1780 		kn = SLIST_FIRST(list);
   1781 	}
   1782 }
   1783 
   1784 
   1785 /*
   1786  * fileops close method for a kqueue descriptor.
   1787  */
   1788 static int
   1789 kqueue_close(file_t *fp)
   1790 {
   1791 	struct kqueue *kq;
   1792 	filedesc_t *fdp;
   1793 	fdfile_t *ff;
   1794 	int i;
   1795 
   1796 	kq = fp->f_kqueue;
   1797 	fp->f_kqueue = NULL;
   1798 	fp->f_type = 0;
   1799 	fdp = curlwp->l_fd;
   1800 
   1801 	mutex_enter(&fdp->fd_lock);
   1802 	for (i = 0; i <= fdp->fd_lastkqfile; i++) {
   1803 		if ((ff = fdp->fd_dt->dt_ff[i]) == NULL)
   1804 			continue;
   1805 		kqueue_doclose(kq, (struct klist *)&ff->ff_knlist, i);
   1806 	}
   1807 	if (fdp->fd_knhashmask != 0) {
   1808 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
   1809 			kqueue_doclose(kq, &fdp->fd_knhash[i], -1);
   1810 		}
   1811 	}
   1812 	mutex_exit(&fdp->fd_lock);
   1813 
   1814 	KASSERT(KQ_COUNT(kq) == 0);
   1815 	mutex_destroy(&kq->kq_lock);
   1816 	cv_destroy(&kq->kq_cv);
   1817 	seldestroy(&kq->kq_sel);
   1818 	kmem_free(kq, sizeof(*kq));
   1819 
   1820 	return (0);
   1821 }
   1822 
   1823 /*
   1824  * struct fileops kqfilter method for a kqueue descriptor.
   1825  * Event triggered when monitored kqueue changes.
   1826  */
   1827 static int
   1828 kqueue_kqfilter(file_t *fp, struct knote *kn)
   1829 {
   1830 	struct kqueue *kq;
   1831 
   1832 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
   1833 
   1834 	KASSERT(fp == kn->kn_obj);
   1835 
   1836 	if (kn->kn_filter != EVFILT_READ)
   1837 		return 1;
   1838 
   1839 	kn->kn_fop = &kqread_filtops;
   1840 	mutex_enter(&kq->kq_lock);
   1841 	selrecord_knote(&kq->kq_sel, kn);
   1842 	mutex_exit(&kq->kq_lock);
   1843 
   1844 	return 0;
   1845 }
   1846 
   1847 
   1848 /*
   1849  * Walk down a list of knotes, activating them if their event has
   1850  * triggered.  The caller's object lock (e.g. device driver lock)
   1851  * must be held.
   1852  */
   1853 void
   1854 knote(struct klist *list, long hint)
   1855 {
   1856 	struct knote *kn, *tmpkn;
   1857 
   1858 	SLIST_FOREACH_SAFE(kn, list, kn_selnext, tmpkn) {
   1859 		KASSERT(kn->kn_fop != NULL);
   1860 		KASSERT(kn->kn_fop->f_event != NULL);
   1861 		if ((*kn->kn_fop->f_event)(kn, hint))
   1862 			knote_activate(kn);
   1863 	}
   1864 }
   1865 
   1866 /*
   1867  * Remove all knotes referencing a specified fd
   1868  */
   1869 void
   1870 knote_fdclose(int fd)
   1871 {
   1872 	struct klist *list;
   1873 	struct knote *kn;
   1874 	filedesc_t *fdp;
   1875 
   1876 	fdp = curlwp->l_fd;
   1877 	mutex_enter(&fdp->fd_lock);
   1878 	list = (struct klist *)&fdp->fd_dt->dt_ff[fd]->ff_knlist;
   1879 	while ((kn = SLIST_FIRST(list)) != NULL) {
   1880 		knote_detach(kn, fdp, true);
   1881 		mutex_enter(&fdp->fd_lock);
   1882 	}
   1883 	mutex_exit(&fdp->fd_lock);
   1884 }
   1885 
   1886 /*
   1887  * Drop knote.  Called with fdp->fd_lock held, and will drop before
   1888  * returning.
   1889  */
   1890 static void
   1891 knote_detach(struct knote *kn, filedesc_t *fdp, bool dofop)
   1892 {
   1893 	struct klist *list;
   1894 	struct kqueue *kq;
   1895 
   1896 	kq = kn->kn_kq;
   1897 
   1898 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1899 	KASSERT(mutex_owned(&fdp->fd_lock));
   1900 
   1901 	KASSERT(kn->kn_fop != NULL);
   1902 	/* Remove from monitored object. */
   1903 	if (dofop) {
   1904 		filter_detach(kn);
   1905 	}
   1906 
   1907 	/* Remove from descriptor table. */
   1908 	if (kn->kn_fop->f_flags & FILTEROP_ISFD)
   1909 		list = (struct klist *)&fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
   1910 	else
   1911 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
   1912 
   1913 	SLIST_REMOVE(list, kn, knote, kn_link);
   1914 
   1915 	/* Remove from kqueue. */
   1916 again:
   1917 	mutex_spin_enter(&kq->kq_lock);
   1918 	if ((kn->kn_status & KN_QUEUED) != 0) {
   1919 		kq_check(kq);
   1920 		kq->kq_count--;
   1921 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   1922 		kn->kn_status &= ~KN_QUEUED;
   1923 		kq_check(kq);
   1924 	} else if (kn->kn_status & KN_BUSY) {
   1925 		mutex_spin_exit(&kq->kq_lock);
   1926 		goto again;
   1927 	}
   1928 	mutex_spin_exit(&kq->kq_lock);
   1929 
   1930 	mutex_exit(&fdp->fd_lock);
   1931 	if (kn->kn_fop->f_flags & FILTEROP_ISFD)
   1932 		fd_putfile(kn->kn_id);
   1933 	atomic_dec_uint(&kn->kn_kfilter->refcnt);
   1934 	kmem_free(kn, sizeof(*kn));
   1935 }
   1936 
   1937 /*
   1938  * Queue new event for knote.
   1939  */
   1940 static void
   1941 knote_enqueue(struct knote *kn)
   1942 {
   1943 	struct kqueue *kq;
   1944 
   1945 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1946 
   1947 	kq = kn->kn_kq;
   1948 
   1949 	mutex_spin_enter(&kq->kq_lock);
   1950 	if ((kn->kn_status & KN_DISABLED) != 0) {
   1951 		kn->kn_status &= ~KN_DISABLED;
   1952 	}
   1953 	if ((kn->kn_status & (KN_ACTIVE | KN_QUEUED)) == KN_ACTIVE) {
   1954 		kq_check(kq);
   1955 		kn->kn_status |= KN_QUEUED;
   1956 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1957 		kq->kq_count++;
   1958 		kq_check(kq);
   1959 		cv_broadcast(&kq->kq_cv);
   1960 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   1961 	}
   1962 	mutex_spin_exit(&kq->kq_lock);
   1963 }
   1964 /*
   1965  * Queue new event for knote.
   1966  */
   1967 static void
   1968 knote_activate(struct knote *kn)
   1969 {
   1970 	struct kqueue *kq;
   1971 
   1972 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1973 
   1974 	kq = kn->kn_kq;
   1975 
   1976 	mutex_spin_enter(&kq->kq_lock);
   1977 	kn->kn_status |= KN_ACTIVE;
   1978 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) {
   1979 		kq_check(kq);
   1980 		kn->kn_status |= KN_QUEUED;
   1981 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1982 		kq->kq_count++;
   1983 		kq_check(kq);
   1984 		cv_broadcast(&kq->kq_cv);
   1985 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   1986 	}
   1987 	mutex_spin_exit(&kq->kq_lock);
   1988 }
   1989