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