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