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