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