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