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