Home | History | Annotate | Line # | Download | only in kern
kern_event.c revision 1.112
      1 /*	$NetBSD: kern_event.c,v 1.112 2021/01/21 18:09:23 jdolecek Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008, 2009 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon (at) FreeBSD.org>
     34  * Copyright (c) 2009 Apple, Inc
     35  * All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  *
     46  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     47  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     49  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     50  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     51  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     52  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     53  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     54  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     55  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     56  * SUCH DAMAGE.
     57  *
     58  * FreeBSD: src/sys/kern/kern_event.c,v 1.27 2001/07/05 17:10:44 rwatson Exp
     59  */
     60 
     61 #include <sys/cdefs.h>
     62 __KERNEL_RCSID(0, "$NetBSD: kern_event.c,v 1.112 2021/01/21 18:09:23 jdolecek Exp $");
     63 
     64 #include <sys/param.h>
     65 #include <sys/systm.h>
     66 #include <sys/kernel.h>
     67 #include <sys/wait.h>
     68 #include <sys/proc.h>
     69 #include <sys/file.h>
     70 #include <sys/select.h>
     71 #include <sys/queue.h>
     72 #include <sys/event.h>
     73 #include <sys/eventvar.h>
     74 #include <sys/poll.h>
     75 #include <sys/kmem.h>
     76 #include <sys/stat.h>
     77 #include <sys/filedesc.h>
     78 #include <sys/syscallargs.h>
     79 #include <sys/kauth.h>
     80 #include <sys/conf.h>
     81 #include <sys/atomic.h>
     82 
     83 static int	kqueue_scan(file_t *, size_t, struct kevent *,
     84 			    const struct timespec *, register_t *,
     85 			    const struct kevent_ops *, struct kevent *,
     86 			    size_t);
     87 static int	kqueue_ioctl(file_t *, u_long, void *);
     88 static int	kqueue_fcntl(file_t *, u_int, void *);
     89 static int	kqueue_poll(file_t *, int);
     90 static int	kqueue_kqfilter(file_t *, struct knote *);
     91 static int	kqueue_stat(file_t *, struct stat *);
     92 static int	kqueue_close(file_t *);
     93 static int	kqueue_register(struct kqueue *, struct kevent *);
     94 static void	kqueue_doclose(struct kqueue *, struct klist *, int);
     95 
     96 static void	knote_detach(struct knote *, filedesc_t *fdp, bool);
     97 static void	knote_enqueue(struct knote *);
     98 static void	knote_activate(struct knote *);
     99 
    100 static void	filt_kqdetach(struct knote *);
    101 static int	filt_kqueue(struct knote *, long hint);
    102 static int	filt_procattach(struct knote *);
    103 static void	filt_procdetach(struct knote *);
    104 static int	filt_proc(struct knote *, long hint);
    105 static int	filt_fileattach(struct knote *);
    106 static void	filt_timerexpire(void *x);
    107 static int	filt_timerattach(struct knote *);
    108 static void	filt_timerdetach(struct knote *);
    109 static int	filt_timer(struct knote *, long hint);
    110 static int	filt_fsattach(struct knote *kn);
    111 static void	filt_fsdetach(struct knote *kn);
    112 static int	filt_fs(struct knote *kn, long hint);
    113 static int	filt_userattach(struct knote *);
    114 static void	filt_userdetach(struct knote *);
    115 static int	filt_user(struct knote *, long hint);
    116 static void	filt_usertouch(struct knote *, struct kevent *, long type);
    117 
    118 static const struct fileops kqueueops = {
    119 	.fo_name = "kqueue",
    120 	.fo_read = (void *)enxio,
    121 	.fo_write = (void *)enxio,
    122 	.fo_ioctl = kqueue_ioctl,
    123 	.fo_fcntl = kqueue_fcntl,
    124 	.fo_poll = kqueue_poll,
    125 	.fo_stat = kqueue_stat,
    126 	.fo_close = kqueue_close,
    127 	.fo_kqfilter = kqueue_kqfilter,
    128 	.fo_restart = fnullop_restart,
    129 };
    130 
    131 static const struct filterops kqread_filtops = {
    132 	.f_isfd = 1,
    133 	.f_attach = NULL,
    134 	.f_detach = filt_kqdetach,
    135 	.f_event = filt_kqueue,
    136 };
    137 
    138 static const struct filterops proc_filtops = {
    139 	.f_isfd = 0,
    140 	.f_attach = filt_procattach,
    141 	.f_detach = filt_procdetach,
    142 	.f_event = filt_proc,
    143 };
    144 
    145 static const struct filterops file_filtops = {
    146 	.f_isfd = 1,
    147 	.f_attach = filt_fileattach,
    148 	.f_detach = NULL,
    149 	.f_event = NULL,
    150 };
    151 
    152 static const struct filterops timer_filtops = {
    153 	.f_isfd = 0,
    154 	.f_attach = filt_timerattach,
    155 	.f_detach = filt_timerdetach,
    156 	.f_event = filt_timer,
    157 };
    158 
    159 static const struct filterops fs_filtops = {
    160 	.f_isfd = 0,
    161 	.f_attach = filt_fsattach,
    162 	.f_detach = filt_fsdetach,
    163 	.f_event = filt_fs,
    164 };
    165 
    166 static const struct filterops user_filtops = {
    167 	.f_isfd = 0,
    168 	.f_attach = filt_userattach,
    169 	.f_detach = filt_userdetach,
    170 	.f_event = filt_user,
    171 	.f_touch = filt_usertouch,
    172 };
    173 
    174 static u_int	kq_ncallouts = 0;
    175 static int	kq_calloutmax = (4 * 1024);
    176 
    177 #define	KN_HASHSIZE		64		/* XXX should be tunable */
    178 #define	KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
    179 
    180 extern const struct filterops sig_filtops;
    181 
    182 #define KQ_FLUX_WAKEUP(kq)	cv_broadcast(&kq->kq_cv)
    183 
    184 /*
    185  * Table for for all system-defined filters.
    186  * These should be listed in the numeric order of the EVFILT_* defines.
    187  * If filtops is NULL, the filter isn't implemented in NetBSD.
    188  * End of list is when name is NULL.
    189  *
    190  * Note that 'refcnt' is meaningless for built-in filters.
    191  */
    192 struct kfilter {
    193 	const char	*name;		/* name of filter */
    194 	uint32_t	filter;		/* id of filter */
    195 	unsigned	refcnt;		/* reference count */
    196 	const struct filterops *filtops;/* operations for filter */
    197 	size_t		namelen;	/* length of name string */
    198 };
    199 
    200 /* System defined filters */
    201 static struct kfilter sys_kfilters[] = {
    202 	{ "EVFILT_READ",	EVFILT_READ,	0, &file_filtops, 0 },
    203 	{ "EVFILT_WRITE",	EVFILT_WRITE,	0, &file_filtops, 0, },
    204 	{ "EVFILT_AIO",		EVFILT_AIO,	0, NULL, 0 },
    205 	{ "EVFILT_VNODE",	EVFILT_VNODE,	0, &file_filtops, 0 },
    206 	{ "EVFILT_PROC",	EVFILT_PROC,	0, &proc_filtops, 0 },
    207 	{ "EVFILT_SIGNAL",	EVFILT_SIGNAL,	0, &sig_filtops, 0 },
    208 	{ "EVFILT_TIMER",	EVFILT_TIMER,	0, &timer_filtops, 0 },
    209 	{ "EVFILT_FS",		EVFILT_FS,	0, &fs_filtops, 0 },
    210 	{ "EVFILT_USER",	EVFILT_USER,	0, &user_filtops, 0 },
    211 	{ NULL,			0,		0, NULL, 0 },
    212 };
    213 
    214 /* User defined kfilters */
    215 static struct kfilter	*user_kfilters;		/* array */
    216 static int		user_kfilterc;		/* current offset */
    217 static int		user_kfiltermaxc;	/* max size so far */
    218 static size_t		user_kfiltersz;		/* size of allocated memory */
    219 
    220 /*
    221  * Global Locks.
    222  *
    223  * Lock order:
    224  *
    225  *	kqueue_filter_lock
    226  *	-> kn_kq->kq_fdp->fd_lock
    227  *	-> object lock (e.g., device driver lock, kqueue_misc_lock, &c.)
    228  *	-> kn_kq->kq_lock
    229  *
    230  * Locking rules:
    231  *
    232  *	f_attach: fdp->fd_lock, KERNEL_LOCK
    233  *	f_detach: fdp->fd_lock, KERNEL_LOCK
    234  *	f_event(!NOTE_SUBMIT) via kevent: fdp->fd_lock, _no_ object lock
    235  *	f_event via knote: whatever caller guarantees
    236  *		Typically,	f_event(NOTE_SUBMIT) via knote: object lock
    237  *				f_event(!NOTE_SUBMIT) via knote: nothing,
    238  *					acquires/releases object lock inside.
    239  */
    240 static krwlock_t	kqueue_filter_lock;	/* lock on filter lists */
    241 static kmutex_t		kqueue_misc_lock;	/* miscellaneous */
    242 
    243 static kauth_listener_t	kqueue_listener;
    244 
    245 static int
    246 kqueue_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    247     void *arg0, void *arg1, void *arg2, void *arg3)
    248 {
    249 	struct proc *p;
    250 	int result;
    251 
    252 	result = KAUTH_RESULT_DEFER;
    253 	p = arg0;
    254 
    255 	if (action != KAUTH_PROCESS_KEVENT_FILTER)
    256 		return result;
    257 
    258 	if ((kauth_cred_getuid(p->p_cred) != kauth_cred_getuid(cred) ||
    259 	    ISSET(p->p_flag, PK_SUGID)))
    260 		return result;
    261 
    262 	result = KAUTH_RESULT_ALLOW;
    263 
    264 	return result;
    265 }
    266 
    267 /*
    268  * Initialize the kqueue subsystem.
    269  */
    270 void
    271 kqueue_init(void)
    272 {
    273 
    274 	rw_init(&kqueue_filter_lock);
    275 	mutex_init(&kqueue_misc_lock, MUTEX_DEFAULT, IPL_NONE);
    276 
    277 	kqueue_listener = kauth_listen_scope(KAUTH_SCOPE_PROCESS,
    278 	    kqueue_listener_cb, NULL);
    279 }
    280 
    281 /*
    282  * Find kfilter entry by name, or NULL if not found.
    283  */
    284 static struct kfilter *
    285 kfilter_byname_sys(const char *name)
    286 {
    287 	int i;
    288 
    289 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    290 
    291 	for (i = 0; sys_kfilters[i].name != NULL; i++) {
    292 		if (strcmp(name, sys_kfilters[i].name) == 0)
    293 			return &sys_kfilters[i];
    294 	}
    295 	return NULL;
    296 }
    297 
    298 static struct kfilter *
    299 kfilter_byname_user(const char *name)
    300 {
    301 	int i;
    302 
    303 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    304 
    305 	/* user filter slots have a NULL name if previously deregistered */
    306 	for (i = 0; i < user_kfilterc ; i++) {
    307 		if (user_kfilters[i].name != NULL &&
    308 		    strcmp(name, user_kfilters[i].name) == 0)
    309 			return &user_kfilters[i];
    310 	}
    311 	return NULL;
    312 }
    313 
    314 static struct kfilter *
    315 kfilter_byname(const char *name)
    316 {
    317 	struct kfilter *kfilter;
    318 
    319 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    320 
    321 	if ((kfilter = kfilter_byname_sys(name)) != NULL)
    322 		return kfilter;
    323 
    324 	return kfilter_byname_user(name);
    325 }
    326 
    327 /*
    328  * Find kfilter entry by filter id, or NULL if not found.
    329  * Assumes entries are indexed in filter id order, for speed.
    330  */
    331 static struct kfilter *
    332 kfilter_byfilter(uint32_t filter)
    333 {
    334 	struct kfilter *kfilter;
    335 
    336 	KASSERT(rw_lock_held(&kqueue_filter_lock));
    337 
    338 	if (filter < EVFILT_SYSCOUNT)	/* it's a system filter */
    339 		kfilter = &sys_kfilters[filter];
    340 	else if (user_kfilters != NULL &&
    341 	    filter < EVFILT_SYSCOUNT + user_kfilterc)
    342 					/* it's a user filter */
    343 		kfilter = &user_kfilters[filter - EVFILT_SYSCOUNT];
    344 	else
    345 		return (NULL);		/* out of range */
    346 	KASSERT(kfilter->filter == filter);	/* sanity check! */
    347 	return (kfilter);
    348 }
    349 
    350 /*
    351  * Register a new kfilter. Stores the entry in user_kfilters.
    352  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    353  * If retfilter != NULL, the new filterid is returned in it.
    354  */
    355 int
    356 kfilter_register(const char *name, const struct filterops *filtops,
    357 		 int *retfilter)
    358 {
    359 	struct kfilter *kfilter;
    360 	size_t len;
    361 	int i;
    362 
    363 	if (name == NULL || name[0] == '\0' || filtops == NULL)
    364 		return (EINVAL);	/* invalid args */
    365 
    366 	rw_enter(&kqueue_filter_lock, RW_WRITER);
    367 	if (kfilter_byname(name) != NULL) {
    368 		rw_exit(&kqueue_filter_lock);
    369 		return (EEXIST);	/* already exists */
    370 	}
    371 	if (user_kfilterc > 0xffffffff - EVFILT_SYSCOUNT) {
    372 		rw_exit(&kqueue_filter_lock);
    373 		return (EINVAL);	/* too many */
    374 	}
    375 
    376 	for (i = 0; i < user_kfilterc; i++) {
    377 		kfilter = &user_kfilters[i];
    378 		if (kfilter->name == NULL) {
    379 			/* Previously deregistered slot.  Reuse. */
    380 			goto reuse;
    381 		}
    382 	}
    383 
    384 	/* check if need to grow user_kfilters */
    385 	if (user_kfilterc + 1 > user_kfiltermaxc) {
    386 		/* Grow in KFILTER_EXTENT chunks. */
    387 		user_kfiltermaxc += KFILTER_EXTENT;
    388 		len = user_kfiltermaxc * sizeof(*kfilter);
    389 		kfilter = kmem_alloc(len, KM_SLEEP);
    390 		memset((char *)kfilter + user_kfiltersz, 0, len - user_kfiltersz);
    391 		if (user_kfilters != NULL) {
    392 			memcpy(kfilter, user_kfilters, user_kfiltersz);
    393 			kmem_free(user_kfilters, user_kfiltersz);
    394 		}
    395 		user_kfiltersz = len;
    396 		user_kfilters = kfilter;
    397 	}
    398 	/* Adding new slot */
    399 	kfilter = &user_kfilters[user_kfilterc++];
    400 reuse:
    401 	kfilter->name = kmem_strdupsize(name, &kfilter->namelen, KM_SLEEP);
    402 
    403 	kfilter->filter = (kfilter - user_kfilters) + EVFILT_SYSCOUNT;
    404 
    405 	kfilter->filtops = kmem_alloc(sizeof(*filtops), KM_SLEEP);
    406 	memcpy(__UNCONST(kfilter->filtops), filtops, sizeof(*filtops));
    407 
    408 	if (retfilter != NULL)
    409 		*retfilter = kfilter->filter;
    410 	rw_exit(&kqueue_filter_lock);
    411 
    412 	return (0);
    413 }
    414 
    415 /*
    416  * Unregister a kfilter previously registered with kfilter_register.
    417  * This retains the filter id, but clears the name and frees filtops (filter
    418  * operations), so that the number isn't reused during a boot.
    419  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    420  */
    421 int
    422 kfilter_unregister(const char *name)
    423 {
    424 	struct kfilter *kfilter;
    425 
    426 	if (name == NULL || name[0] == '\0')
    427 		return (EINVAL);	/* invalid name */
    428 
    429 	rw_enter(&kqueue_filter_lock, RW_WRITER);
    430 	if (kfilter_byname_sys(name) != NULL) {
    431 		rw_exit(&kqueue_filter_lock);
    432 		return (EINVAL);	/* can't detach system filters */
    433 	}
    434 
    435 	kfilter = kfilter_byname_user(name);
    436 	if (kfilter == NULL) {
    437 		rw_exit(&kqueue_filter_lock);
    438 		return (ENOENT);
    439 	}
    440 	if (kfilter->refcnt != 0) {
    441 		rw_exit(&kqueue_filter_lock);
    442 		return (EBUSY);
    443 	}
    444 
    445 	/* Cast away const (but we know it's safe. */
    446 	kmem_free(__UNCONST(kfilter->name), kfilter->namelen);
    447 	kfilter->name = NULL;	/* mark as `not implemented' */
    448 
    449 	if (kfilter->filtops != NULL) {
    450 		/* Cast away const (but we know it's safe. */
    451 		kmem_free(__UNCONST(kfilter->filtops),
    452 		    sizeof(*kfilter->filtops));
    453 		kfilter->filtops = NULL; /* mark as `not implemented' */
    454 	}
    455 	rw_exit(&kqueue_filter_lock);
    456 
    457 	return (0);
    458 }
    459 
    460 
    461 /*
    462  * Filter attach method for EVFILT_READ and EVFILT_WRITE on normal file
    463  * descriptors. Calls fileops kqfilter method for given file descriptor.
    464  */
    465 static int
    466 filt_fileattach(struct knote *kn)
    467 {
    468 	file_t *fp;
    469 
    470 	fp = kn->kn_obj;
    471 
    472 	return (*fp->f_ops->fo_kqfilter)(fp, kn);
    473 }
    474 
    475 /*
    476  * Filter detach method for EVFILT_READ on kqueue descriptor.
    477  */
    478 static void
    479 filt_kqdetach(struct knote *kn)
    480 {
    481 	struct kqueue *kq;
    482 
    483 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
    484 
    485 	mutex_spin_enter(&kq->kq_lock);
    486 	selremove_knote(&kq->kq_sel, kn);
    487 	mutex_spin_exit(&kq->kq_lock);
    488 }
    489 
    490 /*
    491  * Filter event method for EVFILT_READ on kqueue descriptor.
    492  */
    493 /*ARGSUSED*/
    494 static int
    495 filt_kqueue(struct knote *kn, long hint)
    496 {
    497 	struct kqueue *kq;
    498 	int rv;
    499 
    500 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
    501 
    502 	if (hint != NOTE_SUBMIT)
    503 		mutex_spin_enter(&kq->kq_lock);
    504 	kn->kn_data = kq->kq_count;
    505 	rv = (kn->kn_data > 0);
    506 	if (hint != NOTE_SUBMIT)
    507 		mutex_spin_exit(&kq->kq_lock);
    508 
    509 	return rv;
    510 }
    511 
    512 /*
    513  * Filter attach method for EVFILT_PROC.
    514  */
    515 static int
    516 filt_procattach(struct knote *kn)
    517 {
    518 	struct proc *p;
    519 	struct lwp *curl;
    520 
    521 	curl = curlwp;
    522 
    523 	mutex_enter(&proc_lock);
    524 	if (kn->kn_flags & EV_FLAG1) {
    525 		/*
    526 		 * NOTE_TRACK attaches to the child process too early
    527 		 * for proc_find, so do a raw look up and check the state
    528 		 * explicitly.
    529 		 */
    530 		p = proc_find_raw(kn->kn_id);
    531 		if (p != NULL && p->p_stat != SIDL)
    532 			p = NULL;
    533 	} else {
    534 		p = proc_find(kn->kn_id);
    535 	}
    536 
    537 	if (p == NULL) {
    538 		mutex_exit(&proc_lock);
    539 		return ESRCH;
    540 	}
    541 
    542 	/*
    543 	 * Fail if it's not owned by you, or the last exec gave us
    544 	 * setuid/setgid privs (unless you're root).
    545 	 */
    546 	mutex_enter(p->p_lock);
    547 	mutex_exit(&proc_lock);
    548 	if (kauth_authorize_process(curl->l_cred, KAUTH_PROCESS_KEVENT_FILTER,
    549 	    p, NULL, NULL, NULL) != 0) {
    550 	    	mutex_exit(p->p_lock);
    551 		return EACCES;
    552 	}
    553 
    554 	kn->kn_obj = p;
    555 	kn->kn_flags |= EV_CLEAR;	/* automatically set */
    556 
    557 	/*
    558 	 * internal flag indicating registration done by kernel
    559 	 */
    560 	if (kn->kn_flags & EV_FLAG1) {
    561 		kn->kn_data = kn->kn_sdata;	/* ppid */
    562 		kn->kn_fflags = NOTE_CHILD;
    563 		kn->kn_flags &= ~EV_FLAG1;
    564 	}
    565 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
    566     	mutex_exit(p->p_lock);
    567 
    568 	return 0;
    569 }
    570 
    571 /*
    572  * Filter detach method for EVFILT_PROC.
    573  *
    574  * The knote may be attached to a different process, which may exit,
    575  * leaving nothing for the knote to be attached to.  So when the process
    576  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
    577  * it will be deleted when read out.  However, as part of the knote deletion,
    578  * this routine is called, so a check is needed to avoid actually performing
    579  * a detach, because the original process might not exist any more.
    580  */
    581 static void
    582 filt_procdetach(struct knote *kn)
    583 {
    584 	struct proc *p;
    585 
    586 	if (kn->kn_status & KN_DETACHED)
    587 		return;
    588 
    589 	p = kn->kn_obj;
    590 
    591 	mutex_enter(p->p_lock);
    592 	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
    593 	mutex_exit(p->p_lock);
    594 }
    595 
    596 /*
    597  * Filter event method for EVFILT_PROC.
    598  */
    599 static int
    600 filt_proc(struct knote *kn, long hint)
    601 {
    602 	u_int event, fflag;
    603 	struct kevent kev;
    604 	struct kqueue *kq;
    605 	int error;
    606 
    607 	event = (u_int)hint & NOTE_PCTRLMASK;
    608 	kq = kn->kn_kq;
    609 	fflag = 0;
    610 
    611 	/* If the user is interested in this event, record it. */
    612 	if (kn->kn_sfflags & event)
    613 		fflag |= event;
    614 
    615 	if (event == NOTE_EXIT) {
    616 		struct proc *p = kn->kn_obj;
    617 
    618 		if (p != NULL)
    619 			kn->kn_data = P_WAITSTATUS(p);
    620 		/*
    621 		 * Process is gone, so flag the event as finished.
    622 		 *
    623 		 * Detach the knote from watched process and mark
    624 		 * it as such. We can't leave this to kqueue_scan(),
    625 		 * since the process might not exist by then. And we
    626 		 * have to do this now, since psignal KNOTE() is called
    627 		 * also for zombies and we might end up reading freed
    628 		 * memory if the kevent would already be picked up
    629 		 * and knote g/c'ed.
    630 		 */
    631 		filt_procdetach(kn);
    632 
    633 		mutex_spin_enter(&kq->kq_lock);
    634 		kn->kn_status |= KN_DETACHED;
    635 		/* Mark as ONESHOT, so that the knote it g/c'ed when read */
    636 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
    637 		kn->kn_fflags |= fflag;
    638 		mutex_spin_exit(&kq->kq_lock);
    639 
    640 		return 1;
    641 	}
    642 
    643 	mutex_spin_enter(&kq->kq_lock);
    644 	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
    645 		/*
    646 		 * Process forked, and user wants to track the new process,
    647 		 * so attach a new knote to it, and immediately report an
    648 		 * event with the parent's pid.  Register knote with new
    649 		 * process.
    650 		 */
    651 		memset(&kev, 0, sizeof(kev));
    652 		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
    653 		kev.filter = kn->kn_filter;
    654 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
    655 		kev.fflags = kn->kn_sfflags;
    656 		kev.data = kn->kn_id;			/* parent */
    657 		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
    658 		mutex_spin_exit(&kq->kq_lock);
    659 		error = kqueue_register(kq, &kev);
    660 		mutex_spin_enter(&kq->kq_lock);
    661 		if (error != 0)
    662 			kn->kn_fflags |= NOTE_TRACKERR;
    663 	}
    664 	kn->kn_fflags |= fflag;
    665 	fflag = kn->kn_fflags;
    666 	mutex_spin_exit(&kq->kq_lock);
    667 
    668 	return fflag != 0;
    669 }
    670 
    671 static void
    672 filt_timerexpire(void *knx)
    673 {
    674 	struct knote *kn = knx;
    675 	int tticks;
    676 
    677 	mutex_enter(&kqueue_misc_lock);
    678 	kn->kn_data++;
    679 	knote_activate(kn);
    680 	if ((kn->kn_flags & EV_ONESHOT) == 0) {
    681 		tticks = mstohz(kn->kn_sdata);
    682 		if (tticks <= 0)
    683 			tticks = 1;
    684 		callout_schedule((callout_t *)kn->kn_hook, tticks);
    685 	}
    686 	mutex_exit(&kqueue_misc_lock);
    687 }
    688 
    689 /*
    690  * data contains amount of time to sleep, in milliseconds
    691  */
    692 static int
    693 filt_timerattach(struct knote *kn)
    694 {
    695 	callout_t *calloutp;
    696 	struct kqueue *kq;
    697 	int tticks;
    698 
    699 	tticks = mstohz(kn->kn_sdata);
    700 
    701 	/* if the supplied value is under our resolution, use 1 tick */
    702 	if (tticks == 0) {
    703 		if (kn->kn_sdata == 0)
    704 			return EINVAL;
    705 		tticks = 1;
    706 	}
    707 
    708 	if (atomic_inc_uint_nv(&kq_ncallouts) >= kq_calloutmax ||
    709 	    (calloutp = kmem_alloc(sizeof(*calloutp), KM_NOSLEEP)) == NULL) {
    710 		atomic_dec_uint(&kq_ncallouts);
    711 		return ENOMEM;
    712 	}
    713 	callout_init(calloutp, CALLOUT_MPSAFE);
    714 
    715 	kq = kn->kn_kq;
    716 	mutex_spin_enter(&kq->kq_lock);
    717 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
    718 	kn->kn_hook = calloutp;
    719 	mutex_spin_exit(&kq->kq_lock);
    720 
    721 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
    722 
    723 	return (0);
    724 }
    725 
    726 static void
    727 filt_timerdetach(struct knote *kn)
    728 {
    729 	callout_t *calloutp;
    730 	struct kqueue *kq = kn->kn_kq;
    731 
    732 	mutex_spin_enter(&kq->kq_lock);
    733 	/* prevent rescheduling when we expire */
    734 	kn->kn_flags |= EV_ONESHOT;
    735 	mutex_spin_exit(&kq->kq_lock);
    736 
    737 	calloutp = (callout_t *)kn->kn_hook;
    738 	callout_halt(calloutp, NULL);
    739 	callout_destroy(calloutp);
    740 	kmem_free(calloutp, sizeof(*calloutp));
    741 	atomic_dec_uint(&kq_ncallouts);
    742 }
    743 
    744 static int
    745 filt_timer(struct knote *kn, long hint)
    746 {
    747 	int rv;
    748 
    749 	mutex_enter(&kqueue_misc_lock);
    750 	rv = (kn->kn_data != 0);
    751 	mutex_exit(&kqueue_misc_lock);
    752 
    753 	return rv;
    754 }
    755 
    756 /*
    757  * Filter event method for EVFILT_FS.
    758  */
    759 struct klist fs_klist = SLIST_HEAD_INITIALIZER(&fs_klist);
    760 
    761 static int
    762 filt_fsattach(struct knote *kn)
    763 {
    764 
    765 	mutex_enter(&kqueue_misc_lock);
    766 	kn->kn_flags |= EV_CLEAR;
    767 	SLIST_INSERT_HEAD(&fs_klist, kn, kn_selnext);
    768 	mutex_exit(&kqueue_misc_lock);
    769 
    770 	return 0;
    771 }
    772 
    773 static void
    774 filt_fsdetach(struct knote *kn)
    775 {
    776 
    777 	mutex_enter(&kqueue_misc_lock);
    778 	SLIST_REMOVE(&fs_klist, kn, knote, kn_selnext);
    779 	mutex_exit(&kqueue_misc_lock);
    780 }
    781 
    782 static int
    783 filt_fs(struct knote *kn, long hint)
    784 {
    785 	int rv;
    786 
    787 	mutex_enter(&kqueue_misc_lock);
    788 	kn->kn_fflags |= hint;
    789 	rv = (kn->kn_fflags != 0);
    790 	mutex_exit(&kqueue_misc_lock);
    791 
    792 	return rv;
    793 }
    794 
    795 static int
    796 filt_userattach(struct knote *kn)
    797 {
    798 	struct kqueue *kq = kn->kn_kq;
    799 
    800 	/*
    801 	 * EVFILT_USER knotes are not attached to anything in the kernel.
    802 	 */
    803 	mutex_spin_enter(&kq->kq_lock);
    804 	kn->kn_hook = NULL;
    805 	if (kn->kn_fflags & NOTE_TRIGGER)
    806 		kn->kn_hookid = 1;
    807 	else
    808 		kn->kn_hookid = 0;
    809 	mutex_spin_exit(&kq->kq_lock);
    810 	return (0);
    811 }
    812 
    813 static void
    814 filt_userdetach(struct knote *kn)
    815 {
    816 
    817 	/*
    818 	 * EVFILT_USER knotes are not attached to anything in the kernel.
    819 	 */
    820 }
    821 
    822 static int
    823 filt_user(struct knote *kn, long hint)
    824 {
    825 	struct kqueue *kq = kn->kn_kq;
    826 	int hookid;
    827 
    828 	mutex_spin_enter(&kq->kq_lock);
    829 	hookid = kn->kn_hookid;
    830 	mutex_spin_exit(&kq->kq_lock);
    831 
    832 	return hookid;
    833 }
    834 
    835 static void
    836 filt_usertouch(struct knote *kn, struct kevent *kev, long type)
    837 {
    838 	struct kqueue *kq = kn->kn_kq;
    839 	int ffctrl;
    840 
    841 	mutex_spin_enter(&kq->kq_lock);
    842 	switch (type) {
    843 	case EVENT_REGISTER:
    844 		if (kev->fflags & NOTE_TRIGGER)
    845 			kn->kn_hookid = 1;
    846 
    847 		ffctrl = kev->fflags & NOTE_FFCTRLMASK;
    848 		kev->fflags &= NOTE_FFLAGSMASK;
    849 		switch (ffctrl) {
    850 		case NOTE_FFNOP:
    851 			break;
    852 
    853 		case NOTE_FFAND:
    854 			kn->kn_sfflags &= kev->fflags;
    855 			break;
    856 
    857 		case NOTE_FFOR:
    858 			kn->kn_sfflags |= kev->fflags;
    859 			break;
    860 
    861 		case NOTE_FFCOPY:
    862 			kn->kn_sfflags = kev->fflags;
    863 			break;
    864 
    865 		default:
    866 			/* XXX Return error? */
    867 			break;
    868 		}
    869 		kn->kn_sdata = kev->data;
    870 		if (kev->flags & EV_CLEAR) {
    871 			kn->kn_hookid = 0;
    872 			kn->kn_data = 0;
    873 			kn->kn_fflags = 0;
    874 		}
    875 		break;
    876 
    877 	case EVENT_PROCESS:
    878 		*kev = kn->kn_kevent;
    879 		kev->fflags = kn->kn_sfflags;
    880 		kev->data = kn->kn_sdata;
    881 		if (kn->kn_flags & EV_CLEAR) {
    882 			kn->kn_hookid = 0;
    883 			kn->kn_data = 0;
    884 			kn->kn_fflags = 0;
    885 		}
    886 		break;
    887 
    888 	default:
    889 		panic("filt_usertouch() - invalid type (%ld)", type);
    890 		break;
    891 	}
    892 	mutex_spin_exit(&kq->kq_lock);
    893 }
    894 
    895 /*
    896  * filt_seltrue:
    897  *
    898  *	This filter "event" routine simulates seltrue().
    899  */
    900 int
    901 filt_seltrue(struct knote *kn, long hint)
    902 {
    903 
    904 	/*
    905 	 * We don't know how much data can be read/written,
    906 	 * but we know that it *can* be.  This is about as
    907 	 * good as select/poll does as well.
    908 	 */
    909 	kn->kn_data = 0;
    910 	return (1);
    911 }
    912 
    913 /*
    914  * This provides full kqfilter entry for device switch tables, which
    915  * has same effect as filter using filt_seltrue() as filter method.
    916  */
    917 static void
    918 filt_seltruedetach(struct knote *kn)
    919 {
    920 	/* Nothing to do */
    921 }
    922 
    923 const struct filterops seltrue_filtops = {
    924 	.f_isfd = 1,
    925 	.f_attach = NULL,
    926 	.f_detach = filt_seltruedetach,
    927 	.f_event = filt_seltrue,
    928 	.f_touch = NULL,
    929 };
    930 
    931 int
    932 seltrue_kqfilter(dev_t dev, struct knote *kn)
    933 {
    934 	switch (kn->kn_filter) {
    935 	case EVFILT_READ:
    936 	case EVFILT_WRITE:
    937 		kn->kn_fop = &seltrue_filtops;
    938 		break;
    939 	default:
    940 		return (EINVAL);
    941 	}
    942 
    943 	/* Nothing more to do */
    944 	return (0);
    945 }
    946 
    947 /*
    948  * kqueue(2) system call.
    949  */
    950 static int
    951 kqueue1(struct lwp *l, int flags, register_t *retval)
    952 {
    953 	struct kqueue *kq;
    954 	file_t *fp;
    955 	int fd, error;
    956 
    957 	if ((error = fd_allocfile(&fp, &fd)) != 0)
    958 		return error;
    959 	fp->f_flag = FREAD | FWRITE | (flags & (FNONBLOCK|FNOSIGPIPE));
    960 	fp->f_type = DTYPE_KQUEUE;
    961 	fp->f_ops = &kqueueops;
    962 	kq = kmem_zalloc(sizeof(*kq), KM_SLEEP);
    963 	mutex_init(&kq->kq_lock, MUTEX_DEFAULT, IPL_SCHED);
    964 	cv_init(&kq->kq_cv, "kqueue");
    965 	selinit(&kq->kq_sel);
    966 	TAILQ_INIT(&kq->kq_head);
    967 	fp->f_kqueue = kq;
    968 	*retval = fd;
    969 	kq->kq_fdp = curlwp->l_fd;
    970 	fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0);
    971 	fd_affix(curproc, fp, fd);
    972 	return error;
    973 }
    974 
    975 /*
    976  * kqueue(2) system call.
    977  */
    978 int
    979 sys_kqueue(struct lwp *l, const void *v, register_t *retval)
    980 {
    981 	return kqueue1(l, 0, retval);
    982 }
    983 
    984 int
    985 sys_kqueue1(struct lwp *l, const struct sys_kqueue1_args *uap,
    986     register_t *retval)
    987 {
    988 	/* {
    989 		syscallarg(int) flags;
    990 	} */
    991 	return kqueue1(l, SCARG(uap, flags), retval);
    992 }
    993 
    994 /*
    995  * kevent(2) system call.
    996  */
    997 int
    998 kevent_fetch_changes(void *ctx, const struct kevent *changelist,
    999     struct kevent *changes, size_t index, int n)
   1000 {
   1001 
   1002 	return copyin(changelist + index, changes, n * sizeof(*changes));
   1003 }
   1004 
   1005 int
   1006 kevent_put_events(void *ctx, struct kevent *events,
   1007     struct kevent *eventlist, size_t index, int n)
   1008 {
   1009 
   1010 	return copyout(events, eventlist + index, n * sizeof(*events));
   1011 }
   1012 
   1013 static const struct kevent_ops kevent_native_ops = {
   1014 	.keo_private = NULL,
   1015 	.keo_fetch_timeout = copyin,
   1016 	.keo_fetch_changes = kevent_fetch_changes,
   1017 	.keo_put_events = kevent_put_events,
   1018 };
   1019 
   1020 int
   1021 sys___kevent50(struct lwp *l, const struct sys___kevent50_args *uap,
   1022     register_t *retval)
   1023 {
   1024 	/* {
   1025 		syscallarg(int) fd;
   1026 		syscallarg(const struct kevent *) changelist;
   1027 		syscallarg(size_t) nchanges;
   1028 		syscallarg(struct kevent *) eventlist;
   1029 		syscallarg(size_t) nevents;
   1030 		syscallarg(const struct timespec *) timeout;
   1031 	} */
   1032 
   1033 	return kevent1(retval, SCARG(uap, fd), SCARG(uap, changelist),
   1034 	    SCARG(uap, nchanges), SCARG(uap, eventlist), SCARG(uap, nevents),
   1035 	    SCARG(uap, timeout), &kevent_native_ops);
   1036 }
   1037 
   1038 int
   1039 kevent1(register_t *retval, int fd,
   1040 	const struct kevent *changelist, size_t nchanges,
   1041 	struct kevent *eventlist, size_t nevents,
   1042 	const struct timespec *timeout,
   1043 	const struct kevent_ops *keops)
   1044 {
   1045 	struct kevent *kevp;
   1046 	struct kqueue *kq;
   1047 	struct timespec	ts;
   1048 	size_t i, n, ichange;
   1049 	int nerrors, error;
   1050 	struct kevent kevbuf[KQ_NEVENTS];	/* approx 300 bytes on 64-bit */
   1051 	file_t *fp;
   1052 
   1053 	/* check that we're dealing with a kq */
   1054 	fp = fd_getfile(fd);
   1055 	if (fp == NULL)
   1056 		return (EBADF);
   1057 
   1058 	if (fp->f_type != DTYPE_KQUEUE) {
   1059 		fd_putfile(fd);
   1060 		return (EBADF);
   1061 	}
   1062 
   1063 	if (timeout != NULL) {
   1064 		error = (*keops->keo_fetch_timeout)(timeout, &ts, sizeof(ts));
   1065 		if (error)
   1066 			goto done;
   1067 		timeout = &ts;
   1068 	}
   1069 
   1070 	kq = fp->f_kqueue;
   1071 	nerrors = 0;
   1072 	ichange = 0;
   1073 
   1074 	/* traverse list of events to register */
   1075 	while (nchanges > 0) {
   1076 		n = MIN(nchanges, __arraycount(kevbuf));
   1077 		error = (*keops->keo_fetch_changes)(keops->keo_private,
   1078 		    changelist, kevbuf, ichange, n);
   1079 		if (error)
   1080 			goto done;
   1081 		for (i = 0; i < n; i++) {
   1082 			kevp = &kevbuf[i];
   1083 			kevp->flags &= ~EV_SYSFLAGS;
   1084 			/* register each knote */
   1085 			error = kqueue_register(kq, kevp);
   1086 			if (!error && !(kevp->flags & EV_RECEIPT))
   1087 				continue;
   1088 			if (nevents == 0)
   1089 				goto done;
   1090 			kevp->flags = EV_ERROR;
   1091 			kevp->data = error;
   1092 			error = (*keops->keo_put_events)
   1093 				(keops->keo_private, kevp,
   1094 				 eventlist, nerrors, 1);
   1095 			if (error)
   1096 				goto done;
   1097 			nevents--;
   1098 			nerrors++;
   1099 		}
   1100 		nchanges -= n;	/* update the results */
   1101 		ichange += n;
   1102 	}
   1103 	if (nerrors) {
   1104 		*retval = nerrors;
   1105 		error = 0;
   1106 		goto done;
   1107 	}
   1108 
   1109 	/* actually scan through the events */
   1110 	error = kqueue_scan(fp, nevents, eventlist, timeout, retval, keops,
   1111 	    kevbuf, __arraycount(kevbuf));
   1112  done:
   1113 	fd_putfile(fd);
   1114 	return (error);
   1115 }
   1116 
   1117 /*
   1118  * Register a given kevent kev onto the kqueue
   1119  */
   1120 static int
   1121 kqueue_register(struct kqueue *kq, struct kevent *kev)
   1122 {
   1123 	struct kfilter *kfilter;
   1124 	filedesc_t *fdp;
   1125 	file_t *fp;
   1126 	fdfile_t *ff;
   1127 	struct knote *kn, *newkn;
   1128 	struct klist *list;
   1129 	int error, fd, rv;
   1130 
   1131 	fdp = kq->kq_fdp;
   1132 	fp = NULL;
   1133 	kn = NULL;
   1134 	error = 0;
   1135 	fd = 0;
   1136 
   1137 	newkn = kmem_zalloc(sizeof(*newkn), KM_SLEEP);
   1138 
   1139 	rw_enter(&kqueue_filter_lock, RW_READER);
   1140 	kfilter = kfilter_byfilter(kev->filter);
   1141 	if (kfilter == NULL || kfilter->filtops == NULL) {
   1142 		/* filter not found nor implemented */
   1143 		rw_exit(&kqueue_filter_lock);
   1144 		kmem_free(newkn, sizeof(*newkn));
   1145 		return (EINVAL);
   1146 	}
   1147 
   1148 	/* search if knote already exists */
   1149 	if (kfilter->filtops->f_isfd) {
   1150 		/* monitoring a file descriptor */
   1151 		/* validate descriptor */
   1152 		if (kev->ident > INT_MAX
   1153 		    || (fp = fd_getfile(fd = kev->ident)) == NULL) {
   1154 			rw_exit(&kqueue_filter_lock);
   1155 			kmem_free(newkn, sizeof(*newkn));
   1156 			return EBADF;
   1157 		}
   1158 		mutex_enter(&fdp->fd_lock);
   1159 		ff = fdp->fd_dt->dt_ff[fd];
   1160 		if (ff->ff_refcnt & FR_CLOSING) {
   1161 			error = EBADF;
   1162 			goto doneunlock;
   1163 		}
   1164 		if (fd <= fdp->fd_lastkqfile) {
   1165 			SLIST_FOREACH(kn, &ff->ff_knlist, kn_link) {
   1166 				if (kq == kn->kn_kq &&
   1167 				    kev->filter == kn->kn_filter)
   1168 					break;
   1169 			}
   1170 		}
   1171 	} else {
   1172 		/*
   1173 		 * not monitoring a file descriptor, so
   1174 		 * lookup knotes in internal hash table
   1175 		 */
   1176 		mutex_enter(&fdp->fd_lock);
   1177 		if (fdp->fd_knhashmask != 0) {
   1178 			list = &fdp->fd_knhash[
   1179 			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
   1180 			SLIST_FOREACH(kn, list, kn_link) {
   1181 				if (kev->ident == kn->kn_id &&
   1182 				    kq == kn->kn_kq &&
   1183 				    kev->filter == kn->kn_filter)
   1184 					break;
   1185 			}
   1186 		}
   1187 	}
   1188 
   1189 	/*
   1190 	 * kn now contains the matching knote, or NULL if no match
   1191 	 */
   1192 	if (kn == NULL) {
   1193 		if (kev->flags & EV_ADD) {
   1194 			/* create new knote */
   1195 			kn = newkn;
   1196 			newkn = NULL;
   1197 			kn->kn_obj = fp;
   1198 			kn->kn_id = kev->ident;
   1199 			kn->kn_kq = kq;
   1200 			kn->kn_fop = kfilter->filtops;
   1201 			kn->kn_kfilter = kfilter;
   1202 			kn->kn_sfflags = kev->fflags;
   1203 			kn->kn_sdata = kev->data;
   1204 			kev->fflags = 0;
   1205 			kev->data = 0;
   1206 			kn->kn_kevent = *kev;
   1207 
   1208 			KASSERT(kn->kn_fop != NULL);
   1209 			/*
   1210 			 * apply reference count to knote structure, and
   1211 			 * do not release it at the end of this routine.
   1212 			 */
   1213 			fp = NULL;
   1214 
   1215 			if (!kn->kn_fop->f_isfd) {
   1216 				/*
   1217 				 * If knote is not on an fd, store on
   1218 				 * internal hash table.
   1219 				 */
   1220 				if (fdp->fd_knhashmask == 0) {
   1221 					/* XXXAD can block with fd_lock held */
   1222 					fdp->fd_knhash = hashinit(KN_HASHSIZE,
   1223 					    HASH_LIST, true,
   1224 					    &fdp->fd_knhashmask);
   1225 				}
   1226 				list = &fdp->fd_knhash[KN_HASH(kn->kn_id,
   1227 				    fdp->fd_knhashmask)];
   1228 			} else {
   1229 				/* Otherwise, knote is on an fd. */
   1230 				list = (struct klist *)
   1231 				    &fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
   1232 				if ((int)kn->kn_id > fdp->fd_lastkqfile)
   1233 					fdp->fd_lastkqfile = kn->kn_id;
   1234 			}
   1235 			SLIST_INSERT_HEAD(list, kn, kn_link);
   1236 
   1237 			KERNEL_LOCK(1, NULL);		/* XXXSMP */
   1238 			error = (*kfilter->filtops->f_attach)(kn);
   1239 			KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
   1240 			if (error != 0) {
   1241 #ifdef DEBUG
   1242 				struct proc *p = curlwp->l_proc;
   1243 				const file_t *ft = kn->kn_obj;
   1244 				printf("%s: %s[%d]: event type %d not "
   1245 				    "supported for file type %d/%s "
   1246 				    "(error %d)\n", __func__,
   1247 				    p->p_comm, p->p_pid,
   1248 				    kn->kn_filter, ft ? ft->f_type : -1,
   1249 				    ft ? ft->f_ops->fo_name : "?", error);
   1250 #endif
   1251 
   1252 				/* knote_detach() drops fdp->fd_lock */
   1253 				knote_detach(kn, fdp, false);
   1254 				goto done;
   1255 			}
   1256 			atomic_inc_uint(&kfilter->refcnt);
   1257 			goto done_ev_add;
   1258 		} else {
   1259 			/* No matching knote and the EV_ADD flag is not set. */
   1260 			error = ENOENT;
   1261 			goto doneunlock;
   1262 		}
   1263 	}
   1264 
   1265 	if (kev->flags & EV_DELETE) {
   1266 		/* knote_detach() drops fdp->fd_lock */
   1267 		knote_detach(kn, fdp, true);
   1268 		goto done;
   1269 	}
   1270 
   1271 	/*
   1272 	 * The user may change some filter values after the
   1273 	 * initial EV_ADD, but doing so will not reset any
   1274 	 * filter which have already been triggered.
   1275 	 */
   1276 	kn->kn_kevent.udata = kev->udata;
   1277 	KASSERT(kn->kn_fop != NULL);
   1278 	if (!kn->kn_fop->f_isfd && kn->kn_fop->f_touch != NULL) {
   1279 		KERNEL_LOCK(1, NULL);			/* XXXSMP */
   1280 		(*kn->kn_fop->f_touch)(kn, kev, EVENT_REGISTER);
   1281 		KERNEL_UNLOCK_ONE(NULL);		/* XXXSMP */
   1282 	} else {
   1283 		kn->kn_sfflags = kev->fflags;
   1284 		kn->kn_sdata = kev->data;
   1285 	}
   1286 
   1287 	/*
   1288 	 * We can get here if we are trying to attach
   1289 	 * an event to a file descriptor that does not
   1290 	 * support events, and the attach routine is
   1291 	 * broken and does not return an error.
   1292 	 */
   1293 done_ev_add:
   1294 	KASSERT(kn->kn_fop != NULL);
   1295 	KASSERT(kn->kn_fop->f_event != NULL);
   1296 	KERNEL_LOCK(1, NULL);			/* XXXSMP */
   1297 	rv = (*kn->kn_fop->f_event)(kn, 0);
   1298 	KERNEL_UNLOCK_ONE(NULL);		/* XXXSMP */
   1299 	if (rv)
   1300 		knote_activate(kn);
   1301 
   1302 	/* disable knote */
   1303 	if ((kev->flags & EV_DISABLE)) {
   1304 		mutex_spin_enter(&kq->kq_lock);
   1305 		if ((kn->kn_status & KN_DISABLED) == 0)
   1306 			kn->kn_status |= KN_DISABLED;
   1307 		mutex_spin_exit(&kq->kq_lock);
   1308 	}
   1309 
   1310 	/* enable knote */
   1311 	if ((kev->flags & EV_ENABLE)) {
   1312 		knote_enqueue(kn);
   1313 	}
   1314 doneunlock:
   1315 	mutex_exit(&fdp->fd_lock);
   1316  done:
   1317 	rw_exit(&kqueue_filter_lock);
   1318 	if (newkn != NULL)
   1319 		kmem_free(newkn, sizeof(*newkn));
   1320 	if (fp != NULL)
   1321 		fd_putfile(fd);
   1322 	return (error);
   1323 }
   1324 
   1325 #define DEBUG
   1326 #if defined(DEBUG)
   1327 #define KN_FMT(buf, kn) \
   1328     (snprintb((buf), sizeof(buf), __KN_FLAG_BITS, (kn)->kn_status), buf)
   1329 
   1330 static void
   1331 kqueue_check(const char *func, size_t line, const struct kqueue *kq)
   1332 {
   1333 	const struct knote *kn;
   1334 	int count;
   1335 	int nmarker;
   1336 	char buf[128];
   1337 
   1338 	KASSERT(mutex_owned(&kq->kq_lock));
   1339 	KASSERT(kq->kq_count >= 0);
   1340 
   1341 	count = 0;
   1342 	nmarker = 0;
   1343 	TAILQ_FOREACH(kn, &kq->kq_head, kn_tqe) {
   1344 		if ((kn->kn_status & (KN_MARKER | KN_QUEUED)) == 0) {
   1345 			panic("%s,%zu: kq=%p kn=%p !(MARKER|QUEUED) %s",
   1346 			    func, line, kq, kn, KN_FMT(buf, kn));
   1347 		}
   1348 		if ((kn->kn_status & KN_MARKER) == 0) {
   1349 			if (kn->kn_kq != kq) {
   1350 				panic("%s,%zu: kq=%p kn(%p) != kn->kq(%p): %s",
   1351 				    func, line, kq, kn, kn->kn_kq,
   1352 				    KN_FMT(buf, kn));
   1353 			}
   1354 			if ((kn->kn_status & KN_ACTIVE) == 0) {
   1355 				panic("%s,%zu: kq=%p kn=%p: !ACTIVE %s",
   1356 				    func, line, kq, kn, KN_FMT(buf, kn));
   1357 			}
   1358 			count++;
   1359 			if (count > kq->kq_count) {
   1360 				panic("%s,%zu: kq=%p kq->kq_count(%d) != "
   1361 				    "count(%d), nmarker=%d",
   1362 		    		    func, line, kq, kq->kq_count, count,
   1363 				    nmarker);
   1364 			}
   1365 		} else {
   1366 			nmarker++;
   1367 #if 0
   1368 			if (nmarker > 10000) {
   1369 				panic("%s,%zu: kq=%p too many markers: "
   1370 				    "%d != %d, nmarker=%d",
   1371 				    func, line, kq, kq->kq_count, count,
   1372 				    nmarker);
   1373 			}
   1374 #endif
   1375 		}
   1376 	}
   1377 }
   1378 #define kq_check(a) kqueue_check(__func__, __LINE__, (a))
   1379 #else /* defined(DEBUG) */
   1380 #define	kq_check(a)	/* nothing */
   1381 #endif /* defined(DEBUG) */
   1382 
   1383 /*
   1384  * Scan through the list of events on fp (for a maximum of maxevents),
   1385  * returning the results in to ulistp. Timeout is determined by tsp; if
   1386  * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
   1387  * as appropriate.
   1388  */
   1389 static int
   1390 kqueue_scan(file_t *fp, size_t maxevents, struct kevent *ulistp,
   1391 	    const struct timespec *tsp, register_t *retval,
   1392 	    const struct kevent_ops *keops, struct kevent *kevbuf,
   1393 	    size_t kevcnt)
   1394 {
   1395 	struct kqueue	*kq;
   1396 	struct kevent	*kevp;
   1397 	struct timespec	ats, sleepts;
   1398 	struct knote	*kn, *marker, morker;
   1399 	size_t		count, nkev, nevents;
   1400 	int		timeout, error, touch, rv, influx;
   1401 	filedesc_t	*fdp;
   1402 
   1403 	fdp = curlwp->l_fd;
   1404 	kq = fp->f_kqueue;
   1405 	count = maxevents;
   1406 	nkev = nevents = error = 0;
   1407 	if (count == 0) {
   1408 		*retval = 0;
   1409 		return 0;
   1410 	}
   1411 
   1412 	if (tsp) {				/* timeout supplied */
   1413 		ats = *tsp;
   1414 		if (inittimeleft(&ats, &sleepts) == -1) {
   1415 			*retval = maxevents;
   1416 			return EINVAL;
   1417 		}
   1418 		timeout = tstohz(&ats);
   1419 		if (timeout <= 0)
   1420 			timeout = -1;           /* do poll */
   1421 	} else {
   1422 		/* no timeout, wait forever */
   1423 		timeout = 0;
   1424 	}
   1425 
   1426 	memset(&morker, 0, sizeof(morker));
   1427 	marker = &morker;
   1428 	marker->kn_status = KN_MARKER;
   1429 	mutex_spin_enter(&kq->kq_lock);
   1430  retry:
   1431 	kevp = kevbuf;
   1432 	if (kq->kq_count == 0) {
   1433 		if (timeout >= 0) {
   1434 			error = cv_timedwait_sig(&kq->kq_cv,
   1435 			    &kq->kq_lock, timeout);
   1436 			if (error == 0) {
   1437 				 if (tsp == NULL || (timeout =
   1438 				     gettimeleft(&ats, &sleepts)) > 0)
   1439 					goto retry;
   1440 			} else {
   1441 				/* don't restart after signals... */
   1442 				if (error == ERESTART)
   1443 					error = EINTR;
   1444 				if (error == EWOULDBLOCK)
   1445 					error = 0;
   1446 			}
   1447 		}
   1448 		mutex_spin_exit(&kq->kq_lock);
   1449 		goto done;
   1450 	}
   1451 
   1452 	/* mark end of knote list */
   1453 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
   1454 	influx = 0;
   1455 
   1456 	/*
   1457 	 * Acquire the fdp->fd_lock interlock to avoid races with
   1458 	 * file creation/destruction from other threads.
   1459 	 */
   1460 relock:
   1461 	mutex_spin_exit(&kq->kq_lock);
   1462 	mutex_enter(&fdp->fd_lock);
   1463 	mutex_spin_enter(&kq->kq_lock);
   1464 
   1465 	while (count != 0) {
   1466 		kn = TAILQ_FIRST(&kq->kq_head);	/* get next knote */
   1467 
   1468 		if ((kn->kn_status & KN_MARKER) != 0 && kn != marker) {
   1469 			if (influx) {
   1470 				influx = 0;
   1471 				KQ_FLUX_WAKEUP(kq);
   1472 			}
   1473 			mutex_exit(&fdp->fd_lock);
   1474 			(void)cv_wait_sig(&kq->kq_cv, &kq->kq_lock);
   1475 			goto relock;
   1476 		}
   1477 
   1478 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   1479 		if (kn == marker) {
   1480 			/* it's our marker, stop */
   1481 			KQ_FLUX_WAKEUP(kq);
   1482 			if (count == maxevents) {
   1483 				mutex_exit(&fdp->fd_lock);
   1484 				goto retry;
   1485 			}
   1486 			break;
   1487 		}
   1488 		KASSERT((kn->kn_status & KN_BUSY) == 0);
   1489 
   1490 		kq_check(kq);
   1491 		kn->kn_status |= KN_BUSY;
   1492 		kq_check(kq);
   1493 		if (kn->kn_status & KN_DISABLED) {
   1494 			kq->kq_count--;
   1495 			kn->kn_status &= ~(KN_QUEUED|KN_BUSY);
   1496 			/* don't want disabled events */
   1497 			continue;
   1498 		}
   1499 		if ((kn->kn_flags & EV_ONESHOT) == 0) {
   1500 			mutex_spin_exit(&kq->kq_lock);
   1501 			KASSERT(kn->kn_fop != NULL);
   1502 			KASSERT(kn->kn_fop->f_event != NULL);
   1503 			KERNEL_LOCK(1, NULL);		/* XXXSMP */
   1504 			KASSERT(mutex_owned(&fdp->fd_lock));
   1505 			rv = (*kn->kn_fop->f_event)(kn, 0);
   1506 			KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
   1507 			mutex_spin_enter(&kq->kq_lock);
   1508 			if (rv == 0) {
   1509 				/*
   1510 				 * non-ONESHOT event that hasn't
   1511 				 * triggered again, so de-queue.
   1512 				 */
   1513 				kn->kn_status &= ~(KN_QUEUED|KN_ACTIVE|KN_BUSY);
   1514 				kq->kq_count--;
   1515 				influx = 1;
   1516 				continue;
   1517 			}
   1518 		}
   1519 		KASSERT(kn->kn_fop != NULL);
   1520 		touch = (!kn->kn_fop->f_isfd &&
   1521 				kn->kn_fop->f_touch != NULL);
   1522 		/* XXXAD should be got from f_event if !oneshot. */
   1523 		if (touch) {
   1524 			mutex_spin_exit(&kq->kq_lock);
   1525 			KERNEL_LOCK(1, NULL);		/* XXXSMP */
   1526 			(*kn->kn_fop->f_touch)(kn, kevp, EVENT_PROCESS);
   1527 			KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
   1528 			mutex_spin_enter(&kq->kq_lock);
   1529 		} else {
   1530 			*kevp = kn->kn_kevent;
   1531 		}
   1532 		kevp++;
   1533 		nkev++;
   1534 		influx = 1;
   1535 		if (kn->kn_flags & EV_ONESHOT) {
   1536 			/* delete ONESHOT events after retrieval */
   1537 			kn->kn_status &= ~(KN_QUEUED|KN_BUSY);
   1538 			kq->kq_count--;
   1539 			mutex_spin_exit(&kq->kq_lock);
   1540 			knote_detach(kn, fdp, true);
   1541 			mutex_enter(&fdp->fd_lock);
   1542 			mutex_spin_enter(&kq->kq_lock);
   1543 		} else if (kn->kn_flags & EV_CLEAR) {
   1544 			/* clear state after retrieval */
   1545 			kn->kn_data = 0;
   1546 			kn->kn_fflags = 0;
   1547 			/*
   1548 			 * Manually clear knotes who weren't
   1549 			 * 'touch'ed.
   1550 			 */
   1551 			if (touch == 0) {
   1552 				kn->kn_data = 0;
   1553 				kn->kn_fflags = 0;
   1554 			}
   1555 			kn->kn_status &= ~(KN_QUEUED|KN_ACTIVE|KN_BUSY);
   1556 			kq->kq_count--;
   1557 		} else if (kn->kn_flags & EV_DISPATCH) {
   1558 			kn->kn_status |= KN_DISABLED;
   1559 			kn->kn_status &= ~(KN_QUEUED|KN_ACTIVE|KN_BUSY);
   1560 			kq->kq_count--;
   1561 		} else {
   1562 			/* add event back on list */
   1563 			kq_check(kq);
   1564 			kn->kn_status &= ~KN_BUSY;
   1565 			TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1566 			kq_check(kq);
   1567 		}
   1568 
   1569 		if (nkev == kevcnt) {
   1570 			/* do copyouts in kevcnt chunks */
   1571 			influx = 0;
   1572 			KQ_FLUX_WAKEUP(kq);
   1573 			mutex_spin_exit(&kq->kq_lock);
   1574 			mutex_exit(&fdp->fd_lock);
   1575 			error = (*keops->keo_put_events)
   1576 			    (keops->keo_private,
   1577 			    kevbuf, ulistp, nevents, nkev);
   1578 			mutex_enter(&fdp->fd_lock);
   1579 			mutex_spin_enter(&kq->kq_lock);
   1580 			nevents += nkev;
   1581 			nkev = 0;
   1582 			kevp = kevbuf;
   1583 		}
   1584 		count--;
   1585 		if (error != 0 || count == 0) {
   1586 			/* remove marker */
   1587 			TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
   1588 			break;
   1589 		}
   1590 	}
   1591 	KQ_FLUX_WAKEUP(kq);
   1592 	mutex_spin_exit(&kq->kq_lock);
   1593 	mutex_exit(&fdp->fd_lock);
   1594 
   1595 done:
   1596 	if (nkev != 0) {
   1597 		/* copyout remaining events */
   1598 		error = (*keops->keo_put_events)(keops->keo_private,
   1599 		    kevbuf, ulistp, nevents, nkev);
   1600 	}
   1601 	*retval = maxevents - count;
   1602 
   1603 	return error;
   1604 }
   1605 
   1606 /*
   1607  * fileops ioctl method for a kqueue descriptor.
   1608  *
   1609  * Two ioctls are currently supported. They both use struct kfilter_mapping:
   1610  *	KFILTER_BYNAME		find name for filter, and return result in
   1611  *				name, which is of size len.
   1612  *	KFILTER_BYFILTER	find filter for name. len is ignored.
   1613  */
   1614 /*ARGSUSED*/
   1615 static int
   1616 kqueue_ioctl(file_t *fp, u_long com, void *data)
   1617 {
   1618 	struct kfilter_mapping	*km;
   1619 	const struct kfilter	*kfilter;
   1620 	char			*name;
   1621 	int			error;
   1622 
   1623 	km = data;
   1624 	error = 0;
   1625 	name = kmem_alloc(KFILTER_MAXNAME, KM_SLEEP);
   1626 
   1627 	switch (com) {
   1628 	case KFILTER_BYFILTER:	/* convert filter -> name */
   1629 		rw_enter(&kqueue_filter_lock, RW_READER);
   1630 		kfilter = kfilter_byfilter(km->filter);
   1631 		if (kfilter != NULL) {
   1632 			strlcpy(name, kfilter->name, KFILTER_MAXNAME);
   1633 			rw_exit(&kqueue_filter_lock);
   1634 			error = copyoutstr(name, km->name, km->len, NULL);
   1635 		} else {
   1636 			rw_exit(&kqueue_filter_lock);
   1637 			error = ENOENT;
   1638 		}
   1639 		break;
   1640 
   1641 	case KFILTER_BYNAME:	/* convert name -> filter */
   1642 		error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
   1643 		if (error) {
   1644 			break;
   1645 		}
   1646 		rw_enter(&kqueue_filter_lock, RW_READER);
   1647 		kfilter = kfilter_byname(name);
   1648 		if (kfilter != NULL)
   1649 			km->filter = kfilter->filter;
   1650 		else
   1651 			error = ENOENT;
   1652 		rw_exit(&kqueue_filter_lock);
   1653 		break;
   1654 
   1655 	default:
   1656 		error = ENOTTY;
   1657 		break;
   1658 
   1659 	}
   1660 	kmem_free(name, KFILTER_MAXNAME);
   1661 	return (error);
   1662 }
   1663 
   1664 /*
   1665  * fileops fcntl method for a kqueue descriptor.
   1666  */
   1667 static int
   1668 kqueue_fcntl(file_t *fp, u_int com, void *data)
   1669 {
   1670 
   1671 	return (ENOTTY);
   1672 }
   1673 
   1674 /*
   1675  * fileops poll method for a kqueue descriptor.
   1676  * Determine if kqueue has events pending.
   1677  */
   1678 static int
   1679 kqueue_poll(file_t *fp, int events)
   1680 {
   1681 	struct kqueue	*kq;
   1682 	int		revents;
   1683 
   1684 	kq = fp->f_kqueue;
   1685 
   1686 	revents = 0;
   1687 	if (events & (POLLIN | POLLRDNORM)) {
   1688 		mutex_spin_enter(&kq->kq_lock);
   1689 		if (kq->kq_count != 0) {
   1690 			revents |= events & (POLLIN | POLLRDNORM);
   1691 		} else {
   1692 			selrecord(curlwp, &kq->kq_sel);
   1693 		}
   1694 		kq_check(kq);
   1695 		mutex_spin_exit(&kq->kq_lock);
   1696 	}
   1697 
   1698 	return revents;
   1699 }
   1700 
   1701 /*
   1702  * fileops stat method for a kqueue descriptor.
   1703  * Returns dummy info, with st_size being number of events pending.
   1704  */
   1705 static int
   1706 kqueue_stat(file_t *fp, struct stat *st)
   1707 {
   1708 	struct kqueue *kq;
   1709 
   1710 	kq = fp->f_kqueue;
   1711 
   1712 	memset(st, 0, sizeof(*st));
   1713 	st->st_size = kq->kq_count;
   1714 	st->st_blksize = sizeof(struct kevent);
   1715 	st->st_mode = S_IFIFO;
   1716 
   1717 	return 0;
   1718 }
   1719 
   1720 static void
   1721 kqueue_doclose(struct kqueue *kq, struct klist *list, int fd)
   1722 {
   1723 	struct knote *kn;
   1724 	filedesc_t *fdp;
   1725 
   1726 	fdp = kq->kq_fdp;
   1727 
   1728 	KASSERT(mutex_owned(&fdp->fd_lock));
   1729 
   1730 	for (kn = SLIST_FIRST(list); kn != NULL;) {
   1731 		if (kq != kn->kn_kq) {
   1732 			kn = SLIST_NEXT(kn, kn_link);
   1733 			continue;
   1734 		}
   1735 		knote_detach(kn, fdp, true);
   1736 		mutex_enter(&fdp->fd_lock);
   1737 		kn = SLIST_FIRST(list);
   1738 	}
   1739 }
   1740 
   1741 
   1742 /*
   1743  * fileops close method for a kqueue descriptor.
   1744  */
   1745 static int
   1746 kqueue_close(file_t *fp)
   1747 {
   1748 	struct kqueue *kq;
   1749 	filedesc_t *fdp;
   1750 	fdfile_t *ff;
   1751 	int i;
   1752 
   1753 	kq = fp->f_kqueue;
   1754 	fp->f_kqueue = NULL;
   1755 	fp->f_type = 0;
   1756 	fdp = curlwp->l_fd;
   1757 
   1758 	mutex_enter(&fdp->fd_lock);
   1759 	for (i = 0; i <= fdp->fd_lastkqfile; i++) {
   1760 		if ((ff = fdp->fd_dt->dt_ff[i]) == NULL)
   1761 			continue;
   1762 		kqueue_doclose(kq, (struct klist *)&ff->ff_knlist, i);
   1763 	}
   1764 	if (fdp->fd_knhashmask != 0) {
   1765 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
   1766 			kqueue_doclose(kq, &fdp->fd_knhash[i], -1);
   1767 		}
   1768 	}
   1769 	mutex_exit(&fdp->fd_lock);
   1770 
   1771 	KASSERT(kq->kq_count == 0);
   1772 	mutex_destroy(&kq->kq_lock);
   1773 	cv_destroy(&kq->kq_cv);
   1774 	seldestroy(&kq->kq_sel);
   1775 	kmem_free(kq, sizeof(*kq));
   1776 
   1777 	return (0);
   1778 }
   1779 
   1780 /*
   1781  * struct fileops kqfilter method for a kqueue descriptor.
   1782  * Event triggered when monitored kqueue changes.
   1783  */
   1784 static int
   1785 kqueue_kqfilter(file_t *fp, struct knote *kn)
   1786 {
   1787 	struct kqueue *kq;
   1788 
   1789 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
   1790 
   1791 	KASSERT(fp == kn->kn_obj);
   1792 
   1793 	if (kn->kn_filter != EVFILT_READ)
   1794 		return 1;
   1795 
   1796 	kn->kn_fop = &kqread_filtops;
   1797 	mutex_enter(&kq->kq_lock);
   1798 	selrecord_knote(&kq->kq_sel, kn);
   1799 	mutex_exit(&kq->kq_lock);
   1800 
   1801 	return 0;
   1802 }
   1803 
   1804 
   1805 /*
   1806  * Walk down a list of knotes, activating them if their event has
   1807  * triggered.  The caller's object lock (e.g. device driver lock)
   1808  * must be held.
   1809  */
   1810 void
   1811 knote(struct klist *list, long hint)
   1812 {
   1813 	struct knote *kn, *tmpkn;
   1814 
   1815 	SLIST_FOREACH_SAFE(kn, list, kn_selnext, tmpkn) {
   1816 		KASSERT(kn->kn_fop != NULL);
   1817 		KASSERT(kn->kn_fop->f_event != NULL);
   1818 		if ((*kn->kn_fop->f_event)(kn, hint))
   1819 			knote_activate(kn);
   1820 	}
   1821 }
   1822 
   1823 /*
   1824  * Remove all knotes referencing a specified fd
   1825  */
   1826 void
   1827 knote_fdclose(int fd)
   1828 {
   1829 	struct klist *list;
   1830 	struct knote *kn;
   1831 	filedesc_t *fdp;
   1832 
   1833 	fdp = curlwp->l_fd;
   1834 	mutex_enter(&fdp->fd_lock);
   1835 	list = (struct klist *)&fdp->fd_dt->dt_ff[fd]->ff_knlist;
   1836 	while ((kn = SLIST_FIRST(list)) != NULL) {
   1837 		knote_detach(kn, fdp, true);
   1838 		mutex_enter(&fdp->fd_lock);
   1839 	}
   1840 	mutex_exit(&fdp->fd_lock);
   1841 }
   1842 
   1843 /*
   1844  * Drop knote.  Called with fdp->fd_lock held, and will drop before
   1845  * returning.
   1846  */
   1847 static void
   1848 knote_detach(struct knote *kn, filedesc_t *fdp, bool dofop)
   1849 {
   1850 	struct klist *list;
   1851 	struct kqueue *kq;
   1852 
   1853 	kq = kn->kn_kq;
   1854 
   1855 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1856 	KASSERT(mutex_owned(&fdp->fd_lock));
   1857 
   1858 	KASSERT(kn->kn_fop != NULL);
   1859 	/* Remove from monitored object. */
   1860 	if (dofop) {
   1861 		KASSERT(kn->kn_fop->f_detach != NULL);
   1862 		KERNEL_LOCK(1, NULL);		/* XXXSMP */
   1863 		(*kn->kn_fop->f_detach)(kn);
   1864 		KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
   1865 	}
   1866 
   1867 	/* Remove from descriptor table. */
   1868 	if (kn->kn_fop->f_isfd)
   1869 		list = (struct klist *)&fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
   1870 	else
   1871 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
   1872 
   1873 	SLIST_REMOVE(list, kn, knote, kn_link);
   1874 
   1875 	/* Remove from kqueue. */
   1876 again:
   1877 	mutex_spin_enter(&kq->kq_lock);
   1878 	if ((kn->kn_status & KN_QUEUED) != 0) {
   1879 		kq_check(kq);
   1880 		kq->kq_count--;
   1881 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   1882 		kn->kn_status &= ~KN_QUEUED;
   1883 		kq_check(kq);
   1884 	} else if (kn->kn_status & KN_BUSY) {
   1885 		mutex_spin_exit(&kq->kq_lock);
   1886 		goto again;
   1887 	}
   1888 	mutex_spin_exit(&kq->kq_lock);
   1889 
   1890 	mutex_exit(&fdp->fd_lock);
   1891 	if (kn->kn_fop->f_isfd)
   1892 		fd_putfile(kn->kn_id);
   1893 	atomic_dec_uint(&kn->kn_kfilter->refcnt);
   1894 	kmem_free(kn, sizeof(*kn));
   1895 }
   1896 
   1897 /*
   1898  * Queue new event for knote.
   1899  */
   1900 static void
   1901 knote_enqueue(struct knote *kn)
   1902 {
   1903 	struct kqueue *kq;
   1904 
   1905 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1906 
   1907 	kq = kn->kn_kq;
   1908 
   1909 	mutex_spin_enter(&kq->kq_lock);
   1910 	if ((kn->kn_status & KN_DISABLED) != 0) {
   1911 		kn->kn_status &= ~KN_DISABLED;
   1912 	}
   1913 	if ((kn->kn_status & (KN_ACTIVE | KN_QUEUED)) == KN_ACTIVE) {
   1914 		kq_check(kq);
   1915 		kn->kn_status |= KN_QUEUED;
   1916 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1917 		kq->kq_count++;
   1918 		kq_check(kq);
   1919 		cv_broadcast(&kq->kq_cv);
   1920 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   1921 	}
   1922 	mutex_spin_exit(&kq->kq_lock);
   1923 }
   1924 /*
   1925  * Queue new event for knote.
   1926  */
   1927 static void
   1928 knote_activate(struct knote *kn)
   1929 {
   1930 	struct kqueue *kq;
   1931 
   1932 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1933 
   1934 	kq = kn->kn_kq;
   1935 
   1936 	mutex_spin_enter(&kq->kq_lock);
   1937 	kn->kn_status |= KN_ACTIVE;
   1938 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) {
   1939 		kq_check(kq);
   1940 		kn->kn_status |= KN_QUEUED;
   1941 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1942 		kq->kq_count++;
   1943 		kq_check(kq);
   1944 		cv_broadcast(&kq->kq_cv);
   1945 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   1946 	}
   1947 	mutex_spin_exit(&kq->kq_lock);
   1948 }
   1949