Home | History | Annotate | Line # | Download | only in kern
kern_event.c revision 1.131
      1 /*	$NetBSD: kern_event.c,v 1.131 2021/10/11 01:07:36 thorpej Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008, 2009, 2021 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 #ifdef _KERNEL_OPT
     62 #include "opt_ddb.h"
     63 #endif /* _KERNEL_OPT */
     64 
     65 #include <sys/cdefs.h>
     66 __KERNEL_RCSID(0, "$NetBSD: kern_event.c,v 1.131 2021/10/11 01:07:36 thorpej Exp $");
     67 
     68 #include <sys/param.h>
     69 #include <sys/systm.h>
     70 #include <sys/kernel.h>
     71 #include <sys/wait.h>
     72 #include <sys/proc.h>
     73 #include <sys/file.h>
     74 #include <sys/select.h>
     75 #include <sys/queue.h>
     76 #include <sys/event.h>
     77 #include <sys/eventvar.h>
     78 #include <sys/poll.h>
     79 #include <sys/kmem.h>
     80 #include <sys/stat.h>
     81 #include <sys/filedesc.h>
     82 #include <sys/syscallargs.h>
     83 #include <sys/kauth.h>
     84 #include <sys/conf.h>
     85 #include <sys/atomic.h>
     86 
     87 static int	kqueue_scan(file_t *, size_t, struct kevent *,
     88 			    const struct timespec *, register_t *,
     89 			    const struct kevent_ops *, struct kevent *,
     90 			    size_t);
     91 static int	kqueue_ioctl(file_t *, u_long, void *);
     92 static int	kqueue_fcntl(file_t *, u_int, void *);
     93 static int	kqueue_poll(file_t *, int);
     94 static int	kqueue_kqfilter(file_t *, struct knote *);
     95 static int	kqueue_stat(file_t *, struct stat *);
     96 static int	kqueue_close(file_t *);
     97 static void	kqueue_restart(file_t *);
     98 static int	kqueue_register(struct kqueue *, struct kevent *);
     99 static void	kqueue_doclose(struct kqueue *, struct klist *, int);
    100 
    101 static void	knote_detach(struct knote *, filedesc_t *fdp, bool);
    102 static void	knote_enqueue(struct knote *);
    103 static void	knote_activate(struct knote *);
    104 
    105 static void	filt_kqdetach(struct knote *);
    106 static int	filt_kqueue(struct knote *, long hint);
    107 static int	filt_procattach(struct knote *);
    108 static void	filt_procdetach(struct knote *);
    109 static int	filt_proc(struct knote *, long hint);
    110 static int	filt_fileattach(struct knote *);
    111 static void	filt_timerexpire(void *x);
    112 static int	filt_timerattach(struct knote *);
    113 static void	filt_timerdetach(struct knote *);
    114 static int	filt_timer(struct knote *, long hint);
    115 static int	filt_userattach(struct knote *);
    116 static void	filt_userdetach(struct knote *);
    117 static int	filt_user(struct knote *, long hint);
    118 static void	filt_usertouch(struct knote *, struct kevent *, long type);
    119 
    120 static const struct fileops kqueueops = {
    121 	.fo_name = "kqueue",
    122 	.fo_read = (void *)enxio,
    123 	.fo_write = (void *)enxio,
    124 	.fo_ioctl = kqueue_ioctl,
    125 	.fo_fcntl = kqueue_fcntl,
    126 	.fo_poll = kqueue_poll,
    127 	.fo_stat = kqueue_stat,
    128 	.fo_close = kqueue_close,
    129 	.fo_kqfilter = kqueue_kqfilter,
    130 	.fo_restart = kqueue_restart,
    131 };
    132 
    133 static const struct filterops kqread_filtops = {
    134 	.f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
    135 	.f_attach = NULL,
    136 	.f_detach = filt_kqdetach,
    137 	.f_event = filt_kqueue,
    138 };
    139 
    140 static const struct filterops proc_filtops = {
    141 	.f_flags = FILTEROP_MPSAFE,
    142 	.f_attach = filt_procattach,
    143 	.f_detach = filt_procdetach,
    144 	.f_event = filt_proc,
    145 };
    146 
    147 /*
    148  * file_filtops is not marked MPSAFE because it's going to call
    149  * fileops::fo_kqfilter(), which might not be.  That function,
    150  * however, will override the knote's filterops, and thus will
    151  * inherit the MPSAFE-ness of the back-end at that time.
    152  */
    153 static const struct filterops file_filtops = {
    154 	.f_flags = FILTEROP_ISFD,
    155 	.f_attach = filt_fileattach,
    156 	.f_detach = NULL,
    157 	.f_event = NULL,
    158 };
    159 
    160 static const struct filterops timer_filtops = {
    161 	.f_flags = FILTEROP_MPSAFE,
    162 	.f_attach = filt_timerattach,
    163 	.f_detach = filt_timerdetach,
    164 	.f_event = filt_timer,
    165 };
    166 
    167 static const struct filterops user_filtops = {
    168 	.f_flags = FILTEROP_MPSAFE,
    169 	.f_attach = filt_userattach,
    170 	.f_detach = filt_userdetach,
    171 	.f_event = filt_user,
    172 	.f_touch = filt_usertouch,
    173 };
    174 
    175 static u_int	kq_ncallouts = 0;
    176 static int	kq_calloutmax = (4 * 1024);
    177 
    178 #define	KN_HASHSIZE		64		/* XXX should be tunable */
    179 #define	KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
    180 
    181 extern const struct filterops fs_filtops;	/* vfs_syscalls.c */
    182 extern const struct filterops sig_filtops;	/* kern_sig.c */
    183 
    184 /*
    185  * Table for for all system-defined filters.
    186  * These should be listed in the numeric order of the EVFILT_* defines.
    187  * If filtops is NULL, the filter isn't implemented in NetBSD.
    188  * End of list is when name is NULL.
    189  *
    190  * Note that 'refcnt' is meaningless for built-in filters.
    191  */
    192 struct kfilter {
    193 	const char	*name;		/* name of filter */
    194 	uint32_t	filter;		/* id of filter */
    195 	unsigned	refcnt;		/* reference count */
    196 	const struct filterops *filtops;/* operations for filter */
    197 	size_t		namelen;	/* length of name string */
    198 };
    199 
    200 /* System defined filters */
    201 static struct kfilter sys_kfilters[] = {
    202 	{ "EVFILT_READ",	EVFILT_READ,	0, &file_filtops, 0 },
    203 	{ "EVFILT_WRITE",	EVFILT_WRITE,	0, &file_filtops, 0, },
    204 	{ "EVFILT_AIO",		EVFILT_AIO,	0, NULL, 0 },
    205 	{ "EVFILT_VNODE",	EVFILT_VNODE,	0, &file_filtops, 0 },
    206 	{ "EVFILT_PROC",	EVFILT_PROC,	0, &proc_filtops, 0 },
    207 	{ "EVFILT_SIGNAL",	EVFILT_SIGNAL,	0, &sig_filtops, 0 },
    208 	{ "EVFILT_TIMER",	EVFILT_TIMER,	0, &timer_filtops, 0 },
    209 	{ "EVFILT_FS",		EVFILT_FS,	0, &fs_filtops, 0 },
    210 	{ "EVFILT_USER",	EVFILT_USER,	0, &user_filtops, 0 },
    211 	{ NULL,			0,		0, NULL, 0 },
    212 };
    213 
    214 /* User defined kfilters */
    215 static struct kfilter	*user_kfilters;		/* array */
    216 static int		user_kfilterc;		/* current offset */
    217 static int		user_kfiltermaxc;	/* max size so far */
    218 static size_t		user_kfiltersz;		/* size of allocated memory */
    219 
    220 /*
    221  * Global Locks.
    222  *
    223  * Lock order:
    224  *
    225  *	kqueue_filter_lock
    226  *	-> kn_kq->kq_fdp->fd_lock
    227  *	-> object lock (e.g., device driver lock, &c.)
    228  *	-> kn_kq->kq_lock
    229  *
    230  * Locking rules:
    231  *
    232  *	f_attach: fdp->fd_lock, KERNEL_LOCK
    233  *	f_detach: fdp->fd_lock, KERNEL_LOCK
    234  *	f_event(!NOTE_SUBMIT) via kevent: fdp->fd_lock, _no_ object lock
    235  *	f_event via knote: whatever caller guarantees
    236  *		Typically,	f_event(NOTE_SUBMIT) via knote: object lock
    237  *				f_event(!NOTE_SUBMIT) via knote: nothing,
    238  *					acquires/releases object lock inside.
    239  *
    240  * Locking rules when detaching knotes:
    241  *
    242  * There are some situations where knote submission may require dropping
    243  * locks (see knote_proc_fork()).  In order to support this, it's possible
    244  * to mark a knote as being 'in-flux'.  Such a knote is guaranteed not to
    245  * be detached while it remains in-flux.  Because it will not be detached,
    246  * locks can be dropped so e.g. memory can be allocated, locks on other
    247  * data structures can be acquired, etc.  During this time, any attempt to
    248  * detach an in-flux knote must wait until the knote is no longer in-flux.
    249  * When this happens, the knote is marked for death (KN_WILLDETACH) and the
    250  * LWP who gets to finish the detach operation is recorded in the knote's
    251  * 'udata' field (which is no longer required for its original purpose once
    252  * a knote is so marked).  Code paths that lead to knote_detach() must ensure
    253  * that their LWP is the one tasked with its final demise after waiting for
    254  * the in-flux status of the knote to clear.  Note that once a knote is
    255  * marked KN_WILLDETACH, no code paths may put it into an in-flux state.
    256  *
    257  * Once the special circumstances have been handled, the locks are re-
    258  * acquired in the proper order (object lock -> kq_lock), the knote taken
    259  * out of flux, and any waiters are notified.  Because waiters must have
    260  * also dropped *their* locks in order to safely block, they must re-
    261  * validate all of their assumptions; see knote_detach_quiesce().  See also
    262  * the kqueue_register() (EV_ADD, EV_DELETE) and kqueue_scan() (EV_ONESHOT)
    263  * cases.
    264  *
    265  * When kqueue_scan() encounters an in-flux knote, the situation is
    266  * treated like another LWP's list marker.
    267  *
    268  * LISTEN WELL: It is important to not hold knotes in flux for an
    269  * extended period of time! In-flux knotes effectively block any
    270  * progress of the kqueue_scan() operation.  Any code paths that place
    271  * knotes in-flux should be careful to not block for indefinite periods
    272  * of time, such as for memory allocation (i.e. KM_NOSLEEP is OK, but
    273  * KM_SLEEP is not).
    274  */
    275 static krwlock_t	kqueue_filter_lock;	/* lock on filter lists */
    276 static kmutex_t		kqueue_timer_lock;	/* for EVFILT_TIMER */
    277 
    278 #define	KQ_FLUX_WAIT(kq)	(void)cv_wait(&kq->kq_cv, &kq->kq_lock)
    279 #define	KQ_FLUX_WAKEUP(kq)	cv_broadcast(&kq->kq_cv)
    280 
    281 static inline bool
    282 kn_in_flux(struct knote *kn)
    283 {
    284 	KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
    285 	return kn->kn_influx != 0;
    286 }
    287 
    288 static inline bool
    289 kn_enter_flux(struct knote *kn)
    290 {
    291 	KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
    292 
    293 	if (kn->kn_status & KN_WILLDETACH) {
    294 		return false;
    295 	}
    296 
    297 	KASSERT(kn->kn_influx < UINT_MAX);
    298 	kn->kn_influx++;
    299 
    300 	return true;
    301 }
    302 
    303 static inline bool
    304 kn_leave_flux(struct knote *kn)
    305 {
    306 	KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
    307 	KASSERT(kn->kn_influx > 0);
    308 	kn->kn_influx--;
    309 	return kn->kn_influx == 0;
    310 }
    311 
    312 static void
    313 kn_wait_flux(struct knote *kn, bool can_loop)
    314 {
    315 	bool loop;
    316 
    317 	KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
    318 
    319 	/*
    320 	 * It may not be safe for us to touch the knote again after
    321 	 * dropping the kq_lock.  The caller has let us know in
    322 	 * 'can_loop'.
    323 	 */
    324 	for (loop = true; loop && kn->kn_influx != 0; loop = can_loop) {
    325 		KQ_FLUX_WAIT(kn->kn_kq);
    326 	}
    327 }
    328 
    329 #define	KNOTE_WILLDETACH(kn)						\
    330 do {									\
    331 	(kn)->kn_status |= KN_WILLDETACH;				\
    332 	(kn)->kn_kevent.udata = curlwp;					\
    333 } while (/*CONSTCOND*/0)
    334 
    335 /*
    336  * Wait until the specified knote is in a quiescent state and
    337  * safe to detach.  Returns true if we potentially blocked (and
    338  * thus dropped our locks).
    339  */
    340 static bool
    341 knote_detach_quiesce(struct knote *kn)
    342 {
    343 	struct kqueue *kq = kn->kn_kq;
    344 	filedesc_t *fdp = kq->kq_fdp;
    345 
    346 	KASSERT(mutex_owned(&fdp->fd_lock));
    347 
    348 	mutex_spin_enter(&kq->kq_lock);
    349 	/*
    350 	 * There are two cases where we might see KN_WILLDETACH here:
    351 	 *
    352 	 * 1. Someone else has already started detaching the knote but
    353 	 *    had to wait for it to settle first.
    354 	 *
    355 	 * 2. We had to wait for it to settle, and had to come back
    356 	 *    around after re-acquiring the locks.
    357 	 *
    358 	 * When KN_WILLDETACH is set, we also set the LWP that claimed
    359 	 * the prize of finishing the detach in the 'udata' field of the
    360 	 * knote (which will never be used again for its usual purpose
    361 	 * once the note is in this state).  If it doesn't point to us,
    362 	 * we must drop the locks and let them in to finish the job.
    363 	 *
    364 	 * Otherwise, once we have claimed the knote for ourselves, we
    365 	 * can finish waiting for it to settle.  The is the only scenario
    366 	 * where touching a detaching knote is safe after dropping the
    367 	 * locks.
    368 	 */
    369 	if ((kn->kn_status & KN_WILLDETACH) != 0 &&
    370 	    kn->kn_kevent.udata != curlwp) {
    371 		/*
    372 		 * N.B. it is NOT safe for us to touch the knote again
    373 		 * after dropping the locks here.  The caller must go
    374 		 * back around and re-validate everything.  However, if
    375 		 * the knote is in-flux, we want to block to minimize
    376 		 * busy-looping.
    377 		 */
    378 		mutex_exit(&fdp->fd_lock);
    379 		if (kn_in_flux(kn)) {
    380 			kn_wait_flux(kn, false);
    381 			mutex_spin_exit(&kq->kq_lock);
    382 			return true;
    383 		}
    384 		mutex_spin_exit(&kq->kq_lock);
    385 		preempt_point();
    386 		return true;
    387 	}
    388 	/*
    389 	 * If we get here, we know that we will be claiming the
    390 	 * detach responsibilies, or that we already have and
    391 	 * this is the second attempt after re-validation.
    392 	 */
    393 	KASSERT((kn->kn_status & KN_WILLDETACH) == 0 ||
    394 		kn->kn_kevent.udata == curlwp);
    395 	/*
    396 	 * Similarly, if we get here, either we are just claiming it
    397 	 * and may have to wait for it to settle, or if this is the
    398 	 * second attempt after re-validation that no other code paths
    399 	 * have put it in-flux.
    400 	 */
    401 	KASSERT((kn->kn_status & KN_WILLDETACH) == 0 ||
    402 		kn_in_flux(kn) == false);
    403 	KNOTE_WILLDETACH(kn);
    404 	if (kn_in_flux(kn)) {
    405 		mutex_exit(&fdp->fd_lock);
    406 		kn_wait_flux(kn, true);
    407 		/*
    408 		 * It is safe for us to touch the knote again after
    409 		 * dropping the locks, but the caller must still
    410 		 * re-validate everything because other aspects of
    411 		 * the environment may have changed while we blocked.
    412 		 */
    413 		KASSERT(kn_in_flux(kn) == false);
    414 		mutex_spin_exit(&kq->kq_lock);
    415 		return true;
    416 	}
    417 	mutex_spin_exit(&kq->kq_lock);
    418 
    419 	return false;
    420 }
    421 
    422 static int
    423 filter_attach(struct knote *kn)
    424 {
    425 	int rv;
    426 
    427 	KASSERT(kn->kn_fop != NULL);
    428 	KASSERT(kn->kn_fop->f_attach != NULL);
    429 
    430 	/*
    431 	 * N.B. that kn->kn_fop may change as the result of calling
    432 	 * f_attach().
    433 	 */
    434 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
    435 		rv = kn->kn_fop->f_attach(kn);
    436 	} else {
    437 		KERNEL_LOCK(1, NULL);
    438 		rv = kn->kn_fop->f_attach(kn);
    439 		KERNEL_UNLOCK_ONE(NULL);
    440 	}
    441 
    442 	return rv;
    443 }
    444 
    445 static void
    446 filter_detach(struct knote *kn)
    447 {
    448 	KASSERT(kn->kn_fop != NULL);
    449 	KASSERT(kn->kn_fop->f_detach != NULL);
    450 
    451 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
    452 		kn->kn_fop->f_detach(kn);
    453 	} else {
    454 		KERNEL_LOCK(1, NULL);
    455 		kn->kn_fop->f_detach(kn);
    456 		KERNEL_UNLOCK_ONE(NULL);
    457 	}
    458 }
    459 
    460 static int
    461 filter_event(struct knote *kn, long hint)
    462 {
    463 	int rv;
    464 
    465 	KASSERT(kn->kn_fop != NULL);
    466 	KASSERT(kn->kn_fop->f_event != NULL);
    467 
    468 	if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
    469 		rv = kn->kn_fop->f_event(kn, hint);
    470 	} else {
    471 		KERNEL_LOCK(1, NULL);
    472 		rv = kn->kn_fop->f_event(kn, hint);
    473 		KERNEL_UNLOCK_ONE(NULL);
    474 	}
    475 
    476 	return rv;
    477 }
    478 
    479 static void
    480 filter_touch(struct knote *kn, struct kevent *kev, long type)
    481 {
    482 	kn->kn_fop->f_touch(kn, kev, type);
    483 }
    484 
    485 static kauth_listener_t	kqueue_listener;
    486 
    487 static int
    488 kqueue_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    489     void *arg0, void *arg1, void *arg2, void *arg3)
    490 {
    491 	struct proc *p;
    492 	int result;
    493 
    494 	result = KAUTH_RESULT_DEFER;
    495 	p = arg0;
    496 
    497 	if (action != KAUTH_PROCESS_KEVENT_FILTER)
    498 		return result;
    499 
    500 	if ((kauth_cred_getuid(p->p_cred) != kauth_cred_getuid(cred) ||
    501 	    ISSET(p->p_flag, PK_SUGID)))
    502 		return result;
    503 
    504 	result = KAUTH_RESULT_ALLOW;
    505 
    506 	return result;
    507 }
    508 
    509 /*
    510  * Initialize the kqueue subsystem.
    511  */
    512 void
    513 kqueue_init(void)
    514 {
    515 
    516 	rw_init(&kqueue_filter_lock);
    517 	mutex_init(&kqueue_timer_lock, MUTEX_DEFAULT, IPL_SOFTCLOCK);
    518 
    519 	kqueue_listener = kauth_listen_scope(KAUTH_SCOPE_PROCESS,
    520 	    kqueue_listener_cb, NULL);
    521 }
    522 
    523 /*
    524  * Find kfilter entry by name, or NULL if not found.
    525  */
    526 static struct kfilter *
    527 kfilter_byname_sys(const char *name)
    528 {
    529 	int i;
    530 
    531 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    532 
    533 	for (i = 0; sys_kfilters[i].name != NULL; i++) {
    534 		if (strcmp(name, sys_kfilters[i].name) == 0)
    535 			return &sys_kfilters[i];
    536 	}
    537 	return NULL;
    538 }
    539 
    540 static struct kfilter *
    541 kfilter_byname_user(const char *name)
    542 {
    543 	int i;
    544 
    545 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    546 
    547 	/* user filter slots have a NULL name if previously deregistered */
    548 	for (i = 0; i < user_kfilterc ; i++) {
    549 		if (user_kfilters[i].name != NULL &&
    550 		    strcmp(name, user_kfilters[i].name) == 0)
    551 			return &user_kfilters[i];
    552 	}
    553 	return NULL;
    554 }
    555 
    556 static struct kfilter *
    557 kfilter_byname(const char *name)
    558 {
    559 	struct kfilter *kfilter;
    560 
    561 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    562 
    563 	if ((kfilter = kfilter_byname_sys(name)) != NULL)
    564 		return kfilter;
    565 
    566 	return kfilter_byname_user(name);
    567 }
    568 
    569 /*
    570  * Find kfilter entry by filter id, or NULL if not found.
    571  * Assumes entries are indexed in filter id order, for speed.
    572  */
    573 static struct kfilter *
    574 kfilter_byfilter(uint32_t filter)
    575 {
    576 	struct kfilter *kfilter;
    577 
    578 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    579 
    580 	if (filter < EVFILT_SYSCOUNT)	/* it's a system filter */
    581 		kfilter = &sys_kfilters[filter];
    582 	else if (user_kfilters != NULL &&
    583 	    filter < EVFILT_SYSCOUNT + user_kfilterc)
    584 					/* it's a user filter */
    585 		kfilter = &user_kfilters[filter - EVFILT_SYSCOUNT];
    586 	else
    587 		return (NULL);		/* out of range */
    588 	KASSERT(kfilter->filter == filter);	/* sanity check! */
    589 	return (kfilter);
    590 }
    591 
    592 /*
    593  * Register a new kfilter. Stores the entry in user_kfilters.
    594  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    595  * If retfilter != NULL, the new filterid is returned in it.
    596  */
    597 int
    598 kfilter_register(const char *name, const struct filterops *filtops,
    599 		 int *retfilter)
    600 {
    601 	struct kfilter *kfilter;
    602 	size_t len;
    603 	int i;
    604 
    605 	if (name == NULL || name[0] == '\0' || filtops == NULL)
    606 		return (EINVAL);	/* invalid args */
    607 
    608 	rw_enter(&kqueue_filter_lock, RW_WRITER);
    609 	if (kfilter_byname(name) != NULL) {
    610 		rw_exit(&kqueue_filter_lock);
    611 		return (EEXIST);	/* already exists */
    612 	}
    613 	if (user_kfilterc > 0xffffffff - EVFILT_SYSCOUNT) {
    614 		rw_exit(&kqueue_filter_lock);
    615 		return (EINVAL);	/* too many */
    616 	}
    617 
    618 	for (i = 0; i < user_kfilterc; i++) {
    619 		kfilter = &user_kfilters[i];
    620 		if (kfilter->name == NULL) {
    621 			/* Previously deregistered slot.  Reuse. */
    622 			goto reuse;
    623 		}
    624 	}
    625 
    626 	/* check if need to grow user_kfilters */
    627 	if (user_kfilterc + 1 > user_kfiltermaxc) {
    628 		/* Grow in KFILTER_EXTENT chunks. */
    629 		user_kfiltermaxc += KFILTER_EXTENT;
    630 		len = user_kfiltermaxc * sizeof(*kfilter);
    631 		kfilter = kmem_alloc(len, KM_SLEEP);
    632 		memset((char *)kfilter + user_kfiltersz, 0, len - user_kfiltersz);
    633 		if (user_kfilters != NULL) {
    634 			memcpy(kfilter, user_kfilters, user_kfiltersz);
    635 			kmem_free(user_kfilters, user_kfiltersz);
    636 		}
    637 		user_kfiltersz = len;
    638 		user_kfilters = kfilter;
    639 	}
    640 	/* Adding new slot */
    641 	kfilter = &user_kfilters[user_kfilterc++];
    642 reuse:
    643 	kfilter->name = kmem_strdupsize(name, &kfilter->namelen, KM_SLEEP);
    644 
    645 	kfilter->filter = (kfilter - user_kfilters) + EVFILT_SYSCOUNT;
    646 
    647 	kfilter->filtops = kmem_alloc(sizeof(*filtops), KM_SLEEP);
    648 	memcpy(__UNCONST(kfilter->filtops), filtops, sizeof(*filtops));
    649 
    650 	if (retfilter != NULL)
    651 		*retfilter = kfilter->filter;
    652 	rw_exit(&kqueue_filter_lock);
    653 
    654 	return (0);
    655 }
    656 
    657 /*
    658  * Unregister a kfilter previously registered with kfilter_register.
    659  * This retains the filter id, but clears the name and frees filtops (filter
    660  * operations), so that the number isn't reused during a boot.
    661  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    662  */
    663 int
    664 kfilter_unregister(const char *name)
    665 {
    666 	struct kfilter *kfilter;
    667 
    668 	if (name == NULL || name[0] == '\0')
    669 		return (EINVAL);	/* invalid name */
    670 
    671 	rw_enter(&kqueue_filter_lock, RW_WRITER);
    672 	if (kfilter_byname_sys(name) != NULL) {
    673 		rw_exit(&kqueue_filter_lock);
    674 		return (EINVAL);	/* can't detach system filters */
    675 	}
    676 
    677 	kfilter = kfilter_byname_user(name);
    678 	if (kfilter == NULL) {
    679 		rw_exit(&kqueue_filter_lock);
    680 		return (ENOENT);
    681 	}
    682 	if (kfilter->refcnt != 0) {
    683 		rw_exit(&kqueue_filter_lock);
    684 		return (EBUSY);
    685 	}
    686 
    687 	/* Cast away const (but we know it's safe. */
    688 	kmem_free(__UNCONST(kfilter->name), kfilter->namelen);
    689 	kfilter->name = NULL;	/* mark as `not implemented' */
    690 
    691 	if (kfilter->filtops != NULL) {
    692 		/* Cast away const (but we know it's safe. */
    693 		kmem_free(__UNCONST(kfilter->filtops),
    694 		    sizeof(*kfilter->filtops));
    695 		kfilter->filtops = NULL; /* mark as `not implemented' */
    696 	}
    697 	rw_exit(&kqueue_filter_lock);
    698 
    699 	return (0);
    700 }
    701 
    702 
    703 /*
    704  * Filter attach method for EVFILT_READ and EVFILT_WRITE on normal file
    705  * descriptors. Calls fileops kqfilter method for given file descriptor.
    706  */
    707 static int
    708 filt_fileattach(struct knote *kn)
    709 {
    710 	file_t *fp;
    711 
    712 	fp = kn->kn_obj;
    713 
    714 	return (*fp->f_ops->fo_kqfilter)(fp, kn);
    715 }
    716 
    717 /*
    718  * Filter detach method for EVFILT_READ on kqueue descriptor.
    719  */
    720 static void
    721 filt_kqdetach(struct knote *kn)
    722 {
    723 	struct kqueue *kq;
    724 
    725 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
    726 
    727 	mutex_spin_enter(&kq->kq_lock);
    728 	selremove_knote(&kq->kq_sel, kn);
    729 	mutex_spin_exit(&kq->kq_lock);
    730 }
    731 
    732 /*
    733  * Filter event method for EVFILT_READ on kqueue descriptor.
    734  */
    735 /*ARGSUSED*/
    736 static int
    737 filt_kqueue(struct knote *kn, long hint)
    738 {
    739 	struct kqueue *kq;
    740 	int rv;
    741 
    742 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
    743 
    744 	if (hint != NOTE_SUBMIT)
    745 		mutex_spin_enter(&kq->kq_lock);
    746 	kn->kn_data = KQ_COUNT(kq);
    747 	rv = (kn->kn_data > 0);
    748 	if (hint != NOTE_SUBMIT)
    749 		mutex_spin_exit(&kq->kq_lock);
    750 
    751 	return rv;
    752 }
    753 
    754 /*
    755  * Filter attach method for EVFILT_PROC.
    756  */
    757 static int
    758 filt_procattach(struct knote *kn)
    759 {
    760 	struct proc *p;
    761 
    762 	mutex_enter(&proc_lock);
    763 	p = proc_find(kn->kn_id);
    764 	if (p == NULL) {
    765 		mutex_exit(&proc_lock);
    766 		return ESRCH;
    767 	}
    768 
    769 	/*
    770 	 * Fail if it's not owned by you, or the last exec gave us
    771 	 * setuid/setgid privs (unless you're root).
    772 	 */
    773 	mutex_enter(p->p_lock);
    774 	mutex_exit(&proc_lock);
    775 	if (kauth_authorize_process(curlwp->l_cred,
    776 	    KAUTH_PROCESS_KEVENT_FILTER, p, NULL, NULL, NULL) != 0) {
    777 	    	mutex_exit(p->p_lock);
    778 		return EACCES;
    779 	}
    780 
    781 	kn->kn_obj = p;
    782 	kn->kn_flags |= EV_CLEAR;	/* automatically set */
    783 
    784 	/*
    785 	 * NOTE_CHILD is only ever generated internally; don't let it
    786 	 * leak in from user-space.  See knote_proc_fork_track().
    787 	 */
    788 	kn->kn_sfflags &= ~NOTE_CHILD;
    789 
    790 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
    791     	mutex_exit(p->p_lock);
    792 
    793 	return 0;
    794 }
    795 
    796 /*
    797  * Filter detach method for EVFILT_PROC.
    798  *
    799  * The knote may be attached to a different process, which may exit,
    800  * leaving nothing for the knote to be attached to.  So when the process
    801  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
    802  * it will be deleted when read out.  However, as part of the knote deletion,
    803  * this routine is called, so a check is needed to avoid actually performing
    804  * a detach, because the original process might not exist any more.
    805  */
    806 static void
    807 filt_procdetach(struct knote *kn)
    808 {
    809 	struct kqueue *kq = kn->kn_kq;
    810 	struct proc *p;
    811 
    812 	/*
    813 	 * We have to synchronize with knote_proc_exit(), but we
    814 	 * are forced to acquire the locks in the wrong order here
    815 	 * because we can't be sure kn->kn_obj is valid unless
    816 	 * KN_DETACHED is not set.
    817 	 */
    818  again:
    819 	mutex_spin_enter(&kq->kq_lock);
    820 	if ((kn->kn_status & KN_DETACHED) == 0) {
    821 		p = kn->kn_obj;
    822 		if (!mutex_tryenter(p->p_lock)) {
    823 			mutex_spin_exit(&kq->kq_lock);
    824 			preempt_point();
    825 			goto again;
    826 		}
    827 		kn->kn_status |= KN_DETACHED;
    828 		SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
    829 		mutex_exit(p->p_lock);
    830 	}
    831 	mutex_spin_exit(&kq->kq_lock);
    832 }
    833 
    834 /*
    835  * Filter event method for EVFILT_PROC.
    836  *
    837  * Due to some of the complexities of process locking, we have special
    838  * entry points for delivering knote submissions.  filt_proc() is used
    839  * only to check for activation from kqueue_register() and kqueue_scan().
    840  */
    841 static int
    842 filt_proc(struct knote *kn, long hint)
    843 {
    844 	struct kqueue *kq = kn->kn_kq;
    845 	uint32_t fflags;
    846 
    847 	/*
    848 	 * Because we share the same klist with signal knotes, just
    849 	 * ensure that we're not being invoked for the proc-related
    850 	 * submissions.
    851 	 */
    852 	KASSERT((hint & (NOTE_EXEC | NOTE_EXIT | NOTE_FORK)) == 0);
    853 
    854 	mutex_spin_enter(&kq->kq_lock);
    855 	fflags = kn->kn_fflags;
    856 	mutex_spin_exit(&kq->kq_lock);
    857 
    858 	return fflags != 0;
    859 }
    860 
    861 void
    862 knote_proc_exec(struct proc *p)
    863 {
    864 	struct knote *kn, *tmpkn;
    865 	struct kqueue *kq;
    866 	uint32_t fflags;
    867 
    868 	mutex_enter(p->p_lock);
    869 
    870 	SLIST_FOREACH_SAFE(kn, &p->p_klist, kn_selnext, tmpkn) {
    871 		/* N.B. EVFILT_SIGNAL knotes are on this same list. */
    872 		if (kn->kn_fop == &sig_filtops) {
    873 			continue;
    874 		}
    875 		KASSERT(kn->kn_fop == &proc_filtops);
    876 
    877 		kq = kn->kn_kq;
    878 		mutex_spin_enter(&kq->kq_lock);
    879 		fflags = (kn->kn_fflags |= (kn->kn_sfflags & NOTE_EXEC));
    880 		mutex_spin_exit(&kq->kq_lock);
    881 		if (fflags) {
    882 			knote_activate(kn);
    883 		}
    884 	}
    885 
    886 	mutex_exit(p->p_lock);
    887 }
    888 
    889 static int __noinline
    890 knote_proc_fork_track(struct proc *p1, struct proc *p2, struct knote *okn)
    891 {
    892 	struct kqueue *kq = okn->kn_kq;
    893 
    894 	KASSERT(mutex_owned(&kq->kq_lock));
    895 	KASSERT(mutex_owned(p1->p_lock));
    896 
    897 	/*
    898 	 * We're going to put this knote into flux while we drop
    899 	 * the locks and create and attach a new knote to track the
    900 	 * child.  If we are not able to enter flux, then this knote
    901 	 * is about to go away, so skip the notification.
    902 	 */
    903 	if (!kn_enter_flux(okn)) {
    904 		return 0;
    905 	}
    906 
    907 	mutex_spin_exit(&kq->kq_lock);
    908 	mutex_exit(p1->p_lock);
    909 
    910 	/*
    911 	 * We actually have to register *two* new knotes:
    912 	 *
    913 	 * ==> One for the NOTE_CHILD notification.  This is a forced
    914 	 *     ONESHOT note.
    915 	 *
    916 	 * ==> One to actually track the child process as it subsequently
    917 	 *     forks, execs, and, ultimately, exits.
    918 	 *
    919 	 * If we only register a single knote, then it's possible for
    920 	 * for the NOTE_CHILD and NOTE_EXIT to be collapsed into a single
    921 	 * notification if the child exits before the tracking process
    922 	 * has received the NOTE_CHILD notification, which applications
    923 	 * aren't expecting (the event's 'data' field would be clobbered,
    924 	 * for exmaple).
    925 	 *
    926 	 * To do this, what we have here is an **extremely** stripped-down
    927 	 * version of kqueue_register() that has the following properties:
    928 	 *
    929 	 * ==> Does not block to allocate memory.  If we are unable
    930 	 *     to allocate memory, we return ENOMEM.
    931 	 *
    932 	 * ==> Does not search for existing knotes; we know there
    933 	 *     are not any because this is a new process that isn't
    934 	 *     even visible to other processes yet.
    935 	 *
    936 	 * ==> Assumes that the knhash for our kq's descriptor table
    937 	 *     already exists (after all, we're already tracking
    938 	 *     processes with knotes if we got here).
    939 	 *
    940 	 * ==> Directly attaches the new tracking knote to the child
    941 	 *     process.
    942 	 *
    943 	 * The whole point is to do the minimum amount of work while the
    944 	 * knote is held in-flux, and to avoid doing extra work in general
    945 	 * (we already have the new child process; why bother looking it
    946 	 * up again?).
    947 	 */
    948 	filedesc_t *fdp = kq->kq_fdp;
    949 	struct knote *knchild, *kntrack;
    950 	int error = 0;
    951 
    952 	knchild = kmem_zalloc(sizeof(*knchild), KM_NOSLEEP);
    953 	kntrack = kmem_zalloc(sizeof(*knchild), KM_NOSLEEP);
    954 	if (__predict_false(knchild == NULL || kntrack == NULL)) {
    955 		error = ENOMEM;
    956 		goto out;
    957 	}
    958 
    959 	kntrack->kn_obj = p2;
    960 	kntrack->kn_id = p2->p_pid;
    961 	kntrack->kn_kq = kq;
    962 	kntrack->kn_fop = okn->kn_fop;
    963 	kntrack->kn_kfilter = okn->kn_kfilter;
    964 	kntrack->kn_sfflags = okn->kn_sfflags;
    965 	kntrack->kn_sdata = p1->p_pid;
    966 
    967 	kntrack->kn_kevent.ident = p2->p_pid;
    968 	kntrack->kn_kevent.filter = okn->kn_filter;
    969 	kntrack->kn_kevent.flags =
    970 	    okn->kn_flags | EV_ADD | EV_ENABLE | EV_CLEAR;
    971 	kntrack->kn_kevent.fflags = 0;
    972 	kntrack->kn_kevent.data = 0;
    973 	kntrack->kn_kevent.udata = okn->kn_kevent.udata; /* preserve udata */
    974 
    975 	/*
    976 	 * The child note does not need to be attached to the
    977 	 * new proc's klist at all.
    978 	 */
    979 	*knchild = *kntrack;
    980 	knchild->kn_status = KN_DETACHED;
    981 	knchild->kn_sfflags = 0;
    982 	knchild->kn_kevent.flags |= EV_ONESHOT;
    983 	knchild->kn_kevent.fflags = NOTE_CHILD;
    984 	knchild->kn_kevent.data = p1->p_pid;		 /* parent */
    985 
    986 	mutex_enter(&fdp->fd_lock);
    987 
    988 	/*
    989 	 * We need to check to see if the kq is closing, and skip
    990 	 * attaching the knote if so.  Normally, this isn't necessary
    991 	 * when coming in the front door because the file descriptor
    992 	 * layer will synchronize this.
    993 	 *
    994 	 * It's safe to test KQ_CLOSING without taking the kq_lock
    995 	 * here because that flag is only ever set when the fd_lock
    996 	 * is also held.
    997 	 */
    998 	if (__predict_false(kq->kq_count & KQ_CLOSING)) {
    999 		mutex_exit(&fdp->fd_lock);
   1000 		goto out;
   1001 	}
   1002 
   1003 	/*
   1004 	 * We do the "insert into FD table" and "attach to klist" steps
   1005 	 * in the opposite order of kqueue_register() here to avoid
   1006 	 * having to take p2->p_lock twice.  But this is OK because we
   1007 	 * hold fd_lock across the entire operation.
   1008 	 */
   1009 
   1010 	mutex_enter(p2->p_lock);
   1011 	error = kauth_authorize_process(curlwp->l_cred,
   1012 	    KAUTH_PROCESS_KEVENT_FILTER, p2, NULL, NULL, NULL);
   1013 	if (__predict_false(error != 0)) {
   1014 		mutex_exit(p2->p_lock);
   1015 		mutex_exit(&fdp->fd_lock);
   1016 		error = EACCES;
   1017 		goto out;
   1018 	}
   1019 	SLIST_INSERT_HEAD(&p2->p_klist, kntrack, kn_selnext);
   1020 	mutex_exit(p2->p_lock);
   1021 
   1022 	KASSERT(fdp->fd_knhashmask != 0);
   1023 	KASSERT(fdp->fd_knhash != NULL);
   1024 	struct klist *list = &fdp->fd_knhash[KN_HASH(kntrack->kn_id,
   1025 	    fdp->fd_knhashmask)];
   1026 	SLIST_INSERT_HEAD(list, kntrack, kn_link);
   1027 	SLIST_INSERT_HEAD(list, knchild, kn_link);
   1028 
   1029 	/* This adds references for knchild *and* kntrack. */
   1030 	atomic_add_int(&kntrack->kn_kfilter->refcnt, 2);
   1031 
   1032 	knote_activate(knchild);
   1033 
   1034 	kntrack = NULL;
   1035 	knchild = NULL;
   1036 
   1037 	mutex_exit(&fdp->fd_lock);
   1038 
   1039  out:
   1040 	if (__predict_false(knchild != NULL)) {
   1041 		kmem_free(knchild, sizeof(*knchild));
   1042 	}
   1043 	if (__predict_false(kntrack != NULL)) {
   1044 		kmem_free(kntrack, sizeof(*kntrack));
   1045 	}
   1046 	mutex_enter(p1->p_lock);
   1047 	mutex_spin_enter(&kq->kq_lock);
   1048 
   1049 	if (kn_leave_flux(okn)) {
   1050 		KQ_FLUX_WAKEUP(kq);
   1051 	}
   1052 
   1053 	return error;
   1054 }
   1055 
   1056 void
   1057 knote_proc_fork(struct proc *p1, struct proc *p2)
   1058 {
   1059 	struct knote *kn;
   1060 	struct kqueue *kq;
   1061 	uint32_t fflags;
   1062 
   1063 	mutex_enter(p1->p_lock);
   1064 
   1065 	/*
   1066 	 * N.B. We DO NOT use SLIST_FOREACH_SAFE() here because we
   1067 	 * don't want to pre-fetch the next knote; in the event we
   1068 	 * have to drop p_lock, we will have put the knote in-flux,
   1069 	 * meaning that no one will be able to detach it until we
   1070 	 * have taken the knote out of flux.  However, that does
   1071 	 * NOT stop someone else from detaching the next note in the
   1072 	 * list while we have it unlocked.  Thus, we want to fetch
   1073 	 * the next note in the list only after we have re-acquired
   1074 	 * the lock, and using SLIST_FOREACH() will satisfy that.
   1075 	 */
   1076 	SLIST_FOREACH(kn, &p1->p_klist, kn_selnext) {
   1077 		/* N.B. EVFILT_SIGNAL knotes are on this same list. */
   1078 		if (kn->kn_fop == &sig_filtops) {
   1079 			continue;
   1080 		}
   1081 		KASSERT(kn->kn_fop == &proc_filtops);
   1082 
   1083 		kq = kn->kn_kq;
   1084 		mutex_spin_enter(&kq->kq_lock);
   1085 		kn->kn_fflags |= (kn->kn_sfflags & NOTE_FORK);
   1086 		if (__predict_false(kn->kn_sfflags & NOTE_TRACK)) {
   1087 			/*
   1088 			 * This will drop kq_lock and p_lock and
   1089 			 * re-acquire them before it returns.
   1090 			 */
   1091 			if (knote_proc_fork_track(p1, p2, kn)) {
   1092 				kn->kn_fflags |= NOTE_TRACKERR;
   1093 			}
   1094 			KASSERT(mutex_owned(p1->p_lock));
   1095 			KASSERT(mutex_owned(&kq->kq_lock));
   1096 		}
   1097 		fflags = kn->kn_fflags;
   1098 		mutex_spin_exit(&kq->kq_lock);
   1099 		if (fflags) {
   1100 			knote_activate(kn);
   1101 		}
   1102 	}
   1103 
   1104 	mutex_exit(p1->p_lock);
   1105 }
   1106 
   1107 void
   1108 knote_proc_exit(struct proc *p)
   1109 {
   1110 	struct knote *kn;
   1111 	struct kqueue *kq;
   1112 
   1113 	KASSERT(mutex_owned(p->p_lock));
   1114 
   1115 	while (!SLIST_EMPTY(&p->p_klist)) {
   1116 		kn = SLIST_FIRST(&p->p_klist);
   1117 		kq = kn->kn_kq;
   1118 
   1119 		KASSERT(kn->kn_obj == p);
   1120 
   1121 		mutex_spin_enter(&kq->kq_lock);
   1122 		kn->kn_data = P_WAITSTATUS(p);
   1123 		/*
   1124 		 * Mark as ONESHOT, so that the knote is g/c'ed
   1125 		 * when read.
   1126 		 */
   1127 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
   1128 		kn->kn_fflags |= kn->kn_sfflags & NOTE_EXIT;
   1129 
   1130 		/*
   1131 		 * Detach the knote from the process and mark it as such.
   1132 		 * N.B. EVFILT_SIGNAL are also on p_klist, but by the
   1133 		 * time we get here, all open file descriptors for this
   1134 		 * process have been released, meaning that signal knotes
   1135 		 * will have already been detached.
   1136 		 *
   1137 		 * We need to synchronize this with filt_procdetach().
   1138 		 */
   1139 		KASSERT(kn->kn_fop == &proc_filtops);
   1140 		if ((kn->kn_status & KN_DETACHED) == 0) {
   1141 			kn->kn_status |= KN_DETACHED;
   1142 			SLIST_REMOVE_HEAD(&p->p_klist, kn_selnext);
   1143 		}
   1144 		mutex_spin_exit(&kq->kq_lock);
   1145 
   1146 		/*
   1147 		 * Always activate the knote for NOTE_EXIT regardless
   1148 		 * of whether or not the listener cares about it.
   1149 		 * This matches historical behavior.
   1150 		 */
   1151 		knote_activate(kn);
   1152 	}
   1153 }
   1154 
   1155 static void
   1156 filt_timerexpire(void *knx)
   1157 {
   1158 	struct knote *kn = knx;
   1159 	int tticks;
   1160 
   1161 	mutex_enter(&kqueue_timer_lock);
   1162 	kn->kn_data++;
   1163 	knote_activate(kn);
   1164 	if ((kn->kn_flags & EV_ONESHOT) == 0) {
   1165 		tticks = mstohz(kn->kn_sdata);
   1166 		if (tticks <= 0)
   1167 			tticks = 1;
   1168 		callout_schedule((callout_t *)kn->kn_hook, tticks);
   1169 	}
   1170 	mutex_exit(&kqueue_timer_lock);
   1171 }
   1172 
   1173 /*
   1174  * data contains amount of time to sleep, in milliseconds
   1175  */
   1176 static int
   1177 filt_timerattach(struct knote *kn)
   1178 {
   1179 	callout_t *calloutp;
   1180 	struct kqueue *kq;
   1181 	int tticks;
   1182 
   1183 	tticks = mstohz(kn->kn_sdata);
   1184 
   1185 	/* if the supplied value is under our resolution, use 1 tick */
   1186 	if (tticks == 0) {
   1187 		if (kn->kn_sdata == 0)
   1188 			return EINVAL;
   1189 		tticks = 1;
   1190 	}
   1191 
   1192 	if (atomic_inc_uint_nv(&kq_ncallouts) >= kq_calloutmax ||
   1193 	    (calloutp = kmem_alloc(sizeof(*calloutp), KM_NOSLEEP)) == NULL) {
   1194 		atomic_dec_uint(&kq_ncallouts);
   1195 		return ENOMEM;
   1196 	}
   1197 	callout_init(calloutp, CALLOUT_MPSAFE);
   1198 
   1199 	kq = kn->kn_kq;
   1200 	mutex_spin_enter(&kq->kq_lock);
   1201 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
   1202 	kn->kn_hook = calloutp;
   1203 	mutex_spin_exit(&kq->kq_lock);
   1204 
   1205 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
   1206 
   1207 	return (0);
   1208 }
   1209 
   1210 static void
   1211 filt_timerdetach(struct knote *kn)
   1212 {
   1213 	callout_t *calloutp;
   1214 	struct kqueue *kq = kn->kn_kq;
   1215 
   1216 	/*
   1217 	 * We don't need to hold the kqueue_timer_lock here; even
   1218 	 * if filt_timerexpire() misses our setting of EV_ONESHOT,
   1219 	 * we are guaranteed that the callout will no longer be
   1220 	 * scheduled even if we attempted to halt it after it already
   1221 	 * started running, even if it rescheduled itself.
   1222 	 */
   1223 
   1224 	mutex_spin_enter(&kq->kq_lock);
   1225 	/* prevent rescheduling when we expire */
   1226 	kn->kn_flags |= EV_ONESHOT;
   1227 	mutex_spin_exit(&kq->kq_lock);
   1228 
   1229 	calloutp = (callout_t *)kn->kn_hook;
   1230 
   1231 	/*
   1232 	 * Attempt to stop the callout.  This will block if it's
   1233 	 * already running.
   1234 	 */
   1235 	callout_halt(calloutp, NULL);
   1236 
   1237 	callout_destroy(calloutp);
   1238 	kmem_free(calloutp, sizeof(*calloutp));
   1239 	atomic_dec_uint(&kq_ncallouts);
   1240 }
   1241 
   1242 static int
   1243 filt_timer(struct knote *kn, long hint)
   1244 {
   1245 	int rv;
   1246 
   1247 	mutex_enter(&kqueue_timer_lock);
   1248 	rv = (kn->kn_data != 0);
   1249 	mutex_exit(&kqueue_timer_lock);
   1250 
   1251 	return rv;
   1252 }
   1253 
   1254 static int
   1255 filt_userattach(struct knote *kn)
   1256 {
   1257 	struct kqueue *kq = kn->kn_kq;
   1258 
   1259 	/*
   1260 	 * EVFILT_USER knotes are not attached to anything in the kernel.
   1261 	 */
   1262 	mutex_spin_enter(&kq->kq_lock);
   1263 	kn->kn_hook = NULL;
   1264 	if (kn->kn_fflags & NOTE_TRIGGER)
   1265 		kn->kn_hookid = 1;
   1266 	else
   1267 		kn->kn_hookid = 0;
   1268 	mutex_spin_exit(&kq->kq_lock);
   1269 	return (0);
   1270 }
   1271 
   1272 static void
   1273 filt_userdetach(struct knote *kn)
   1274 {
   1275 
   1276 	/*
   1277 	 * EVFILT_USER knotes are not attached to anything in the kernel.
   1278 	 */
   1279 }
   1280 
   1281 static int
   1282 filt_user(struct knote *kn, long hint)
   1283 {
   1284 	struct kqueue *kq = kn->kn_kq;
   1285 	int hookid;
   1286 
   1287 	mutex_spin_enter(&kq->kq_lock);
   1288 	hookid = kn->kn_hookid;
   1289 	mutex_spin_exit(&kq->kq_lock);
   1290 
   1291 	return hookid;
   1292 }
   1293 
   1294 static void
   1295 filt_usertouch(struct knote *kn, struct kevent *kev, long type)
   1296 {
   1297 	int ffctrl;
   1298 
   1299 	KASSERT(mutex_owned(&kn->kn_kq->kq_lock));
   1300 
   1301 	switch (type) {
   1302 	case EVENT_REGISTER:
   1303 		if (kev->fflags & NOTE_TRIGGER)
   1304 			kn->kn_hookid = 1;
   1305 
   1306 		ffctrl = kev->fflags & NOTE_FFCTRLMASK;
   1307 		kev->fflags &= NOTE_FFLAGSMASK;
   1308 		switch (ffctrl) {
   1309 		case NOTE_FFNOP:
   1310 			break;
   1311 
   1312 		case NOTE_FFAND:
   1313 			kn->kn_sfflags &= kev->fflags;
   1314 			break;
   1315 
   1316 		case NOTE_FFOR:
   1317 			kn->kn_sfflags |= kev->fflags;
   1318 			break;
   1319 
   1320 		case NOTE_FFCOPY:
   1321 			kn->kn_sfflags = kev->fflags;
   1322 			break;
   1323 
   1324 		default:
   1325 			/* XXX Return error? */
   1326 			break;
   1327 		}
   1328 		kn->kn_sdata = kev->data;
   1329 		if (kev->flags & EV_CLEAR) {
   1330 			kn->kn_hookid = 0;
   1331 			kn->kn_data = 0;
   1332 			kn->kn_fflags = 0;
   1333 		}
   1334 		break;
   1335 
   1336 	case EVENT_PROCESS:
   1337 		*kev = kn->kn_kevent;
   1338 		kev->fflags = kn->kn_sfflags;
   1339 		kev->data = kn->kn_sdata;
   1340 		if (kn->kn_flags & EV_CLEAR) {
   1341 			kn->kn_hookid = 0;
   1342 			kn->kn_data = 0;
   1343 			kn->kn_fflags = 0;
   1344 		}
   1345 		break;
   1346 
   1347 	default:
   1348 		panic("filt_usertouch() - invalid type (%ld)", type);
   1349 		break;
   1350 	}
   1351 }
   1352 
   1353 /*
   1354  * filt_seltrue:
   1355  *
   1356  *	This filter "event" routine simulates seltrue().
   1357  */
   1358 int
   1359 filt_seltrue(struct knote *kn, long hint)
   1360 {
   1361 
   1362 	/*
   1363 	 * We don't know how much data can be read/written,
   1364 	 * but we know that it *can* be.  This is about as
   1365 	 * good as select/poll does as well.
   1366 	 */
   1367 	kn->kn_data = 0;
   1368 	return (1);
   1369 }
   1370 
   1371 /*
   1372  * This provides full kqfilter entry for device switch tables, which
   1373  * has same effect as filter using filt_seltrue() as filter method.
   1374  */
   1375 static void
   1376 filt_seltruedetach(struct knote *kn)
   1377 {
   1378 	/* Nothing to do */
   1379 }
   1380 
   1381 const struct filterops seltrue_filtops = {
   1382 	.f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
   1383 	.f_attach = NULL,
   1384 	.f_detach = filt_seltruedetach,
   1385 	.f_event = filt_seltrue,
   1386 };
   1387 
   1388 int
   1389 seltrue_kqfilter(dev_t dev, struct knote *kn)
   1390 {
   1391 	switch (kn->kn_filter) {
   1392 	case EVFILT_READ:
   1393 	case EVFILT_WRITE:
   1394 		kn->kn_fop = &seltrue_filtops;
   1395 		break;
   1396 	default:
   1397 		return (EINVAL);
   1398 	}
   1399 
   1400 	/* Nothing more to do */
   1401 	return (0);
   1402 }
   1403 
   1404 /*
   1405  * kqueue(2) system call.
   1406  */
   1407 static int
   1408 kqueue1(struct lwp *l, int flags, register_t *retval)
   1409 {
   1410 	struct kqueue *kq;
   1411 	file_t *fp;
   1412 	int fd, error;
   1413 
   1414 	if ((error = fd_allocfile(&fp, &fd)) != 0)
   1415 		return error;
   1416 	fp->f_flag = FREAD | FWRITE | (flags & (FNONBLOCK|FNOSIGPIPE));
   1417 	fp->f_type = DTYPE_KQUEUE;
   1418 	fp->f_ops = &kqueueops;
   1419 	kq = kmem_zalloc(sizeof(*kq), KM_SLEEP);
   1420 	mutex_init(&kq->kq_lock, MUTEX_DEFAULT, IPL_SCHED);
   1421 	cv_init(&kq->kq_cv, "kqueue");
   1422 	selinit(&kq->kq_sel);
   1423 	TAILQ_INIT(&kq->kq_head);
   1424 	fp->f_kqueue = kq;
   1425 	*retval = fd;
   1426 	kq->kq_fdp = curlwp->l_fd;
   1427 	fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0);
   1428 	fd_affix(curproc, fp, fd);
   1429 	return error;
   1430 }
   1431 
   1432 /*
   1433  * kqueue(2) system call.
   1434  */
   1435 int
   1436 sys_kqueue(struct lwp *l, const void *v, register_t *retval)
   1437 {
   1438 	return kqueue1(l, 0, retval);
   1439 }
   1440 
   1441 int
   1442 sys_kqueue1(struct lwp *l, const struct sys_kqueue1_args *uap,
   1443     register_t *retval)
   1444 {
   1445 	/* {
   1446 		syscallarg(int) flags;
   1447 	} */
   1448 	return kqueue1(l, SCARG(uap, flags), retval);
   1449 }
   1450 
   1451 /*
   1452  * kevent(2) system call.
   1453  */
   1454 int
   1455 kevent_fetch_changes(void *ctx, const struct kevent *changelist,
   1456     struct kevent *changes, size_t index, int n)
   1457 {
   1458 
   1459 	return copyin(changelist + index, changes, n * sizeof(*changes));
   1460 }
   1461 
   1462 int
   1463 kevent_put_events(void *ctx, struct kevent *events,
   1464     struct kevent *eventlist, size_t index, int n)
   1465 {
   1466 
   1467 	return copyout(events, eventlist + index, n * sizeof(*events));
   1468 }
   1469 
   1470 static const struct kevent_ops kevent_native_ops = {
   1471 	.keo_private = NULL,
   1472 	.keo_fetch_timeout = copyin,
   1473 	.keo_fetch_changes = kevent_fetch_changes,
   1474 	.keo_put_events = kevent_put_events,
   1475 };
   1476 
   1477 int
   1478 sys___kevent50(struct lwp *l, const struct sys___kevent50_args *uap,
   1479     register_t *retval)
   1480 {
   1481 	/* {
   1482 		syscallarg(int) fd;
   1483 		syscallarg(const struct kevent *) changelist;
   1484 		syscallarg(size_t) nchanges;
   1485 		syscallarg(struct kevent *) eventlist;
   1486 		syscallarg(size_t) nevents;
   1487 		syscallarg(const struct timespec *) timeout;
   1488 	} */
   1489 
   1490 	return kevent1(retval, SCARG(uap, fd), SCARG(uap, changelist),
   1491 	    SCARG(uap, nchanges), SCARG(uap, eventlist), SCARG(uap, nevents),
   1492 	    SCARG(uap, timeout), &kevent_native_ops);
   1493 }
   1494 
   1495 int
   1496 kevent1(register_t *retval, int fd,
   1497 	const struct kevent *changelist, size_t nchanges,
   1498 	struct kevent *eventlist, size_t nevents,
   1499 	const struct timespec *timeout,
   1500 	const struct kevent_ops *keops)
   1501 {
   1502 	struct kevent *kevp;
   1503 	struct kqueue *kq;
   1504 	struct timespec	ts;
   1505 	size_t i, n, ichange;
   1506 	int nerrors, error;
   1507 	struct kevent kevbuf[KQ_NEVENTS];	/* approx 300 bytes on 64-bit */
   1508 	file_t *fp;
   1509 
   1510 	/* check that we're dealing with a kq */
   1511 	fp = fd_getfile(fd);
   1512 	if (fp == NULL)
   1513 		return (EBADF);
   1514 
   1515 	if (fp->f_type != DTYPE_KQUEUE) {
   1516 		fd_putfile(fd);
   1517 		return (EBADF);
   1518 	}
   1519 
   1520 	if (timeout != NULL) {
   1521 		error = (*keops->keo_fetch_timeout)(timeout, &ts, sizeof(ts));
   1522 		if (error)
   1523 			goto done;
   1524 		timeout = &ts;
   1525 	}
   1526 
   1527 	kq = fp->f_kqueue;
   1528 	nerrors = 0;
   1529 	ichange = 0;
   1530 
   1531 	/* traverse list of events to register */
   1532 	while (nchanges > 0) {
   1533 		n = MIN(nchanges, __arraycount(kevbuf));
   1534 		error = (*keops->keo_fetch_changes)(keops->keo_private,
   1535 		    changelist, kevbuf, ichange, n);
   1536 		if (error)
   1537 			goto done;
   1538 		for (i = 0; i < n; i++) {
   1539 			kevp = &kevbuf[i];
   1540 			kevp->flags &= ~EV_SYSFLAGS;
   1541 			/* register each knote */
   1542 			error = kqueue_register(kq, kevp);
   1543 			if (!error && !(kevp->flags & EV_RECEIPT))
   1544 				continue;
   1545 			if (nevents == 0)
   1546 				goto done;
   1547 			kevp->flags = EV_ERROR;
   1548 			kevp->data = error;
   1549 			error = (*keops->keo_put_events)
   1550 				(keops->keo_private, kevp,
   1551 				 eventlist, nerrors, 1);
   1552 			if (error)
   1553 				goto done;
   1554 			nevents--;
   1555 			nerrors++;
   1556 		}
   1557 		nchanges -= n;	/* update the results */
   1558 		ichange += n;
   1559 	}
   1560 	if (nerrors) {
   1561 		*retval = nerrors;
   1562 		error = 0;
   1563 		goto done;
   1564 	}
   1565 
   1566 	/* actually scan through the events */
   1567 	error = kqueue_scan(fp, nevents, eventlist, timeout, retval, keops,
   1568 	    kevbuf, __arraycount(kevbuf));
   1569  done:
   1570 	fd_putfile(fd);
   1571 	return (error);
   1572 }
   1573 
   1574 /*
   1575  * Register a given kevent kev onto the kqueue
   1576  */
   1577 static int
   1578 kqueue_register(struct kqueue *kq, struct kevent *kev)
   1579 {
   1580 	struct kfilter *kfilter;
   1581 	filedesc_t *fdp;
   1582 	file_t *fp;
   1583 	fdfile_t *ff;
   1584 	struct knote *kn, *newkn;
   1585 	struct klist *list;
   1586 	int error, fd, rv;
   1587 
   1588 	fdp = kq->kq_fdp;
   1589 	fp = NULL;
   1590 	kn = NULL;
   1591 	error = 0;
   1592 	fd = 0;
   1593 
   1594 	newkn = kmem_zalloc(sizeof(*newkn), KM_SLEEP);
   1595 
   1596 	rw_enter(&kqueue_filter_lock, RW_READER);
   1597 	kfilter = kfilter_byfilter(kev->filter);
   1598 	if (kfilter == NULL || kfilter->filtops == NULL) {
   1599 		/* filter not found nor implemented */
   1600 		rw_exit(&kqueue_filter_lock);
   1601 		kmem_free(newkn, sizeof(*newkn));
   1602 		return (EINVAL);
   1603 	}
   1604 
   1605 	/* search if knote already exists */
   1606 	if (kfilter->filtops->f_flags & FILTEROP_ISFD) {
   1607 		/* monitoring a file descriptor */
   1608 		/* validate descriptor */
   1609 		if (kev->ident > INT_MAX
   1610 		    || (fp = fd_getfile(fd = kev->ident)) == NULL) {
   1611 			rw_exit(&kqueue_filter_lock);
   1612 			kmem_free(newkn, sizeof(*newkn));
   1613 			return EBADF;
   1614 		}
   1615 		mutex_enter(&fdp->fd_lock);
   1616 		ff = fdp->fd_dt->dt_ff[fd];
   1617 		if (ff->ff_refcnt & FR_CLOSING) {
   1618 			error = EBADF;
   1619 			goto doneunlock;
   1620 		}
   1621 		if (fd <= fdp->fd_lastkqfile) {
   1622 			SLIST_FOREACH(kn, &ff->ff_knlist, kn_link) {
   1623 				if (kq == kn->kn_kq &&
   1624 				    kev->filter == kn->kn_filter)
   1625 					break;
   1626 			}
   1627 		}
   1628 	} else {
   1629 		/*
   1630 		 * not monitoring a file descriptor, so
   1631 		 * lookup knotes in internal hash table
   1632 		 */
   1633 		mutex_enter(&fdp->fd_lock);
   1634 		if (fdp->fd_knhashmask != 0) {
   1635 			list = &fdp->fd_knhash[
   1636 			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
   1637 			SLIST_FOREACH(kn, list, kn_link) {
   1638 				if (kev->ident == kn->kn_id &&
   1639 				    kq == kn->kn_kq &&
   1640 				    kev->filter == kn->kn_filter)
   1641 					break;
   1642 			}
   1643 		}
   1644 	}
   1645 
   1646 	/* It's safe to test KQ_CLOSING while holding only the fd_lock. */
   1647 	KASSERT(mutex_owned(&fdp->fd_lock));
   1648 	KASSERT((kq->kq_count & KQ_CLOSING) == 0);
   1649 
   1650 	/*
   1651 	 * kn now contains the matching knote, or NULL if no match
   1652 	 */
   1653 	if (kn == NULL) {
   1654 		if (kev->flags & EV_ADD) {
   1655 			/* create new knote */
   1656 			kn = newkn;
   1657 			newkn = NULL;
   1658 			kn->kn_obj = fp;
   1659 			kn->kn_id = kev->ident;
   1660 			kn->kn_kq = kq;
   1661 			kn->kn_fop = kfilter->filtops;
   1662 			kn->kn_kfilter = kfilter;
   1663 			kn->kn_sfflags = kev->fflags;
   1664 			kn->kn_sdata = kev->data;
   1665 			kev->fflags = 0;
   1666 			kev->data = 0;
   1667 			kn->kn_kevent = *kev;
   1668 
   1669 			KASSERT(kn->kn_fop != NULL);
   1670 			/*
   1671 			 * apply reference count to knote structure, and
   1672 			 * do not release it at the end of this routine.
   1673 			 */
   1674 			fp = NULL;
   1675 
   1676 			if (!(kn->kn_fop->f_flags & FILTEROP_ISFD)) {
   1677 				/*
   1678 				 * If knote is not on an fd, store on
   1679 				 * internal hash table.
   1680 				 */
   1681 				if (fdp->fd_knhashmask == 0) {
   1682 					/* XXXAD can block with fd_lock held */
   1683 					fdp->fd_knhash = hashinit(KN_HASHSIZE,
   1684 					    HASH_LIST, true,
   1685 					    &fdp->fd_knhashmask);
   1686 				}
   1687 				list = &fdp->fd_knhash[KN_HASH(kn->kn_id,
   1688 				    fdp->fd_knhashmask)];
   1689 			} else {
   1690 				/* Otherwise, knote is on an fd. */
   1691 				list = (struct klist *)
   1692 				    &fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
   1693 				if ((int)kn->kn_id > fdp->fd_lastkqfile)
   1694 					fdp->fd_lastkqfile = kn->kn_id;
   1695 			}
   1696 			SLIST_INSERT_HEAD(list, kn, kn_link);
   1697 
   1698 			/*
   1699 			 * N.B. kn->kn_fop may change as the result
   1700 			 * of filter_attach()!
   1701 			 */
   1702 			error = filter_attach(kn);
   1703 			if (error != 0) {
   1704 #ifdef DEBUG
   1705 				struct proc *p = curlwp->l_proc;
   1706 				const file_t *ft = kn->kn_obj;
   1707 				printf("%s: %s[%d]: event type %d not "
   1708 				    "supported for file type %d/%s "
   1709 				    "(error %d)\n", __func__,
   1710 				    p->p_comm, p->p_pid,
   1711 				    kn->kn_filter, ft ? ft->f_type : -1,
   1712 				    ft ? ft->f_ops->fo_name : "?", error);
   1713 #endif
   1714 
   1715 				/*
   1716 				 * N.B. no need to check for this note to
   1717 				 * be in-flux, since it was never visible
   1718 				 * to the monitored object.
   1719 				 *
   1720 				 * knote_detach() drops fdp->fd_lock
   1721 				 */
   1722 				mutex_enter(&kq->kq_lock);
   1723 				KNOTE_WILLDETACH(kn);
   1724 				KASSERT(kn_in_flux(kn) == false);
   1725 				mutex_exit(&kq->kq_lock);
   1726 				knote_detach(kn, fdp, false);
   1727 				goto done;
   1728 			}
   1729 			atomic_inc_uint(&kfilter->refcnt);
   1730 			goto done_ev_add;
   1731 		} else {
   1732 			/* No matching knote and the EV_ADD flag is not set. */
   1733 			error = ENOENT;
   1734 			goto doneunlock;
   1735 		}
   1736 	}
   1737 
   1738 	if (kev->flags & EV_DELETE) {
   1739 		/*
   1740 		 * Let the world know that this knote is about to go
   1741 		 * away, and wait for it to settle if it's currently
   1742 		 * in-flux.
   1743 		 */
   1744 		mutex_spin_enter(&kq->kq_lock);
   1745 		if (kn->kn_status & KN_WILLDETACH) {
   1746 			/*
   1747 			 * This knote is already on its way out,
   1748 			 * so just be done.
   1749 			 */
   1750 			mutex_spin_exit(&kq->kq_lock);
   1751 			goto doneunlock;
   1752 		}
   1753 		KNOTE_WILLDETACH(kn);
   1754 		if (kn_in_flux(kn)) {
   1755 			mutex_exit(&fdp->fd_lock);
   1756 			/*
   1757 			 * It's safe for us to conclusively wait for
   1758 			 * this knote to settle because we know we'll
   1759 			 * be completing the detach.
   1760 			 */
   1761 			kn_wait_flux(kn, true);
   1762 			KASSERT(kn_in_flux(kn) == false);
   1763 			mutex_spin_exit(&kq->kq_lock);
   1764 			mutex_enter(&fdp->fd_lock);
   1765 		} else {
   1766 			mutex_spin_exit(&kq->kq_lock);
   1767 		}
   1768 
   1769 		/* knote_detach() drops fdp->fd_lock */
   1770 		knote_detach(kn, fdp, true);
   1771 		goto done;
   1772 	}
   1773 
   1774 	/*
   1775 	 * The user may change some filter values after the
   1776 	 * initial EV_ADD, but doing so will not reset any
   1777 	 * filter which have already been triggered.
   1778 	 */
   1779 	kn->kn_kevent.udata = kev->udata;
   1780 	KASSERT(kn->kn_fop != NULL);
   1781 	if (!(kn->kn_fop->f_flags & FILTEROP_ISFD) &&
   1782 	    kn->kn_fop->f_touch != NULL) {
   1783 		mutex_spin_enter(&kq->kq_lock);
   1784 		filter_touch(kn, kev, EVENT_REGISTER);
   1785 		mutex_spin_exit(&kq->kq_lock);
   1786 	} else {
   1787 		kn->kn_sfflags = kev->fflags;
   1788 		kn->kn_sdata = kev->data;
   1789 	}
   1790 
   1791 	/*
   1792 	 * We can get here if we are trying to attach
   1793 	 * an event to a file descriptor that does not
   1794 	 * support events, and the attach routine is
   1795 	 * broken and does not return an error.
   1796 	 */
   1797 done_ev_add:
   1798 	rv = filter_event(kn, 0);
   1799 	if (rv)
   1800 		knote_activate(kn);
   1801 
   1802 	/* disable knote */
   1803 	if ((kev->flags & EV_DISABLE)) {
   1804 		mutex_spin_enter(&kq->kq_lock);
   1805 		if ((kn->kn_status & KN_DISABLED) == 0)
   1806 			kn->kn_status |= KN_DISABLED;
   1807 		mutex_spin_exit(&kq->kq_lock);
   1808 	}
   1809 
   1810 	/* enable knote */
   1811 	if ((kev->flags & EV_ENABLE)) {
   1812 		knote_enqueue(kn);
   1813 	}
   1814 doneunlock:
   1815 	mutex_exit(&fdp->fd_lock);
   1816  done:
   1817 	rw_exit(&kqueue_filter_lock);
   1818 	if (newkn != NULL)
   1819 		kmem_free(newkn, sizeof(*newkn));
   1820 	if (fp != NULL)
   1821 		fd_putfile(fd);
   1822 	return (error);
   1823 }
   1824 
   1825 #define KN_FMT(buf, kn) \
   1826     (snprintb((buf), sizeof(buf), __KN_FLAG_BITS, (kn)->kn_status), buf)
   1827 
   1828 #if defined(DDB)
   1829 void
   1830 kqueue_printit(struct kqueue *kq, bool full, void (*pr)(const char *, ...))
   1831 {
   1832 	const struct knote *kn;
   1833 	u_int count;
   1834 	int nmarker;
   1835 	char buf[128];
   1836 
   1837 	count = 0;
   1838 	nmarker = 0;
   1839 
   1840 	(*pr)("kqueue %p (restart=%d count=%u):\n", kq,
   1841 	    !!(kq->kq_count & KQ_RESTART), KQ_COUNT(kq));
   1842 	(*pr)("  Queued knotes:\n");
   1843 	TAILQ_FOREACH(kn, &kq->kq_head, kn_tqe) {
   1844 		if (kn->kn_status & KN_MARKER) {
   1845 			nmarker++;
   1846 		} else {
   1847 			count++;
   1848 		}
   1849 		(*pr)("    knote %p: kq=%p status=%s\n",
   1850 		    kn, kn->kn_kq, KN_FMT(buf, kn));
   1851 		(*pr)("      id=0x%lx (%lu) filter=%d\n",
   1852 		    (u_long)kn->kn_id, (u_long)kn->kn_id, kn->kn_filter);
   1853 		if (kn->kn_kq != kq) {
   1854 			(*pr)("      !!! kn->kn_kq != kq\n");
   1855 		}
   1856 	}
   1857 	if (count != KQ_COUNT(kq)) {
   1858 		(*pr)("  !!! count(%u) != KQ_COUNT(%u)\n",
   1859 		    count, KQ_COUNT(kq));
   1860 	}
   1861 }
   1862 #endif /* DDB */
   1863 
   1864 #if defined(DEBUG)
   1865 static void
   1866 kqueue_check(const char *func, size_t line, const struct kqueue *kq)
   1867 {
   1868 	const struct knote *kn;
   1869 	u_int count;
   1870 	int nmarker;
   1871 	char buf[128];
   1872 
   1873 	KASSERT(mutex_owned(&kq->kq_lock));
   1874 
   1875 	count = 0;
   1876 	nmarker = 0;
   1877 	TAILQ_FOREACH(kn, &kq->kq_head, kn_tqe) {
   1878 		if ((kn->kn_status & (KN_MARKER | KN_QUEUED)) == 0) {
   1879 			panic("%s,%zu: kq=%p kn=%p !(MARKER|QUEUED) %s",
   1880 			    func, line, kq, kn, KN_FMT(buf, kn));
   1881 		}
   1882 		if ((kn->kn_status & KN_MARKER) == 0) {
   1883 			if (kn->kn_kq != kq) {
   1884 				panic("%s,%zu: kq=%p kn(%p) != kn->kq(%p): %s",
   1885 				    func, line, kq, kn, kn->kn_kq,
   1886 				    KN_FMT(buf, kn));
   1887 			}
   1888 			if ((kn->kn_status & KN_ACTIVE) == 0) {
   1889 				panic("%s,%zu: kq=%p kn=%p: !ACTIVE %s",
   1890 				    func, line, kq, kn, KN_FMT(buf, kn));
   1891 			}
   1892 			count++;
   1893 			if (count > KQ_COUNT(kq)) {
   1894 				panic("%s,%zu: kq=%p kq->kq_count(%u) != "
   1895 				    "count(%d), nmarker=%d",
   1896 		    		    func, line, kq, KQ_COUNT(kq), count,
   1897 				    nmarker);
   1898 			}
   1899 		} else {
   1900 			nmarker++;
   1901 		}
   1902 	}
   1903 }
   1904 #define kq_check(a) kqueue_check(__func__, __LINE__, (a))
   1905 #else /* defined(DEBUG) */
   1906 #define	kq_check(a)	/* nothing */
   1907 #endif /* defined(DEBUG) */
   1908 
   1909 static void
   1910 kqueue_restart(file_t *fp)
   1911 {
   1912 	struct kqueue *kq = fp->f_kqueue;
   1913 	KASSERT(kq != NULL);
   1914 
   1915 	mutex_spin_enter(&kq->kq_lock);
   1916 	kq->kq_count |= KQ_RESTART;
   1917 	cv_broadcast(&kq->kq_cv);
   1918 	mutex_spin_exit(&kq->kq_lock);
   1919 }
   1920 
   1921 /*
   1922  * Scan through the list of events on fp (for a maximum of maxevents),
   1923  * returning the results in to ulistp. Timeout is determined by tsp; if
   1924  * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
   1925  * as appropriate.
   1926  */
   1927 static int
   1928 kqueue_scan(file_t *fp, size_t maxevents, struct kevent *ulistp,
   1929 	    const struct timespec *tsp, register_t *retval,
   1930 	    const struct kevent_ops *keops, struct kevent *kevbuf,
   1931 	    size_t kevcnt)
   1932 {
   1933 	struct kqueue	*kq;
   1934 	struct kevent	*kevp;
   1935 	struct timespec	ats, sleepts;
   1936 	struct knote	*kn, *marker, morker;
   1937 	size_t		count, nkev, nevents;
   1938 	int		timeout, error, touch, rv, influx;
   1939 	filedesc_t	*fdp;
   1940 
   1941 	fdp = curlwp->l_fd;
   1942 	kq = fp->f_kqueue;
   1943 	count = maxevents;
   1944 	nkev = nevents = error = 0;
   1945 	if (count == 0) {
   1946 		*retval = 0;
   1947 		return 0;
   1948 	}
   1949 
   1950 	if (tsp) {				/* timeout supplied */
   1951 		ats = *tsp;
   1952 		if (inittimeleft(&ats, &sleepts) == -1) {
   1953 			*retval = maxevents;
   1954 			return EINVAL;
   1955 		}
   1956 		timeout = tstohz(&ats);
   1957 		if (timeout <= 0)
   1958 			timeout = -1;           /* do poll */
   1959 	} else {
   1960 		/* no timeout, wait forever */
   1961 		timeout = 0;
   1962 	}
   1963 
   1964 	memset(&morker, 0, sizeof(morker));
   1965 	marker = &morker;
   1966 	marker->kn_kq = kq;
   1967 	marker->kn_status = KN_MARKER;
   1968 	mutex_spin_enter(&kq->kq_lock);
   1969  retry:
   1970 	kevp = kevbuf;
   1971 	if (KQ_COUNT(kq) == 0) {
   1972 		if (timeout >= 0) {
   1973 			error = cv_timedwait_sig(&kq->kq_cv,
   1974 			    &kq->kq_lock, timeout);
   1975 			if (error == 0) {
   1976 				if (KQ_COUNT(kq) == 0 &&
   1977 				    (kq->kq_count & KQ_RESTART)) {
   1978 					/* return to clear file reference */
   1979 					error = ERESTART;
   1980 				} else if (tsp == NULL || (timeout =
   1981 				    gettimeleft(&ats, &sleepts)) > 0) {
   1982 					goto retry;
   1983 				}
   1984 			} else {
   1985 				/* don't restart after signals... */
   1986 				if (error == ERESTART)
   1987 					error = EINTR;
   1988 				if (error == EWOULDBLOCK)
   1989 					error = 0;
   1990 			}
   1991 		}
   1992 		mutex_spin_exit(&kq->kq_lock);
   1993 		goto done;
   1994 	}
   1995 
   1996 	/* mark end of knote list */
   1997 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
   1998 	influx = 0;
   1999 
   2000 	/*
   2001 	 * Acquire the fdp->fd_lock interlock to avoid races with
   2002 	 * file creation/destruction from other threads.
   2003 	 */
   2004 	mutex_spin_exit(&kq->kq_lock);
   2005 relock:
   2006 	mutex_enter(&fdp->fd_lock);
   2007 	mutex_spin_enter(&kq->kq_lock);
   2008 
   2009 	while (count != 0) {
   2010 		/*
   2011 		 * Get next knote.  We are guaranteed this will never
   2012 		 * be NULL because of the marker we inserted above.
   2013 		 */
   2014 		kn = TAILQ_FIRST(&kq->kq_head);
   2015 
   2016 		bool kn_is_other_marker =
   2017 		    (kn->kn_status & KN_MARKER) != 0 && kn != marker;
   2018 		bool kn_is_detaching = (kn->kn_status & KN_WILLDETACH) != 0;
   2019 		bool kn_is_in_flux = kn_in_flux(kn);
   2020 
   2021 		/*
   2022 		 * If we found a marker that's not ours, or this knote
   2023 		 * is in a state of flux, then wait for everything to
   2024 		 * settle down and go around again.
   2025 		 */
   2026 		if (kn_is_other_marker || kn_is_detaching || kn_is_in_flux) {
   2027 			if (influx) {
   2028 				influx = 0;
   2029 				KQ_FLUX_WAKEUP(kq);
   2030 			}
   2031 			mutex_exit(&fdp->fd_lock);
   2032 			if (kn_is_other_marker || kn_is_in_flux) {
   2033 				KQ_FLUX_WAIT(kq);
   2034 				mutex_spin_exit(&kq->kq_lock);
   2035 			} else {
   2036 				/*
   2037 				 * Detaching but not in-flux?  Someone is
   2038 				 * actively trying to finish the job; just
   2039 				 * go around and try again.
   2040 				 */
   2041 				KASSERT(kn_is_detaching);
   2042 				mutex_spin_exit(&kq->kq_lock);
   2043 				preempt_point();
   2044 			}
   2045 			goto relock;
   2046 		}
   2047 
   2048 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   2049 		if (kn == marker) {
   2050 			/* it's our marker, stop */
   2051 			KQ_FLUX_WAKEUP(kq);
   2052 			if (count == maxevents) {
   2053 				mutex_exit(&fdp->fd_lock);
   2054 				goto retry;
   2055 			}
   2056 			break;
   2057 		}
   2058 		KASSERT((kn->kn_status & KN_BUSY) == 0);
   2059 
   2060 		kq_check(kq);
   2061 		kn->kn_status &= ~KN_QUEUED;
   2062 		kn->kn_status |= KN_BUSY;
   2063 		kq_check(kq);
   2064 		if (kn->kn_status & KN_DISABLED) {
   2065 			kn->kn_status &= ~KN_BUSY;
   2066 			kq->kq_count--;
   2067 			/* don't want disabled events */
   2068 			continue;
   2069 		}
   2070 		if ((kn->kn_flags & EV_ONESHOT) == 0) {
   2071 			mutex_spin_exit(&kq->kq_lock);
   2072 			KASSERT(mutex_owned(&fdp->fd_lock));
   2073 			rv = filter_event(kn, 0);
   2074 			mutex_spin_enter(&kq->kq_lock);
   2075 			/* Re-poll if note was re-enqueued. */
   2076 			if ((kn->kn_status & KN_QUEUED) != 0) {
   2077 				kn->kn_status &= ~KN_BUSY;
   2078 				/* Re-enqueue raised kq_count, lower it again */
   2079 				kq->kq_count--;
   2080 				influx = 1;
   2081 				continue;
   2082 			}
   2083 			if (rv == 0) {
   2084 				/*
   2085 				 * non-ONESHOT event that hasn't triggered
   2086 				 * again, so it will remain de-queued.
   2087 				 */
   2088 				kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
   2089 				kq->kq_count--;
   2090 				influx = 1;
   2091 				continue;
   2092 			}
   2093 		} else {
   2094 			/*
   2095 			 * This ONESHOT note is going to be detached
   2096 			 * below.  Mark the knote as not long for this
   2097 			 * world before we release the kq lock so that
   2098 			 * no one else will put it in a state of flux.
   2099 			 */
   2100 			KNOTE_WILLDETACH(kn);
   2101 		}
   2102 		KASSERT(kn->kn_fop != NULL);
   2103 		touch = (!(kn->kn_fop->f_flags & FILTEROP_ISFD) &&
   2104 				kn->kn_fop->f_touch != NULL);
   2105 		/* XXXAD should be got from f_event if !oneshot. */
   2106 		if (touch) {
   2107 			filter_touch(kn, kevp, EVENT_PROCESS);
   2108 		} else {
   2109 			*kevp = kn->kn_kevent;
   2110 		}
   2111 		kevp++;
   2112 		nkev++;
   2113 		influx = 1;
   2114 		if (kn->kn_flags & EV_ONESHOT) {
   2115 			/* delete ONESHOT events after retrieval */
   2116 			kn->kn_status &= ~KN_BUSY;
   2117 			kq->kq_count--;
   2118 			KASSERT(kn_in_flux(kn) == false);
   2119 			KASSERT((kn->kn_status & KN_WILLDETACH) != 0 &&
   2120 				kn->kn_kevent.udata == curlwp);
   2121 			mutex_spin_exit(&kq->kq_lock);
   2122 			knote_detach(kn, fdp, true);
   2123 			mutex_enter(&fdp->fd_lock);
   2124 			mutex_spin_enter(&kq->kq_lock);
   2125 		} else if (kn->kn_flags & EV_CLEAR) {
   2126 			/* clear state after retrieval */
   2127 			kn->kn_data = 0;
   2128 			kn->kn_fflags = 0;
   2129 			/*
   2130 			 * Manually clear knotes who weren't
   2131 			 * 'touch'ed.
   2132 			 */
   2133 			if (touch == 0) {
   2134 				kn->kn_data = 0;
   2135 				kn->kn_fflags = 0;
   2136 			}
   2137 			kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
   2138 			kq->kq_count--;
   2139 		} else if (kn->kn_flags & EV_DISPATCH) {
   2140 			kn->kn_status |= KN_DISABLED;
   2141 			kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
   2142 			kq->kq_count--;
   2143 		} else {
   2144 			/* add event back on list */
   2145 			kq_check(kq);
   2146 			kn->kn_status |= KN_QUEUED;
   2147 			kn->kn_status &= ~KN_BUSY;
   2148 			TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   2149 			kq_check(kq);
   2150 		}
   2151 
   2152 		if (nkev == kevcnt) {
   2153 			/* do copyouts in kevcnt chunks */
   2154 			influx = 0;
   2155 			KQ_FLUX_WAKEUP(kq);
   2156 			mutex_spin_exit(&kq->kq_lock);
   2157 			mutex_exit(&fdp->fd_lock);
   2158 			error = (*keops->keo_put_events)
   2159 			    (keops->keo_private,
   2160 			    kevbuf, ulistp, nevents, nkev);
   2161 			mutex_enter(&fdp->fd_lock);
   2162 			mutex_spin_enter(&kq->kq_lock);
   2163 			nevents += nkev;
   2164 			nkev = 0;
   2165 			kevp = kevbuf;
   2166 		}
   2167 		count--;
   2168 		if (error != 0 || count == 0) {
   2169 			/* remove marker */
   2170 			TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
   2171 			break;
   2172 		}
   2173 	}
   2174 	KQ_FLUX_WAKEUP(kq);
   2175 	mutex_spin_exit(&kq->kq_lock);
   2176 	mutex_exit(&fdp->fd_lock);
   2177 
   2178 done:
   2179 	if (nkev != 0) {
   2180 		/* copyout remaining events */
   2181 		error = (*keops->keo_put_events)(keops->keo_private,
   2182 		    kevbuf, ulistp, nevents, nkev);
   2183 	}
   2184 	*retval = maxevents - count;
   2185 
   2186 	return error;
   2187 }
   2188 
   2189 /*
   2190  * fileops ioctl method for a kqueue descriptor.
   2191  *
   2192  * Two ioctls are currently supported. They both use struct kfilter_mapping:
   2193  *	KFILTER_BYNAME		find name for filter, and return result in
   2194  *				name, which is of size len.
   2195  *	KFILTER_BYFILTER	find filter for name. len is ignored.
   2196  */
   2197 /*ARGSUSED*/
   2198 static int
   2199 kqueue_ioctl(file_t *fp, u_long com, void *data)
   2200 {
   2201 	struct kfilter_mapping	*km;
   2202 	const struct kfilter	*kfilter;
   2203 	char			*name;
   2204 	int			error;
   2205 
   2206 	km = data;
   2207 	error = 0;
   2208 	name = kmem_alloc(KFILTER_MAXNAME, KM_SLEEP);
   2209 
   2210 	switch (com) {
   2211 	case KFILTER_BYFILTER:	/* convert filter -> name */
   2212 		rw_enter(&kqueue_filter_lock, RW_READER);
   2213 		kfilter = kfilter_byfilter(km->filter);
   2214 		if (kfilter != NULL) {
   2215 			strlcpy(name, kfilter->name, KFILTER_MAXNAME);
   2216 			rw_exit(&kqueue_filter_lock);
   2217 			error = copyoutstr(name, km->name, km->len, NULL);
   2218 		} else {
   2219 			rw_exit(&kqueue_filter_lock);
   2220 			error = ENOENT;
   2221 		}
   2222 		break;
   2223 
   2224 	case KFILTER_BYNAME:	/* convert name -> filter */
   2225 		error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
   2226 		if (error) {
   2227 			break;
   2228 		}
   2229 		rw_enter(&kqueue_filter_lock, RW_READER);
   2230 		kfilter = kfilter_byname(name);
   2231 		if (kfilter != NULL)
   2232 			km->filter = kfilter->filter;
   2233 		else
   2234 			error = ENOENT;
   2235 		rw_exit(&kqueue_filter_lock);
   2236 		break;
   2237 
   2238 	default:
   2239 		error = ENOTTY;
   2240 		break;
   2241 
   2242 	}
   2243 	kmem_free(name, KFILTER_MAXNAME);
   2244 	return (error);
   2245 }
   2246 
   2247 /*
   2248  * fileops fcntl method for a kqueue descriptor.
   2249  */
   2250 static int
   2251 kqueue_fcntl(file_t *fp, u_int com, void *data)
   2252 {
   2253 
   2254 	return (ENOTTY);
   2255 }
   2256 
   2257 /*
   2258  * fileops poll method for a kqueue descriptor.
   2259  * Determine if kqueue has events pending.
   2260  */
   2261 static int
   2262 kqueue_poll(file_t *fp, int events)
   2263 {
   2264 	struct kqueue	*kq;
   2265 	int		revents;
   2266 
   2267 	kq = fp->f_kqueue;
   2268 
   2269 	revents = 0;
   2270 	if (events & (POLLIN | POLLRDNORM)) {
   2271 		mutex_spin_enter(&kq->kq_lock);
   2272 		if (KQ_COUNT(kq) != 0) {
   2273 			revents |= events & (POLLIN | POLLRDNORM);
   2274 		} else {
   2275 			selrecord(curlwp, &kq->kq_sel);
   2276 		}
   2277 		kq_check(kq);
   2278 		mutex_spin_exit(&kq->kq_lock);
   2279 	}
   2280 
   2281 	return revents;
   2282 }
   2283 
   2284 /*
   2285  * fileops stat method for a kqueue descriptor.
   2286  * Returns dummy info, with st_size being number of events pending.
   2287  */
   2288 static int
   2289 kqueue_stat(file_t *fp, struct stat *st)
   2290 {
   2291 	struct kqueue *kq;
   2292 
   2293 	kq = fp->f_kqueue;
   2294 
   2295 	memset(st, 0, sizeof(*st));
   2296 	st->st_size = KQ_COUNT(kq);
   2297 	st->st_blksize = sizeof(struct kevent);
   2298 	st->st_mode = S_IFIFO | S_IRUSR | S_IWUSR;
   2299 	st->st_blocks = 1;
   2300 	st->st_uid = kauth_cred_geteuid(fp->f_cred);
   2301 	st->st_gid = kauth_cred_getegid(fp->f_cred);
   2302 
   2303 	return 0;
   2304 }
   2305 
   2306 static void
   2307 kqueue_doclose(struct kqueue *kq, struct klist *list, int fd)
   2308 {
   2309 	struct knote *kn;
   2310 	filedesc_t *fdp;
   2311 
   2312 	fdp = kq->kq_fdp;
   2313 
   2314 	KASSERT(mutex_owned(&fdp->fd_lock));
   2315 
   2316  again:
   2317 	for (kn = SLIST_FIRST(list); kn != NULL;) {
   2318 		if (kq != kn->kn_kq) {
   2319 			kn = SLIST_NEXT(kn, kn_link);
   2320 			continue;
   2321 		}
   2322 		if (knote_detach_quiesce(kn)) {
   2323 			mutex_enter(&fdp->fd_lock);
   2324 			goto again;
   2325 		}
   2326 		knote_detach(kn, fdp, true);
   2327 		mutex_enter(&fdp->fd_lock);
   2328 		kn = SLIST_FIRST(list);
   2329 	}
   2330 }
   2331 
   2332 /*
   2333  * fileops close method for a kqueue descriptor.
   2334  */
   2335 static int
   2336 kqueue_close(file_t *fp)
   2337 {
   2338 	struct kqueue *kq;
   2339 	filedesc_t *fdp;
   2340 	fdfile_t *ff;
   2341 	int i;
   2342 
   2343 	kq = fp->f_kqueue;
   2344 	fp->f_kqueue = NULL;
   2345 	fp->f_type = 0;
   2346 	fdp = curlwp->l_fd;
   2347 
   2348 	KASSERT(kq->kq_fdp == fdp);
   2349 
   2350 	mutex_enter(&fdp->fd_lock);
   2351 
   2352 	/*
   2353 	 * We're doing to drop the fd_lock multiple times while
   2354 	 * we detach knotes.  During this time, attempts to register
   2355 	 * knotes via the back door (e.g. knote_proc_fork_track())
   2356 	 * need to fail, lest they sneak in to attach a knote after
   2357 	 * we've already drained the list it's destined for.
   2358 	 *
   2359 	 * We must aquire kq_lock here to set KQ_CLOSING (to serialize
   2360 	 * with other code paths that modify kq_count without holding
   2361 	 * the fd_lock), but once this bit is set, it's only safe to
   2362 	 * test it while holding the fd_lock, and holding kq_lock while
   2363 	 * doing so is not necessary.
   2364 	 */
   2365 	mutex_enter(&kq->kq_lock);
   2366 	kq->kq_count |= KQ_CLOSING;
   2367 	mutex_exit(&kq->kq_lock);
   2368 
   2369 	for (i = 0; i <= fdp->fd_lastkqfile; i++) {
   2370 		if ((ff = fdp->fd_dt->dt_ff[i]) == NULL)
   2371 			continue;
   2372 		kqueue_doclose(kq, (struct klist *)&ff->ff_knlist, i);
   2373 	}
   2374 	if (fdp->fd_knhashmask != 0) {
   2375 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
   2376 			kqueue_doclose(kq, &fdp->fd_knhash[i], -1);
   2377 		}
   2378 	}
   2379 
   2380 	mutex_exit(&fdp->fd_lock);
   2381 
   2382 #if defined(DEBUG)
   2383 	mutex_enter(&kq->kq_lock);
   2384 	kq_check(kq);
   2385 	mutex_exit(&kq->kq_lock);
   2386 #endif /* DEBUG */
   2387 	KASSERT(TAILQ_EMPTY(&kq->kq_head));
   2388 	KASSERT(KQ_COUNT(kq) == 0);
   2389 	mutex_destroy(&kq->kq_lock);
   2390 	cv_destroy(&kq->kq_cv);
   2391 	seldestroy(&kq->kq_sel);
   2392 	kmem_free(kq, sizeof(*kq));
   2393 
   2394 	return (0);
   2395 }
   2396 
   2397 /*
   2398  * struct fileops kqfilter method for a kqueue descriptor.
   2399  * Event triggered when monitored kqueue changes.
   2400  */
   2401 static int
   2402 kqueue_kqfilter(file_t *fp, struct knote *kn)
   2403 {
   2404 	struct kqueue *kq;
   2405 
   2406 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
   2407 
   2408 	KASSERT(fp == kn->kn_obj);
   2409 
   2410 	if (kn->kn_filter != EVFILT_READ)
   2411 		return EINVAL;
   2412 
   2413 	kn->kn_fop = &kqread_filtops;
   2414 	mutex_enter(&kq->kq_lock);
   2415 	selrecord_knote(&kq->kq_sel, kn);
   2416 	mutex_exit(&kq->kq_lock);
   2417 
   2418 	return 0;
   2419 }
   2420 
   2421 
   2422 /*
   2423  * Walk down a list of knotes, activating them if their event has
   2424  * triggered.  The caller's object lock (e.g. device driver lock)
   2425  * must be held.
   2426  */
   2427 void
   2428 knote(struct klist *list, long hint)
   2429 {
   2430 	struct knote *kn, *tmpkn;
   2431 
   2432 	SLIST_FOREACH_SAFE(kn, list, kn_selnext, tmpkn) {
   2433 		if (filter_event(kn, hint)) {
   2434 			knote_activate(kn);
   2435 		}
   2436 	}
   2437 }
   2438 
   2439 /*
   2440  * Remove all knotes referencing a specified fd
   2441  */
   2442 void
   2443 knote_fdclose(int fd)
   2444 {
   2445 	struct klist *list;
   2446 	struct knote *kn;
   2447 	filedesc_t *fdp;
   2448 
   2449  again:
   2450 	fdp = curlwp->l_fd;
   2451 	mutex_enter(&fdp->fd_lock);
   2452 	list = (struct klist *)&fdp->fd_dt->dt_ff[fd]->ff_knlist;
   2453 	while ((kn = SLIST_FIRST(list)) != NULL) {
   2454 		if (knote_detach_quiesce(kn)) {
   2455 			goto again;
   2456 		}
   2457 		knote_detach(kn, fdp, true);
   2458 		mutex_enter(&fdp->fd_lock);
   2459 	}
   2460 	mutex_exit(&fdp->fd_lock);
   2461 }
   2462 
   2463 /*
   2464  * Drop knote.  Called with fdp->fd_lock held, and will drop before
   2465  * returning.
   2466  */
   2467 static void
   2468 knote_detach(struct knote *kn, filedesc_t *fdp, bool dofop)
   2469 {
   2470 	struct klist *list;
   2471 	struct kqueue *kq;
   2472 
   2473 	kq = kn->kn_kq;
   2474 
   2475 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   2476 	KASSERT((kn->kn_status & KN_WILLDETACH) != 0);
   2477 	KASSERT(kn->kn_fop != NULL);
   2478 	KASSERT(mutex_owned(&fdp->fd_lock));
   2479 
   2480 	/* Remove from monitored object. */
   2481 	if (dofop) {
   2482 		filter_detach(kn);
   2483 	}
   2484 
   2485 	/* Remove from descriptor table. */
   2486 	if (kn->kn_fop->f_flags & FILTEROP_ISFD)
   2487 		list = (struct klist *)&fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
   2488 	else
   2489 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
   2490 
   2491 	SLIST_REMOVE(list, kn, knote, kn_link);
   2492 
   2493 	/* Remove from kqueue. */
   2494 again:
   2495 	mutex_spin_enter(&kq->kq_lock);
   2496 	KASSERT(kn_in_flux(kn) == false);
   2497 	if ((kn->kn_status & KN_QUEUED) != 0) {
   2498 		kq_check(kq);
   2499 		KASSERT(KQ_COUNT(kq) != 0);
   2500 		kq->kq_count--;
   2501 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   2502 		kn->kn_status &= ~KN_QUEUED;
   2503 		kq_check(kq);
   2504 	} else if (kn->kn_status & KN_BUSY) {
   2505 		mutex_spin_exit(&kq->kq_lock);
   2506 		goto again;
   2507 	}
   2508 	mutex_spin_exit(&kq->kq_lock);
   2509 
   2510 	mutex_exit(&fdp->fd_lock);
   2511 	if (kn->kn_fop->f_flags & FILTEROP_ISFD)
   2512 		fd_putfile(kn->kn_id);
   2513 	atomic_dec_uint(&kn->kn_kfilter->refcnt);
   2514 	kmem_free(kn, sizeof(*kn));
   2515 }
   2516 
   2517 /*
   2518  * Queue new event for knote.
   2519  */
   2520 static void
   2521 knote_enqueue(struct knote *kn)
   2522 {
   2523 	struct kqueue *kq;
   2524 
   2525 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   2526 
   2527 	kq = kn->kn_kq;
   2528 
   2529 	mutex_spin_enter(&kq->kq_lock);
   2530 	if (__predict_false(kn->kn_status & KN_WILLDETACH)) {
   2531 		/* Don't bother enqueueing a dying knote. */
   2532 		goto out;
   2533 	}
   2534 	if ((kn->kn_status & KN_DISABLED) != 0) {
   2535 		kn->kn_status &= ~KN_DISABLED;
   2536 	}
   2537 	if ((kn->kn_status & (KN_ACTIVE | KN_QUEUED)) == KN_ACTIVE) {
   2538 		kq_check(kq);
   2539 		kn->kn_status |= KN_QUEUED;
   2540 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   2541 		KASSERT(KQ_COUNT(kq) < KQ_MAXCOUNT);
   2542 		kq->kq_count++;
   2543 		kq_check(kq);
   2544 		cv_broadcast(&kq->kq_cv);
   2545 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   2546 	}
   2547  out:
   2548 	mutex_spin_exit(&kq->kq_lock);
   2549 }
   2550 /*
   2551  * Queue new event for knote.
   2552  */
   2553 static void
   2554 knote_activate(struct knote *kn)
   2555 {
   2556 	struct kqueue *kq;
   2557 
   2558 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   2559 
   2560 	kq = kn->kn_kq;
   2561 
   2562 	mutex_spin_enter(&kq->kq_lock);
   2563 	if (__predict_false(kn->kn_status & KN_WILLDETACH)) {
   2564 		/* Don't bother enqueueing a dying knote. */
   2565 		goto out;
   2566 	}
   2567 	kn->kn_status |= KN_ACTIVE;
   2568 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) {
   2569 		kq_check(kq);
   2570 		kn->kn_status |= KN_QUEUED;
   2571 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   2572 		KASSERT(KQ_COUNT(kq) < KQ_MAXCOUNT);
   2573 		kq->kq_count++;
   2574 		kq_check(kq);
   2575 		cv_broadcast(&kq->kq_cv);
   2576 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   2577 	}
   2578  out:
   2579 	mutex_spin_exit(&kq->kq_lock);
   2580 }
   2581 
   2582 /*
   2583  * Set EV_EOF on the specified knote.  Also allows additional
   2584  * EV_* flags to be set (e.g. EV_ONESHOT).
   2585  */
   2586 void
   2587 knote_set_eof(struct knote *kn, uint32_t flags)
   2588 {
   2589 	struct kqueue *kq = kn->kn_kq;
   2590 
   2591 	mutex_spin_enter(&kq->kq_lock);
   2592 	kn->kn_flags |= EV_EOF | flags;
   2593 	mutex_spin_exit(&kq->kq_lock);
   2594 }
   2595 
   2596 /*
   2597  * Clear EV_EOF on the specified knote.
   2598  */
   2599 void
   2600 knote_clear_eof(struct knote *kn)
   2601 {
   2602 	struct kqueue *kq = kn->kn_kq;
   2603 
   2604 	mutex_spin_enter(&kq->kq_lock);
   2605 	kn->kn_flags &= ~EV_EOF;
   2606 	mutex_spin_exit(&kq->kq_lock);
   2607 }
   2608