Home | History | Annotate | Line # | Download | only in kern
kern_event.c revision 1.96
      1 /*	$NetBSD: kern_event.c,v 1.96 2017/10/25 08:12:39 maya 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.96 2017/10/25 08:12:39 maya 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->namelen = strlen(name) + 1;
    374 	kfilter->name = kmem_alloc(kfilter->namelen, KM_SLEEP);
    375 	memcpy(__UNCONST(kfilter->name), name, kfilter->namelen);
    376 
    377 	kfilter->filter = (kfilter - user_kfilters) + EVFILT_SYSCOUNT;
    378 
    379 	kfilter->filtops = kmem_alloc(sizeof(*filtops), KM_SLEEP);
    380 	memcpy(__UNCONST(kfilter->filtops), filtops, sizeof(*filtops));
    381 
    382 	if (retfilter != NULL)
    383 		*retfilter = kfilter->filter;
    384 	rw_exit(&kqueue_filter_lock);
    385 
    386 	return (0);
    387 }
    388 
    389 /*
    390  * Unregister a kfilter previously registered with kfilter_register.
    391  * This retains the filter id, but clears the name and frees filtops (filter
    392  * operations), so that the number isn't reused during a boot.
    393  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
    394  */
    395 int
    396 kfilter_unregister(const char *name)
    397 {
    398 	struct kfilter *kfilter;
    399 
    400 	if (name == NULL || name[0] == '\0')
    401 		return (EINVAL);	/* invalid name */
    402 
    403 	rw_enter(&kqueue_filter_lock, RW_WRITER);
    404 	if (kfilter_byname_sys(name) != NULL) {
    405 		rw_exit(&kqueue_filter_lock);
    406 		return (EINVAL);	/* can't detach system filters */
    407 	}
    408 
    409 	kfilter = kfilter_byname_user(name);
    410 	if (kfilter == NULL) {
    411 		rw_exit(&kqueue_filter_lock);
    412 		return (ENOENT);
    413 	}
    414 	if (kfilter->refcnt != 0) {
    415 		rw_exit(&kqueue_filter_lock);
    416 		return (EBUSY);
    417 	}
    418 
    419 	/* Cast away const (but we know it's safe. */
    420 	kmem_free(__UNCONST(kfilter->name), kfilter->namelen);
    421 	kfilter->name = NULL;	/* mark as `not implemented' */
    422 
    423 	if (kfilter->filtops != NULL) {
    424 		/* Cast away const (but we know it's safe. */
    425 		kmem_free(__UNCONST(kfilter->filtops),
    426 		    sizeof(*kfilter->filtops));
    427 		kfilter->filtops = NULL; /* mark as `not implemented' */
    428 	}
    429 	rw_exit(&kqueue_filter_lock);
    430 
    431 	return (0);
    432 }
    433 
    434 
    435 /*
    436  * Filter attach method for EVFILT_READ and EVFILT_WRITE on normal file
    437  * descriptors. Calls fileops kqfilter method for given file descriptor.
    438  */
    439 static int
    440 filt_fileattach(struct knote *kn)
    441 {
    442 	file_t *fp;
    443 
    444 	fp = kn->kn_obj;
    445 
    446 	return (*fp->f_ops->fo_kqfilter)(fp, kn);
    447 }
    448 
    449 /*
    450  * Filter detach method for EVFILT_READ on kqueue descriptor.
    451  */
    452 static void
    453 filt_kqdetach(struct knote *kn)
    454 {
    455 	struct kqueue *kq;
    456 
    457 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
    458 
    459 	mutex_spin_enter(&kq->kq_lock);
    460 	SLIST_REMOVE(&kq->kq_sel.sel_klist, kn, knote, kn_selnext);
    461 	mutex_spin_exit(&kq->kq_lock);
    462 }
    463 
    464 /*
    465  * Filter event method for EVFILT_READ on kqueue descriptor.
    466  */
    467 /*ARGSUSED*/
    468 static int
    469 filt_kqueue(struct knote *kn, long hint)
    470 {
    471 	struct kqueue *kq;
    472 	int rv;
    473 
    474 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
    475 
    476 	if (hint != NOTE_SUBMIT)
    477 		mutex_spin_enter(&kq->kq_lock);
    478 	kn->kn_data = kq->kq_count;
    479 	rv = (kn->kn_data > 0);
    480 	if (hint != NOTE_SUBMIT)
    481 		mutex_spin_exit(&kq->kq_lock);
    482 
    483 	return rv;
    484 }
    485 
    486 /*
    487  * Filter attach method for EVFILT_PROC.
    488  */
    489 static int
    490 filt_procattach(struct knote *kn)
    491 {
    492 	struct proc *p;
    493 	struct lwp *curl;
    494 
    495 	curl = curlwp;
    496 
    497 	mutex_enter(proc_lock);
    498 	if (kn->kn_flags & EV_FLAG1) {
    499 		/*
    500 		 * NOTE_TRACK attaches to the child process too early
    501 		 * for proc_find, so do a raw look up and check the state
    502 		 * explicitly.
    503 		 */
    504 		p = proc_find_raw(kn->kn_id);
    505 		if (p != NULL && p->p_stat != SIDL)
    506 			p = NULL;
    507 	} else {
    508 		p = proc_find(kn->kn_id);
    509 	}
    510 
    511 	if (p == NULL) {
    512 		mutex_exit(proc_lock);
    513 		return ESRCH;
    514 	}
    515 
    516 	/*
    517 	 * Fail if it's not owned by you, or the last exec gave us
    518 	 * setuid/setgid privs (unless you're root).
    519 	 */
    520 	mutex_enter(p->p_lock);
    521 	mutex_exit(proc_lock);
    522 	if (kauth_authorize_process(curl->l_cred, KAUTH_PROCESS_KEVENT_FILTER,
    523 	    p, NULL, NULL, NULL) != 0) {
    524 	    	mutex_exit(p->p_lock);
    525 		return EACCES;
    526 	}
    527 
    528 	kn->kn_obj = p;
    529 	kn->kn_flags |= EV_CLEAR;	/* automatically set */
    530 
    531 	/*
    532 	 * internal flag indicating registration done by kernel
    533 	 */
    534 	if (kn->kn_flags & EV_FLAG1) {
    535 		kn->kn_data = kn->kn_sdata;	/* ppid */
    536 		kn->kn_fflags = NOTE_CHILD;
    537 		kn->kn_flags &= ~EV_FLAG1;
    538 	}
    539 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
    540     	mutex_exit(p->p_lock);
    541 
    542 	return 0;
    543 }
    544 
    545 /*
    546  * Filter detach method for EVFILT_PROC.
    547  *
    548  * The knote may be attached to a different process, which may exit,
    549  * leaving nothing for the knote to be attached to.  So when the process
    550  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
    551  * it will be deleted when read out.  However, as part of the knote deletion,
    552  * this routine is called, so a check is needed to avoid actually performing
    553  * a detach, because the original process might not exist any more.
    554  */
    555 static void
    556 filt_procdetach(struct knote *kn)
    557 {
    558 	struct proc *p;
    559 
    560 	if (kn->kn_status & KN_DETACHED)
    561 		return;
    562 
    563 	p = kn->kn_obj;
    564 
    565 	mutex_enter(p->p_lock);
    566 	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
    567 	mutex_exit(p->p_lock);
    568 }
    569 
    570 /*
    571  * Filter event method for EVFILT_PROC.
    572  */
    573 static int
    574 filt_proc(struct knote *kn, long hint)
    575 {
    576 	u_int event, fflag;
    577 	struct kevent kev;
    578 	struct kqueue *kq;
    579 	int error;
    580 
    581 	event = (u_int)hint & NOTE_PCTRLMASK;
    582 	kq = kn->kn_kq;
    583 	fflag = 0;
    584 
    585 	/* If the user is interested in this event, record it. */
    586 	if (kn->kn_sfflags & event)
    587 		fflag |= event;
    588 
    589 	if (event == NOTE_EXIT) {
    590 		struct proc *p = kn->kn_obj;
    591 
    592 		if (p != NULL)
    593 			kn->kn_data = P_WAITSTATUS(p);
    594 		/*
    595 		 * Process is gone, so flag the event as finished.
    596 		 *
    597 		 * Detach the knote from watched process and mark
    598 		 * it as such. We can't leave this to kqueue_scan(),
    599 		 * since the process might not exist by then. And we
    600 		 * have to do this now, since psignal KNOTE() is called
    601 		 * also for zombies and we might end up reading freed
    602 		 * memory if the kevent would already be picked up
    603 		 * and knote g/c'ed.
    604 		 */
    605 		filt_procdetach(kn);
    606 
    607 		mutex_spin_enter(&kq->kq_lock);
    608 		kn->kn_status |= KN_DETACHED;
    609 		/* Mark as ONESHOT, so that the knote it g/c'ed when read */
    610 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
    611 		kn->kn_fflags |= fflag;
    612 		mutex_spin_exit(&kq->kq_lock);
    613 
    614 		return 1;
    615 	}
    616 
    617 	mutex_spin_enter(&kq->kq_lock);
    618 	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
    619 		/*
    620 		 * Process forked, and user wants to track the new process,
    621 		 * so attach a new knote to it, and immediately report an
    622 		 * event with the parent's pid.  Register knote with new
    623 		 * process.
    624 		 */
    625 		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
    626 		kev.filter = kn->kn_filter;
    627 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
    628 		kev.fflags = kn->kn_sfflags;
    629 		kev.data = kn->kn_id;			/* parent */
    630 		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
    631 		mutex_spin_exit(&kq->kq_lock);
    632 		error = kqueue_register(kq, &kev);
    633 		mutex_spin_enter(&kq->kq_lock);
    634 		if (error != 0)
    635 			kn->kn_fflags |= NOTE_TRACKERR;
    636 	}
    637 	kn->kn_fflags |= fflag;
    638 	fflag = kn->kn_fflags;
    639 	mutex_spin_exit(&kq->kq_lock);
    640 
    641 	return fflag != 0;
    642 }
    643 
    644 static void
    645 filt_timerexpire(void *knx)
    646 {
    647 	struct knote *kn = knx;
    648 	int tticks;
    649 
    650 	mutex_enter(&kqueue_misc_lock);
    651 	kn->kn_data++;
    652 	knote_activate(kn);
    653 	if ((kn->kn_flags & EV_ONESHOT) == 0) {
    654 		tticks = mstohz(kn->kn_sdata);
    655 		if (tticks <= 0)
    656 			tticks = 1;
    657 		callout_schedule((callout_t *)kn->kn_hook, tticks);
    658 	}
    659 	mutex_exit(&kqueue_misc_lock);
    660 }
    661 
    662 /*
    663  * data contains amount of time to sleep, in milliseconds
    664  */
    665 static int
    666 filt_timerattach(struct knote *kn)
    667 {
    668 	callout_t *calloutp;
    669 	struct kqueue *kq;
    670 	int tticks;
    671 
    672 	tticks = mstohz(kn->kn_sdata);
    673 
    674 	/* if the supplied value is under our resolution, use 1 tick */
    675 	if (tticks == 0) {
    676 		if (kn->kn_sdata == 0)
    677 			return EINVAL;
    678 		tticks = 1;
    679 	}
    680 
    681 	if (atomic_inc_uint_nv(&kq_ncallouts) >= kq_calloutmax ||
    682 	    (calloutp = kmem_alloc(sizeof(*calloutp), KM_NOSLEEP)) == NULL) {
    683 		atomic_dec_uint(&kq_ncallouts);
    684 		return ENOMEM;
    685 	}
    686 	callout_init(calloutp, CALLOUT_MPSAFE);
    687 
    688 	kq = kn->kn_kq;
    689 	mutex_spin_enter(&kq->kq_lock);
    690 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
    691 	kn->kn_hook = calloutp;
    692 	mutex_spin_exit(&kq->kq_lock);
    693 
    694 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
    695 
    696 	return (0);
    697 }
    698 
    699 static void
    700 filt_timerdetach(struct knote *kn)
    701 {
    702 	callout_t *calloutp;
    703 
    704 	calloutp = (callout_t *)kn->kn_hook;
    705 	callout_halt(calloutp, NULL);
    706 	callout_destroy(calloutp);
    707 	kmem_free(calloutp, sizeof(*calloutp));
    708 	atomic_dec_uint(&kq_ncallouts);
    709 }
    710 
    711 static int
    712 filt_timer(struct knote *kn, long hint)
    713 {
    714 	int rv;
    715 
    716 	mutex_enter(&kqueue_misc_lock);
    717 	rv = (kn->kn_data != 0);
    718 	mutex_exit(&kqueue_misc_lock);
    719 
    720 	return rv;
    721 }
    722 
    723 /*
    724  * filt_seltrue:
    725  *
    726  *	This filter "event" routine simulates seltrue().
    727  */
    728 int
    729 filt_seltrue(struct knote *kn, long hint)
    730 {
    731 
    732 	/*
    733 	 * We don't know how much data can be read/written,
    734 	 * but we know that it *can* be.  This is about as
    735 	 * good as select/poll does as well.
    736 	 */
    737 	kn->kn_data = 0;
    738 	return (1);
    739 }
    740 
    741 /*
    742  * This provides full kqfilter entry for device switch tables, which
    743  * has same effect as filter using filt_seltrue() as filter method.
    744  */
    745 static void
    746 filt_seltruedetach(struct knote *kn)
    747 {
    748 	/* Nothing to do */
    749 }
    750 
    751 const struct filterops seltrue_filtops = {
    752 	.f_isfd = 1,
    753 	.f_attach = NULL,
    754 	.f_detach = filt_seltruedetach,
    755 	.f_event = filt_seltrue,
    756 };
    757 
    758 int
    759 seltrue_kqfilter(dev_t dev, struct knote *kn)
    760 {
    761 	switch (kn->kn_filter) {
    762 	case EVFILT_READ:
    763 	case EVFILT_WRITE:
    764 		kn->kn_fop = &seltrue_filtops;
    765 		break;
    766 	default:
    767 		return (EINVAL);
    768 	}
    769 
    770 	/* Nothing more to do */
    771 	return (0);
    772 }
    773 
    774 /*
    775  * kqueue(2) system call.
    776  */
    777 static int
    778 kqueue1(struct lwp *l, int flags, register_t *retval)
    779 {
    780 	struct kqueue *kq;
    781 	file_t *fp;
    782 	int fd, error;
    783 
    784 	if ((error = fd_allocfile(&fp, &fd)) != 0)
    785 		return error;
    786 	fp->f_flag = FREAD | FWRITE | (flags & (FNONBLOCK|FNOSIGPIPE));
    787 	fp->f_type = DTYPE_KQUEUE;
    788 	fp->f_ops = &kqueueops;
    789 	kq = kmem_zalloc(sizeof(*kq), KM_SLEEP);
    790 	mutex_init(&kq->kq_lock, MUTEX_DEFAULT, IPL_SCHED);
    791 	cv_init(&kq->kq_cv, "kqueue");
    792 	selinit(&kq->kq_sel);
    793 	TAILQ_INIT(&kq->kq_head);
    794 	fp->f_kqueue = kq;
    795 	*retval = fd;
    796 	kq->kq_fdp = curlwp->l_fd;
    797 	fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0);
    798 	fd_affix(curproc, fp, fd);
    799 	return error;
    800 }
    801 
    802 /*
    803  * kqueue(2) system call.
    804  */
    805 int
    806 sys_kqueue(struct lwp *l, const void *v, register_t *retval)
    807 {
    808 	return kqueue1(l, 0, retval);
    809 }
    810 
    811 int
    812 sys_kqueue1(struct lwp *l, const struct sys_kqueue1_args *uap,
    813     register_t *retval)
    814 {
    815 	/* {
    816 		syscallarg(int) flags;
    817 	} */
    818 	return kqueue1(l, SCARG(uap, flags), retval);
    819 }
    820 
    821 /*
    822  * kevent(2) system call.
    823  */
    824 int
    825 kevent_fetch_changes(void *ctx, const struct kevent *changelist,
    826     struct kevent *changes, size_t index, int n)
    827 {
    828 
    829 	return copyin(changelist + index, changes, n * sizeof(*changes));
    830 }
    831 
    832 int
    833 kevent_put_events(void *ctx, struct kevent *events,
    834     struct kevent *eventlist, size_t index, int n)
    835 {
    836 
    837 	return copyout(events, eventlist + index, n * sizeof(*events));
    838 }
    839 
    840 static const struct kevent_ops kevent_native_ops = {
    841 	.keo_private = NULL,
    842 	.keo_fetch_timeout = copyin,
    843 	.keo_fetch_changes = kevent_fetch_changes,
    844 	.keo_put_events = kevent_put_events,
    845 };
    846 
    847 int
    848 sys___kevent50(struct lwp *l, const struct sys___kevent50_args *uap,
    849     register_t *retval)
    850 {
    851 	/* {
    852 		syscallarg(int) fd;
    853 		syscallarg(const struct kevent *) changelist;
    854 		syscallarg(size_t) nchanges;
    855 		syscallarg(struct kevent *) eventlist;
    856 		syscallarg(size_t) nevents;
    857 		syscallarg(const struct timespec *) timeout;
    858 	} */
    859 
    860 	return kevent1(retval, SCARG(uap, fd), SCARG(uap, changelist),
    861 	    SCARG(uap, nchanges), SCARG(uap, eventlist), SCARG(uap, nevents),
    862 	    SCARG(uap, timeout), &kevent_native_ops);
    863 }
    864 
    865 int
    866 kevent1(register_t *retval, int fd,
    867 	const struct kevent *changelist, size_t nchanges,
    868 	struct kevent *eventlist, size_t nevents,
    869 	const struct timespec *timeout,
    870 	const struct kevent_ops *keops)
    871 {
    872 	struct kevent *kevp;
    873 	struct kqueue *kq;
    874 	struct timespec	ts;
    875 	size_t i, n, ichange;
    876 	int nerrors, error;
    877 	struct kevent kevbuf[KQ_NEVENTS];	/* approx 300 bytes on 64-bit */
    878 	file_t *fp;
    879 
    880 	/* check that we're dealing with a kq */
    881 	fp = fd_getfile(fd);
    882 	if (fp == NULL)
    883 		return (EBADF);
    884 
    885 	if (fp->f_type != DTYPE_KQUEUE) {
    886 		fd_putfile(fd);
    887 		return (EBADF);
    888 	}
    889 
    890 	if (timeout != NULL) {
    891 		error = (*keops->keo_fetch_timeout)(timeout, &ts, sizeof(ts));
    892 		if (error)
    893 			goto done;
    894 		timeout = &ts;
    895 	}
    896 
    897 	kq = fp->f_kqueue;
    898 	nerrors = 0;
    899 	ichange = 0;
    900 
    901 	/* traverse list of events to register */
    902 	while (nchanges > 0) {
    903 		n = MIN(nchanges, __arraycount(kevbuf));
    904 		error = (*keops->keo_fetch_changes)(keops->keo_private,
    905 		    changelist, kevbuf, ichange, n);
    906 		if (error)
    907 			goto done;
    908 		for (i = 0; i < n; i++) {
    909 			kevp = &kevbuf[i];
    910 			kevp->flags &= ~EV_SYSFLAGS;
    911 			/* register each knote */
    912 			error = kqueue_register(kq, kevp);
    913 			if (!error && !(kevp->flags & EV_RECEIPT))
    914 				continue;
    915 			if (nevents == 0)
    916 				goto done;
    917 			kevp->flags = EV_ERROR;
    918 			kevp->data = error;
    919 			error = (*keops->keo_put_events)
    920 				(keops->keo_private, kevp,
    921 				 eventlist, nerrors, 1);
    922 			if (error)
    923 				goto done;
    924 			nevents--;
    925 			nerrors++;
    926 		}
    927 		nchanges -= n;	/* update the results */
    928 		ichange += n;
    929 	}
    930 	if (nerrors) {
    931 		*retval = nerrors;
    932 		error = 0;
    933 		goto done;
    934 	}
    935 
    936 	/* actually scan through the events */
    937 	error = kqueue_scan(fp, nevents, eventlist, timeout, retval, keops,
    938 	    kevbuf, __arraycount(kevbuf));
    939  done:
    940 	fd_putfile(fd);
    941 	return (error);
    942 }
    943 
    944 /*
    945  * Register a given kevent kev onto the kqueue
    946  */
    947 static int
    948 kqueue_register(struct kqueue *kq, struct kevent *kev)
    949 {
    950 	struct kfilter *kfilter;
    951 	filedesc_t *fdp;
    952 	file_t *fp;
    953 	fdfile_t *ff;
    954 	struct knote *kn, *newkn;
    955 	struct klist *list;
    956 	int error, fd, rv;
    957 
    958 	fdp = kq->kq_fdp;
    959 	fp = NULL;
    960 	kn = NULL;
    961 	error = 0;
    962 	fd = 0;
    963 
    964 	newkn = kmem_zalloc(sizeof(*newkn), KM_SLEEP);
    965 
    966 	rw_enter(&kqueue_filter_lock, RW_READER);
    967 	kfilter = kfilter_byfilter(kev->filter);
    968 	if (kfilter == NULL || kfilter->filtops == NULL) {
    969 		/* filter not found nor implemented */
    970 		rw_exit(&kqueue_filter_lock);
    971 		kmem_free(newkn, sizeof(*newkn));
    972 		return (EINVAL);
    973 	}
    974 
    975 	/* search if knote already exists */
    976 	if (kfilter->filtops->f_isfd) {
    977 		/* monitoring a file descriptor */
    978 		/* validate descriptor */
    979 		if (kev->ident > INT_MAX
    980 		    || (fp = fd_getfile(fd = kev->ident)) == NULL) {
    981 			rw_exit(&kqueue_filter_lock);
    982 			kmem_free(newkn, sizeof(*newkn));
    983 			return EBADF;
    984 		}
    985 		mutex_enter(&fdp->fd_lock);
    986 		ff = fdp->fd_dt->dt_ff[fd];
    987 		if (fd <= fdp->fd_lastkqfile) {
    988 			SLIST_FOREACH(kn, &ff->ff_knlist, kn_link) {
    989 				if (kq == kn->kn_kq &&
    990 				    kev->filter == kn->kn_filter)
    991 					break;
    992 			}
    993 		}
    994 	} else {
    995 		/*
    996 		 * not monitoring a file descriptor, so
    997 		 * lookup knotes in internal hash table
    998 		 */
    999 		mutex_enter(&fdp->fd_lock);
   1000 		if (fdp->fd_knhashmask != 0) {
   1001 			list = &fdp->fd_knhash[
   1002 			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
   1003 			SLIST_FOREACH(kn, list, kn_link) {
   1004 				if (kev->ident == kn->kn_id &&
   1005 				    kq == kn->kn_kq &&
   1006 				    kev->filter == kn->kn_filter)
   1007 					break;
   1008 			}
   1009 		}
   1010 	}
   1011 
   1012 	/*
   1013 	 * kn now contains the matching knote, or NULL if no match
   1014 	 */
   1015 	if (kev->flags & EV_ADD) {
   1016 		if (kn == NULL) {
   1017 			/* create new knote */
   1018 			kn = newkn;
   1019 			newkn = NULL;
   1020 			kn->kn_obj = fp;
   1021 			kn->kn_id = kev->ident;
   1022 			kn->kn_kq = kq;
   1023 			kn->kn_fop = kfilter->filtops;
   1024 			kn->kn_kfilter = kfilter;
   1025 			kn->kn_sfflags = kev->fflags;
   1026 			kn->kn_sdata = kev->data;
   1027 			kev->fflags = 0;
   1028 			kev->data = 0;
   1029 			kn->kn_kevent = *kev;
   1030 
   1031 			KASSERT(kn->kn_fop != NULL);
   1032 			/*
   1033 			 * apply reference count to knote structure, and
   1034 			 * do not release it at the end of this routine.
   1035 			 */
   1036 			fp = NULL;
   1037 
   1038 			if (!kn->kn_fop->f_isfd) {
   1039 				/*
   1040 				 * If knote is not on an fd, store on
   1041 				 * internal hash table.
   1042 				 */
   1043 				if (fdp->fd_knhashmask == 0) {
   1044 					/* XXXAD can block with fd_lock held */
   1045 					fdp->fd_knhash = hashinit(KN_HASHSIZE,
   1046 					    HASH_LIST, true,
   1047 					    &fdp->fd_knhashmask);
   1048 				}
   1049 				list = &fdp->fd_knhash[KN_HASH(kn->kn_id,
   1050 				    fdp->fd_knhashmask)];
   1051 			} else {
   1052 				/* Otherwise, knote is on an fd. */
   1053 				list = (struct klist *)
   1054 				    &fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
   1055 				if ((int)kn->kn_id > fdp->fd_lastkqfile)
   1056 					fdp->fd_lastkqfile = kn->kn_id;
   1057 			}
   1058 			SLIST_INSERT_HEAD(list, kn, kn_link);
   1059 
   1060 			KERNEL_LOCK(1, NULL);		/* XXXSMP */
   1061 			error = (*kfilter->filtops->f_attach)(kn);
   1062 			KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
   1063 			if (error != 0) {
   1064 #ifdef DIAGNOSTIC
   1065 				printf("%s: event type %d not supported for "
   1066 				    "file type %d (error %d)\n", __func__,
   1067 				    kn->kn_filter, kn->kn_obj ?
   1068 				    ((file_t *)kn->kn_obj)->f_type : -1, error);
   1069 #endif
   1070 				/* knote_detach() drops fdp->fd_lock */
   1071 				knote_detach(kn, fdp, false);
   1072 				goto done;
   1073 			}
   1074 			atomic_inc_uint(&kfilter->refcnt);
   1075 		} else {
   1076 			/*
   1077 			 * The user may change some filter values after the
   1078 			 * initial EV_ADD, but doing so will not reset any
   1079 			 * filter which have already been triggered.
   1080 			 */
   1081 			kn->kn_sfflags = kev->fflags;
   1082 			kn->kn_sdata = kev->data;
   1083 			kn->kn_kevent.udata = kev->udata;
   1084 		}
   1085 		/*
   1086 		 * We can get here if we are trying to attach
   1087 		 * an event to a file descriptor that does not
   1088 		 * support events, and the attach routine is
   1089 		 * broken and does not return an error.
   1090 		 */
   1091 		KASSERT(kn->kn_fop != NULL);
   1092 		KASSERT(kn->kn_fop->f_event != NULL);
   1093 		KERNEL_LOCK(1, NULL);			/* XXXSMP */
   1094 		rv = (*kn->kn_fop->f_event)(kn, 0);
   1095 		KERNEL_UNLOCK_ONE(NULL);		/* XXXSMP */
   1096 		if (rv)
   1097 			knote_activate(kn);
   1098 	} else {
   1099 		if (kn == NULL) {
   1100 			error = ENOENT;
   1101 		 	mutex_exit(&fdp->fd_lock);
   1102 			goto done;
   1103 		}
   1104 		if (kev->flags & EV_DELETE) {
   1105 			/* knote_detach() drops fdp->fd_lock */
   1106 			knote_detach(kn, fdp, true);
   1107 			goto done;
   1108 		}
   1109 	}
   1110 
   1111 	/* disable knote */
   1112 	if ((kev->flags & EV_DISABLE)) {
   1113 		mutex_spin_enter(&kq->kq_lock);
   1114 		if ((kn->kn_status & KN_DISABLED) == 0)
   1115 			kn->kn_status |= KN_DISABLED;
   1116 		mutex_spin_exit(&kq->kq_lock);
   1117 	}
   1118 
   1119 	/* enable knote */
   1120 	if ((kev->flags & EV_ENABLE)) {
   1121 		knote_enqueue(kn);
   1122 	}
   1123 	mutex_exit(&fdp->fd_lock);
   1124  done:
   1125 	rw_exit(&kqueue_filter_lock);
   1126 	if (newkn != NULL)
   1127 		kmem_free(newkn, sizeof(*newkn));
   1128 	if (fp != NULL)
   1129 		fd_putfile(fd);
   1130 	return (error);
   1131 }
   1132 
   1133 #if defined(DEBUG)
   1134 #define KN_FMT(buf, kn) \
   1135     (snprintb((buf), sizeof(buf), __KN_FLAG_BITS, (kn)->kn_status), buf)
   1136 
   1137 static void
   1138 kqueue_check(const char *func, size_t line, const struct kqueue *kq)
   1139 {
   1140 	const struct knote *kn;
   1141 	int count;
   1142 	int nmarker;
   1143 	char buf[128];
   1144 
   1145 	KASSERT(mutex_owned(&kq->kq_lock));
   1146 	KASSERT(kq->kq_count >= 0);
   1147 
   1148 	count = 0;
   1149 	nmarker = 0;
   1150 	TAILQ_FOREACH(kn, &kq->kq_head, kn_tqe) {
   1151 		if ((kn->kn_status & (KN_MARKER | KN_QUEUED)) == 0) {
   1152 			panic("%s,%zu: kq=%p kn=%p !(MARKER|QUEUED) %s",
   1153 			    func, line, kq, kn, KN_FMT(buf, kn));
   1154 		}
   1155 		if ((kn->kn_status & KN_MARKER) == 0) {
   1156 			if (kn->kn_kq != kq) {
   1157 				panic("%s,%zu: kq=%p kn(%p) != kn->kq(%p): %s",
   1158 				    func, line, kq, kn, kn->kn_kq,
   1159 				    KN_FMT(buf, kn));
   1160 			}
   1161 			if ((kn->kn_status & KN_ACTIVE) == 0) {
   1162 				panic("%s,%zu: kq=%p kn=%p: !ACTIVE %s",
   1163 				    func, line, kq, kn, KN_FMT(buf, kn));
   1164 			}
   1165 			count++;
   1166 			if (count > kq->kq_count) {
   1167 				goto bad;
   1168 			}
   1169 		} else {
   1170 			nmarker++;
   1171 #if 0
   1172 			if (nmarker > 10000) {
   1173 				panic("%s,%zu: kq=%p too many markers: "
   1174 				    "%d != %d, nmarker=%d",
   1175 				    func, line, kq, kq->kq_count, count,
   1176 				    nmarker);
   1177 			}
   1178 #endif
   1179 		}
   1180 	}
   1181 	if (kq->kq_count != count) {
   1182 bad:
   1183 		panic("%s,%zu: kq=%p kq->kq_count(%d) != count(%d), nmarker=%d",
   1184 		    func, line, kq, kq->kq_count, count, nmarker);
   1185 	}
   1186 }
   1187 #define kq_check(a) kqueue_check(__func__, __LINE__, (a))
   1188 #else /* defined(DEBUG) */
   1189 #define	kq_check(a)	/* nothing */
   1190 #endif /* defined(DEBUG) */
   1191 
   1192 /*
   1193  * Scan through the list of events on fp (for a maximum of maxevents),
   1194  * returning the results in to ulistp. Timeout is determined by tsp; if
   1195  * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
   1196  * as appropriate.
   1197  */
   1198 static int
   1199 kqueue_scan(file_t *fp, size_t maxevents, struct kevent *ulistp,
   1200 	    const struct timespec *tsp, register_t *retval,
   1201 	    const struct kevent_ops *keops, struct kevent *kevbuf,
   1202 	    size_t kevcnt)
   1203 {
   1204 	struct kqueue	*kq;
   1205 	struct kevent	*kevp;
   1206 	struct timespec	ats, sleepts;
   1207 	struct knote	*kn, *marker, morker;
   1208 	size_t		count, nkev, nevents;
   1209 	int		timeout, error, rv;
   1210 	filedesc_t	*fdp;
   1211 
   1212 	fdp = curlwp->l_fd;
   1213 	kq = fp->f_kqueue;
   1214 	count = maxevents;
   1215 	nkev = nevents = error = 0;
   1216 	if (count == 0) {
   1217 		*retval = 0;
   1218 		return 0;
   1219 	}
   1220 
   1221 	if (tsp) {				/* timeout supplied */
   1222 		ats = *tsp;
   1223 		if (inittimeleft(&ats, &sleepts) == -1) {
   1224 			*retval = maxevents;
   1225 			return EINVAL;
   1226 		}
   1227 		timeout = tstohz(&ats);
   1228 		if (timeout <= 0)
   1229 			timeout = -1;           /* do poll */
   1230 	} else {
   1231 		/* no timeout, wait forever */
   1232 		timeout = 0;
   1233 	}
   1234 
   1235 	memset(&morker, 0, sizeof(morker));
   1236 	marker = &morker;
   1237 	marker->kn_status = KN_MARKER;
   1238 	mutex_spin_enter(&kq->kq_lock);
   1239  retry:
   1240 	kevp = kevbuf;
   1241 	if (kq->kq_count == 0) {
   1242 		if (timeout >= 0) {
   1243 			error = cv_timedwait_sig(&kq->kq_cv,
   1244 			    &kq->kq_lock, timeout);
   1245 			if (error == 0) {
   1246 				 if (tsp == NULL || (timeout =
   1247 				     gettimeleft(&ats, &sleepts)) > 0)
   1248 					goto retry;
   1249 			} else {
   1250 				/* don't restart after signals... */
   1251 				if (error == ERESTART)
   1252 					error = EINTR;
   1253 				if (error == EWOULDBLOCK)
   1254 					error = 0;
   1255 			}
   1256 		}
   1257 		mutex_spin_exit(&kq->kq_lock);
   1258 	} else {
   1259 		/* mark end of knote list */
   1260 		TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
   1261 
   1262 		/*
   1263 		 * Acquire the fdp->fd_lock interlock to avoid races with
   1264 		 * file creation/destruction from other threads.
   1265 		 */
   1266 		mutex_spin_exit(&kq->kq_lock);
   1267 		mutex_enter(&fdp->fd_lock);
   1268 		mutex_spin_enter(&kq->kq_lock);
   1269 
   1270 		while (count != 0) {
   1271 			kn = TAILQ_FIRST(&kq->kq_head);	/* get next knote */
   1272 			while ((kn->kn_status & KN_MARKER) != 0) {
   1273 				if (kn == marker) {
   1274 					/* it's our marker, stop */
   1275 					TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   1276 					if (count < maxevents || (tsp != NULL &&
   1277 					    (timeout = gettimeleft(&ats,
   1278 					    &sleepts)) <= 0))
   1279 						goto done;
   1280 					mutex_exit(&fdp->fd_lock);
   1281 					goto retry;
   1282 				}
   1283 				/* someone else's marker. */
   1284 				kn = TAILQ_NEXT(kn, kn_tqe);
   1285 			}
   1286 			kq_check(kq);
   1287 			kq->kq_count--;
   1288 			TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   1289 			kn->kn_status &= ~KN_QUEUED;
   1290 			kn->kn_status |= KN_BUSY;
   1291 			kq_check(kq);
   1292 			if (kn->kn_status & KN_DISABLED) {
   1293 				kn->kn_status &= ~KN_BUSY;
   1294 				/* don't want disabled events */
   1295 				continue;
   1296 			}
   1297 			if ((kn->kn_flags & EV_ONESHOT) == 0) {
   1298 				mutex_spin_exit(&kq->kq_lock);
   1299 				KASSERT(kn->kn_fop != NULL);
   1300 				KASSERT(kn->kn_fop->f_event != NULL);
   1301 				KERNEL_LOCK(1, NULL);		/* XXXSMP */
   1302 				KASSERT(mutex_owned(&fdp->fd_lock));
   1303 				rv = (*kn->kn_fop->f_event)(kn, 0);
   1304 				KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
   1305 				mutex_spin_enter(&kq->kq_lock);
   1306 				/* Re-poll if note was re-enqueued. */
   1307 				if ((kn->kn_status & KN_QUEUED) != 0) {
   1308 					kn->kn_status &= ~KN_BUSY;
   1309 					continue;
   1310 				}
   1311 				if (rv == 0) {
   1312 					/*
   1313 					 * non-ONESHOT event that hasn't
   1314 					 * triggered again, so de-queue.
   1315 					 */
   1316 					kn->kn_status &= ~(KN_ACTIVE|KN_BUSY);
   1317 					continue;
   1318 				}
   1319 			}
   1320 			/* XXXAD should be got from f_event if !oneshot. */
   1321 			*kevp++ = kn->kn_kevent;
   1322 			nkev++;
   1323 			if (kn->kn_flags & EV_ONESHOT) {
   1324 				/* delete ONESHOT events after retrieval */
   1325 				kn->kn_status &= ~KN_BUSY;
   1326 				mutex_spin_exit(&kq->kq_lock);
   1327 				knote_detach(kn, fdp, true);
   1328 				mutex_enter(&fdp->fd_lock);
   1329 				mutex_spin_enter(&kq->kq_lock);
   1330 			} else if (kn->kn_flags & EV_CLEAR) {
   1331 				/* clear state after retrieval */
   1332 				kn->kn_data = 0;
   1333 				kn->kn_fflags = 0;
   1334 				kn->kn_status &= ~(KN_QUEUED|KN_ACTIVE|KN_BUSY);
   1335 			} else if (kn->kn_flags & EV_DISPATCH) {
   1336 				kn->kn_status |= KN_DISABLED;
   1337 				kn->kn_status &= ~(KN_QUEUED|KN_ACTIVE|KN_BUSY);
   1338 			} else {
   1339 				/* add event back on list */
   1340 				kq_check(kq);
   1341 				kn->kn_status |= KN_QUEUED;
   1342 				kn->kn_status &= ~KN_BUSY;
   1343 				TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1344 				kq->kq_count++;
   1345 				kq_check(kq);
   1346 			}
   1347 			if (nkev == kevcnt) {
   1348 				/* do copyouts in kevcnt chunks */
   1349 				mutex_spin_exit(&kq->kq_lock);
   1350 				mutex_exit(&fdp->fd_lock);
   1351 				error = (*keops->keo_put_events)
   1352 				    (keops->keo_private,
   1353 				    kevbuf, ulistp, nevents, nkev);
   1354 				mutex_enter(&fdp->fd_lock);
   1355 				mutex_spin_enter(&kq->kq_lock);
   1356 				nevents += nkev;
   1357 				nkev = 0;
   1358 				kevp = kevbuf;
   1359 			}
   1360 			count--;
   1361 			if (error != 0 || count == 0) {
   1362 				/* remove marker */
   1363 				TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
   1364 				break;
   1365 			}
   1366 		}
   1367  done:
   1368 		mutex_spin_exit(&kq->kq_lock);
   1369 		mutex_exit(&fdp->fd_lock);
   1370 	}
   1371 	if (nkev != 0) {
   1372 		/* copyout remaining events */
   1373 		error = (*keops->keo_put_events)(keops->keo_private,
   1374 		    kevbuf, ulistp, nevents, nkev);
   1375 	}
   1376 	*retval = maxevents - count;
   1377 
   1378 	return error;
   1379 }
   1380 
   1381 /*
   1382  * fileops ioctl method for a kqueue descriptor.
   1383  *
   1384  * Two ioctls are currently supported. They both use struct kfilter_mapping:
   1385  *	KFILTER_BYNAME		find name for filter, and return result in
   1386  *				name, which is of size len.
   1387  *	KFILTER_BYFILTER	find filter for name. len is ignored.
   1388  */
   1389 /*ARGSUSED*/
   1390 static int
   1391 kqueue_ioctl(file_t *fp, u_long com, void *data)
   1392 {
   1393 	struct kfilter_mapping	*km;
   1394 	const struct kfilter	*kfilter;
   1395 	char			*name;
   1396 	int			error;
   1397 
   1398 	km = data;
   1399 	error = 0;
   1400 	name = kmem_alloc(KFILTER_MAXNAME, KM_SLEEP);
   1401 
   1402 	switch (com) {
   1403 	case KFILTER_BYFILTER:	/* convert filter -> name */
   1404 		rw_enter(&kqueue_filter_lock, RW_READER);
   1405 		kfilter = kfilter_byfilter(km->filter);
   1406 		if (kfilter != NULL) {
   1407 			strlcpy(name, kfilter->name, KFILTER_MAXNAME);
   1408 			rw_exit(&kqueue_filter_lock);
   1409 			error = copyoutstr(name, km->name, km->len, NULL);
   1410 		} else {
   1411 			rw_exit(&kqueue_filter_lock);
   1412 			error = ENOENT;
   1413 		}
   1414 		break;
   1415 
   1416 	case KFILTER_BYNAME:	/* convert name -> filter */
   1417 		error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
   1418 		if (error) {
   1419 			break;
   1420 		}
   1421 		rw_enter(&kqueue_filter_lock, RW_READER);
   1422 		kfilter = kfilter_byname(name);
   1423 		if (kfilter != NULL)
   1424 			km->filter = kfilter->filter;
   1425 		else
   1426 			error = ENOENT;
   1427 		rw_exit(&kqueue_filter_lock);
   1428 		break;
   1429 
   1430 	default:
   1431 		error = ENOTTY;
   1432 		break;
   1433 
   1434 	}
   1435 	kmem_free(name, KFILTER_MAXNAME);
   1436 	return (error);
   1437 }
   1438 
   1439 /*
   1440  * fileops fcntl method for a kqueue descriptor.
   1441  */
   1442 static int
   1443 kqueue_fcntl(file_t *fp, u_int com, void *data)
   1444 {
   1445 
   1446 	return (ENOTTY);
   1447 }
   1448 
   1449 /*
   1450  * fileops poll method for a kqueue descriptor.
   1451  * Determine if kqueue has events pending.
   1452  */
   1453 static int
   1454 kqueue_poll(file_t *fp, int events)
   1455 {
   1456 	struct kqueue	*kq;
   1457 	int		revents;
   1458 
   1459 	kq = fp->f_kqueue;
   1460 
   1461 	revents = 0;
   1462 	if (events & (POLLIN | POLLRDNORM)) {
   1463 		mutex_spin_enter(&kq->kq_lock);
   1464 		if (kq->kq_count != 0) {
   1465 			revents |= events & (POLLIN | POLLRDNORM);
   1466 		} else {
   1467 			selrecord(curlwp, &kq->kq_sel);
   1468 		}
   1469 		kq_check(kq);
   1470 		mutex_spin_exit(&kq->kq_lock);
   1471 	}
   1472 
   1473 	return revents;
   1474 }
   1475 
   1476 /*
   1477  * fileops stat method for a kqueue descriptor.
   1478  * Returns dummy info, with st_size being number of events pending.
   1479  */
   1480 static int
   1481 kqueue_stat(file_t *fp, struct stat *st)
   1482 {
   1483 	struct kqueue *kq;
   1484 
   1485 	kq = fp->f_kqueue;
   1486 
   1487 	memset(st, 0, sizeof(*st));
   1488 	st->st_size = kq->kq_count;
   1489 	st->st_blksize = sizeof(struct kevent);
   1490 	st->st_mode = S_IFIFO;
   1491 
   1492 	return 0;
   1493 }
   1494 
   1495 static void
   1496 kqueue_doclose(struct kqueue *kq, struct klist *list, int fd)
   1497 {
   1498 	struct knote *kn;
   1499 	filedesc_t *fdp;
   1500 
   1501 	fdp = kq->kq_fdp;
   1502 
   1503 	KASSERT(mutex_owned(&fdp->fd_lock));
   1504 
   1505 	for (kn = SLIST_FIRST(list); kn != NULL;) {
   1506 		if (kq != kn->kn_kq) {
   1507 			kn = SLIST_NEXT(kn, kn_link);
   1508 			continue;
   1509 		}
   1510 		knote_detach(kn, fdp, true);
   1511 		mutex_enter(&fdp->fd_lock);
   1512 		kn = SLIST_FIRST(list);
   1513 	}
   1514 }
   1515 
   1516 
   1517 /*
   1518  * fileops close method for a kqueue descriptor.
   1519  */
   1520 static int
   1521 kqueue_close(file_t *fp)
   1522 {
   1523 	struct kqueue *kq;
   1524 	filedesc_t *fdp;
   1525 	fdfile_t *ff;
   1526 	int i;
   1527 
   1528 	kq = fp->f_kqueue;
   1529 	fp->f_kqueue = NULL;
   1530 	fp->f_type = 0;
   1531 	fdp = curlwp->l_fd;
   1532 
   1533 	mutex_enter(&fdp->fd_lock);
   1534 	for (i = 0; i <= fdp->fd_lastkqfile; i++) {
   1535 		if ((ff = fdp->fd_dt->dt_ff[i]) == NULL)
   1536 			continue;
   1537 		kqueue_doclose(kq, (struct klist *)&ff->ff_knlist, i);
   1538 	}
   1539 	if (fdp->fd_knhashmask != 0) {
   1540 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
   1541 			kqueue_doclose(kq, &fdp->fd_knhash[i], -1);
   1542 		}
   1543 	}
   1544 	mutex_exit(&fdp->fd_lock);
   1545 
   1546 	KASSERT(kq->kq_count == 0);
   1547 	mutex_destroy(&kq->kq_lock);
   1548 	cv_destroy(&kq->kq_cv);
   1549 	seldestroy(&kq->kq_sel);
   1550 	kmem_free(kq, sizeof(*kq));
   1551 
   1552 	return (0);
   1553 }
   1554 
   1555 /*
   1556  * struct fileops kqfilter method for a kqueue descriptor.
   1557  * Event triggered when monitored kqueue changes.
   1558  */
   1559 static int
   1560 kqueue_kqfilter(file_t *fp, struct knote *kn)
   1561 {
   1562 	struct kqueue *kq;
   1563 
   1564 	kq = ((file_t *)kn->kn_obj)->f_kqueue;
   1565 
   1566 	KASSERT(fp == kn->kn_obj);
   1567 
   1568 	if (kn->kn_filter != EVFILT_READ)
   1569 		return 1;
   1570 
   1571 	kn->kn_fop = &kqread_filtops;
   1572 	mutex_enter(&kq->kq_lock);
   1573 	SLIST_INSERT_HEAD(&kq->kq_sel.sel_klist, kn, kn_selnext);
   1574 	mutex_exit(&kq->kq_lock);
   1575 
   1576 	return 0;
   1577 }
   1578 
   1579 
   1580 /*
   1581  * Walk down a list of knotes, activating them if their event has
   1582  * triggered.  The caller's object lock (e.g. device driver lock)
   1583  * must be held.
   1584  */
   1585 void
   1586 knote(struct klist *list, long hint)
   1587 {
   1588 	struct knote *kn, *tmpkn;
   1589 
   1590 	SLIST_FOREACH_SAFE(kn, list, kn_selnext, tmpkn) {
   1591 		KASSERT(kn->kn_fop != NULL);
   1592 		KASSERT(kn->kn_fop->f_event != NULL);
   1593 		if ((*kn->kn_fop->f_event)(kn, hint))
   1594 			knote_activate(kn);
   1595 	}
   1596 }
   1597 
   1598 /*
   1599  * Remove all knotes referencing a specified fd
   1600  */
   1601 void
   1602 knote_fdclose(int fd)
   1603 {
   1604 	struct klist *list;
   1605 	struct knote *kn;
   1606 	filedesc_t *fdp;
   1607 
   1608 	fdp = curlwp->l_fd;
   1609 	list = (struct klist *)&fdp->fd_dt->dt_ff[fd]->ff_knlist;
   1610 	mutex_enter(&fdp->fd_lock);
   1611 	while ((kn = SLIST_FIRST(list)) != NULL) {
   1612 		knote_detach(kn, fdp, true);
   1613 		mutex_enter(&fdp->fd_lock);
   1614 	}
   1615 	mutex_exit(&fdp->fd_lock);
   1616 }
   1617 
   1618 /*
   1619  * Drop knote.  Called with fdp->fd_lock held, and will drop before
   1620  * returning.
   1621  */
   1622 static void
   1623 knote_detach(struct knote *kn, filedesc_t *fdp, bool dofop)
   1624 {
   1625 	struct klist *list;
   1626 	struct kqueue *kq;
   1627 
   1628 	kq = kn->kn_kq;
   1629 
   1630 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1631 	KASSERT(mutex_owned(&fdp->fd_lock));
   1632 
   1633 	KASSERT(kn->kn_fop != NULL);
   1634 	/* Remove from monitored object. */
   1635 	if (dofop) {
   1636 		KASSERT(kn->kn_fop->f_detach != NULL);
   1637 		KERNEL_LOCK(1, NULL);		/* XXXSMP */
   1638 		(*kn->kn_fop->f_detach)(kn);
   1639 		KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
   1640 	}
   1641 
   1642 	/* Remove from descriptor table. */
   1643 	if (kn->kn_fop->f_isfd)
   1644 		list = (struct klist *)&fdp->fd_dt->dt_ff[kn->kn_id]->ff_knlist;
   1645 	else
   1646 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
   1647 
   1648 	SLIST_REMOVE(list, kn, knote, kn_link);
   1649 
   1650 	/* Remove from kqueue. */
   1651 again:
   1652 	mutex_spin_enter(&kq->kq_lock);
   1653 	if ((kn->kn_status & KN_QUEUED) != 0) {
   1654 		kq_check(kq);
   1655 		kq->kq_count--;
   1656 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
   1657 		kn->kn_status &= ~KN_QUEUED;
   1658 		kq_check(kq);
   1659 	} else if (kn->kn_status & KN_BUSY) {
   1660 		mutex_spin_exit(&kq->kq_lock);
   1661 		goto again;
   1662 	}
   1663 	mutex_spin_exit(&kq->kq_lock);
   1664 
   1665 	mutex_exit(&fdp->fd_lock);
   1666 	if (kn->kn_fop->f_isfd)
   1667 		fd_putfile(kn->kn_id);
   1668 	atomic_dec_uint(&kn->kn_kfilter->refcnt);
   1669 	kmem_free(kn, sizeof(*kn));
   1670 }
   1671 
   1672 /*
   1673  * Queue new event for knote.
   1674  */
   1675 static void
   1676 knote_enqueue(struct knote *kn)
   1677 {
   1678 	struct kqueue *kq;
   1679 
   1680 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1681 
   1682 	kq = kn->kn_kq;
   1683 
   1684 	mutex_spin_enter(&kq->kq_lock);
   1685 	if ((kn->kn_status & KN_DISABLED) != 0) {
   1686 		kn->kn_status &= ~KN_DISABLED;
   1687 	}
   1688 	if ((kn->kn_status & (KN_ACTIVE | KN_QUEUED)) == KN_ACTIVE) {
   1689 		kq_check(kq);
   1690 		kn->kn_status |= KN_QUEUED;
   1691 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1692 		kq->kq_count++;
   1693 		kq_check(kq);
   1694 		cv_broadcast(&kq->kq_cv);
   1695 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   1696 	}
   1697 	mutex_spin_exit(&kq->kq_lock);
   1698 }
   1699 /*
   1700  * Queue new event for knote.
   1701  */
   1702 static void
   1703 knote_activate(struct knote *kn)
   1704 {
   1705 	struct kqueue *kq;
   1706 
   1707 	KASSERT((kn->kn_status & KN_MARKER) == 0);
   1708 
   1709 	kq = kn->kn_kq;
   1710 
   1711 	mutex_spin_enter(&kq->kq_lock);
   1712 	kn->kn_status |= KN_ACTIVE;
   1713 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) {
   1714 		kq_check(kq);
   1715 		kn->kn_status |= KN_QUEUED;
   1716 		TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
   1717 		kq->kq_count++;
   1718 		kq_check(kq);
   1719 		cv_broadcast(&kq->kq_cv);
   1720 		selnotify(&kq->kq_sel, 0, NOTE_SUBMIT);
   1721 	}
   1722 	mutex_spin_exit(&kq->kq_lock);
   1723 }
   1724