xref: /netbsd-src/sys/kern/kern_event.c (revision 267197ec1eebfcb9810ea27a89625b6ddf68e3e7)
1 /*	$NetBSD: kern_event.c,v 1.46 2008/01/23 15:04:39 elad Exp $	*/
2 
3 /*-
4  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD: src/sys/kern/kern_event.c,v 1.27 2001/07/05 17:10:44 rwatson Exp $
29  */
30 
31 #include <sys/cdefs.h>
32 __KERNEL_RCSID(0, "$NetBSD: kern_event.c,v 1.46 2008/01/23 15:04:39 elad Exp $");
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/proc.h>
38 #include <sys/malloc.h>
39 #include <sys/unistd.h>
40 #include <sys/file.h>
41 #include <sys/fcntl.h>
42 #include <sys/select.h>
43 #include <sys/queue.h>
44 #include <sys/event.h>
45 #include <sys/eventvar.h>
46 #include <sys/poll.h>
47 #include <sys/pool.h>
48 #include <sys/protosw.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/stat.h>
52 #include <sys/uio.h>
53 #include <sys/mount.h>
54 #include <sys/filedesc.h>
55 #include <sys/syscallargs.h>
56 #include <sys/kauth.h>
57 #include <sys/conf.h>
58 
59 static void	kqueue_wakeup(struct kqueue *kq);
60 
61 static int	kqueue_scan(struct file *, size_t, struct kevent *,
62     const struct timespec *, struct lwp *, register_t *,
63     const struct kevent_ops *);
64 static int	kqueue_read(struct file *fp, off_t *offset, struct uio *uio,
65 		    kauth_cred_t cred, int flags);
66 static int	kqueue_write(struct file *fp, off_t *offset, struct uio *uio,
67 		    kauth_cred_t cred, int flags);
68 static int	kqueue_ioctl(struct file *fp, u_long com, void *data,
69 		    struct lwp *l);
70 static int	kqueue_fcntl(struct file *fp, u_int com, void *data,
71 		    struct lwp *l);
72 static int	kqueue_poll(struct file *fp, int events, struct lwp *l);
73 static int	kqueue_kqfilter(struct file *fp, struct knote *kn);
74 static int	kqueue_stat(struct file *fp, struct stat *sp, struct lwp *l);
75 static int	kqueue_close(struct file *fp, struct lwp *l);
76 
77 static const struct fileops kqueueops = {
78 	kqueue_read, kqueue_write, kqueue_ioctl, kqueue_fcntl, kqueue_poll,
79 	kqueue_stat, kqueue_close, kqueue_kqfilter
80 };
81 
82 static void	knote_attach(struct knote *kn, struct filedesc *fdp);
83 static void	knote_drop(struct knote *kn, struct lwp *l,
84 		    struct filedesc *fdp);
85 static void	knote_enqueue(struct knote *kn);
86 static void	knote_dequeue(struct knote *kn);
87 
88 static void	filt_kqdetach(struct knote *kn);
89 static int	filt_kqueue(struct knote *kn, long hint);
90 static int	filt_procattach(struct knote *kn);
91 static void	filt_procdetach(struct knote *kn);
92 static int	filt_proc(struct knote *kn, long hint);
93 static int	filt_fileattach(struct knote *kn);
94 static void	filt_timerexpire(void *knx);
95 static int	filt_timerattach(struct knote *kn);
96 static void	filt_timerdetach(struct knote *kn);
97 static int	filt_timer(struct knote *kn, long hint);
98 
99 static const struct filterops kqread_filtops =
100 	{ 1, NULL, filt_kqdetach, filt_kqueue };
101 static const struct filterops proc_filtops =
102 	{ 0, filt_procattach, filt_procdetach, filt_proc };
103 static const struct filterops file_filtops =
104 	{ 1, filt_fileattach, NULL, NULL };
105 static const struct filterops timer_filtops =
106 	{ 0, filt_timerattach, filt_timerdetach, filt_timer };
107 
108 static POOL_INIT(kqueue_pool, sizeof(struct kqueue), 0, 0, 0, "kqueuepl", NULL,
109     IPL_VM);
110 static POOL_INIT(knote_pool, sizeof(struct knote), 0, 0, 0, "knotepl", NULL,
111     IPL_VM);
112 static int	kq_ncallouts = 0;
113 static int	kq_calloutmax = (4 * 1024);
114 
115 MALLOC_DEFINE(M_KEVENT, "kevent", "kevents/knotes");
116 
117 #define	KNOTE_ACTIVATE(kn)						\
118 do {									\
119 	kn->kn_status |= KN_ACTIVE;					\
120 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
121 		knote_enqueue(kn);					\
122 } while(0)
123 
124 #define	KN_HASHSIZE		64		/* XXX should be tunable */
125 #define	KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
126 
127 extern const struct filterops sig_filtops;
128 
129 /*
130  * Table for for all system-defined filters.
131  * These should be listed in the numeric order of the EVFILT_* defines.
132  * If filtops is NULL, the filter isn't implemented in NetBSD.
133  * End of list is when name is NULL.
134  */
135 struct kfilter {
136 	const char	 *name;		/* name of filter */
137 	uint32_t	  filter;	/* id of filter */
138 	const struct filterops *filtops;/* operations for filter */
139 };
140 
141 		/* System defined filters */
142 static const struct kfilter sys_kfilters[] = {
143 	{ "EVFILT_READ",	EVFILT_READ,	&file_filtops },
144 	{ "EVFILT_WRITE",	EVFILT_WRITE,	&file_filtops },
145 	{ "EVFILT_AIO",		EVFILT_AIO,	NULL },
146 	{ "EVFILT_VNODE",	EVFILT_VNODE,	&file_filtops },
147 	{ "EVFILT_PROC",	EVFILT_PROC,	&proc_filtops },
148 	{ "EVFILT_SIGNAL",	EVFILT_SIGNAL,	&sig_filtops },
149 	{ "EVFILT_TIMER",	EVFILT_TIMER,	&timer_filtops },
150 	{ NULL,			0,		NULL },	/* end of list */
151 };
152 
153 		/* User defined kfilters */
154 static struct kfilter	*user_kfilters;		/* array */
155 static int		user_kfilterc;		/* current offset */
156 static int		user_kfiltermaxc;	/* max size so far */
157 
158 /*
159  * Find kfilter entry by name, or NULL if not found.
160  */
161 static const struct kfilter *
162 kfilter_byname_sys(const char *name)
163 {
164 	int i;
165 
166 	for (i = 0; sys_kfilters[i].name != NULL; i++) {
167 		if (strcmp(name, sys_kfilters[i].name) == 0)
168 			return (&sys_kfilters[i]);
169 	}
170 	return (NULL);
171 }
172 
173 static struct kfilter *
174 kfilter_byname_user(const char *name)
175 {
176 	int i;
177 
178 	/* user filter slots have a NULL name if previously deregistered */
179 	for (i = 0; i < user_kfilterc ; i++) {
180 		if (user_kfilters[i].name != NULL &&
181 		    strcmp(name, user_kfilters[i].name) == 0)
182 			return (&user_kfilters[i]);
183 	}
184 	return (NULL);
185 }
186 
187 static const struct kfilter *
188 kfilter_byname(const char *name)
189 {
190 	const struct kfilter *kfilter;
191 
192 	if ((kfilter = kfilter_byname_sys(name)) != NULL)
193 		return (kfilter);
194 
195 	return (kfilter_byname_user(name));
196 }
197 
198 /*
199  * Find kfilter entry by filter id, or NULL if not found.
200  * Assumes entries are indexed in filter id order, for speed.
201  */
202 static const struct kfilter *
203 kfilter_byfilter(uint32_t filter)
204 {
205 	const struct kfilter *kfilter;
206 
207 	if (filter < EVFILT_SYSCOUNT)	/* it's a system filter */
208 		kfilter = &sys_kfilters[filter];
209 	else if (user_kfilters != NULL &&
210 	    filter < EVFILT_SYSCOUNT + user_kfilterc)
211 					/* it's a user filter */
212 		kfilter = &user_kfilters[filter - EVFILT_SYSCOUNT];
213 	else
214 		return (NULL);		/* out of range */
215 	KASSERT(kfilter->filter == filter);	/* sanity check! */
216 	return (kfilter);
217 }
218 
219 /*
220  * Register a new kfilter. Stores the entry in user_kfilters.
221  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
222  * If retfilter != NULL, the new filterid is returned in it.
223  */
224 int
225 kfilter_register(const char *name, const struct filterops *filtops,
226     int *retfilter)
227 {
228 	struct kfilter *kfilter;
229 	void *space;
230 	int len;
231 	int i;
232 
233 	if (name == NULL || name[0] == '\0' || filtops == NULL)
234 		return (EINVAL);	/* invalid args */
235 	if (kfilter_byname(name) != NULL)
236 		return (EEXIST);	/* already exists */
237 	if (user_kfilterc > 0xffffffff - EVFILT_SYSCOUNT)
238 		return (EINVAL);	/* too many */
239 
240 	for (i = 0; i < user_kfilterc; i++) {
241 		kfilter = &user_kfilters[i];
242 		if (kfilter->name == NULL) {
243 			/* Previously deregistered slot.  Reuse. */
244 			goto reuse;
245 		}
246 	}
247 
248 	/* check if need to grow user_kfilters */
249 	if (user_kfilterc + 1 > user_kfiltermaxc) {
250 		/*
251 		 * Grow in KFILTER_EXTENT chunks. Use malloc(9), because we
252 		 * want to traverse user_kfilters as an array.
253 		 */
254 		user_kfiltermaxc += KFILTER_EXTENT;
255 		kfilter = malloc(user_kfiltermaxc * sizeof(struct filter *),
256 		    M_KEVENT, M_WAITOK);
257 
258 		/* copy existing user_kfilters */
259 		if (user_kfilters != NULL)
260 			memcpy((void *)kfilter, (void *)user_kfilters,
261 			    user_kfilterc * sizeof(struct kfilter *));
262 					/* zero new sections */
263 		memset((char *)kfilter +
264 		    user_kfilterc * sizeof(struct kfilter *), 0,
265 		    (user_kfiltermaxc - user_kfilterc) *
266 		    sizeof(struct kfilter *));
267 					/* switch to new kfilter */
268 		if (user_kfilters != NULL)
269 			free(user_kfilters, M_KEVENT);
270 		user_kfilters = kfilter;
271 	}
272 	/* Adding new slot */
273 	kfilter = &user_kfilters[user_kfilterc++];
274 reuse:
275 	len = strlen(name) + 1;		/* copy name */
276 	space = malloc(len, M_KEVENT, M_WAITOK);
277 	memcpy(space, name, len);
278 	kfilter->name = space;
279 
280 	kfilter->filter = (kfilter - user_kfilters) + EVFILT_SYSCOUNT;
281 
282 	len = sizeof(struct filterops);	/* copy filtops */
283 	space = malloc(len, M_KEVENT, M_WAITOK);
284 	memcpy(space, filtops, len);
285 	kfilter->filtops = space;
286 
287 	if (retfilter != NULL)
288 		*retfilter = kfilter->filter;
289 	return (0);
290 }
291 
292 /*
293  * Unregister a kfilter previously registered with kfilter_register.
294  * This retains the filter id, but clears the name and frees filtops (filter
295  * operations), so that the number isn't reused during a boot.
296  * Returns 0 if operation succeeded, or an appropriate errno(2) otherwise.
297  */
298 int
299 kfilter_unregister(const char *name)
300 {
301 	struct kfilter *kfilter;
302 
303 	if (name == NULL || name[0] == '\0')
304 		return (EINVAL);	/* invalid name */
305 
306 	if (kfilter_byname_sys(name) != NULL)
307 		return (EINVAL);	/* can't detach system filters */
308 
309 	kfilter = kfilter_byname_user(name);
310 	if (kfilter == NULL)		/* not found */
311 		return (ENOENT);
312 
313 	/* XXXUNCONST Cast away const (but we know it's safe. */
314 	free(__UNCONST(kfilter->name), M_KEVENT);
315 	kfilter->name = NULL;	/* mark as `not implemented' */
316 
317 	if (kfilter->filtops != NULL) {
318 		/* XXXUNCONST Cast away const (but we know it's safe. */
319 		free(__UNCONST(kfilter->filtops), M_KEVENT);
320 		kfilter->filtops = NULL; /* mark as `not implemented' */
321 	}
322 	return (0);
323 }
324 
325 
326 /*
327  * Filter attach method for EVFILT_READ and EVFILT_WRITE on normal file
328  * descriptors. Calls struct fileops kqfilter method for given file descriptor.
329  */
330 static int
331 filt_fileattach(struct knote *kn)
332 {
333 	struct file *fp;
334 
335 	fp = kn->kn_fp;
336 	return ((*fp->f_ops->fo_kqfilter)(fp, kn));
337 }
338 
339 /*
340  * Filter detach method for EVFILT_READ on kqueue descriptor.
341  */
342 static void
343 filt_kqdetach(struct knote *kn)
344 {
345 	struct kqueue *kq;
346 
347 	kq = (struct kqueue *)kn->kn_fp->f_data;
348 	SLIST_REMOVE(&kq->kq_sel.sel_klist, kn, knote, kn_selnext);
349 }
350 
351 /*
352  * Filter event method for EVFILT_READ on kqueue descriptor.
353  */
354 /*ARGSUSED*/
355 static int
356 filt_kqueue(struct knote *kn, long hint)
357 {
358 	struct kqueue *kq;
359 
360 	kq = (struct kqueue *)kn->kn_fp->f_data;
361 	kn->kn_data = kq->kq_count;
362 	return (kn->kn_data > 0);
363 }
364 
365 /*
366  * Filter attach method for EVFILT_PROC.
367  */
368 static int
369 filt_procattach(struct knote *kn)
370 {
371 	struct proc *p, *curp;
372 	struct lwp *curl;
373 
374 	curl = curlwp;
375 	curp = curl->l_proc;
376 
377 	p = pfind(kn->kn_id);
378 	if (p == NULL)
379 		return (ESRCH);
380 
381 	/*
382 	 * Fail if it's not owned by you, or the last exec gave us
383 	 * setuid/setgid privs (unless you're root).
384 	 */
385 	if (kauth_authorize_process(curl->l_cred, KAUTH_PROCESS_KEVENT_FILTER,
386 	    p, NULL, NULL, NULL) != 0)
387 		return (EACCES);
388 
389 	kn->kn_ptr.p_proc = p;
390 	kn->kn_flags |= EV_CLEAR;	/* automatically set */
391 
392 	/*
393 	 * internal flag indicating registration done by kernel
394 	 */
395 	if (kn->kn_flags & EV_FLAG1) {
396 		kn->kn_data = kn->kn_sdata;	/* ppid */
397 		kn->kn_fflags = NOTE_CHILD;
398 		kn->kn_flags &= ~EV_FLAG1;
399 	}
400 
401 	/* XXXSMP lock the process? */
402 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
403 
404 	return (0);
405 }
406 
407 /*
408  * Filter detach method for EVFILT_PROC.
409  *
410  * The knote may be attached to a different process, which may exit,
411  * leaving nothing for the knote to be attached to.  So when the process
412  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
413  * it will be deleted when read out.  However, as part of the knote deletion,
414  * this routine is called, so a check is needed to avoid actually performing
415  * a detach, because the original process might not exist any more.
416  */
417 static void
418 filt_procdetach(struct knote *kn)
419 {
420 	struct proc *p;
421 
422 	if (kn->kn_status & KN_DETACHED)
423 		return;
424 
425 	p = kn->kn_ptr.p_proc;
426 
427 	/* XXXSMP lock the process? */
428 	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
429 }
430 
431 /*
432  * Filter event method for EVFILT_PROC.
433  */
434 static int
435 filt_proc(struct knote *kn, long hint)
436 {
437 	u_int event;
438 
439 	/*
440 	 * mask off extra data
441 	 */
442 	event = (u_int)hint & NOTE_PCTRLMASK;
443 
444 	/*
445 	 * if the user is interested in this event, record it.
446 	 */
447 	if (kn->kn_sfflags & event)
448 		kn->kn_fflags |= event;
449 
450 	/*
451 	 * process is gone, so flag the event as finished.
452 	 */
453 	if (event == NOTE_EXIT) {
454 		/*
455 		 * Detach the knote from watched process and mark
456 		 * it as such. We can't leave this to kqueue_scan(),
457 		 * since the process might not exist by then. And we
458 		 * have to do this now, since psignal KNOTE() is called
459 		 * also for zombies and we might end up reading freed
460 		 * memory if the kevent would already be picked up
461 		 * and knote g/c'ed.
462 		 */
463 		kn->kn_fop->f_detach(kn);
464 		kn->kn_status |= KN_DETACHED;
465 
466 		/* Mark as ONESHOT, so that the knote it g/c'ed when read */
467 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
468 		return (1);
469 	}
470 
471 	/*
472 	 * process forked, and user wants to track the new process,
473 	 * so attach a new knote to it, and immediately report an
474 	 * event with the parent's pid.
475 	 */
476 	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
477 		struct kevent kev;
478 		int error;
479 
480 		/*
481 		 * register knote with new process.
482 		 */
483 		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
484 		kev.filter = kn->kn_filter;
485 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
486 		kev.fflags = kn->kn_sfflags;
487 		kev.data = kn->kn_id;			/* parent */
488 		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
489 		error = kqueue_register(kn->kn_kq, &kev, NULL);
490 		if (error)
491 			kn->kn_fflags |= NOTE_TRACKERR;
492 	}
493 
494 	return (kn->kn_fflags != 0);
495 }
496 
497 static void
498 filt_timerexpire(void *knx)
499 {
500 	struct knote *kn = knx;
501 	int tticks;
502 
503 	kn->kn_data++;
504 	KNOTE_ACTIVATE(kn);
505 
506 	if ((kn->kn_flags & EV_ONESHOT) == 0) {
507 		tticks = mstohz(kn->kn_sdata);
508 		callout_schedule((callout_t *)kn->kn_hook, tticks);
509 	}
510 }
511 
512 /*
513  * data contains amount of time to sleep, in milliseconds
514  */
515 static int
516 filt_timerattach(struct knote *kn)
517 {
518 	callout_t *calloutp;
519 	int tticks;
520 
521 	if (kq_ncallouts >= kq_calloutmax)
522 		return (ENOMEM);
523 	kq_ncallouts++;
524 
525 	tticks = mstohz(kn->kn_sdata);
526 
527 	/* if the supplied value is under our resolution, use 1 tick */
528 	if (tticks == 0) {
529 		if (kn->kn_sdata == 0)
530 			return (EINVAL);
531 		tticks = 1;
532 	}
533 
534 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
535 	MALLOC(calloutp, callout_t *, sizeof(*calloutp),
536 	    M_KEVENT, 0);
537 	callout_init(calloutp, 0);
538 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
539 	kn->kn_hook = calloutp;
540 
541 	return (0);
542 }
543 
544 static void
545 filt_timerdetach(struct knote *kn)
546 {
547 	callout_t *calloutp;
548 
549 	calloutp = (callout_t *)kn->kn_hook;
550 	callout_stop(calloutp);
551 	callout_destroy(calloutp);
552 	FREE(calloutp, M_KEVENT);
553 	kq_ncallouts--;
554 }
555 
556 static int
557 filt_timer(struct knote *kn, long hint)
558 {
559 	return (kn->kn_data != 0);
560 }
561 
562 /*
563  * filt_seltrue:
564  *
565  *	This filter "event" routine simulates seltrue().
566  */
567 int
568 filt_seltrue(struct knote *kn, long hint)
569 {
570 
571 	/*
572 	 * We don't know how much data can be read/written,
573 	 * but we know that it *can* be.  This is about as
574 	 * good as select/poll does as well.
575 	 */
576 	kn->kn_data = 0;
577 	return (1);
578 }
579 
580 /*
581  * This provides full kqfilter entry for device switch tables, which
582  * has same effect as filter using filt_seltrue() as filter method.
583  */
584 static void
585 filt_seltruedetach(struct knote *kn)
586 {
587 	/* Nothing to do */
588 }
589 
590 const struct filterops seltrue_filtops =
591 	{ 1, NULL, filt_seltruedetach, filt_seltrue };
592 
593 int
594 seltrue_kqfilter(dev_t dev, struct knote *kn)
595 {
596 	switch (kn->kn_filter) {
597 	case EVFILT_READ:
598 	case EVFILT_WRITE:
599 		kn->kn_fop = &seltrue_filtops;
600 		break;
601 	default:
602 		return (EINVAL);
603 	}
604 
605 	/* Nothing more to do */
606 	return (0);
607 }
608 
609 /*
610  * kqueue(2) system call.
611  */
612 int
613 sys_kqueue(struct lwp *l, const void *v, register_t *retval)
614 {
615 	struct filedesc	*fdp;
616 	struct kqueue	*kq;
617 	struct file	*fp;
618 	int		fd, error;
619 
620 	fdp = l->l_proc->p_fd;
621 	error = falloc(l, &fp, &fd);	/* setup a new file descriptor */
622 	if (error)
623 		return (error);
624 	fp->f_flag = FREAD | FWRITE;
625 	fp->f_type = DTYPE_KQUEUE;
626 	fp->f_ops = &kqueueops;
627 	kq = pool_get(&kqueue_pool, PR_WAITOK);
628 	memset((char *)kq, 0, sizeof(struct kqueue));
629 	simple_lock_init(&kq->kq_lock);
630 	TAILQ_INIT(&kq->kq_head);
631 	fp->f_data = (void *)kq;	/* store the kqueue with the fp */
632 	*retval = fd;
633 	if (fdp->fd_knlistsize < 0)
634 		fdp->fd_knlistsize = 0;	/* this process has a kq */
635 	kq->kq_fdp = fdp;
636 	FILE_SET_MATURE(fp);
637 	FILE_UNUSE(fp, l);		/* falloc() does FILE_USE() */
638 	return (error);
639 }
640 
641 /*
642  * kevent(2) system call.
643  */
644 static int
645 kevent_fetch_changes(void *private, const struct kevent *changelist,
646     struct kevent *changes, size_t index, int n)
647 {
648 	return copyin(changelist + index, changes, n * sizeof(*changes));
649 }
650 
651 static int
652 kevent_put_events(void *private, struct kevent *events,
653     struct kevent *eventlist, size_t index, int n)
654 {
655 	return copyout(events, eventlist + index, n * sizeof(*events));
656 }
657 
658 static const struct kevent_ops kevent_native_ops = {
659 	keo_private: NULL,
660 	keo_fetch_timeout: copyin,
661 	keo_fetch_changes: kevent_fetch_changes,
662 	keo_put_events: kevent_put_events,
663 };
664 
665 int
666 sys_kevent(struct lwp *l, const struct sys_kevent_args *uap, register_t *retval)
667 {
668 	/* {
669 		syscallarg(int) fd;
670 		syscallarg(const struct kevent *) changelist;
671 		syscallarg(size_t) nchanges;
672 		syscallarg(struct kevent *) eventlist;
673 		syscallarg(size_t) nevents;
674 		syscallarg(const struct timespec *) timeout;
675 	} */
676 
677 	return kevent1(l, retval, SCARG(uap, fd), SCARG(uap, changelist),
678 	    SCARG(uap, nchanges), SCARG(uap, eventlist), SCARG(uap, nevents),
679 	    SCARG(uap, timeout), &kevent_native_ops);
680 }
681 
682 int
683 kevent1(struct lwp *l, register_t *retval, int fd,
684     const struct kevent *changelist, size_t nchanges, struct kevent *eventlist,
685     size_t nevents, const struct timespec *timeout,
686     const struct kevent_ops *keops)
687 {
688 	struct kevent	*kevp;
689 	struct kqueue	*kq;
690 	struct file	*fp;
691 	struct timespec	ts;
692 	struct proc	*p;
693 	size_t		i, n, ichange;
694 	int		nerrors, error;
695 
696 	p = l->l_proc;
697 	/* check that we're dealing with a kq */
698 	fp = fd_getfile(p->p_fd, fd);
699 	if (fp == NULL)
700 		return (EBADF);
701 
702 	if (fp->f_type != DTYPE_KQUEUE) {
703 		FILE_UNLOCK(fp);
704 		return (EBADF);
705 	}
706 
707 	FILE_USE(fp);
708 
709 	if (timeout != NULL) {
710 		error = (*keops->keo_fetch_timeout)(timeout, &ts, sizeof(ts));
711 		if (error)
712 			goto done;
713 		timeout = &ts;
714 	}
715 
716 	kq = (struct kqueue *)fp->f_data;
717 	nerrors = 0;
718 	ichange = 0;
719 
720 	/* traverse list of events to register */
721 	while (nchanges > 0) {
722 		/* copyin a maximum of KQ_EVENTS at each pass */
723 		n = MIN(nchanges, KQ_NEVENTS);
724 		error = (*keops->keo_fetch_changes)(keops->keo_private,
725 		    changelist, kq->kq_kev, ichange, n);
726 		if (error)
727 			goto done;
728 		for (i = 0; i < n; i++) {
729 			kevp = &kq->kq_kev[i];
730 			kevp->flags &= ~EV_SYSFLAGS;
731 			/* register each knote */
732 			error = kqueue_register(kq, kevp, l);
733 			if (error) {
734 				if (nevents != 0) {
735 					kevp->flags = EV_ERROR;
736 					kevp->data = error;
737 					error = (*keops->keo_put_events)
738 					    (keops->keo_private, kevp,
739 					    eventlist, nerrors, 1);
740 					if (error)
741 						goto done;
742 					nevents--;
743 					nerrors++;
744 				} else {
745 					goto done;
746 				}
747 			}
748 		}
749 		nchanges -= n;	/* update the results */
750 		ichange += n;
751 	}
752 	if (nerrors) {
753 		*retval = nerrors;
754 		error = 0;
755 		goto done;
756 	}
757 
758 	/* actually scan through the events */
759 	error = kqueue_scan(fp, nevents, eventlist, timeout, l, retval, keops);
760  done:
761 	FILE_UNUSE(fp, l);
762 	return (error);
763 }
764 
765 /*
766  * Register a given kevent kev onto the kqueue
767  */
768 int
769 kqueue_register(struct kqueue *kq, struct kevent *kev, struct lwp *l)
770 {
771 	const struct kfilter *kfilter;
772 	struct filedesc	*fdp;
773 	struct file	*fp;
774 	struct knote	*kn;
775 	int		s, error;
776 
777 	fdp = kq->kq_fdp;
778 	fp = NULL;
779 	kn = NULL;
780 	error = 0;
781 	kfilter = kfilter_byfilter(kev->filter);
782 	if (kfilter == NULL || kfilter->filtops == NULL) {
783 		/* filter not found nor implemented */
784 		return (EINVAL);
785 	}
786 
787 	/* search if knote already exists */
788 	if (kfilter->filtops->f_isfd) {
789 		/* monitoring a file descriptor */
790 		if ((fp = fd_getfile(fdp, kev->ident)) == NULL)
791 			return (EBADF);	/* validate descriptor */
792 		FILE_USE(fp);
793 
794 		if (kev->ident < fdp->fd_knlistsize) {
795 			SLIST_FOREACH(kn, &fdp->fd_knlist[kev->ident], kn_link)
796 				if (kq == kn->kn_kq &&
797 				    kev->filter == kn->kn_filter)
798 					break;
799 		}
800 	} else {
801 		/*
802 		 * not monitoring a file descriptor, so
803 		 * lookup knotes in internal hash table
804 		 */
805 		if (fdp->fd_knhashmask != 0) {
806 			struct klist *list;
807 
808 			list = &fdp->fd_knhash[
809 			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
810 			SLIST_FOREACH(kn, list, kn_link)
811 				if (kev->ident == kn->kn_id &&
812 				    kq == kn->kn_kq &&
813 				    kev->filter == kn->kn_filter)
814 					break;
815 		}
816 	}
817 
818 	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
819 		error = ENOENT;		/* filter not found */
820 		goto done;
821 	}
822 
823 	/*
824 	 * kn now contains the matching knote, or NULL if no match
825 	 */
826 	if (kev->flags & EV_ADD) {
827 		/* add knote */
828 
829 		if (kn == NULL) {
830 			/* create new knote */
831 			kn = pool_get(&knote_pool, PR_WAITOK);
832 			if (kn == NULL) {
833 				error = ENOMEM;
834 				goto done;
835 			}
836 			kn->kn_fp = fp;
837 			kn->kn_kq = kq;
838 			kn->kn_fop = kfilter->filtops;
839 
840 			/*
841 			 * apply reference count to knote structure, and
842 			 * do not release it at the end of this routine.
843 			 */
844 			fp = NULL;
845 
846 			kn->kn_sfflags = kev->fflags;
847 			kn->kn_sdata = kev->data;
848 			kev->fflags = 0;
849 			kev->data = 0;
850 			kn->kn_kevent = *kev;
851 
852 			knote_attach(kn, fdp);
853 			if ((error = kfilter->filtops->f_attach(kn)) != 0) {
854 				knote_drop(kn, l, fdp);
855 				goto done;
856 			}
857 		} else {
858 			/* modify existing knote */
859 
860 			/*
861 			 * The user may change some filter values after the
862 			 * initial EV_ADD, but doing so will not reset any
863 			 * filter which have already been triggered.
864 			 */
865 			kn->kn_sfflags = kev->fflags;
866 			kn->kn_sdata = kev->data;
867 			kn->kn_kevent.udata = kev->udata;
868 		}
869 
870 		s = splsched();
871 		if (kn->kn_fop->f_event(kn, 0))
872 			KNOTE_ACTIVATE(kn);
873 		splx(s);
874 
875 	} else if (kev->flags & EV_DELETE) {	/* delete knote */
876 		kn->kn_fop->f_detach(kn);
877 		knote_drop(kn, l, fdp);
878 		goto done;
879 	}
880 
881 	/* disable knote */
882 	if ((kev->flags & EV_DISABLE) &&
883 	    ((kn->kn_status & KN_DISABLED) == 0)) {
884 		s = splsched();
885 		kn->kn_status |= KN_DISABLED;
886 		splx(s);
887 	}
888 
889 	/* enable knote */
890 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
891 		s = splsched();
892 		kn->kn_status &= ~KN_DISABLED;
893 		if ((kn->kn_status & KN_ACTIVE) &&
894 		    ((kn->kn_status & KN_QUEUED) == 0))
895 			knote_enqueue(kn);
896 		splx(s);
897 	}
898 
899  done:
900 	if (fp != NULL)
901 		FILE_UNUSE(fp, l);
902 	return (error);
903 }
904 
905 /*
906  * Scan through the list of events on fp (for a maximum of maxevents),
907  * returning the results in to ulistp. Timeout is determined by tsp; if
908  * NULL, wait indefinitely, if 0 valued, perform a poll, otherwise wait
909  * as appropriate.
910  */
911 static int
912 kqueue_scan(struct file *fp, size_t maxevents, struct kevent *ulistp,
913     const struct timespec *tsp, struct lwp *l, register_t *retval,
914     const struct kevent_ops *keops)
915 {
916 	struct proc	*p = l->l_proc;
917 	struct kqueue	*kq;
918 	struct kevent	*kevp;
919 	struct timeval	atv, sleeptv;
920 	struct knote	*kn, *marker=NULL;
921 	size_t		count, nkev, nevents;
922 	int		s, timeout, error;
923 
924 	kq = (struct kqueue *)fp->f_data;
925 	count = maxevents;
926 	nkev = nevents = error = 0;
927 	if (count == 0)
928 		goto done;
929 
930 	if (tsp) {				/* timeout supplied */
931 		TIMESPEC_TO_TIMEVAL(&atv, tsp);
932 		if (inittimeleft(&atv, &sleeptv) == -1) {
933 			error = EINVAL;
934 			goto done;
935 		}
936 		timeout = tvtohz(&atv);
937 		if (timeout <= 0)
938 			timeout = -1;           /* do poll */
939 	} else {
940 		/* no timeout, wait forever */
941 		timeout = 0;
942 	}
943 
944 	MALLOC(marker, struct knote *, sizeof(*marker), M_KEVENT, M_WAITOK);
945 	memset(marker, 0, sizeof(*marker));
946 
947 	goto start;
948 
949  retry:
950 	if (tsp && (timeout = gettimeleft(&atv, &sleeptv)) <= 0) {
951 		goto done;
952 	}
953 
954  start:
955 	kevp = kq->kq_kev;
956 	s = splsched();
957 	simple_lock(&kq->kq_lock);
958 	if (kq->kq_count == 0) {
959 		if (timeout < 0) {
960 			error = EWOULDBLOCK;
961 			simple_unlock(&kq->kq_lock);
962 		} else {
963 			kq->kq_state |= KQ_SLEEP;
964 			error = ltsleep(kq, PSOCK | PCATCH | PNORELOCK,
965 					"kqread", timeout, &kq->kq_lock);
966 		}
967 		splx(s);
968 		if (error == 0)
969 			goto retry;
970 		/* don't restart after signals... */
971 		if (error == ERESTART)
972 			error = EINTR;
973 		else if (error == EWOULDBLOCK)
974 			error = 0;
975 		goto done;
976 	}
977 
978 	/* mark end of knote list */
979 	TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
980 	simple_unlock(&kq->kq_lock);
981 
982 	while (count) {				/* while user wants data ... */
983 		simple_lock(&kq->kq_lock);
984 		kn = TAILQ_FIRST(&kq->kq_head);	/* get next knote */
985 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
986 		if (kn == marker) {		/* if it's our marker, stop */
987 			/* What if it's some else's marker? */
988 			simple_unlock(&kq->kq_lock);
989 			splx(s);
990 			if (count == maxevents)
991 				goto retry;
992 			goto done;
993 		}
994 		kq->kq_count--;
995 		simple_unlock(&kq->kq_lock);
996 
997 		if (kn->kn_status & KN_DISABLED) {
998 			/* don't want disabled events */
999 			kn->kn_status &= ~KN_QUEUED;
1000 			continue;
1001 		}
1002 		if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1003 		    kn->kn_fop->f_event(kn, 0) == 0) {
1004 			/*
1005 			 * non-ONESHOT event that hasn't
1006 			 * triggered again, so de-queue.
1007 			 */
1008 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1009 			continue;
1010 		}
1011 		*kevp = kn->kn_kevent;
1012 		kevp++;
1013 		nkev++;
1014 		if (kn->kn_flags & EV_ONESHOT) {
1015 			/* delete ONESHOT events after retrieval */
1016 			kn->kn_status &= ~KN_QUEUED;
1017 			splx(s);
1018 			kn->kn_fop->f_detach(kn);
1019 			knote_drop(kn, l, p->p_fd);
1020 			s = splsched();
1021 		} else if (kn->kn_flags & EV_CLEAR) {
1022 			/* clear state after retrieval */
1023 			kn->kn_data = 0;
1024 			kn->kn_fflags = 0;
1025 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1026 		} else {
1027 			/* add event back on list */
1028 			simple_lock(&kq->kq_lock);
1029 			TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1030 			kq->kq_count++;
1031 			simple_unlock(&kq->kq_lock);
1032 		}
1033 		count--;
1034 		if (nkev == KQ_NEVENTS) {
1035 			/* do copyouts in KQ_NEVENTS chunks */
1036 			splx(s);
1037 			error = (*keops->keo_put_events)(keops->keo_private,
1038 			    &kq->kq_kev[0], ulistp, nevents, nkev);
1039 			nevents += nkev;
1040 			nkev = 0;
1041 			kevp = kq->kq_kev;
1042 			s = splsched();
1043 			if (error)
1044 				break;
1045 		}
1046 	}
1047 
1048 	/* remove marker */
1049 	simple_lock(&kq->kq_lock);
1050 	TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1051 	simple_unlock(&kq->kq_lock);
1052 	splx(s);
1053  done:
1054 	if (marker)
1055 		FREE(marker, M_KEVENT);
1056 
1057 	if (nkev != 0)
1058 		/* copyout remaining events */
1059 		error = (*keops->keo_put_events)(keops->keo_private,
1060 		    &kq->kq_kev[0], ulistp, nevents, nkev);
1061 	*retval = maxevents - count;
1062 
1063 	return (error);
1064 }
1065 
1066 /*
1067  * struct fileops read method for a kqueue descriptor.
1068  * Not implemented.
1069  * XXX: This could be expanded to call kqueue_scan, if desired.
1070  */
1071 /*ARGSUSED*/
1072 static int
1073 kqueue_read(struct file *fp, off_t *offset, struct uio *uio, kauth_cred_t cred,
1074     int flags)
1075 {
1076 
1077 	return (ENXIO);
1078 }
1079 
1080 /*
1081  * struct fileops write method for a kqueue descriptor.
1082  * Not implemented.
1083  */
1084 /*ARGSUSED*/
1085 static int
1086 kqueue_write(struct file *fp, off_t *offset, struct uio *uio, kauth_cred_t cred,
1087     int flags)
1088 {
1089 
1090 	return (ENXIO);
1091 }
1092 
1093 /*
1094  * struct fileops ioctl method for a kqueue descriptor.
1095  *
1096  * Two ioctls are currently supported. They both use struct kfilter_mapping:
1097  *	KFILTER_BYNAME		find name for filter, and return result in
1098  *				name, which is of size len.
1099  *	KFILTER_BYFILTER	find filter for name. len is ignored.
1100  */
1101 /*ARGSUSED*/
1102 static int
1103 kqueue_ioctl(struct file *fp, u_long com, void *data, struct lwp *l)
1104 {
1105 	struct kfilter_mapping	*km;
1106 	const struct kfilter	*kfilter;
1107 	char			*name;
1108 	int			error;
1109 
1110 	km = (struct kfilter_mapping *)data;
1111 	error = 0;
1112 
1113 	switch (com) {
1114 	case KFILTER_BYFILTER:	/* convert filter -> name */
1115 		kfilter = kfilter_byfilter(km->filter);
1116 		if (kfilter != NULL)
1117 			error = copyoutstr(kfilter->name, km->name, km->len,
1118 			    NULL);
1119 		else
1120 			error = ENOENT;
1121 		break;
1122 
1123 	case KFILTER_BYNAME:	/* convert name -> filter */
1124 		MALLOC(name, char *, KFILTER_MAXNAME, M_KEVENT, M_WAITOK);
1125 		error = copyinstr(km->name, name, KFILTER_MAXNAME, NULL);
1126 		if (error) {
1127 			FREE(name, M_KEVENT);
1128 			break;
1129 		}
1130 		kfilter = kfilter_byname(name);
1131 		if (kfilter != NULL)
1132 			km->filter = kfilter->filter;
1133 		else
1134 			error = ENOENT;
1135 		FREE(name, M_KEVENT);
1136 		break;
1137 
1138 	default:
1139 		error = ENOTTY;
1140 
1141 	}
1142 	return (error);
1143 }
1144 
1145 /*
1146  * struct fileops fcntl method for a kqueue descriptor.
1147  * Not implemented.
1148  */
1149 /*ARGSUSED*/
1150 static int
1151 kqueue_fcntl(struct file *fp, u_int com, void *data, struct lwp *l)
1152 {
1153 
1154 	return (ENOTTY);
1155 }
1156 
1157 /*
1158  * struct fileops poll method for a kqueue descriptor.
1159  * Determine if kqueue has events pending.
1160  */
1161 static int
1162 kqueue_poll(struct file *fp, int events, struct lwp *l)
1163 {
1164 	struct kqueue	*kq;
1165 	int		revents;
1166 
1167 	kq = (struct kqueue *)fp->f_data;
1168 	revents = 0;
1169 	if (events & (POLLIN | POLLRDNORM)) {
1170 		if (kq->kq_count) {
1171 			revents |= events & (POLLIN | POLLRDNORM);
1172 		} else {
1173 			selrecord(l, &kq->kq_sel);
1174 		}
1175 	}
1176 	return (revents);
1177 }
1178 
1179 /*
1180  * struct fileops stat method for a kqueue descriptor.
1181  * Returns dummy info, with st_size being number of events pending.
1182  */
1183 static int
1184 kqueue_stat(struct file *fp, struct stat *st, struct lwp *l)
1185 {
1186 	struct kqueue	*kq;
1187 
1188 	kq = (struct kqueue *)fp->f_data;
1189 	memset((void *)st, 0, sizeof(*st));
1190 	st->st_size = kq->kq_count;
1191 	st->st_blksize = sizeof(struct kevent);
1192 	st->st_mode = S_IFIFO;
1193 	return (0);
1194 }
1195 
1196 /*
1197  * struct fileops close method for a kqueue descriptor.
1198  * Cleans up kqueue.
1199  */
1200 static int
1201 kqueue_close(struct file *fp, struct lwp *l)
1202 {
1203 	struct proc	*p = l->l_proc;
1204 	struct kqueue	*kq;
1205 	struct filedesc	*fdp;
1206 	struct knote	**knp, *kn, *kn0;
1207 	int		i;
1208 
1209 	kq = (struct kqueue *)fp->f_data;
1210 	fdp = p->p_fd;
1211 	for (i = 0; i < fdp->fd_knlistsize; i++) {
1212 		knp = &SLIST_FIRST(&fdp->fd_knlist[i]);
1213 		kn = *knp;
1214 		while (kn != NULL) {
1215 			kn0 = SLIST_NEXT(kn, kn_link);
1216 			if (kq == kn->kn_kq) {
1217 				kn->kn_fop->f_detach(kn);
1218 				FILE_UNUSE(kn->kn_fp, l);
1219 				pool_put(&knote_pool, kn);
1220 				*knp = kn0;
1221 			} else {
1222 				knp = &SLIST_NEXT(kn, kn_link);
1223 			}
1224 			kn = kn0;
1225 		}
1226 	}
1227 	if (fdp->fd_knhashmask != 0) {
1228 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
1229 			knp = &SLIST_FIRST(&fdp->fd_knhash[i]);
1230 			kn = *knp;
1231 			while (kn != NULL) {
1232 				kn0 = SLIST_NEXT(kn, kn_link);
1233 				if (kq == kn->kn_kq) {
1234 					kn->kn_fop->f_detach(kn);
1235 					/* XXX non-fd release of kn->kn_ptr */
1236 					pool_put(&knote_pool, kn);
1237 					*knp = kn0;
1238 				} else {
1239 					knp = &SLIST_NEXT(kn, kn_link);
1240 				}
1241 				kn = kn0;
1242 			}
1243 		}
1244 	}
1245 	pool_put(&kqueue_pool, kq);
1246 	fp->f_data = NULL;
1247 
1248 	return (0);
1249 }
1250 
1251 /*
1252  * wakeup a kqueue
1253  */
1254 static void
1255 kqueue_wakeup(struct kqueue *kq)
1256 {
1257 	int s;
1258 
1259 	s = splsched();
1260 	simple_lock(&kq->kq_lock);
1261 	if (kq->kq_state & KQ_SLEEP) {		/* if currently sleeping ...  */
1262 		kq->kq_state &= ~KQ_SLEEP;
1263 		wakeup(kq);			/* ... wakeup */
1264 	}
1265 
1266 	/* Notify select/poll and kevent. */
1267 	selnotify(&kq->kq_sel, 0);
1268 	simple_unlock(&kq->kq_lock);
1269 	splx(s);
1270 }
1271 
1272 /*
1273  * struct fileops kqfilter method for a kqueue descriptor.
1274  * Event triggered when monitored kqueue changes.
1275  */
1276 /*ARGSUSED*/
1277 static int
1278 kqueue_kqfilter(struct file *fp, struct knote *kn)
1279 {
1280 	struct kqueue *kq;
1281 
1282 	KASSERT(fp == kn->kn_fp);
1283 	kq = (struct kqueue *)kn->kn_fp->f_data;
1284 	if (kn->kn_filter != EVFILT_READ)
1285 		return (1);
1286 	kn->kn_fop = &kqread_filtops;
1287 	SLIST_INSERT_HEAD(&kq->kq_sel.sel_klist, kn, kn_selnext);
1288 	return (0);
1289 }
1290 
1291 
1292 /*
1293  * Walk down a list of knotes, activating them if their event has triggered.
1294  */
1295 void
1296 knote(struct klist *list, long hint)
1297 {
1298 	struct knote *kn;
1299 
1300 	SLIST_FOREACH(kn, list, kn_selnext)
1301 		if (kn->kn_fop->f_event(kn, hint))
1302 			KNOTE_ACTIVATE(kn);
1303 }
1304 
1305 /*
1306  * Remove all knotes from a specified klist
1307  */
1308 void
1309 knote_remove(struct lwp *l, struct klist *list)
1310 {
1311 	struct knote *kn;
1312 
1313 	while ((kn = SLIST_FIRST(list)) != NULL) {
1314 		kn->kn_fop->f_detach(kn);
1315 		knote_drop(kn, l, l->l_proc->p_fd);
1316 	}
1317 }
1318 
1319 /*
1320  * Remove all knotes referencing a specified fd
1321  */
1322 void
1323 knote_fdclose(struct lwp *l, int fd)
1324 {
1325 	struct filedesc	*fdp;
1326 	struct klist	*list;
1327 
1328 	fdp = l->l_proc->p_fd;
1329 	list = &fdp->fd_knlist[fd];
1330 	knote_remove(l, list);
1331 }
1332 
1333 /*
1334  * Attach a new knote to a file descriptor
1335  */
1336 static void
1337 knote_attach(struct knote *kn, struct filedesc *fdp)
1338 {
1339 	struct klist	*list;
1340 	int		size;
1341 
1342 	if (! kn->kn_fop->f_isfd) {
1343 		/* if knote is not on an fd, store on internal hash table */
1344 		if (fdp->fd_knhashmask == 0)
1345 			fdp->fd_knhash = hashinit(KN_HASHSIZE, HASH_LIST,
1346 			    M_KEVENT, M_WAITOK, &fdp->fd_knhashmask);
1347 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1348 		goto done;
1349 	}
1350 
1351 	/*
1352 	 * otherwise, knote is on an fd.
1353 	 * knotes are stored in fd_knlist indexed by kn->kn_id.
1354 	 */
1355 	if (fdp->fd_knlistsize <= kn->kn_id) {
1356 		/* expand list, it's too small */
1357 		size = fdp->fd_knlistsize;
1358 		while (size <= kn->kn_id) {
1359 			/* grow in KQ_EXTENT chunks */
1360 			size += KQ_EXTENT;
1361 		}
1362 		list = malloc(size * sizeof(struct klist *), M_KEVENT,M_WAITOK);
1363 		if (fdp->fd_knlist) {
1364 			/* copy existing knlist */
1365 			memcpy((void *)list, (void *)fdp->fd_knlist,
1366 			    fdp->fd_knlistsize * sizeof(struct klist *));
1367 		}
1368 		/*
1369 		 * Zero new memory. Stylistically, SLIST_INIT() should be
1370 		 * used here, but that does same thing as the memset() anyway.
1371 		 */
1372 		memset(&list[fdp->fd_knlistsize], 0,
1373 		    (size - fdp->fd_knlistsize) * sizeof(struct klist *));
1374 
1375 		/* switch to new knlist */
1376 		if (fdp->fd_knlist != NULL)
1377 			free(fdp->fd_knlist, M_KEVENT);
1378 		fdp->fd_knlistsize = size;
1379 		fdp->fd_knlist = list;
1380 	}
1381 
1382 	/* get list head for this fd */
1383 	list = &fdp->fd_knlist[kn->kn_id];
1384  done:
1385 	/* add new knote */
1386 	SLIST_INSERT_HEAD(list, kn, kn_link);
1387 	kn->kn_status = 0;
1388 }
1389 
1390 /*
1391  * Drop knote.
1392  * Should be called at spl == 0, since we don't want to hold spl
1393  * while calling FILE_UNUSE and free.
1394  */
1395 static void
1396 knote_drop(struct knote *kn, struct lwp *l, struct filedesc *fdp)
1397 {
1398 	struct klist	*list;
1399 
1400 	if (kn->kn_fop->f_isfd)
1401 		list = &fdp->fd_knlist[kn->kn_id];
1402 	else
1403 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1404 
1405 	SLIST_REMOVE(list, kn, knote, kn_link);
1406 	if (kn->kn_status & KN_QUEUED)
1407 		knote_dequeue(kn);
1408 	if (kn->kn_fop->f_isfd)
1409 		FILE_UNUSE(kn->kn_fp, l);
1410 	pool_put(&knote_pool, kn);
1411 }
1412 
1413 
1414 /*
1415  * Queue new event for knote.
1416  */
1417 static void
1418 knote_enqueue(struct knote *kn)
1419 {
1420 	struct kqueue	*kq;
1421 	int		s;
1422 
1423 	kq = kn->kn_kq;
1424 	KASSERT((kn->kn_status & KN_QUEUED) == 0);
1425 
1426 	s = splsched();
1427 	simple_lock(&kq->kq_lock);
1428 	TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1429 	kn->kn_status |= KN_QUEUED;
1430 	kq->kq_count++;
1431 	simple_unlock(&kq->kq_lock);
1432 	splx(s);
1433 	kqueue_wakeup(kq);
1434 }
1435 
1436 /*
1437  * Dequeue event for knote.
1438  */
1439 static void
1440 knote_dequeue(struct knote *kn)
1441 {
1442 	struct kqueue	*kq;
1443 	int		s;
1444 
1445 	KASSERT(kn->kn_status & KN_QUEUED);
1446 	kq = kn->kn_kq;
1447 
1448 	s = splsched();
1449 	simple_lock(&kq->kq_lock);
1450 	TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1451 	kn->kn_status &= ~KN_QUEUED;
1452 	kq->kq_count--;
1453 	simple_unlock(&kq->kq_lock);
1454 	splx(s);
1455 }
1456