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