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