xref: /dragonfly/sys/kern/kern_event.c (revision 5153f92b)
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: src/sys/kern/kern_event.c,v 1.2.2.10 2004/04/04 07:03:14 cperciva Exp $
27  * $DragonFly: src/sys/kern/kern_event.c,v 1.13 2004/11/12 00:09:23 dillon Exp $
28  */
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/proc.h>
34 #include <sys/malloc.h>
35 #include <sys/unistd.h>
36 #include <sys/file.h>
37 #include <sys/fcntl.h>
38 #include <sys/select.h>
39 #include <sys/queue.h>
40 #include <sys/event.h>
41 #include <sys/eventvar.h>
42 #include <sys/poll.h>
43 #include <sys/protosw.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/stat.h>
47 #include <sys/sysctl.h>
48 #include <sys/sysproto.h>
49 #include <sys/uio.h>
50 #include <sys/file2.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 proc *p, int *res);
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 	NULL,	/* port */
74 	NULL,	/* clone */
75 	kqueue_read,
76 	kqueue_write,
77 	kqueue_ioctl,
78 	kqueue_poll,
79 	kqueue_kqfilter,
80 	kqueue_stat,
81 	kqueue_close
82 };
83 
84 static void 	knote_attach(struct knote *kn, struct filedesc *fdp);
85 static void 	knote_drop(struct knote *kn, struct thread *td);
86 static void 	knote_enqueue(struct knote *kn);
87 static void 	knote_dequeue(struct knote *kn);
88 static void 	knote_init(void);
89 static struct 	knote *knote_alloc(void);
90 static void 	knote_free(struct knote *kn);
91 
92 static void	filt_kqdetach(struct knote *kn);
93 static int	filt_kqueue(struct knote *kn, long hint);
94 static int	filt_procattach(struct knote *kn);
95 static void	filt_procdetach(struct knote *kn);
96 static int	filt_proc(struct knote *kn, long hint);
97 static int	filt_fileattach(struct knote *kn);
98 static void	filt_timerexpire(void *knx);
99 static int	filt_timerattach(struct knote *kn);
100 static void	filt_timerdetach(struct knote *kn);
101 static int	filt_timer(struct knote *kn, long hint);
102 
103 static struct filterops file_filtops =
104 	{ 1, filt_fileattach, NULL, NULL };
105 static struct filterops kqread_filtops =
106 	{ 1, NULL, filt_kqdetach, filt_kqueue };
107 static struct filterops proc_filtops =
108 	{ 0, filt_procattach, filt_procdetach, filt_proc };
109 static struct filterops timer_filtops =
110 	{ 0, filt_timerattach, filt_timerdetach, filt_timer };
111 
112 static vm_zone_t	knote_zone;
113 static int 		kq_ncallouts = 0;
114 static int 		kq_calloutmax = (4 * 1024);
115 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
116     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
117 
118 #define KNOTE_ACTIVATE(kn) do { 					\
119 	kn->kn_status |= KN_ACTIVE;					\
120 	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
121 		knote_enqueue(kn);					\
122 } while(0)
123 
124 #define	KN_HASHSIZE		64		/* XXX should be tunable */
125 #define KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
126 
127 extern struct filterops aio_filtops;
128 extern struct filterops sig_filtops;
129 
130 /*
131  * Table for for all system-defined filters.
132  */
133 static struct filterops *sysfilt_ops[] = {
134 	&file_filtops,			/* EVFILT_READ */
135 	&file_filtops,			/* EVFILT_WRITE */
136 	&aio_filtops,			/* EVFILT_AIO */
137 	&file_filtops,			/* EVFILT_VNODE */
138 	&proc_filtops,			/* EVFILT_PROC */
139 	&sig_filtops,			/* EVFILT_SIGNAL */
140 	&timer_filtops,			/* EVFILT_TIMER */
141 };
142 
143 static int
144 filt_fileattach(struct knote *kn)
145 {
146 	return (fo_kqfilter(kn->kn_fp, kn));
147 }
148 
149 /*ARGSUSED*/
150 static int
151 kqueue_kqfilter(struct file *fp, struct knote *kn)
152 {
153 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
154 
155 	if (kn->kn_filter != EVFILT_READ)
156 		return (1);
157 
158 	kn->kn_fop = &kqread_filtops;
159 	SLIST_INSERT_HEAD(&kq->kq_sel.si_note, kn, kn_selnext);
160 	return (0);
161 }
162 
163 static void
164 filt_kqdetach(struct knote *kn)
165 {
166 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
167 
168 	SLIST_REMOVE(&kq->kq_sel.si_note, kn, knote, kn_selnext);
169 }
170 
171 /*ARGSUSED*/
172 static int
173 filt_kqueue(struct knote *kn, long hint)
174 {
175 	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
176 
177 	kn->kn_data = kq->kq_count;
178 	return (kn->kn_data > 0);
179 }
180 
181 static int
182 filt_procattach(struct knote *kn)
183 {
184 	struct proc *p;
185 	int immediate;
186 
187 	immediate = 0;
188 	p = pfind(kn->kn_id);
189 	if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
190 		p = zpfind(kn->kn_id);
191 		immediate = 1;
192 	}
193 	if (p == NULL)
194 		return (ESRCH);
195 	if (! PRISON_CHECK(curproc->p_ucred, p->p_ucred))
196 		return (EACCES);
197 
198 	kn->kn_ptr.p_proc = p;
199 	kn->kn_flags |= EV_CLEAR;		/* automatically set */
200 
201 	/*
202 	 * internal flag indicating registration done by kernel
203 	 */
204 	if (kn->kn_flags & EV_FLAG1) {
205 		kn->kn_data = kn->kn_sdata;		/* ppid */
206 		kn->kn_fflags = NOTE_CHILD;
207 		kn->kn_flags &= ~EV_FLAG1;
208 	}
209 
210 	/* XXX lock the proc here while adding to the list? */
211 	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
212 
213 	/*
214 	 * Immediately activate any exit notes if the target process is a
215 	 * zombie.  This is necessary to handle the case where the target
216 	 * process, e.g. a child, dies before the kevent is registered.
217 	 */
218 	if (immediate && filt_proc(kn, NOTE_EXIT))
219 		KNOTE_ACTIVATE(kn);
220 
221 	return (0);
222 }
223 
224 /*
225  * The knote may be attached to a different process, which may exit,
226  * leaving nothing for the knote to be attached to.  So when the process
227  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
228  * it will be deleted when read out.  However, as part of the knote deletion,
229  * this routine is called, so a check is needed to avoid actually performing
230  * a detach, because the original process does not exist any more.
231  */
232 static void
233 filt_procdetach(struct knote *kn)
234 {
235 	struct proc *p = kn->kn_ptr.p_proc;
236 
237 	if (kn->kn_status & KN_DETACHED)
238 		return;
239 
240 	/* XXX locking?  this might modify another process. */
241 	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
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_high(&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_high(&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);
337 	kn->kn_hook = (caddr_t)calloutp;
338 	callout_reset(calloutp, tticks, filt_timerexpire, kn);
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 int
362 kqueue(struct kqueue_args *uap)
363 {
364 	struct proc *p = curproc;
365 	struct filedesc *fdp = p->p_fd;
366 	struct kqueue *kq;
367 	struct file *fp;
368 	int fd, error;
369 
370 	error = falloc(p, &fp, &fd);
371 	if (error)
372 		return (error);
373 	fp->f_flag = FREAD | FWRITE;
374 	fp->f_type = DTYPE_KQUEUE;
375 	fp->f_ops = &kqueueops;
376 	kq = malloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
377 	TAILQ_INIT(&kq->kq_head);
378 	fp->f_data = (caddr_t)kq;
379 	uap->sysmsg_result = fd;
380 	fdrop(fp, curthread);
381 	if (fdp->fd_knlistsize < 0)
382 		fdp->fd_knlistsize = 0;		/* this process has a kq */
383 	kq->kq_fdp = fdp;
384 	return (error);
385 }
386 
387 int
388 kevent(struct kevent_args *uap)
389 {
390 	struct thread *td = curthread;
391 	struct proc *p = td->td_proc;
392 	struct filedesc *fdp;
393 	struct kevent *kevp;
394 	struct kqueue *kq;
395 	struct file *fp = NULL;
396 	struct timespec ts;
397 	int i, n, nerrors, error;
398 
399 	KKASSERT(p);
400 	fdp = p->p_fd;
401 
402         if (((u_int)uap->fd) >= fdp->fd_nfiles ||
403             (fp = fdp->fd_ofiles[uap->fd]) == NULL ||
404 	    (fp->f_type != DTYPE_KQUEUE))
405 		return (EBADF);
406 
407 	fhold(fp);
408 
409 	if (uap->timeout != NULL) {
410 		error = copyin(uap->timeout, &ts, sizeof(ts));
411 		if (error)
412 			goto done;
413 		uap->timeout = &ts;
414 	}
415 
416 	kq = (struct kqueue *)fp->f_data;
417 	nerrors = 0;
418 
419 	while (uap->nchanges > 0) {
420 		n = uap->nchanges > KQ_NEVENTS ? KQ_NEVENTS : uap->nchanges;
421 		error = copyin(uap->changelist, kq->kq_kev,
422 		    n * sizeof(struct kevent));
423 		if (error)
424 			goto done;
425 		for (i = 0; i < n; i++) {
426 			kevp = &kq->kq_kev[i];
427 			kevp->flags &= ~EV_SYSFLAGS;
428 			error = kqueue_register(kq, kevp, td);
429 			if (error) {
430 				if (uap->nevents != 0) {
431 					kevp->flags = EV_ERROR;
432 					kevp->data = error;
433 					(void) copyout((caddr_t)kevp,
434 					    (caddr_t)uap->eventlist,
435 					    sizeof(*kevp));
436 					uap->eventlist++;
437 					uap->nevents--;
438 					nerrors++;
439 				} else {
440 					goto done;
441 				}
442 			}
443 		}
444 		uap->nchanges -= n;
445 		uap->changelist += n;
446 	}
447 	if (nerrors) {
448         	uap->sysmsg_result = nerrors;
449 		error = 0;
450 		goto done;
451 	}
452 
453 	error = kqueue_scan(fp, uap->nevents, uap->eventlist, uap->timeout, p, &uap->sysmsg_result);
454 done:
455 	if (fp != NULL)
456 		fdrop(fp, p->p_thread);
457 	return (error);
458 }
459 
460 int
461 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td)
462 {
463 	struct filedesc *fdp = kq->kq_fdp;
464 	struct filterops *fops;
465 	struct file *fp = NULL;
466 	struct knote *kn = NULL;
467 	int s, error = 0;
468 
469 	if (kev->filter < 0) {
470 		if (kev->filter + EVFILT_SYSCOUNT < 0)
471 			return (EINVAL);
472 		fops = sysfilt_ops[~kev->filter];	/* to 0-base index */
473 	} else {
474 		/*
475 		 * XXX
476 		 * filter attach routine is responsible for insuring that
477 		 * the identifier can be attached to it.
478 		 */
479 		printf("unknown filter: %d\n", kev->filter);
480 		return (EINVAL);
481 	}
482 
483 	if (fops->f_isfd) {
484 		/* validate descriptor */
485 		if ((u_int)kev->ident >= fdp->fd_nfiles ||
486 		    (fp = fdp->fd_ofiles[kev->ident]) == NULL)
487 			return (EBADF);
488 		fhold(fp);
489 
490 		if (kev->ident < fdp->fd_knlistsize) {
491 			SLIST_FOREACH(kn, &fdp->fd_knlist[kev->ident], kn_link)
492 				if (kq == kn->kn_kq &&
493 				    kev->filter == kn->kn_filter)
494 					break;
495 		}
496 	} else {
497 		if (fdp->fd_knhashmask != 0) {
498 			struct klist *list;
499 
500 			list = &fdp->fd_knhash[
501 			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
502 			SLIST_FOREACH(kn, list, kn_link)
503 				if (kev->ident == kn->kn_id &&
504 				    kq == kn->kn_kq &&
505 				    kev->filter == kn->kn_filter)
506 					break;
507 		}
508 	}
509 
510 	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
511 		error = ENOENT;
512 		goto done;
513 	}
514 
515 	/*
516 	 * kn now contains the matching knote, or NULL if no match
517 	 */
518 	if (kev->flags & EV_ADD) {
519 
520 		if (kn == NULL) {
521 			kn = knote_alloc();
522 			if (kn == NULL) {
523 				error = ENOMEM;
524 				goto done;
525 			}
526 			kn->kn_fp = fp;
527 			kn->kn_kq = kq;
528 			kn->kn_fop = fops;
529 
530 			/*
531 			 * apply reference count to knote structure, and
532 			 * do not release it at the end of this routine.
533 			 */
534 			fp = NULL;
535 
536 			kn->kn_sfflags = kev->fflags;
537 			kn->kn_sdata = kev->data;
538 			kev->fflags = 0;
539 			kev->data = 0;
540 			kn->kn_kevent = *kev;
541 
542 			knote_attach(kn, fdp);
543 			if ((error = fops->f_attach(kn)) != 0) {
544 				knote_drop(kn, td);
545 				goto done;
546 			}
547 		} else {
548 			/*
549 			 * The user may change some filter values after the
550 			 * initial EV_ADD, but doing so will not reset any
551 			 * filter which have already been triggered.
552 			 */
553 			kn->kn_sfflags = kev->fflags;
554 			kn->kn_sdata = kev->data;
555 			kn->kn_kevent.udata = kev->udata;
556 		}
557 
558 		s = splhigh();
559 		if (kn->kn_fop->f_event(kn, 0))
560 			KNOTE_ACTIVATE(kn);
561 		splx(s);
562 
563 	} else if (kev->flags & EV_DELETE) {
564 		kn->kn_fop->f_detach(kn);
565 		knote_drop(kn, td);
566 		goto done;
567 	}
568 
569 	if ((kev->flags & EV_DISABLE) &&
570 	    ((kn->kn_status & KN_DISABLED) == 0)) {
571 		s = splhigh();
572 		kn->kn_status |= KN_DISABLED;
573 		splx(s);
574 	}
575 
576 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
577 		s = splhigh();
578 		kn->kn_status &= ~KN_DISABLED;
579 		if ((kn->kn_status & KN_ACTIVE) &&
580 		    ((kn->kn_status & KN_QUEUED) == 0))
581 			knote_enqueue(kn);
582 		splx(s);
583 	}
584 
585 done:
586 	if (fp != NULL)
587 		fdrop(fp, td);
588 	return (error);
589 }
590 
591 static int
592 kqueue_scan(struct file *fp, int maxevents, struct kevent *ulistp,
593 	const struct timespec *tsp, struct proc *p, int *res)
594 {
595 	struct thread *td = p->p_thread;
596 	struct kqueue *kq = (struct kqueue *)fp->f_data;
597 	struct kevent *kevp;
598 	struct timeval atv, rtv, ttv;
599 	struct knote *kn, marker;
600 	int s, count, timeout, nkev = 0, error = 0;
601 
602 	count = maxevents;
603 	if (count == 0)
604 		goto done;
605 
606 	if (tsp != NULL) {
607 		TIMESPEC_TO_TIMEVAL(&atv, tsp);
608 		if (itimerfix(&atv)) {
609 			error = EINVAL;
610 			goto done;
611 		}
612 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
613 			timeout = -1;
614 		else
615 			timeout = atv.tv_sec > 24 * 60 * 60 ?
616 			    24 * 60 * 60 * hz : tvtohz_high(&atv);
617 		getmicrouptime(&rtv);
618 		timevaladd(&atv, &rtv);
619 	} else {
620 		atv.tv_sec = 0;
621 		atv.tv_usec = 0;
622 		timeout = 0;
623 	}
624 	goto start;
625 
626 retry:
627 	if (atv.tv_sec || atv.tv_usec) {
628 		getmicrouptime(&rtv);
629 		if (timevalcmp(&rtv, &atv, >=))
630 			goto done;
631 		ttv = atv;
632 		timevalsub(&ttv, &rtv);
633 		timeout = ttv.tv_sec > 24 * 60 * 60 ?
634 			24 * 60 * 60 * hz : tvtohz_high(&ttv);
635 	}
636 
637 start:
638 	kevp = kq->kq_kev;
639 	s = splhigh();
640 	if (kq->kq_count == 0) {
641 		if (timeout < 0) {
642 			error = EWOULDBLOCK;
643 		} else {
644 			kq->kq_state |= KQ_SLEEP;
645 			error = tsleep(kq, PCATCH, "kqread", timeout);
646 		}
647 		splx(s);
648 		if (error == 0)
649 			goto retry;
650 		/* don't restart after signals... */
651 		if (error == ERESTART)
652 			error = EINTR;
653 		else if (error == EWOULDBLOCK)
654 			error = 0;
655 		goto done;
656 	}
657 
658 	TAILQ_INSERT_TAIL(&kq->kq_head, &marker, kn_tqe);
659 	while (count) {
660 		kn = TAILQ_FIRST(&kq->kq_head);
661 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
662 		if (kn == &marker) {
663 			splx(s);
664 			if (count == maxevents)
665 				goto retry;
666 			goto done;
667 		}
668 		if (kn->kn_status & KN_DISABLED) {
669 			kn->kn_status &= ~KN_QUEUED;
670 			kq->kq_count--;
671 			continue;
672 		}
673 		if ((kn->kn_flags & EV_ONESHOT) == 0 &&
674 		    kn->kn_fop->f_event(kn, 0) == 0) {
675 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
676 			kq->kq_count--;
677 			continue;
678 		}
679 		*kevp = kn->kn_kevent;
680 		kevp++;
681 		nkev++;
682 		if (kn->kn_flags & EV_ONESHOT) {
683 			kn->kn_status &= ~KN_QUEUED;
684 			kq->kq_count--;
685 			splx(s);
686 			kn->kn_fop->f_detach(kn);
687 			knote_drop(kn, td);
688 			s = splhigh();
689 		} else if (kn->kn_flags & EV_CLEAR) {
690 			kn->kn_data = 0;
691 			kn->kn_fflags = 0;
692 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
693 			kq->kq_count--;
694 		} else {
695 			TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
696 		}
697 		count--;
698 		if (nkev == KQ_NEVENTS) {
699 			splx(s);
700 			error = copyout((caddr_t)&kq->kq_kev, (caddr_t)ulistp,
701 			    sizeof(struct kevent) * nkev);
702 			ulistp += nkev;
703 			nkev = 0;
704 			kevp = kq->kq_kev;
705 			s = splhigh();
706 			if (error)
707 				break;
708 		}
709 	}
710 	TAILQ_REMOVE(&kq->kq_head, &marker, kn_tqe);
711 	splx(s);
712 done:
713 	if (nkev != 0)
714 		error = copyout((caddr_t)&kq->kq_kev, (caddr_t)ulistp,
715 		    sizeof(struct kevent) * nkev);
716         *res = maxevents - count;
717 	return (error);
718 }
719 
720 /*
721  * XXX
722  * This could be expanded to call kqueue_scan, if desired.
723  */
724 /*ARGSUSED*/
725 static int
726 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred,
727 	int flags, struct thread *td)
728 {
729 	return (ENXIO);
730 }
731 
732 /*ARGSUSED*/
733 static int
734 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred,
735 	 int flags, struct thread *td)
736 {
737 	return (ENXIO);
738 }
739 
740 /*ARGSUSED*/
741 static int
742 kqueue_ioctl(struct file *fp, u_long com, caddr_t data, struct thread *td)
743 {
744 	return (ENOTTY);
745 }
746 
747 /*ARGSUSED*/
748 static int
749 kqueue_poll(struct file *fp, int events, struct ucred *cred, struct thread *td)
750 {
751 	struct kqueue *kq = (struct kqueue *)fp->f_data;
752 	int revents = 0;
753 	int s = splnet();
754 
755         if (events & (POLLIN | POLLRDNORM)) {
756                 if (kq->kq_count) {
757                         revents |= events & (POLLIN | POLLRDNORM);
758 		} else {
759                         selrecord(td, &kq->kq_sel);
760 			kq->kq_state |= KQ_SEL;
761 		}
762 	}
763 	splx(s);
764 	return (revents);
765 }
766 
767 /*ARGSUSED*/
768 static int
769 kqueue_stat(struct file *fp, struct stat *st, struct thread *td)
770 {
771 	struct kqueue *kq = (struct kqueue *)fp->f_data;
772 
773 	bzero((void *)st, sizeof(*st));
774 	st->st_size = kq->kq_count;
775 	st->st_blksize = sizeof(struct kevent);
776 	st->st_mode = S_IFIFO;
777 	return (0);
778 }
779 
780 /*ARGSUSED*/
781 static int
782 kqueue_close(struct file *fp, struct thread *td)
783 {
784 	struct proc *p = td->td_proc;
785 	struct kqueue *kq = (struct kqueue *)fp->f_data;
786 	struct filedesc *fdp;
787 	struct knote **knp, *kn, *kn0;
788 	int i;
789 
790 	KKASSERT(p);
791 	fdp = p->p_fd;
792 	for (i = 0; i < fdp->fd_knlistsize; i++) {
793 		knp = &SLIST_FIRST(&fdp->fd_knlist[i]);
794 		kn = *knp;
795 		while (kn != NULL) {
796 			kn0 = SLIST_NEXT(kn, kn_link);
797 			if (kq == kn->kn_kq) {
798 				kn->kn_fop->f_detach(kn);
799 				fdrop(kn->kn_fp, td);
800 				knote_free(kn);
801 				*knp = kn0;
802 			} else {
803 				knp = &SLIST_NEXT(kn, kn_link);
804 			}
805 			kn = kn0;
806 		}
807 	}
808 	if (fdp->fd_knhashmask != 0) {
809 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
810 			knp = &SLIST_FIRST(&fdp->fd_knhash[i]);
811 			kn = *knp;
812 			while (kn != NULL) {
813 				kn0 = SLIST_NEXT(kn, kn_link);
814 				if (kq == kn->kn_kq) {
815 					kn->kn_fop->f_detach(kn);
816 		/* XXX non-fd release of kn->kn_ptr */
817 					knote_free(kn);
818 					*knp = kn0;
819 				} else {
820 					knp = &SLIST_NEXT(kn, kn_link);
821 				}
822 				kn = kn0;
823 			}
824 		}
825 	}
826 	free(kq, M_KQUEUE);
827 	fp->f_data = NULL;
828 
829 	return (0);
830 }
831 
832 static void
833 kqueue_wakeup(struct kqueue *kq)
834 {
835 
836 	if (kq->kq_state & KQ_SLEEP) {
837 		kq->kq_state &= ~KQ_SLEEP;
838 		wakeup(kq);
839 	}
840 	if (kq->kq_state & KQ_SEL) {
841 		kq->kq_state &= ~KQ_SEL;
842 		selwakeup(&kq->kq_sel);
843 	}
844 	KNOTE(&kq->kq_sel.si_note, 0);
845 }
846 
847 /*
848  * walk down a list of knotes, activating them if their event has triggered.
849  */
850 void
851 knote(struct klist *list, long hint)
852 {
853 	struct knote *kn;
854 
855 	SLIST_FOREACH(kn, list, kn_selnext)
856 		if (kn->kn_fop->f_event(kn, hint))
857 			KNOTE_ACTIVATE(kn);
858 }
859 
860 /*
861  * remove all knotes from a specified klist
862  */
863 void
864 knote_remove(struct thread *td, struct klist *list)
865 {
866 	struct knote *kn;
867 
868 	while ((kn = SLIST_FIRST(list)) != NULL) {
869 		kn->kn_fop->f_detach(kn);
870 		knote_drop(kn, td);
871 	}
872 }
873 
874 /*
875  * remove all knotes referencing a specified fd
876  */
877 void
878 knote_fdclose(struct proc *p, int fd)
879 {
880 	struct filedesc *fdp = p->p_fd;
881 	struct klist *list = &fdp->fd_knlist[fd];
882 
883 	knote_remove(p->p_thread, list);
884 }
885 
886 static void
887 knote_attach(struct knote *kn, struct filedesc *fdp)
888 {
889 	struct klist *list;
890 	int size;
891 
892 	if (! kn->kn_fop->f_isfd) {
893 		if (fdp->fd_knhashmask == 0)
894 			fdp->fd_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
895 			    &fdp->fd_knhashmask);
896 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
897 		goto done;
898 	}
899 
900 	if (fdp->fd_knlistsize <= kn->kn_id) {
901 		size = fdp->fd_knlistsize;
902 		while (size <= kn->kn_id)
903 			size += KQEXTENT;
904 		MALLOC(list, struct klist *,
905 		    size * sizeof(struct klist *), M_KQUEUE, M_WAITOK);
906 		bcopy((caddr_t)fdp->fd_knlist, (caddr_t)list,
907 		    fdp->fd_knlistsize * sizeof(struct klist *));
908 		bzero((caddr_t)list +
909 		    fdp->fd_knlistsize * sizeof(struct klist *),
910 		    (size - fdp->fd_knlistsize) * sizeof(struct klist *));
911 		if (fdp->fd_knlist != NULL)
912 			FREE(fdp->fd_knlist, M_KQUEUE);
913 		fdp->fd_knlistsize = size;
914 		fdp->fd_knlist = list;
915 	}
916 	list = &fdp->fd_knlist[kn->kn_id];
917 done:
918 	SLIST_INSERT_HEAD(list, kn, kn_link);
919 	kn->kn_status = 0;
920 }
921 
922 /*
923  * should be called at spl == 0, since we don't want to hold spl
924  * while calling fdrop and free.
925  */
926 static void
927 knote_drop(struct knote *kn, struct thread *td)
928 {
929         struct filedesc *fdp;
930 	struct klist *list;
931 
932 	KKASSERT(td->td_proc);
933         fdp = td->td_proc->p_fd;
934 	if (kn->kn_fop->f_isfd)
935 		list = &fdp->fd_knlist[kn->kn_id];
936 	else
937 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
938 
939 	SLIST_REMOVE(list, kn, knote, kn_link);
940 	if (kn->kn_status & KN_QUEUED)
941 		knote_dequeue(kn);
942 	if (kn->kn_fop->f_isfd)
943 		fdrop(kn->kn_fp, td);
944 	knote_free(kn);
945 }
946 
947 
948 static void
949 knote_enqueue(struct knote *kn)
950 {
951 	struct kqueue *kq = kn->kn_kq;
952 	int s = splhigh();
953 
954 	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
955 
956 	TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
957 	kn->kn_status |= KN_QUEUED;
958 	kq->kq_count++;
959 	splx(s);
960 	kqueue_wakeup(kq);
961 }
962 
963 static void
964 knote_dequeue(struct knote *kn)
965 {
966 	struct kqueue *kq = kn->kn_kq;
967 	int s = splhigh();
968 
969 	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
970 
971 	TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
972 	kn->kn_status &= ~KN_QUEUED;
973 	kq->kq_count--;
974 	splx(s);
975 }
976 
977 static void
978 knote_init(void)
979 {
980 	knote_zone = zinit("KNOTE", sizeof(struct knote), 0, 0, 1);
981 }
982 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
983 
984 static struct knote *
985 knote_alloc(void)
986 {
987 	return ((struct knote *)zalloc(knote_zone));
988 }
989 
990 static void
991 knote_free(struct knote *kn)
992 {
993 	zfree(knote_zone, kn);
994 }
995