xref: /freebsd/sys/kern/kern_event.c (revision a3e8fd0b7f663db7eafff527d5c3ca3bcfa8a537)
1 /*-
2  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/kernel.h>
32 #include <sys/lock.h>
33 #include <sys/mutex.h>
34 #include <sys/proc.h>
35 #include <sys/malloc.h>
36 #include <sys/unistd.h>
37 #include <sys/file.h>
38 #include <sys/fcntl.h>
39 #include <sys/selinfo.h>
40 #include <sys/queue.h>
41 #include <sys/event.h>
42 #include <sys/eventvar.h>
43 #include <sys/poll.h>
44 #include <sys/protosw.h>
45 #include <sys/socket.h>
46 #include <sys/socketvar.h>
47 #include <sys/stat.h>
48 #include <sys/sysctl.h>
49 #include <sys/sysproto.h>
50 #include <sys/uio.h>
51 
52 #include <vm/uma.h>
53 
54 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
55 
56 static int	kqueue_scan(struct file *fp, int maxevents,
57 		    struct kevent *ulistp, const struct timespec *timeout,
58 		    struct thread *td);
59 static int 	kqueue_read(struct file *fp, struct uio *uio,
60 		    struct ucred *active_cred, int flags, struct thread *td);
61 static int	kqueue_write(struct file *fp, struct uio *uio,
62 		    struct ucred *active_cred, int flags, struct thread *td);
63 static int	kqueue_ioctl(struct file *fp, u_long com, void *data,
64 		    struct ucred *active_cred, struct thread *td);
65 static int 	kqueue_poll(struct file *fp, int events,
66 		    struct ucred *active_cred, struct thread *td);
67 static int 	kqueue_kqfilter(struct file *fp, struct knote *kn);
68 static int 	kqueue_stat(struct file *fp, struct stat *st,
69 		    struct ucred *active_cred, struct thread *td);
70 static int 	kqueue_close(struct file *fp, struct thread *td);
71 static void 	kqueue_wakeup(struct kqueue *kq);
72 
73 static struct fileops kqueueops = {
74 	kqueue_read,
75 	kqueue_write,
76 	kqueue_ioctl,
77 	kqueue_poll,
78 	kqueue_kqfilter,
79 	kqueue_stat,
80 	kqueue_close
81 };
82 
83 static void 	knote_attach(struct knote *kn, struct filedesc *fdp);
84 static void 	knote_drop(struct knote *kn, struct thread *td);
85 static void 	knote_enqueue(struct knote *kn);
86 static void 	knote_dequeue(struct knote *kn);
87 static void 	knote_init(void);
88 static struct 	knote *knote_alloc(void);
89 static void 	knote_free(struct knote *kn);
90 
91 static void	filt_kqdetach(struct knote *kn);
92 static int	filt_kqueue(struct knote *kn, long hint);
93 static int	filt_procattach(struct knote *kn);
94 static void	filt_procdetach(struct knote *kn);
95 static int	filt_proc(struct knote *kn, long hint);
96 static int	filt_fileattach(struct knote *kn);
97 static void	filt_timerexpire(void *knx);
98 static int	filt_timerattach(struct knote *kn);
99 static void	filt_timerdetach(struct knote *kn);
100 static int	filt_timer(struct knote *kn, long hint);
101 
102 static struct filterops file_filtops =
103 	{ 1, filt_fileattach, NULL, NULL };
104 static struct filterops kqread_filtops =
105 	{ 1, NULL, filt_kqdetach, filt_kqueue };
106 static struct filterops proc_filtops =
107 	{ 0, filt_procattach, filt_procdetach, filt_proc };
108 static struct filterops timer_filtops =
109 	{ 0, filt_timerattach, filt_timerdetach, filt_timer };
110 
111 static uma_zone_t	knote_zone;
112 static int 		kq_ncallouts = 0;
113 static int 		kq_calloutmax = (4 * 1024);
114 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
115     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
116 
117 #define KNOTE_ACTIVATE(kn) do { 					\
118 	kn->kn_status |= KN_ACTIVE;					\
119 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
120 		knote_enqueue(kn);					\
121 } while(0)
122 
123 #define	KN_HASHSIZE		64		/* XXX should be tunable */
124 #define KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
125 
126 static int
127 filt_nullattach(struct knote *kn)
128 {
129 
130 	return (ENXIO);
131 };
132 
133 struct filterops null_filtops =
134 	{ 0, filt_nullattach, NULL, NULL };
135 
136 extern struct filterops sig_filtops;
137 
138 /*
139  * Table for for all system-defined filters.
140  */
141 static struct filterops *sysfilt_ops[] = {
142 	&file_filtops,			/* EVFILT_READ */
143 	&file_filtops,			/* EVFILT_WRITE */
144 	&null_filtops,			/* EVFILT_AIO */
145 	&file_filtops,			/* EVFILT_VNODE */
146 	&proc_filtops,			/* EVFILT_PROC */
147 	&sig_filtops,			/* EVFILT_SIGNAL */
148 	&timer_filtops,			/* EVFILT_TIMER */
149 	&file_filtops,			/* EVFILT_NETDEV */
150 };
151 
152 static int
153 filt_fileattach(struct knote *kn)
154 {
155 
156 	return (fo_kqfilter(kn->kn_fp, kn));
157 }
158 
159 /*ARGSUSED*/
160 static int
161 kqueue_kqfilter(struct file *fp, struct knote *kn)
162 {
163 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
164 
165 	if (kn->kn_filter != EVFILT_READ)
166 		return (1);
167 
168 	kn->kn_fop = &kqread_filtops;
169 	SLIST_INSERT_HEAD(&kq->kq_sel.si_note, kn, kn_selnext);
170 	return (0);
171 }
172 
173 static void
174 filt_kqdetach(struct knote *kn)
175 {
176 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
177 
178 	SLIST_REMOVE(&kq->kq_sel.si_note, kn, knote, kn_selnext);
179 }
180 
181 /*ARGSUSED*/
182 static int
183 filt_kqueue(struct knote *kn, long hint)
184 {
185 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
186 
187 	kn->kn_data = kq->kq_count;
188 	return (kn->kn_data > 0);
189 }
190 
191 static int
192 filt_procattach(struct knote *kn)
193 {
194 	struct proc *p;
195 	int error;
196 
197 	p = pfind(kn->kn_id);
198 	if (p == NULL)
199 		return (ESRCH);
200 	if ((error = p_cansee(curthread, p))) {
201 		PROC_UNLOCK(p);
202 		return (error);
203 	}
204 
205 	kn->kn_ptr.p_proc = p;
206 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
207 
208 	/*
209 	 * internal flag indicating registration done by kernel
210 	 */
211 	if (kn->kn_flags & EV_FLAG1) {
212 		kn->kn_data = kn->kn_sdata;		/* ppid */
213 		kn->kn_fflags = NOTE_CHILD;
214 		kn->kn_flags &= ~EV_FLAG1;
215 	}
216 
217 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
218 	PROC_UNLOCK(p);
219 
220 	return (0);
221 }
222 
223 /*
224  * The knote may be attached to a different process, which may exit,
225  * leaving nothing for the knote to be attached to.  So when the process
226  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
227  * it will be deleted when read out.  However, as part of the knote deletion,
228  * this routine is called, so a check is needed to avoid actually performing
229  * a detach, because the original process does not exist any more.
230  */
231 static void
232 filt_procdetach(struct knote *kn)
233 {
234 	struct proc *p = kn->kn_ptr.p_proc;
235 
236 	if (kn->kn_status & KN_DETACHED)
237 		return;
238 
239 	PROC_LOCK(p);
240 	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
241 	PROC_UNLOCK(p);
242 }
243 
244 static int
245 filt_proc(struct knote *kn, long hint)
246 {
247 	u_int event;
248 
249 	/*
250 	 * mask off extra data
251 	 */
252 	event = (u_int)hint & NOTE_PCTRLMASK;
253 
254 	/*
255 	 * if the user is interested in this event, record it.
256 	 */
257 	if (kn->kn_sfflags & event)
258 		kn->kn_fflags |= event;
259 
260 	/*
261 	 * process is gone, so flag the event as finished.
262 	 */
263 	if (event == NOTE_EXIT) {
264 		kn->kn_status |= KN_DETACHED;
265 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
266 		return (1);
267 	}
268 
269 	/*
270 	 * process forked, and user wants to track the new process,
271 	 * so attach a new knote to it, and immediately report an
272 	 * event with the parent's pid.
273 	 */
274 	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
275 		struct kevent kev;
276 		int error;
277 
278 		/*
279 		 * register knote with new process.
280 		 */
281 		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
282 		kev.filter = kn->kn_filter;
283 		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
284 		kev.fflags = kn->kn_sfflags;
285 		kev.data = kn->kn_id;			/* parent */
286 		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
287 		error = kqueue_register(kn->kn_kq, &kev, NULL);
288 		if (error)
289 			kn->kn_fflags |= NOTE_TRACKERR;
290 	}
291 
292 	return (kn->kn_fflags != 0);
293 }
294 
295 static void
296 filt_timerexpire(void *knx)
297 {
298 	struct knote *kn = knx;
299 	struct callout *calloutp;
300 	struct timeval tv;
301 	int tticks;
302 
303 	kn->kn_data++;
304 	KNOTE_ACTIVATE(kn);
305 
306 	if ((kn->kn_flags & EV_ONESHOT) == 0) {
307 		tv.tv_sec = kn->kn_sdata / 1000;
308 		tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
309 		tticks = tvtohz(&tv);
310 		calloutp = (struct callout *)kn->kn_hook;
311 		callout_reset(calloutp, tticks, filt_timerexpire, kn);
312 	}
313 }
314 
315 /*
316  * data contains amount of time to sleep, in milliseconds
317  */
318 static int
319 filt_timerattach(struct knote *kn)
320 {
321 	struct callout *calloutp;
322 	struct timeval tv;
323 	int tticks;
324 
325 	if (kq_ncallouts >= kq_calloutmax)
326 		return (ENOMEM);
327 	kq_ncallouts++;
328 
329 	tv.tv_sec = kn->kn_sdata / 1000;
330 	tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
331 	tticks = tvtohz(&tv);
332 
333 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
334 	MALLOC(calloutp, struct callout *, sizeof(*calloutp),
335 	    M_KQUEUE, M_WAITOK);
336 	callout_init(calloutp, 0);
337 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
338 	kn->kn_hook = calloutp;
339 
340 	return (0);
341 }
342 
343 static void
344 filt_timerdetach(struct knote *kn)
345 {
346 	struct callout *calloutp;
347 
348 	calloutp = (struct callout *)kn->kn_hook;
349 	callout_stop(calloutp);
350 	FREE(calloutp, M_KQUEUE);
351 	kq_ncallouts--;
352 }
353 
354 static int
355 filt_timer(struct knote *kn, long hint)
356 {
357 
358 	return (kn->kn_data != 0);
359 }
360 
361 /*
362  * MPSAFE
363  */
364 int
365 kqueue(struct thread *td, struct kqueue_args *uap)
366 {
367 	struct filedesc *fdp;
368 	struct kqueue *kq;
369 	struct file *fp;
370 	int fd, error;
371 
372 	mtx_lock(&Giant);
373 	fdp = td->td_proc->p_fd;
374 	error = falloc(td, &fp, &fd);
375 	if (error)
376 		goto done2;
377 	kq = malloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
378 	TAILQ_INIT(&kq->kq_head);
379 	FILE_LOCK(fp);
380 	fp->f_flag = FREAD | FWRITE;
381 	fp->f_type = DTYPE_KQUEUE;
382 	fp->f_ops = &kqueueops;
383 	TAILQ_INIT(&kq->kq_head);
384 	fp->f_data = kq;
385 	FILE_UNLOCK(fp);
386 	FILEDESC_LOCK(fdp);
387 	td->td_retval[0] = fd;
388 	if (fdp->fd_knlistsize < 0)
389 		fdp->fd_knlistsize = 0;		/* this process has a kq */
390 	FILEDESC_UNLOCK(fdp);
391 	kq->kq_fdp = fdp;
392 done2:
393 	mtx_unlock(&Giant);
394 	return (error);
395 }
396 
397 #ifndef _SYS_SYSPROTO_H_
398 struct kevent_args {
399 	int	fd;
400 	const struct kevent *changelist;
401 	int	nchanges;
402 	struct	kevent *eventlist;
403 	int	nevents;
404 	const struct timespec *timeout;
405 };
406 #endif
407 /*
408  * MPSAFE
409  */
410 int
411 kevent(struct thread *td, struct kevent_args *uap)
412 {
413 	struct kevent *kevp;
414 	struct kqueue *kq;
415 	struct file *fp;
416 	struct timespec ts;
417 	int i, n, nerrors, error;
418 
419 	if ((error = fget(td, uap->fd, &fp)) != 0)
420 		return (error);
421 	if (fp->f_type != DTYPE_KQUEUE) {
422 		fdrop(fp, td);
423 		return (EBADF);
424 	}
425 	if (uap->timeout != NULL) {
426 		error = copyin(uap->timeout, &ts, sizeof(ts));
427 		if (error)
428 			goto done_nogiant;
429 		uap->timeout = &ts;
430 	}
431 	mtx_lock(&Giant);
432 
433 	kq = (struct kqueue *)fp->f_data;
434 	nerrors = 0;
435 
436 	while (uap->nchanges > 0) {
437 		n = uap->nchanges > KQ_NEVENTS ? KQ_NEVENTS : uap->nchanges;
438 		error = copyin(uap->changelist, kq->kq_kev,
439 		    n * sizeof(struct kevent));
440 		if (error)
441 			goto done;
442 		for (i = 0; i < n; i++) {
443 			kevp = &kq->kq_kev[i];
444 			kevp->flags &= ~EV_SYSFLAGS;
445 			error = kqueue_register(kq, kevp, td);
446 			if (error) {
447 				if (uap->nevents != 0) {
448 					kevp->flags = EV_ERROR;
449 					kevp->data = error;
450 					(void) copyout(kevp,
451 					    uap->eventlist,
452 					    sizeof(*kevp));
453 					uap->eventlist++;
454 					uap->nevents--;
455 					nerrors++;
456 				} else {
457 					goto done;
458 				}
459 			}
460 		}
461 		uap->nchanges -= n;
462 		uap->changelist += n;
463 	}
464 	if (nerrors) {
465         	td->td_retval[0] = nerrors;
466 		error = 0;
467 		goto done;
468 	}
469 
470 	error = kqueue_scan(fp, uap->nevents, uap->eventlist, uap->timeout, td);
471 done:
472 	mtx_unlock(&Giant);
473 done_nogiant:
474 	if (fp != NULL)
475 		fdrop(fp, td);
476 	return (error);
477 }
478 
479 int
480 kqueue_add_filteropts(int filt, struct filterops *filtops)
481 {
482 
483 	if (filt > 0)
484 		panic("filt(%d) > 0", filt);
485 	if (filt + EVFILT_SYSCOUNT < 0)
486 		panic("filt(%d) + EVFILT_SYSCOUNT(%d) == %d < 0",
487 		    filt, EVFILT_SYSCOUNT, filt + EVFILT_SYSCOUNT);
488 	if (sysfilt_ops[~filt] != &null_filtops)
489 		panic("sysfilt_ops[~filt(%d)] != &null_filtops", filt);
490 	sysfilt_ops[~filt] = filtops;
491 	return (0);
492 }
493 
494 int
495 kqueue_del_filteropts(int filt)
496 {
497 
498 	if (filt > 0)
499 		panic("filt(%d) > 0", filt);
500 	if (filt + EVFILT_SYSCOUNT < 0)
501 		panic("filt(%d) + EVFILT_SYSCOUNT(%d) == %d < 0",
502 		    filt, EVFILT_SYSCOUNT, filt + EVFILT_SYSCOUNT);
503 	if (sysfilt_ops[~filt] == &null_filtops)
504 		panic("sysfilt_ops[~filt(%d)] != &null_filtops", filt);
505 	sysfilt_ops[~filt] = &null_filtops;
506 	return (0);
507 }
508 
509 int
510 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td)
511 {
512 	struct filedesc *fdp = kq->kq_fdp;
513 	struct filterops *fops;
514 	struct file *fp = NULL;
515 	struct knote *kn = NULL;
516 	int s, error = 0;
517 
518 	if (kev->filter < 0) {
519 		if (kev->filter + EVFILT_SYSCOUNT < 0)
520 			return (EINVAL);
521 		fops = sysfilt_ops[~kev->filter];	/* to 0-base index */
522 	} else {
523 		/*
524 		 * XXX
525 		 * filter attach routine is responsible for insuring that
526 		 * the identifier can be attached to it.
527 		 */
528 		printf("unknown filter: %d\n", kev->filter);
529 		return (EINVAL);
530 	}
531 
532 	FILEDESC_LOCK(fdp);
533 	if (fops->f_isfd) {
534 		/* validate descriptor */
535 		if ((u_int)kev->ident >= fdp->fd_nfiles ||
536 		    (fp = fdp->fd_ofiles[kev->ident]) == NULL) {
537 			FILEDESC_UNLOCK(fdp);
538 			return (EBADF);
539 		}
540 		fhold(fp);
541 
542 		if (kev->ident < fdp->fd_knlistsize) {
543 			SLIST_FOREACH(kn, &fdp->fd_knlist[kev->ident], kn_link)
544 				if (kq == kn->kn_kq &&
545 				    kev->filter == kn->kn_filter)
546 					break;
547 		}
548 	} else {
549 		if (fdp->fd_knhashmask != 0) {
550 			struct klist *list;
551 
552 			list = &fdp->fd_knhash[
553 			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
554 			SLIST_FOREACH(kn, list, kn_link)
555 				if (kev->ident == kn->kn_id &&
556 				    kq == kn->kn_kq &&
557 				    kev->filter == kn->kn_filter)
558 					break;
559 		}
560 	}
561 	FILEDESC_UNLOCK(fdp);
562 
563 	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
564 		error = ENOENT;
565 		goto done;
566 	}
567 
568 	/*
569 	 * kn now contains the matching knote, or NULL if no match
570 	 */
571 	if (kev->flags & EV_ADD) {
572 
573 		if (kn == NULL) {
574 			kn = knote_alloc();
575 			if (kn == NULL) {
576 				error = ENOMEM;
577 				goto done;
578 			}
579 			kn->kn_fp = fp;
580 			kn->kn_kq = kq;
581 			kn->kn_fop = fops;
582 
583 			/*
584 			 * apply reference count to knote structure, and
585 			 * do not release it at the end of this routine.
586 			 */
587 			fp = NULL;
588 
589 			kn->kn_sfflags = kev->fflags;
590 			kn->kn_sdata = kev->data;
591 			kev->fflags = 0;
592 			kev->data = 0;
593 			kn->kn_kevent = *kev;
594 
595 			knote_attach(kn, fdp);
596 			if ((error = fops->f_attach(kn)) != 0) {
597 				knote_drop(kn, td);
598 				goto done;
599 			}
600 		} else {
601 			/*
602 			 * The user may change some filter values after the
603 			 * initial EV_ADD, but doing so will not reset any
604 			 * filter which have already been triggered.
605 			 */
606 			kn->kn_sfflags = kev->fflags;
607 			kn->kn_sdata = kev->data;
608 			kn->kn_kevent.udata = kev->udata;
609 		}
610 
611 		s = splhigh();
612 		if (kn->kn_fop->f_event(kn, 0))
613 			KNOTE_ACTIVATE(kn);
614 		splx(s);
615 
616 	} else if (kev->flags & EV_DELETE) {
617 		kn->kn_fop->f_detach(kn);
618 		knote_drop(kn, td);
619 		goto done;
620 	}
621 
622 	if ((kev->flags & EV_DISABLE) &&
623 	    ((kn->kn_status & KN_DISABLED) == 0)) {
624 		s = splhigh();
625 		kn->kn_status |= KN_DISABLED;
626 		splx(s);
627 	}
628 
629 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
630 		s = splhigh();
631 		kn->kn_status &= ~KN_DISABLED;
632 		if ((kn->kn_status & KN_ACTIVE) &&
633 		    ((kn->kn_status & KN_QUEUED) == 0))
634 			knote_enqueue(kn);
635 		splx(s);
636 	}
637 
638 done:
639 	if (fp != NULL)
640 		fdrop(fp, td);
641 	return (error);
642 }
643 
644 static int
645 kqueue_scan(struct file *fp, int maxevents, struct kevent *ulistp,
646 	const struct timespec *tsp, struct thread *td)
647 {
648 	struct kqueue *kq;
649 	struct kevent *kevp;
650 	struct timeval atv, rtv, ttv;
651 	struct knote *kn, marker;
652 	int s, count, timeout, nkev = 0, error = 0;
653 
654 	FILE_LOCK_ASSERT(fp, MA_NOTOWNED);
655 
656 	kq = (struct kqueue *)fp->f_data;
657 	count = maxevents;
658 	if (count == 0)
659 		goto done;
660 
661 	if (tsp != NULL) {
662 		TIMESPEC_TO_TIMEVAL(&atv, tsp);
663 		if (itimerfix(&atv)) {
664 			error = EINVAL;
665 			goto done;
666 		}
667 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
668 			timeout = -1;
669 		else
670 			timeout = atv.tv_sec > 24 * 60 * 60 ?
671 			    24 * 60 * 60 * hz : tvtohz(&atv);
672 		getmicrouptime(&rtv);
673 		timevaladd(&atv, &rtv);
674 	} else {
675 		atv.tv_sec = 0;
676 		atv.tv_usec = 0;
677 		timeout = 0;
678 	}
679 	goto start;
680 
681 retry:
682 	if (atv.tv_sec || atv.tv_usec) {
683 		getmicrouptime(&rtv);
684 		if (timevalcmp(&rtv, &atv, >=))
685 			goto done;
686 		ttv = atv;
687 		timevalsub(&ttv, &rtv);
688 		timeout = ttv.tv_sec > 24 * 60 * 60 ?
689 			24 * 60 * 60 * hz : tvtohz(&ttv);
690 	}
691 
692 start:
693 	kevp = kq->kq_kev;
694 	s = splhigh();
695 	if (kq->kq_count == 0) {
696 		if (timeout < 0) {
697 			error = EWOULDBLOCK;
698 		} else {
699 			kq->kq_state |= KQ_SLEEP;
700 			error = tsleep(kq, PSOCK | PCATCH, "kqread", timeout);
701 		}
702 		splx(s);
703 		if (error == 0)
704 			goto retry;
705 		/* don't restart after signals... */
706 		if (error == ERESTART)
707 			error = EINTR;
708 		else if (error == EWOULDBLOCK)
709 			error = 0;
710 		goto done;
711 	}
712 
713 	TAILQ_INSERT_TAIL(&kq->kq_head, &marker, kn_tqe);
714 	while (count) {
715 		kn = TAILQ_FIRST(&kq->kq_head);
716 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
717 		if (kn == &marker) {
718 			splx(s);
719 			if (count == maxevents)
720 				goto retry;
721 			goto done;
722 		}
723 		if (kn->kn_status & KN_DISABLED) {
724 			kn->kn_status &= ~KN_QUEUED;
725 			kq->kq_count--;
726 			continue;
727 		}
728 		if ((kn->kn_flags & EV_ONESHOT) == 0 &&
729 		    kn->kn_fop->f_event(kn, 0) == 0) {
730 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
731 			kq->kq_count--;
732 			continue;
733 		}
734 		*kevp = kn->kn_kevent;
735 		kevp++;
736 		nkev++;
737 		if (kn->kn_flags & EV_ONESHOT) {
738 			kn->kn_status &= ~KN_QUEUED;
739 			kq->kq_count--;
740 			splx(s);
741 			kn->kn_fop->f_detach(kn);
742 			knote_drop(kn, td);
743 			s = splhigh();
744 		} else if (kn->kn_flags & EV_CLEAR) {
745 			kn->kn_data = 0;
746 			kn->kn_fflags = 0;
747 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
748 			kq->kq_count--;
749 		} else {
750 			TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
751 		}
752 		count--;
753 		if (nkev == KQ_NEVENTS) {
754 			splx(s);
755 			error = copyout(&kq->kq_kev, ulistp,
756 			    sizeof(struct kevent) * nkev);
757 			ulistp += nkev;
758 			nkev = 0;
759 			kevp = kq->kq_kev;
760 			s = splhigh();
761 			if (error)
762 				break;
763 		}
764 	}
765 	TAILQ_REMOVE(&kq->kq_head, &marker, kn_tqe);
766 	splx(s);
767 done:
768 	if (nkev != 0)
769 		error = copyout(&kq->kq_kev, ulistp,
770 		    sizeof(struct kevent) * nkev);
771         td->td_retval[0] = maxevents - count;
772 	return (error);
773 }
774 
775 /*
776  * XXX
777  * This could be expanded to call kqueue_scan, if desired.
778  */
779 /*ARGSUSED*/
780 static int
781 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
782 	int flags, struct thread *td)
783 {
784 	return (ENXIO);
785 }
786 
787 /*ARGSUSED*/
788 static int
789 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
790 	 int flags, struct thread *td)
791 {
792 	return (ENXIO);
793 }
794 
795 /*ARGSUSED*/
796 static int
797 kqueue_ioctl(struct file *fp, u_long com, void *data,
798 	struct ucred *active_cred, struct thread *td)
799 {
800 	return (ENOTTY);
801 }
802 
803 /*ARGSUSED*/
804 static int
805 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
806 	struct thread *td)
807 {
808 	struct kqueue *kq;
809 	int revents = 0;
810 	int s = splnet();
811 
812 	kq = (struct kqueue *)fp->f_data;
813         if (events & (POLLIN | POLLRDNORM)) {
814                 if (kq->kq_count) {
815                         revents |= events & (POLLIN | POLLRDNORM);
816 		} else {
817                         selrecord(td, &kq->kq_sel);
818 			kq->kq_state |= KQ_SEL;
819 		}
820 	}
821 	splx(s);
822 	return (revents);
823 }
824 
825 /*ARGSUSED*/
826 static int
827 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
828 	struct thread *td)
829 {
830 	struct kqueue *kq;
831 
832 	kq = (struct kqueue *)fp->f_data;
833 	bzero((void *)st, sizeof(*st));
834 	st->st_size = kq->kq_count;
835 	st->st_blksize = sizeof(struct kevent);
836 	st->st_mode = S_IFIFO;
837 	return (0);
838 }
839 
840 /*ARGSUSED*/
841 static int
842 kqueue_close(struct file *fp, struct thread *td)
843 {
844 	struct kqueue *kq = (struct kqueue *)fp->f_data;
845 	struct filedesc *fdp = td->td_proc->p_fd;
846 	struct knote **knp, *kn, *kn0;
847 	int i;
848 
849 	FILEDESC_LOCK(fdp);
850 	for (i = 0; i < fdp->fd_knlistsize; i++) {
851 		knp = &SLIST_FIRST(&fdp->fd_knlist[i]);
852 		kn = *knp;
853 		while (kn != NULL) {
854 			kn0 = SLIST_NEXT(kn, kn_link);
855 			if (kq == kn->kn_kq) {
856 				kn->kn_fop->f_detach(kn);
857 				*knp = kn0;
858 				FILE_LOCK(kn->kn_fp);
859 				FILEDESC_UNLOCK(fdp);
860 				fdrop_locked(kn->kn_fp, td);
861 				knote_free(kn);
862 				FILEDESC_LOCK(fdp);
863 			} else {
864 				knp = &SLIST_NEXT(kn, kn_link);
865 			}
866 			kn = kn0;
867 		}
868 	}
869 	if (fdp->fd_knhashmask != 0) {
870 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
871 			knp = &SLIST_FIRST(&fdp->fd_knhash[i]);
872 			kn = *knp;
873 			while (kn != NULL) {
874 				kn0 = SLIST_NEXT(kn, kn_link);
875 				if (kq == kn->kn_kq) {
876 					kn->kn_fop->f_detach(kn);
877 					*knp = kn0;
878 		/* XXX non-fd release of kn->kn_ptr */
879 					FILEDESC_UNLOCK(fdp);
880 					knote_free(kn);
881 					FILEDESC_LOCK(fdp);
882 				} else {
883 					knp = &SLIST_NEXT(kn, kn_link);
884 				}
885 				kn = kn0;
886 			}
887 		}
888 	}
889 	FILEDESC_UNLOCK(fdp);
890 	free(kq, M_KQUEUE);
891 	fp->f_data = NULL;
892 
893 	return (0);
894 }
895 
896 static void
897 kqueue_wakeup(struct kqueue *kq)
898 {
899 
900 	if (kq->kq_state & KQ_SLEEP) {
901 		kq->kq_state &= ~KQ_SLEEP;
902 		wakeup(kq);
903 	}
904 	if (kq->kq_state & KQ_SEL) {
905 		kq->kq_state &= ~KQ_SEL;
906 		selwakeup(&kq->kq_sel);
907 	}
908 	KNOTE(&kq->kq_sel.si_note, 0);
909 }
910 
911 /*
912  * walk down a list of knotes, activating them if their event has triggered.
913  */
914 void
915 knote(struct klist *list, long hint)
916 {
917 	struct knote *kn;
918 
919 	SLIST_FOREACH(kn, list, kn_selnext)
920 		if (kn->kn_fop->f_event(kn, hint))
921 			KNOTE_ACTIVATE(kn);
922 }
923 
924 /*
925  * remove all knotes from a specified klist
926  */
927 void
928 knote_remove(struct thread *td, struct klist *list)
929 {
930 	struct knote *kn;
931 
932 	while ((kn = SLIST_FIRST(list)) != NULL) {
933 		kn->kn_fop->f_detach(kn);
934 		knote_drop(kn, td);
935 	}
936 }
937 
938 /*
939  * remove all knotes referencing a specified fd
940  */
941 void
942 knote_fdclose(struct thread *td, int fd)
943 {
944 	struct filedesc *fdp = td->td_proc->p_fd;
945 	struct klist *list;
946 
947 	FILEDESC_LOCK(fdp);
948 	list = &fdp->fd_knlist[fd];
949 	FILEDESC_UNLOCK(fdp);
950 	knote_remove(td, list);
951 }
952 
953 static void
954 knote_attach(struct knote *kn, struct filedesc *fdp)
955 {
956 	struct klist *list, *oldlist, *tmp_knhash;
957 	u_long tmp_knhashmask;
958 	int size, newsize;
959 
960 	FILEDESC_LOCK(fdp);
961 
962 	if (! kn->kn_fop->f_isfd) {
963 		if (fdp->fd_knhashmask == 0) {
964 			FILEDESC_UNLOCK(fdp);
965 			tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
966 			    &tmp_knhashmask);
967 			FILEDESC_LOCK(fdp);
968 			if (fdp->fd_knhashmask == 0) {
969 				fdp->fd_knhash = tmp_knhash;
970 				fdp->fd_knhashmask = tmp_knhashmask;
971 			} else {
972 				FILEDESC_UNLOCK(fdp);
973 				free(tmp_knhash, M_KQUEUE);
974 				FILEDESC_LOCK(fdp);
975 			}
976 		}
977 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
978 		goto done;
979 	}
980 
981 	if (fdp->fd_knlistsize <= kn->kn_id) {
982 retry:
983 		size = fdp->fd_knlistsize;
984 		while (size <= kn->kn_id)
985 			size += KQEXTENT;
986 		FILEDESC_UNLOCK(fdp);
987 		MALLOC(list, struct klist *,
988 		    size * sizeof(struct klist *), M_KQUEUE, M_WAITOK);
989 		FILEDESC_LOCK(fdp);
990 		newsize = fdp->fd_knlistsize;
991 		while (newsize <= kn->kn_id)
992 			newsize += KQEXTENT;
993 		if (newsize != size) {
994 			FILEDESC_UNLOCK(fdp);
995 			free(list, M_TEMP);
996 			FILEDESC_LOCK(fdp);
997 			goto retry;
998 		}
999 		bcopy(fdp->fd_knlist, list,
1000 		    fdp->fd_knlistsize * sizeof(struct klist *));
1001 		bzero((caddr_t)list +
1002 		    fdp->fd_knlistsize * sizeof(struct klist *),
1003 		    (size - fdp->fd_knlistsize) * sizeof(struct klist *));
1004 		if (fdp->fd_knlist != NULL)
1005 			oldlist = fdp->fd_knlist;
1006 		else
1007 			oldlist = NULL;
1008 		fdp->fd_knlistsize = size;
1009 		fdp->fd_knlist = list;
1010 		FILEDESC_UNLOCK(fdp);
1011 		if (oldlist != NULL)
1012 			FREE(oldlist, M_KQUEUE);
1013 		FILEDESC_LOCK(fdp);
1014 	}
1015 	list = &fdp->fd_knlist[kn->kn_id];
1016 done:
1017 	FILEDESC_UNLOCK(fdp);
1018 	SLIST_INSERT_HEAD(list, kn, kn_link);
1019 	kn->kn_status = 0;
1020 }
1021 
1022 /*
1023  * should be called at spl == 0, since we don't want to hold spl
1024  * while calling fdrop and free.
1025  */
1026 static void
1027 knote_drop(struct knote *kn, struct thread *td)
1028 {
1029         struct filedesc *fdp = td->td_proc->p_fd;
1030 	struct klist *list;
1031 
1032 	FILEDESC_LOCK(fdp);
1033 	if (kn->kn_fop->f_isfd)
1034 		list = &fdp->fd_knlist[kn->kn_id];
1035 	else
1036 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1037 	if (kn->kn_fop->f_isfd)
1038 		FILE_LOCK(kn->kn_fp);
1039 	FILEDESC_UNLOCK(fdp);
1040 
1041 	SLIST_REMOVE(list, kn, knote, kn_link);
1042 	if (kn->kn_status & KN_QUEUED)
1043 		knote_dequeue(kn);
1044 	if (kn->kn_fop->f_isfd)
1045 		fdrop_locked(kn->kn_fp, td);
1046 	knote_free(kn);
1047 }
1048 
1049 
1050 static void
1051 knote_enqueue(struct knote *kn)
1052 {
1053 	struct kqueue *kq = kn->kn_kq;
1054 	int s = splhigh();
1055 
1056 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1057 
1058 	TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1059 	kn->kn_status |= KN_QUEUED;
1060 	kq->kq_count++;
1061 	splx(s);
1062 	kqueue_wakeup(kq);
1063 }
1064 
1065 static void
1066 knote_dequeue(struct knote *kn)
1067 {
1068 	struct kqueue *kq = kn->kn_kq;
1069 	int s = splhigh();
1070 
1071 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1072 
1073 	TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1074 	kn->kn_status &= ~KN_QUEUED;
1075 	kq->kq_count--;
1076 	splx(s);
1077 }
1078 
1079 static void
1080 knote_init(void)
1081 {
1082 	knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
1083 	    NULL, NULL, UMA_ALIGN_PTR, 0);
1084 
1085 }
1086 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1087 
1088 static struct knote *
1089 knote_alloc(void)
1090 {
1091 	return ((struct knote *)uma_zalloc(knote_zone, M_WAITOK));
1092 }
1093 
1094 static void
1095 knote_free(struct knote *kn)
1096 {
1097 	uma_zfree(knote_zone, kn);
1098 }
1099