Home | History | Annotate | Line # | Download | only in kern
kern_event.c revision 1.134
      1 /*	$NetBSD: kern_event.c,v 1.134 2021/10/21 01:11:21 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.134 2021/10/21 01:11:21 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 void	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 void
    480 filter_touch(struct knote *kn, struct kevent *kev, long type)
    481 {
    482 	kn->kn_fop->f_touch(kn, kev, type);
    483 }
    484 
    485 static kauth_listener_t	kqueue_listener;
    486 
    487 static int
    488 kqueue_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    489     void *arg0, void *arg1, void *arg2, void *arg3)
    490 {
    491 	struct proc *p;
    492 	int result;
    493 
    494 	result = KAUTH_RESULT_DEFER;
    495 	p = arg0;
    496 
    497 	if (action != KAUTH_PROCESS_KEVENT_FILTER)
    498 		return result;
    499 
    500 	if ((kauth_cred_getuid(p->p_cred) != kauth_cred_getuid(cred) ||
    501 	    ISSET(p->p_flag, PK_SUGID)))
    502 		return result;
    503 
    504 	result = KAUTH_RESULT_ALLOW;
    505 
    506 	return result;
    507 }
    508 
    509 /*
    510  * Initialize the kqueue subsystem.
    511  */
    512 void
    513 kqueue_init(void)
    514 {
    515 
    516 	rw_init(&kqueue_filter_lock);
    517 
    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 void
   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 
   1446 /*
   1447  * filt_seltrue:
   1448  *
   1449  *	This filter "event" routine simulates seltrue().
   1450  */
   1451 int
   1452 filt_seltrue(struct knote *kn, long hint)
   1453 {
   1454 
   1455 	/*
   1456 	 * We don't know how much data can be read/written,
   1457 	 * but we know that it *can* be.  This is about as
   1458 	 * good as select/poll does as well.
   1459 	 */
   1460 	kn->kn_data = 0;
   1461 	return (1);
   1462 }
   1463 
   1464 /*
   1465  * This provides full kqfilter entry for device switch tables, which
   1466  * has same effect as filter using filt_seltrue() as filter method.
   1467  */
   1468 static void
   1469 filt_seltruedetach(struct knote *kn)
   1470 {
   1471 	/* Nothing to do */
   1472 }
   1473 
   1474 const struct filterops seltrue_filtops = {
   1475 	.f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
   1476 	.f_attach = NULL,
   1477 	.f_detach = filt_seltruedetach,
   1478 	.f_event = filt_seltrue,
   1479 };
   1480 
   1481 int
   1482 seltrue_kqfilter(dev_t dev, struct knote *kn)
   1483 {
   1484 	switch (kn->kn_filter) {
   1485 	case EVFILT_READ:
   1486 	case EVFILT_WRITE:
   1487 		kn->kn_fop = &seltrue_filtops;
   1488 		break;
   1489 	default:
   1490 		return (EINVAL);
   1491 	}
   1492 
   1493 	/* Nothing more to do */
   1494 	return (0);
   1495 }
   1496 
   1497 /*
   1498  * kqueue(2) system call.
   1499  */
   1500 static int
   1501 kqueue1(struct lwp *l, int flags, register_t *retval)
   1502 {
   1503 	struct kqueue *kq;
   1504 	file_t *fp;
   1505 	int fd, error;
   1506 
   1507 	if ((error = fd_allocfile(&fp, &fd)) != 0)
   1508 		return error;
   1509 	fp->f_flag = FREAD | FWRITE | (flags & (FNONBLOCK|FNOSIGPIPE));
   1510 	fp->f_type = DTYPE_KQUEUE;
   1511 	fp->f_ops = &kqueueops;
   1512 	kq = kmem_zalloc(sizeof(*kq), KM_SLEEP);
   1513 	mutex_init(&kq->kq_lock, MUTEX_DEFAULT, IPL_SCHED);
   1514 	cv_init(&kq->kq_cv, "kqueue");
   1515 	selinit(&kq->kq_sel);
   1516 	TAILQ_INIT(&kq->kq_head);
   1517 	fp->f_kqueue = kq;
   1518 	*retval = fd;
   1519 	kq->kq_fdp = curlwp->l_fd;
   1520 	fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0);
   1521 	fd_affix(curproc, fp, fd);
   1522 	return error;
   1523 }
   1524 
   1525 /*
   1526  * kqueue(2) system call.
   1527  */
   1528 int
   1529 sys_kqueue(struct lwp *l, const void *v, register_t *retval)
   1530 {
   1531 	return kqueue1(l, 0, retval);
   1532 }
   1533 
   1534 int
   1535 sys_kqueue1(struct lwp *l, const struct sys_kqueue1_args *uap,
   1536     register_t *retval)
   1537 {
   1538 	/* {
   1539 		syscallarg(int) flags;
   1540 	} */
   1541 	return kqueue1(l, SCARG(uap, flags), retval);
   1542 }
   1543 
   1544 /*
   1545  * kevent(2) system call.
   1546  */
   1547 int
   1548 kevent_fetch_changes(void *ctx, const struct kevent *changelist,
   1549     struct kevent *changes, size_t index, int n)
   1550 {
   1551 
   1552 	return copyin(changelist + index, changes, n * sizeof(*changes));
   1553 }
   1554 
   1555 int
   1556 kevent_put_events(void *ctx, struct kevent *events,
   1557     struct kevent *eventlist, size_t index, int n)
   1558 {
   1559 
   1560 	return copyout(events, eventlist + index, n * sizeof(*events));
   1561 }
   1562 
   1563 static const struct kevent_ops kevent_native_ops = {
   1564 	.keo_private = NULL,
   1565 	.keo_fetch_timeout = copyin,
   1566 	.keo_fetch_changes = kevent_fetch_changes,
   1567 	.keo_put_events = kevent_put_events,
   1568 };
   1569 
   1570 int
   1571 sys___kevent50(struct lwp *l, const struct sys___kevent50_args *uap,
   1572     register_t *retval)
   1573 {
   1574 	/* {
   1575 		syscallarg(int) fd;
   1576 		syscallarg(const struct kevent *) changelist;
   1577 		syscallarg(size_t) nchanges;
   1578 		syscallarg(struct kevent *) eventlist;
   1579 		syscallarg(size_t) nevents;
   1580 		syscallarg(const struct timespec *) timeout;
   1581 	} */
   1582 
   1583 	return kevent1(retval, SCARG(uap, fd), SCARG(uap, changelist),
   1584 	    SCARG(uap, nchanges), SCARG(uap, eventlist), SCARG(uap, nevents),
   1585 	    SCARG(uap, timeout), &kevent_native_ops);
   1586 }
   1587 
   1588 int
   1589 kevent1(register_t *retval, int fd,
   1590 	const struct kevent *changelist, size_t nchanges,
   1591 	struct kevent *eventlist, size_t nevents,
   1592 	const struct timespec *timeout,
   1593 	const struct kevent_ops *keops)
   1594 {
   1595 	struct kevent *kevp;
   1596 	struct kqueue *kq;
   1597 	struct timespec	ts;
   1598 	size_t i, n, ichange;
   1599 	int nerrors, error;
   1600 	struct kevent kevbuf[KQ_NEVENTS];	/* approx 300 bytes on 64-bit */
   1601 	file_t *fp;
   1602 
   1603 	/* check that we're dealing with a kq */
   1604 	fp = fd_getfile(fd);
   1605 	if (fp == NULL)
   1606 		return (EBADF);
   1607 
   1608 	if (fp->f_type != DTYPE_KQUEUE) {
   1609 		fd_putfile(fd);
   1610 		return (EBADF);
   1611 	}
   1612 
   1613 	if (timeout != NULL) {
   1614 		error = (*keops->keo_fetch_timeout)(timeout, &ts, sizeof(ts));
   1615 		if (error)
   1616 			goto done;
   1617 		timeout = &ts;
   1618 	}
   1619 
   1620 	kq = fp->f_kqueue;
   1621 	nerrors = 0;
   1622 	ichange = 0;
   1623 
   1624 	/* traverse list of events to register */
   1625 	while (nchanges > 0) {
   1626 		n = MIN(nchanges, __arraycount(kevbuf));
   1627 		error = (*keops->keo_fetch_changes)(keops->keo_private,
   1628 		    changelist, kevbuf, ichange, n);
   1629 		if (error)
   1630 			goto done;
   1631 		for (i = 0; i < n; i++) {
   1632 			kevp = &kevbuf[i];
   1633 			kevp->flags &= ~EV_SYSFLAGS;
   1634 			/* register each knote */
   1635 			error = kqueue_register(kq, kevp);
   1636 			if (!error && !(kevp->flags & EV_RECEIPT))
   1637 				continue;
   1638 			if (nevents == 0)
   1639 				goto done;
   1640 			kevp->flags = EV_ERROR;
   1641 			kevp->data = error;
   1642 			error = (*keops->keo_put_events)
   1643 				(keops->keo_private, kevp,
   1644 				 eventlist, nerrors, 1);
   1645 			if (error)
   1646 				goto done;
   1647 			nevents--;
   1648 			nerrors++;
   1649 		}
   1650 		nchanges -= n;	/* update the results */
   1651 		ichange += n;
   1652 	}
   1653 	if (nerrors) {
   1654 		*retval = nerrors;
   1655 		error = 0;
   1656 		goto done;
   1657 	}
   1658 
   1659 	/* actually scan through the events */
   1660 	error = kqueue_scan(fp, nevents, eventlist, timeout, retval, keops,
   1661 	    kevbuf, __arraycount(kevbuf));
   1662  done:
   1663 	fd_putfile(fd);
   1664 	return (error);
   1665 }
   1666 
   1667 /*
   1668  * Register a given kevent kev onto the kqueue
   1669  */
   1670 static int
   1671 kqueue_register(struct kqueue *kq, struct kevent *kev)
   1672 {
   1673 	struct kfilter *kfilter;
   1674 	filedesc_t *fdp;
   1675 	file_t *fp;
   1676 	fdfile_t *ff;
   1677 	struct knote *kn, *newkn;
   1678 	struct klist *list;
   1679 	int error, fd, rv;
   1680 
   1681 	fdp = kq->kq_fdp;
   1682 	fp = NULL;
   1683 	kn = NULL;
   1684 	error = 0;
   1685 	fd = 0;
   1686 
   1687 	newkn = kmem_zalloc(sizeof(*newkn), KM_SLEEP);
   1688 
   1689 	rw_enter(&kqueue_filter_lock, RW_READER);
   1690 	kfilter = kfilter_byfilter(kev->filter);
   1691 	if (kfilter == NULL || kfilter->filtops == NULL) {
   1692 		/* filter not found nor implemented */
   1693 		rw_exit(&kqueue_filter_lock);
   1694 		kmem_free(newkn, sizeof(*newkn));
   1695 		return (EINVAL);
   1696 	}
   1697 
   1698 	/* search if knote already exists */
   1699 	if (kfilter->filtops->f_flags & FILTEROP_ISFD) {
   1700 		/* monitoring a file descriptor */
   1701 		/* validate descriptor */
   1702 		if (kev->ident > INT_MAX
   1703 		    || (fp = fd_getfile(fd = kev->ident)) == NULL) {
   1704 			rw_exit(&kqueue_filter_lock);
   1705 			kmem_free(newkn, sizeof(*newkn));
   1706 			return EBADF;
   1707 		}
   1708 		mutex_enter(&fdp->fd_lock);
   1709 		ff = fdp->fd_dt->dt_ff[fd];
   1710 		if (ff->ff_refcnt & FR_CLOSING) {
   1711 			error = EBADF;
   1712 			goto doneunlock;
   1713 		}
   1714 		if (fd <= fdp->fd_lastkqfile) {
   1715 			SLIST_FOREACH(kn, &ff->ff_knlist, kn_link) {
   1716 				if (kq == kn->kn_kq &&
   1717 				    kev->filter == kn->kn_filter)
   1718 					break;
   1719 			}
   1720 		}
   1721 	} else {
   1722 		/*
   1723 		 * not monitoring a file descriptor, so
   1724 		 * lookup knotes in internal hash table
   1725 		 */
   1726 		mutex_enter(&fdp->fd_lock);
   1727 		if (fdp->fd_knhashmask != 0) {
   1728 			list = &fdp->fd_knhash[
   1729 			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
   1730 			SLIST_FOREACH(kn, list, kn_link) {
   1731 				if (kev->ident == kn->kn_id &&
   1732 				    kq == kn->kn_kq &&
   1733 				    kev->filter == kn->kn_filter)
   1734 					break;
   1735 			}
   1736 		}
   1737 	}
   1738 
   1739 	/* It's safe to test KQ_CLOSING while holding only the fd_lock. */
   1740 	KASSERT(mutex_owned(&fdp->fd_lock));
   1741 	KASSERT((kq->kq_count & KQ_CLOSING) == 0);
   1742 
   1743 	/*
   1744 	 * kn now contains the matching knote, or NULL if no match
   1745 	 */
   1746 	if (kn == NULL) {
   1747 		if (kev->flags & EV_ADD) {
   1748 			/* create new knote */
   1749 			kn = newkn;
   1750 			newkn = NULL;
   1751 			kn->kn_obj = fp;
   1752 			kn->kn_id = kev->ident;
   1753 			kn->kn_kq = kq;
   1754 			kn->kn_fop = kfilter->filtops;
   1755 			kn->kn_kfilter = kfilter;
   1756 			kn->kn_sfflags = kev->fflags;
   1757 			kn->kn_sdata = kev->data;
   1758 			kev->fflags = 0;
   1759 			kev->data = 0;
   1760 			kn->kn_kevent = *kev;
   1761 
   1762 			KASSERT(kn->kn_fop != NULL);
   1763 			/*
   1764 			 * apply reference count to knote structure, and
   1765 			 * do not release it at the end of this routine.
   1766 			 */
   1767 			fp = NULL;
   1768 
   1769 			if (!(kn->kn_fop->f_flags & FILTEROP_ISFD)) {
   1770 				/*
   1771 				 * If knote is not on an fd, store on
   1772 				 * internal hash table.
   1773 				 */
   1774 				if (fdp->fd_knhashmask == 0) {
   1775 					/* XXXAD can block with fd_lock held */
   1776 					fdp->fd_knhash = hashinit(KN_HASHSIZE,
   1777 					    HASH_LIST, true,
   1778 					    &fdp->fd_knhashmask);
   1779 				}
   1780 				list = &fdp->fd_knhash[KN_HASH(kn->kn_id,
   1781 				    fdp->fd_knhashmask)];
   1782 			} else {
   1783 				/* Otherwise, knote is on an fd. */
   1784 				list = (struct klist *)
   1785 				    &fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
   1786 				if ((int)kn->kn_id > fdp->fd_lastkqfile)
   1787 					fdp->fd_lastkqfile = kn->kn_id;
   1788 			}
   1789 			SLIST_INSERT_HEAD(list, kn, kn_link);
   1790 
   1791 			/*
   1792 			 * N.B. kn->kn_fop may change as the result
   1793 			 * of filter_attach()!
   1794 			 */
   1795 			error = filter_attach(kn);
   1796 			if (error != 0) {
   1797 #ifdef DEBUG
   1798 				struct proc *p = curlwp->l_proc;
   1799 				const file_t *ft = kn->kn_obj;
   1800 				printf("%s: %s[%d]: event type %d not "
   1801 				    "supported for file type %d/%s "
   1802 				    "(error %d)\n", __func__,
   1803 				    p->p_comm, p->p_pid,
   1804 				    kn->kn_filter, ft ? ft->f_type : -1,
   1805 				    ft ? ft->f_ops->fo_name : "?", error);
   1806 #endif
   1807 
   1808 				/*
   1809 				 * N.B. no need to check for this note to
   1810 				 * be in-flux, since it was never visible
   1811 				 * to the monitored object.
   1812 				 *
   1813 				 * knote_detach() drops fdp->fd_lock
   1814 				 */
   1815 				mutex_enter(&kq->kq_lock);
   1816 				KNOTE_WILLDETACH(kn);
   1817 				KASSERT(kn_in_flux(kn) == false);
   1818 				mutex_exit(&kq->kq_lock);
   1819 				knote_detach(kn, fdp, false);
   1820 				goto done;
   1821 			}
   1822 			atomic_inc_uint(&kfilter->refcnt);
   1823 			goto done_ev_add;
   1824 		} else {
   1825 			/* No matching knote and the EV_ADD flag is not set. */
   1826 			error = ENOENT;
   1827 			goto doneunlock;
   1828 		}
   1829 	}
   1830 
   1831 	if (kev->flags & EV_DELETE) {
   1832 		/*
   1833 		 * Let the world know that this knote is about to go
   1834 		 * away, and wait for it to settle if it's currently
   1835 		 * in-flux.
   1836 		 */
   1837 		mutex_spin_enter(&kq->kq_lock);
   1838 		if (kn->kn_status & KN_WILLDETACH) {
   1839 			/*
   1840 			 * This knote is already on its way out,
   1841 			 * so just be done.
   1842 			 */
   1843 			mutex_spin_exit(&kq->kq_lock);
   1844 			goto doneunlock;
   1845 		}
   1846 		KNOTE_WILLDETACH(kn);
   1847 		if (kn_in_flux(kn)) {
   1848 			mutex_exit(&fdp->fd_lock);
   1849 			/*
   1850 			 * It's safe for us to conclusively wait for
   1851 			 * this knote to settle because we know we'll
   1852 			 * be completing the detach.
   1853 			 */
   1854 			kn_wait_flux(kn, true);
   1855 			KASSERT(kn_in_flux(kn) == false);
   1856 			mutex_spin_exit(&kq->kq_lock);
   1857 			mutex_enter(&fdp->fd_lock);
   1858 		} else {
   1859 			mutex_spin_exit(&kq->kq_lock);
   1860 		}
   1861 
   1862 		/* knote_detach() drops fdp->fd_lock */
   1863 		knote_detach(kn, fdp, true);
   1864 		goto done;
   1865 	}
   1866 
   1867 	/*
   1868 	 * The user may change some filter values after the
   1869 	 * initial EV_ADD, but doing so will not reset any
   1870 	 * filter which have already been triggered.
   1871 	 */
   1872 	kn->kn_kevent.udata = kev->udata;
   1873 	KASSERT(kn->kn_fop != NULL);
   1874 	if (!(kn->kn_fop->f_flags & FILTEROP_ISFD) &&
   1875 	    kn->kn_fop->f_touch != NULL) {
   1876 		mutex_spin_enter(&kq->kq_lock);
   1877 		filter_touch(kn, kev, EVENT_REGISTER);
   1878 		mutex_spin_exit(&kq->kq_lock);
   1879 	} else {
   1880 		kn->kn_sfflags = kev->fflags;
   1881 		kn->kn_sdata = kev->data;
   1882 	}
   1883 
   1884 	/*
   1885 	 * We can get here if we are trying to attach
   1886 	 * an event to a file descriptor that does not
   1887 	 * support events, and the attach routine is
   1888 	 * broken and does not return an error.
   1889 	 */
   1890 done_ev_add:
   1891 	rv = filter_event(kn, 0);
   1892 	if (rv)
   1893 		knote_activate(kn);
   1894 
   1895 	/* disable knote */
   1896 	if ((kev->flags & EV_DISABLE)) {
   1897 		mutex_spin_enter(&kq->kq_lock);
   1898 		if ((kn->kn_status & KN_DISABLED) == 0)
   1899 			kn->kn_status |= KN_DISABLED;
   1900 		mutex_spin_exit(&kq->kq_lock);
   1901 	}
   1902 
   1903 	/* enable knote */
   1904 	if ((kev->flags & EV_ENABLE)) {
   1905 		knote_enqueue(kn);
   1906 	}
   1907 doneunlock:
   1908 	mutex_exit(&fdp->fd_lock);
   1909  done:
   1910 	rw_exit(&kqueue_filter_lock);
   1911 	if (newkn != NULL)
   1912 		kmem_free(newkn, sizeof(*newkn));
   1913 	if (fp != NULL)
   1914 		fd_putfile(fd);
   1915 	return (error);
   1916 }
   1917 
   1918 #define KN_FMT(buf, kn) \
   1919     (snprintb((buf), sizeof(buf), __KN_FLAG_BITS, (kn)->kn_status), buf)
   1920 
   1921 #if defined(DDB)
   1922 void
   1923 kqueue_printit(struct kqueue *kq, bool full, void (*pr)(const char *, ...))
   1924 {
   1925 	const struct knote *kn;
   1926 	u_int count;
   1927 	int nmarker;
   1928 	char buf[128];
   1929 
   1930 	count = 0;
   1931 	nmarker = 0;
   1932 
   1933 	(*pr)("kqueue %p (restart=%d count=%u):\n", kq,
   1934 	    !!(kq->kq_count & KQ_RESTART), KQ_COUNT(kq));
   1935 	(*pr)("  Queued knotes:\n");
   1936 	TAILQ_FOREACH(kn, &kq->kq_head, kn_tqe) {
   1937 		if (kn->kn_status & KN_MARKER) {
   1938 			nmarker++;
   1939 		} else {
   1940 			count++;
   1941 		}
   1942 		(*pr)("    knote %p: kq=%p status=%s\n",
   1943 		    kn, kn->kn_kq, KN_FMT(buf, kn));
   1944 		(*pr)("      id=0x%lx (%lu) filter=%d\n",
   1945 		    (u_long)kn->kn_id, (u_long)kn->kn_id, kn->kn_filter);
   1946 		if (kn->kn_kq != kq) {
   1947 			(*pr)("      !!! kn->kn_kq != kq\n");
   1948 		}
   1949 	}
   1950 	if (count != KQ_COUNT(kq)) {
   1951 		(*pr)("  !!! count(%u) != KQ_COUNT(%u)\n",
   1952 		    count, KQ_COUNT(kq));
   1953 	}
   1954 }
   1955 #endif /* DDB */
   1956 
   1957 #if defined(DEBUG)
   1958 static void
   1959 kqueue_check(const char *func, size_t line, const struct kqueue *kq)
   1960 {
   1961 	const struct knote *kn;
   1962 	u_int count;
   1963 	int nmarker;
   1964 	char buf[128];
   1965 
   1966 	KASSERT(mutex_owned(&kq->kq_lock));
   1967 
   1968 	count = 0;
   1969 	nmarker = 0;
   1970 	TAILQ_FOREACH(kn, &kq->kq_head, kn_tqe) {
   1971 		if ((kn->kn_status & (KN_MARKER | KN_QUEUED)) == 0) {
   1972 			panic("%s,%zu: kq=%p kn=%p !(MARKER|QUEUED) %s",
   1973 			    func, line, kq, kn, KN_FMT(buf, kn));
   1974 		}
   1975 		if ((kn->kn_status & KN_MARKER) == 0) {
   1976 			if (kn->kn_kq != kq) {
   1977 				panic("%s,%zu: kq=%p kn(%p) != kn->kq(%p): %s",
   1978 				    func, line, kq, kn, kn->kn_kq,
   1979 				    KN_FMT(buf, kn));
   1980 			}
   1981 			if ((kn->kn_status & KN_ACTIVE) == 0) {
   1982 				panic("%s,%zu: kq=%p kn=%p: !ACTIVE %s",
   1983 				    func, line, kq, kn, KN_FMT(buf, kn));
   1984 			}
   1985 			count++;
   1986 			if (count > KQ_COUNT(kq)) {
   1987 				panic("%s,%zu: kq=%p kq->kq_count(%u) != "
   1988 				    "count(%d), nmarker=%d",
   1989 		    		    func, line, kq, KQ_COUNT(kq), count,
   1990 				    nmarker);
   1991 			}
   1992 		} else {
   1993 			nmarker++;
   1994 		}
   1995 	}
   1996 }
   1997 #define kq_check(a) kqueue_check(__func__, __LINE__, (a))
   1998 #else /* defined(DEBUG) */
   1999 #define	kq_check(a)	/* nothing */
   2000 #endif /* defined(DEBUG) */
   2001 
   2002 static void
   2003 kqueue_restart(file_t *fp)
   2004 {
   2005 	struct kqueue *kq = fp->f_kqueue;
   2006 	KASSERT(kq != NULL);
   2007 
   2008 	mutex_spin_enter(&kq->kq_lock);
   2009 	kq->kq_count |= KQ_RESTART;
   2010 	cv_broadcast(&kq->kq_cv);
   2011 	mutex_spin_exit(&kq->kq_lock);
   2012 }
   2013 
   2014 /*
   2015  * Scan through the list of events on fp (for a maximum of maxevents),
   2016  * returning the results in to ulistp. Timeout is determined by tsp; if
   2017  * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
   2018  * as appropriate.
   2019  */
   2020 static int
   2021 kqueue_scan(file_t *fp, size_t maxevents, struct kevent *ulistp,
   2022 	    const struct timespec *tsp, register_t *retval,
   2023 	    const struct kevent_ops *keops, struct kevent *kevbuf,
   2024 	    size_t kevcnt)
   2025 {
   2026 	struct kqueue	*kq;
   2027 	struct kevent	*kevp;
   2028 	struct timespec	ats, sleepts;
   2029 	struct knote	*kn, *marker, morker;
   2030 	size_t		count, nkev, nevents;
   2031 	int		timeout, error, touch, rv, influx;
   2032 	filedesc_t	*fdp;
   2033 
   2034 	fdp = curlwp->l_fd;
   2035 	kq = fp->f_kqueue;
   2036 	count = maxevents;
   2037 	nkev = nevents = error = 0;
   2038 	if (count == 0) {
   2039 		*retval = 0;
   2040 		return 0;
   2041 	}
   2042 
   2043 	if (tsp) {				/* timeout supplied */
   2044 		ats = *tsp;
   2045 		if (inittimeleft(&ats, &sleepts) == -1) {
   2046 			*retval = maxevents;
   2047 			return EINVAL;
   2048 		}
   2049 		timeout = tstohz(&ats);
   2050 		if (timeout <= 0)
   2051 			timeout = -1;           /* do poll */
   2052 	} else {
   2053 		/* no timeout, wait forever */
   2054 		timeout = 0;
   2055 	}
   2056 
   2057 	memset(&morker, 0, sizeof(morker));
   2058 	marker = &morker;
   2059 	marker->kn_kq = kq;
   2060 	marker->kn_status = KN_MARKER;
   2061 	mutex_spin_enter(&kq->kq_lock);
   2062  retry:
   2063 	kevp = kevbuf;
   2064 	if (KQ_COUNT(kq) == 0) {
   2065 		if (timeout >= 0) {
   2066 			error = cv_timedwait_sig(&kq->kq_cv,
   2067 			    &kq->kq_lock, timeout);
   2068 			if (error == 0) {
   2069 				if (KQ_COUNT(kq) == 0 &&
   2070 				    (kq->kq_count & KQ_RESTART)) {
   2071 					/* return to clear file reference */
   2072 					error = ERESTART;
   2073 				} else if (tsp == NULL || (timeout =
   2074 				    gettimeleft(&ats, &sleepts)) > 0) {
   2075 					goto retry;
   2076 				}
   2077 			} else {
   2078 				/* don't restart after signals... */
   2079 				if (error == ERESTART)
   2080 					error = EINTR;
   2081 				if (error == EWOULDBLOCK)
   2082 					error = 0;
   2083 			}
   2084 		}
   2085 		mutex_spin_exit(&kq->kq_lock);
   2086 		goto done;
   2087 	}
   2088 
   2089 	/* mark end of knote list */
   2090 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
   2091 	influx = 0;
   2092 
   2093 	/*
   2094 	 * Acquire the fdp->fd_lock interlock to avoid races with
   2095 	 * file creation/destruction from other threads.
   2096 	 */
   2097 	mutex_spin_exit(&kq->kq_lock);
   2098 relock:
   2099 	mutex_enter(&fdp->fd_lock);
   2100 	mutex_spin_enter(&kq->kq_lock);
   2101 
   2102 	while (count != 0) {
   2103 		/*
   2104 		 * Get next knote.  We are guaranteed this will never
   2105 		 * be NULL because of the marker we inserted above.
   2106 		 */
   2107 		kn = TAILQ_FIRST(&kq->kq_head);
   2108 
   2109 		bool kn_is_other_marker =
   2110 		    (kn->kn_status & KN_MARKER) != 0 && kn != marker;
   2111 		bool kn_is_detaching = (kn->kn_status & KN_WILLDETACH) != 0;
   2112 		bool kn_is_in_flux = kn_in_flux(kn);
   2113 
   2114 		/*
   2115 		 * If we found a marker that's not ours, or this knote
   2116 		 * is in a state of flux, then wait for everything to
   2117 		 * settle down and go around again.
   2118 		 */
   2119 		if (kn_is_other_marker || kn_is_detaching || kn_is_in_flux) {
   2120 			if (influx) {
   2121 				influx = 0;
   2122 				KQ_FLUX_WAKEUP(kq);
   2123 			}
   2124 			mutex_exit(&fdp->fd_lock);
   2125 			if (kn_is_other_marker || kn_is_in_flux) {
   2126 				KQ_FLUX_WAIT(kq);
   2127 				mutex_spin_exit(&kq->kq_lock);
   2128 			} else {
   2129 				/*
   2130 				 * Detaching but not in-flux?  Someone is
   2131 				 * actively trying to finish the job; just
   2132 				 * go around and try again.
   2133 				 */
   2134 				KASSERT(kn_is_detaching);
   2135 				mutex_spin_exit(&kq->kq_lock);
   2136 				preempt_point();
   2137 			}
   2138 			goto relock;
   2139 		}
   2140 
   2141 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   2142 		if (kn == marker) {
   2143 			/* it's our marker, stop */
   2144 			KQ_FLUX_WAKEUP(kq);
   2145 			if (count == maxevents) {
   2146 				mutex_exit(&fdp->fd_lock);
   2147 				goto retry;
   2148 			}
   2149 			break;
   2150 		}
   2151 		KASSERT((kn->kn_status & KN_BUSY) == 0);
   2152 
   2153 		kq_check(kq);
   2154 		kn->kn_status &= ~KN_QUEUED;
   2155 		kn->kn_status |= KN_BUSY;
   2156 		kq_check(kq);
   2157 		if (kn->kn_status & KN_DISABLED) {
   2158 			kn->kn_status &= ~KN_BUSY;
   2159 			kq->kq_count--;
   2160 			/* don't want disabled events */
   2161 			continue;
   2162 		}
   2163 		if ((kn->kn_flags & EV_ONESHOT) == 0) {
   2164 			mutex_spin_exit(&kq->kq_lock);
   2165 			KASSERT(mutex_owned(&fdp->fd_lock));
   2166 			rv = filter_event(kn, 0);
   2167 			mutex_spin_enter(&kq->kq_lock);
   2168 			/* Re-poll if note was re-enqueued. */
   2169 			if ((kn->kn_status & KN_QUEUED) != 0) {
   2170 				kn->kn_status &= ~KN_BUSY;
   2171 				/* Re-enqueue raised kq_count, lower it again */
   2172 				kq->kq_count--;
   2173 				influx = 1;
   2174 				continue;
   2175 			}
   2176 			if (rv == 0) {
   2177 				/*
   2178 				 * non-ONESHOT event that hasn't triggered
   2179 				 * again, so it will remain de-queued.
   2180 				 */
   2181 				kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
   2182 				kq->kq_count--;
   2183 				influx = 1;
   2184 				continue;
   2185 			}
   2186 		} else {
   2187 			/*
   2188 			 * This ONESHOT note is going to be detached
   2189 			 * below.  Mark the knote as not long for this
   2190 			 * world before we release the kq lock so that
   2191 			 * no one else will put it in a state of flux.
   2192 			 */
   2193 			KNOTE_WILLDETACH(kn);
   2194 		}
   2195 		KASSERT(kn->kn_fop != NULL);
   2196 		touch = (!(kn->kn_fop->f_flags & FILTEROP_ISFD) &&
   2197 				kn->kn_fop->f_touch != NULL);
   2198 		/* XXXAD should be got from f_event if !oneshot. */
   2199 		if (touch) {
   2200 			filter_touch(kn, kevp, EVENT_PROCESS);
   2201 		} else {
   2202 			*kevp = kn->kn_kevent;
   2203 		}
   2204 		kevp++;
   2205 		nkev++;
   2206 		influx = 1;
   2207 		if (kn->kn_flags & EV_ONESHOT) {
   2208 			/* delete ONESHOT events after retrieval */
   2209 			kn->kn_status &= ~KN_BUSY;
   2210 			kq->kq_count--;
   2211 			KASSERT(kn_in_flux(kn) == false);
   2212 			KASSERT((kn->kn_status & KN_WILLDETACH) != 0 &&
   2213 				kn->kn_kevent.udata == curlwp);
   2214 			mutex_spin_exit(&kq->kq_lock);
   2215 			knote_detach(kn, fdp, true);
   2216 			mutex_enter(&fdp->fd_lock);
   2217 			mutex_spin_enter(&kq->kq_lock);
   2218 		} else if (kn->kn_flags & EV_CLEAR) {
   2219 			/* clear state after retrieval */
   2220 			kn->kn_data = 0;
   2221 			kn->kn_fflags = 0;
   2222 			/*
   2223 			 * Manually clear knotes who weren't
   2224 			 * 'touch'ed.
   2225 			 */
   2226 			if (touch == 0) {
   2227 				kn->kn_data = 0;
   2228 				kn->kn_fflags = 0;
   2229 			}
   2230 			kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
   2231 			kq->kq_count--;
   2232 		} else if (kn->kn_flags & EV_DISPATCH) {
   2233 			kn->kn_status |= KN_DISABLED;
   2234 			kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
   2235 			kq->kq_count--;
   2236 		} else {
   2237 			/* add event back on list */
   2238 			kq_check(kq);
   2239 			kn->kn_status |= KN_QUEUED;
   2240 			kn->kn_status &= ~KN_BUSY;
   2241 			TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   2242 			kq_check(kq);
   2243 		}
   2244 
   2245 		if (nkev == kevcnt) {
   2246 			/* do copyouts in kevcnt chunks */
   2247 			influx = 0;
   2248 			KQ_FLUX_WAKEUP(kq);
   2249 			mutex_spin_exit(&kq->kq_lock);
   2250 			mutex_exit(&fdp->fd_lock);
   2251 			error = (*keops->keo_put_events)
   2252 			    (keops->keo_private,
   2253 			    kevbuf, ulistp, nevents, nkev);
   2254 			mutex_enter(&fdp->fd_lock);
   2255 			mutex_spin_enter(&kq->kq_lock);
   2256 			nevents += nkev;
   2257 			nkev = 0;
   2258 			kevp = kevbuf;
   2259 		}
   2260 		count--;
   2261 		if (error != 0 || count == 0) {
   2262 			/* remove marker */
   2263 			TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
   2264 			break;
   2265 		}
   2266 	}
   2267 	KQ_FLUX_WAKEUP(kq);
   2268 	mutex_spin_exit(&kq->kq_lock);
   2269 	mutex_exit(&fdp->fd_lock);
   2270 
   2271 done:
   2272 	if (nkev != 0) {
   2273 		/* copyout remaining events */
   2274 		error = (*keops->keo_put_events)(keops->keo_private,
   2275 		    kevbuf, ulistp, nevents, nkev);
   2276 	}
   2277 	*retval = maxevents - count;
   2278 
   2279 	return error;
   2280 }
   2281 
   2282 /*
   2283  * fileops ioctl method for a kqueue descriptor.
   2284  *
   2285  * Two ioctls are currently supported. They both use struct kfilter_mapping:
   2286  *	KFILTER_BYNAME		find name for filter, and return result in
   2287  *				name, which is of size len.
   2288  *	KFILTER_BYFILTER	find filter for name. len is ignored.
   2289  */
   2290 /*ARGSUSED*/
   2291 static int
   2292 kqueue_ioctl(file_t *fp, u_long com, void *data)
   2293 {
   2294 	struct kfilter_mapping	*km;
   2295 	const struct kfilter	*kfilter;
   2296 	char			*name;
   2297 	int			error;
   2298 
   2299 	km = data;
   2300 	error = 0;
   2301 	name = kmem_alloc(KFILTER_MAXNAME, KM_SLEEP);
   2302 
   2303 	switch (com) {
   2304 	case KFILTER_BYFILTER:	/* convert filter -> name */
   2305 		rw_enter(&kqueue_filter_lock, RW_READER);
   2306 		kfilter = kfilter_byfilter(km->filter);
   2307 		if (kfilter != NULL) {
   2308 			strlcpy(name, kfilter->name, KFILTER_MAXNAME);
   2309 			rw_exit(&kqueue_filter_lock);
   2310 			error = copyoutstr(name, km->name, km->len, NULL);
   2311 		} else {
   2312 			rw_exit(&kqueue_filter_lock);
   2313 			error = ENOENT;
   2314 		}
   2315 		break;
   2316 
   2317 	case KFILTER_BYNAME:	/* convert name -> filter */
   2318 		error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
   2319 		if (error) {
   2320 			break;
   2321 		}
   2322 		rw_enter(&kqueue_filter_lock, RW_READER);
   2323 		kfilter = kfilter_byname(name);
   2324 		if (kfilter != NULL)
   2325 			km->filter = kfilter->filter;
   2326 		else
   2327 			error = ENOENT;
   2328 		rw_exit(&kqueue_filter_lock);
   2329 		break;
   2330 
   2331 	default:
   2332 		error = ENOTTY;
   2333 		break;
   2334 
   2335 	}
   2336 	kmem_free(name, KFILTER_MAXNAME);
   2337 	return (error);
   2338 }
   2339 
   2340 /*
   2341  * fileops fcntl method for a kqueue descriptor.
   2342  */
   2343 static int
   2344 kqueue_fcntl(file_t *fp, u_int com, void *data)
   2345 {
   2346 
   2347 	return (ENOTTY);
   2348 }
   2349 
   2350 /*
   2351  * fileops poll method for a kqueue descriptor.
   2352  * Determine if kqueue has events pending.
   2353  */
   2354 static int
   2355 kqueue_poll(file_t *fp, int events)
   2356 {
   2357 	struct kqueue	*kq;
   2358 	int		revents;
   2359 
   2360 	kq = fp->f_kqueue;
   2361 
   2362 	revents = 0;
   2363 	if (events & (POLLIN | POLLRDNORM)) {
   2364 		mutex_spin_enter(&kq->kq_lock);
   2365 		if (KQ_COUNT(kq) != 0) {
   2366 			revents |= events & (POLLIN | POLLRDNORM);
   2367 		} else {
   2368 			selrecord(curlwp, &kq->kq_sel);
   2369 		}
   2370 		kq_check(kq);
   2371 		mutex_spin_exit(&kq->kq_lock);
   2372 	}
   2373 
   2374 	return revents;
   2375 }
   2376 
   2377 /*
   2378  * fileops stat method for a kqueue descriptor.
   2379  * Returns dummy info, with st_size being number of events pending.
   2380  */
   2381 static int
   2382 kqueue_stat(file_t *fp, struct stat *st)
   2383 {
   2384 	struct kqueue *kq;
   2385 
   2386 	kq = fp->f_kqueue;
   2387 
   2388 	memset(st, 0, sizeof(*st));
   2389 	st->st_size = KQ_COUNT(kq);
   2390 	st->st_blksize = sizeof(struct kevent);
   2391 	st->st_mode = S_IFIFO | S_IRUSR | S_IWUSR;
   2392 	st->st_blocks = 1;
   2393 	st->st_uid = kauth_cred_geteuid(fp->f_cred);
   2394 	st->st_gid = kauth_cred_getegid(fp->f_cred);
   2395 
   2396 	return 0;
   2397 }
   2398 
   2399 static void
   2400 kqueue_doclose(struct kqueue *kq, struct klist *list, int fd)
   2401 {
   2402 	struct knote *kn;
   2403 	filedesc_t *fdp;
   2404 
   2405 	fdp = kq->kq_fdp;
   2406 
   2407 	KASSERT(mutex_owned(&fdp->fd_lock));
   2408 
   2409  again:
   2410 	for (kn = SLIST_FIRST(list); kn != NULL;) {
   2411 		if (kq != kn->kn_kq) {
   2412 			kn = SLIST_NEXT(kn, kn_link);
   2413 			continue;
   2414 		}
   2415 		if (knote_detach_quiesce(kn)) {
   2416 			mutex_enter(&fdp->fd_lock);
   2417 			goto again;
   2418 		}
   2419 		knote_detach(kn, fdp, true);
   2420 		mutex_enter(&fdp->fd_lock);
   2421 		kn = SLIST_FIRST(list);
   2422 	}
   2423 }
   2424 
   2425 /*
   2426  * fileops close method for a kqueue descriptor.
   2427  */
   2428 static int
   2429 kqueue_close(file_t *fp)
   2430 {
   2431 	struct kqueue *kq;
   2432 	filedesc_t *fdp;
   2433 	fdfile_t *ff;
   2434 	int i;
   2435 
   2436 	kq = fp->f_kqueue;
   2437 	fp->f_kqueue = NULL;
   2438 	fp->f_type = 0;
   2439 	fdp = curlwp->l_fd;
   2440 
   2441 	KASSERT(kq->kq_fdp == fdp);
   2442 
   2443 	mutex_enter(&fdp->fd_lock);
   2444 
   2445 	/*
   2446 	 * We're doing to drop the fd_lock multiple times while
   2447 	 * we detach knotes.  During this time, attempts to register
   2448 	 * knotes via the back door (e.g. knote_proc_fork_track())
   2449 	 * need to fail, lest they sneak in to attach a knote after
   2450 	 * we've already drained the list it's destined for.
   2451 	 *
   2452 	 * We must aquire kq_lock here to set KQ_CLOSING (to serialize
   2453 	 * with other code paths that modify kq_count without holding
   2454 	 * the fd_lock), but once this bit is set, it's only safe to
   2455 	 * test it while holding the fd_lock, and holding kq_lock while
   2456 	 * doing so is not necessary.
   2457 	 */
   2458 	mutex_enter(&kq->kq_lock);
   2459 	kq->kq_count |= KQ_CLOSING;
   2460 	mutex_exit(&kq->kq_lock);
   2461 
   2462 	for (i = 0; i <= fdp->fd_lastkqfile; i++) {
   2463 		if ((ff = fdp->fd_dt->dt_ff[i]) == NULL)
   2464 			continue;
   2465 		kqueue_doclose(kq, (struct klist *)&ff->ff_knlist, i);
   2466 	}
   2467 	if (fdp->fd_knhashmask != 0) {
   2468 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
   2469 			kqueue_doclose(kq, &fdp->fd_knhash[i], -1);
   2470 		}
   2471 	}
   2472 
   2473 	mutex_exit(&fdp->fd_lock);
   2474 
   2475 #if defined(DEBUG)
   2476 	mutex_enter(&kq->kq_lock);
   2477 	kq_check(kq);
   2478 	mutex_exit(&kq->kq_lock);
   2479 #endif /* DEBUG */
   2480 	KASSERT(TAILQ_EMPTY(&kq->kq_head));
   2481 	KASSERT(KQ_COUNT(kq) == 0);
   2482 	mutex_destroy(&kq->kq_lock);
   2483 	cv_destroy(&kq->kq_cv);
   2484 	seldestroy(&kq->kq_sel);
   2485 	kmem_free(kq, sizeof(*kq));
   2486 
   2487 	return (0);
   2488 }
   2489 
   2490 /*
   2491  * struct fileops kqfilter method for a kqueue descriptor.
   2492  * Event triggered when monitored kqueue changes.
   2493  */
   2494 static int
   2495 kqueue_kqfilter(file_t *fp, struct knote *kn)
   2496 {
   2497 	struct kqueue *kq;
   2498 
   2499 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
   2500 
   2501 	KASSERT(fp == kn->kn_obj);
   2502 
   2503 	if (kn->kn_filter != EVFILT_READ)
   2504 		return EINVAL;
   2505 
   2506 	kn->kn_fop = &kqread_filtops;
   2507 	mutex_enter(&kq->kq_lock);
   2508 	selrecord_knote(&kq->kq_sel, kn);
   2509 	mutex_exit(&kq->kq_lock);
   2510 
   2511 	return 0;
   2512 }
   2513 
   2514 
   2515 /*
   2516  * Walk down a list of knotes, activating them if their event has
   2517  * triggered.  The caller's object lock (e.g. device driver lock)
   2518  * must be held.
   2519  */
   2520 void
   2521 knote(struct klist *list, long hint)
   2522 {
   2523 	struct knote *kn, *tmpkn;
   2524 
   2525 	SLIST_FOREACH_SAFE(kn, list, kn_selnext, tmpkn) {
   2526 		if (filter_event(kn, hint)) {
   2527 			knote_activate(kn);
   2528 		}
   2529 	}
   2530 }
   2531 
   2532 /*
   2533  * Remove all knotes referencing a specified fd
   2534  */
   2535 void
   2536 knote_fdclose(int fd)
   2537 {
   2538 	struct klist *list;
   2539 	struct knote *kn;
   2540 	filedesc_t *fdp;
   2541 
   2542  again:
   2543 	fdp = curlwp->l_fd;
   2544 	mutex_enter(&fdp->fd_lock);
   2545 	list = (struct klist *)&fdp->fd_dt->dt_ff[fd]->ff_knlist;
   2546 	while ((kn = SLIST_FIRST(list)) != NULL) {
   2547 		if (knote_detach_quiesce(kn)) {
   2548 			goto again;
   2549 		}
   2550 		knote_detach(kn, fdp, true);
   2551 		mutex_enter(&fdp->fd_lock);
   2552 	}
   2553 	mutex_exit(&fdp->fd_lock);
   2554 }
   2555 
   2556 /*
   2557  * Drop knote.  Called with fdp->fd_lock held, and will drop before
   2558  * returning.
   2559  */
   2560 static void
   2561 knote_detach(struct knote *kn, filedesc_t *fdp, bool dofop)
   2562 {
   2563 	struct klist *list;
   2564 	struct kqueue *kq;
   2565 
   2566 	kq = kn->kn_kq;
   2567 
   2568 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   2569 	KASSERT((kn->kn_status & KN_WILLDETACH) != 0);
   2570 	KASSERT(kn->kn_fop != NULL);
   2571 	KASSERT(mutex_owned(&fdp->fd_lock));
   2572 
   2573 	/* Remove from monitored object. */
   2574 	if (dofop) {
   2575 		filter_detach(kn);
   2576 	}
   2577 
   2578 	/* Remove from descriptor table. */
   2579 	if (kn->kn_fop->f_flags & FILTEROP_ISFD)
   2580 		list = (struct klist *)&fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
   2581 	else
   2582 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
   2583 
   2584 	SLIST_REMOVE(list, kn, knote, kn_link);
   2585 
   2586 	/* Remove from kqueue. */
   2587 again:
   2588 	mutex_spin_enter(&kq->kq_lock);
   2589 	KASSERT(kn_in_flux(kn) == false);
   2590 	if ((kn->kn_status & KN_QUEUED) != 0) {
   2591 		kq_check(kq);
   2592 		KASSERT(KQ_COUNT(kq) != 0);
   2593 		kq->kq_count--;
   2594 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   2595 		kn->kn_status &= ~KN_QUEUED;
   2596 		kq_check(kq);
   2597 	} else if (kn->kn_status & KN_BUSY) {
   2598 		mutex_spin_exit(&kq->kq_lock);
   2599 		goto again;
   2600 	}
   2601 	mutex_spin_exit(&kq->kq_lock);
   2602 
   2603 	mutex_exit(&fdp->fd_lock);
   2604 	if (kn->kn_fop->f_flags & FILTEROP_ISFD)
   2605 		fd_putfile(kn->kn_id);
   2606 	atomic_dec_uint(&kn->kn_kfilter->refcnt);
   2607 	kmem_free(kn, sizeof(*kn));
   2608 }
   2609 
   2610 /*
   2611  * Queue new event for knote.
   2612  */
   2613 static void
   2614 knote_enqueue(struct knote *kn)
   2615 {
   2616 	struct kqueue *kq;
   2617 
   2618 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   2619 
   2620 	kq = kn->kn_kq;
   2621 
   2622 	mutex_spin_enter(&kq->kq_lock);
   2623 	if (__predict_false(kn->kn_status & KN_WILLDETACH)) {
   2624 		/* Don't bother enqueueing a dying knote. */
   2625 		goto out;
   2626 	}
   2627 	if ((kn->kn_status & KN_DISABLED) != 0) {
   2628 		kn->kn_status &= ~KN_DISABLED;
   2629 	}
   2630 	if ((kn->kn_status & (KN_ACTIVE | KN_QUEUED)) == KN_ACTIVE) {
   2631 		kq_check(kq);
   2632 		kn->kn_status |= KN_QUEUED;
   2633 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   2634 		KASSERT(KQ_COUNT(kq) < KQ_MAXCOUNT);
   2635 		kq->kq_count++;
   2636 		kq_check(kq);
   2637 		cv_broadcast(&kq->kq_cv);
   2638 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   2639 	}
   2640  out:
   2641 	mutex_spin_exit(&kq->kq_lock);
   2642 }
   2643 /*
   2644  * Queue new event for knote.
   2645  */
   2646 static void
   2647 knote_activate_locked(struct knote *kn)
   2648 {
   2649 	struct kqueue *kq;
   2650 
   2651 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   2652 
   2653 	kq = kn->kn_kq;
   2654 
   2655 	if (__predict_false(kn->kn_status & KN_WILLDETACH)) {
   2656 		/* Don't bother enqueueing a dying knote. */
   2657 		return;
   2658 	}
   2659 	kn->kn_status |= KN_ACTIVE;
   2660 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) {
   2661 		kq_check(kq);
   2662 		kn->kn_status |= KN_QUEUED;
   2663 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   2664 		KASSERT(KQ_COUNT(kq) < KQ_MAXCOUNT);
   2665 		kq->kq_count++;
   2666 		kq_check(kq);
   2667 		cv_broadcast(&kq->kq_cv);
   2668 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   2669 	}
   2670 }
   2671 
   2672 static void
   2673 knote_activate(struct knote *kn)
   2674 {
   2675 	struct kqueue *kq = kn->kn_kq;
   2676 
   2677 	mutex_spin_enter(&kq->kq_lock);
   2678 	knote_activate_locked(kn);
   2679 	mutex_spin_exit(&kq->kq_lock);
   2680 }
   2681 
   2682 /*
   2683  * Set EV_EOF on the specified knote.  Also allows additional
   2684  * EV_* flags to be set (e.g. EV_ONESHOT).
   2685  */
   2686 void
   2687 knote_set_eof(struct knote *kn, uint32_t flags)
   2688 {
   2689 	struct kqueue *kq = kn->kn_kq;
   2690 
   2691 	mutex_spin_enter(&kq->kq_lock);
   2692 	kn->kn_flags |= EV_EOF | flags;
   2693 	mutex_spin_exit(&kq->kq_lock);
   2694 }
   2695 
   2696 /*
   2697  * Clear EV_EOF on the specified knote.
   2698  */
   2699 void
   2700 knote_clear_eof(struct knote *kn)
   2701 {
   2702 	struct kqueue *kq = kn->kn_kq;
   2703 
   2704 	mutex_spin_enter(&kq->kq_lock);
   2705 	kn->kn_flags &= ~EV_EOF;
   2706 	mutex_spin_exit(&kq->kq_lock);
   2707 }
   2708