xref: /freebsd/sys/kern/kern_event.c (revision 41466b50c1d5bfd1cf6adaae547a579a75d7c04e)
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 filedesc *fdp;
398 	struct kevent *kevp;
399 	struct kqueue *kq;
400 	struct file *fp = NULL;
401 	struct timespec ts;
402 	int i, n, nerrors, error;
403 
404 	mtx_lock(&Giant);
405 	fdp = td->td_proc->p_fd;
406         if (((u_int)uap->fd) >= fdp->fd_nfiles ||
407             (fp = fdp->fd_ofiles[uap->fd]) == NULL ||
408 	    (fp->f_type != DTYPE_KQUEUE)) {
409 		error = EBADF;
410 		goto done;
411 	}
412 	fhold(fp);
413 
414 	if (uap->timeout != NULL) {
415 		error = copyin(uap->timeout, &ts, sizeof(ts));
416 		if (error)
417 			goto done;
418 		uap->timeout = &ts;
419 	}
420 
421 	kq = (struct kqueue *)fp->f_data;
422 	nerrors = 0;
423 
424 	while (uap->nchanges > 0) {
425 		n = uap->nchanges > KQ_NEVENTS ? KQ_NEVENTS : uap->nchanges;
426 		error = copyin(uap->changelist, kq->kq_kev,
427 		    n * sizeof(struct kevent));
428 		if (error)
429 			goto done;
430 		for (i = 0; i < n; i++) {
431 			kevp = &kq->kq_kev[i];
432 			kevp->flags &= ~EV_SYSFLAGS;
433 			error = kqueue_register(kq, kevp, td);
434 			if (error) {
435 				if (uap->nevents != 0) {
436 					kevp->flags = EV_ERROR;
437 					kevp->data = error;
438 					(void) copyout((caddr_t)kevp,
439 					    (caddr_t)uap->eventlist,
440 					    sizeof(*kevp));
441 					uap->eventlist++;
442 					uap->nevents--;
443 					nerrors++;
444 				} else {
445 					goto done;
446 				}
447 			}
448 		}
449 		uap->nchanges -= n;
450 		uap->changelist += n;
451 	}
452 	if (nerrors) {
453         	td->td_retval[0] = nerrors;
454 		error = 0;
455 		goto done;
456 	}
457 
458 	error = kqueue_scan(fp, uap->nevents, uap->eventlist, uap->timeout, td);
459 done:
460 	if (fp != NULL)
461 		fdrop(fp, td);
462 	mtx_unlock(&Giant);
463 	return (error);
464 }
465 
466 int
467 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td)
468 {
469 	struct filedesc *fdp = kq->kq_fdp;
470 	struct filterops *fops;
471 	struct file *fp = NULL;
472 	struct knote *kn = NULL;
473 	int s, error = 0;
474 
475 	if (kev->filter < 0) {
476 		if (kev->filter + EVFILT_SYSCOUNT < 0)
477 			return (EINVAL);
478 		fops = sysfilt_ops[~kev->filter];	/* to 0-base index */
479 	} else {
480 		/*
481 		 * XXX
482 		 * filter attach routine is responsible for insuring that
483 		 * the identifier can be attached to it.
484 		 */
485 		printf("unknown filter: %d\n", kev->filter);
486 		return (EINVAL);
487 	}
488 
489 	if (fops->f_isfd) {
490 		/* validate descriptor */
491 		if ((u_int)kev->ident >= fdp->fd_nfiles ||
492 		    (fp = fdp->fd_ofiles[kev->ident]) == NULL)
493 			return (EBADF);
494 		fhold(fp);
495 
496 		if (kev->ident < fdp->fd_knlistsize) {
497 			SLIST_FOREACH(kn, &fdp->fd_knlist[kev->ident], kn_link)
498 				if (kq == kn->kn_kq &&
499 				    kev->filter == kn->kn_filter)
500 					break;
501 		}
502 	} else {
503 		if (fdp->fd_knhashmask != 0) {
504 			struct klist *list;
505 
506 			list = &fdp->fd_knhash[
507 			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
508 			SLIST_FOREACH(kn, list, kn_link)
509 				if (kev->ident == kn->kn_id &&
510 				    kq == kn->kn_kq &&
511 				    kev->filter == kn->kn_filter)
512 					break;
513 		}
514 	}
515 
516 	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
517 		error = ENOENT;
518 		goto done;
519 	}
520 
521 	/*
522 	 * kn now contains the matching knote, or NULL if no match
523 	 */
524 	if (kev->flags & EV_ADD) {
525 
526 		if (kn == NULL) {
527 			kn = knote_alloc();
528 			if (kn == NULL) {
529 				error = ENOMEM;
530 				goto done;
531 			}
532 			kn->kn_fp = fp;
533 			kn->kn_kq = kq;
534 			kn->kn_fop = fops;
535 
536 			/*
537 			 * apply reference count to knote structure, and
538 			 * do not release it at the end of this routine.
539 			 */
540 			fp = NULL;
541 
542 			kn->kn_sfflags = kev->fflags;
543 			kn->kn_sdata = kev->data;
544 			kev->fflags = 0;
545 			kev->data = 0;
546 			kn->kn_kevent = *kev;
547 
548 			knote_attach(kn, fdp);
549 			if ((error = fops->f_attach(kn)) != 0) {
550 				knote_drop(kn, td);
551 				goto done;
552 			}
553 		} else {
554 			/*
555 			 * The user may change some filter values after the
556 			 * initial EV_ADD, but doing so will not reset any
557 			 * filter which have already been triggered.
558 			 */
559 			kn->kn_sfflags = kev->fflags;
560 			kn->kn_sdata = kev->data;
561 			kn->kn_kevent.udata = kev->udata;
562 		}
563 
564 		s = splhigh();
565 		if (kn->kn_fop->f_event(kn, 0))
566 			KNOTE_ACTIVATE(kn);
567 		splx(s);
568 
569 	} else if (kev->flags & EV_DELETE) {
570 		kn->kn_fop->f_detach(kn);
571 		knote_drop(kn, td);
572 		goto done;
573 	}
574 
575 	if ((kev->flags & EV_DISABLE) &&
576 	    ((kn->kn_status & KN_DISABLED) == 0)) {
577 		s = splhigh();
578 		kn->kn_status |= KN_DISABLED;
579 		splx(s);
580 	}
581 
582 	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
583 		s = splhigh();
584 		kn->kn_status &= ~KN_DISABLED;
585 		if ((kn->kn_status & KN_ACTIVE) &&
586 		    ((kn->kn_status & KN_QUEUED) == 0))
587 			knote_enqueue(kn);
588 		splx(s);
589 	}
590 
591 done:
592 	if (fp != NULL)
593 		fdrop(fp, td);
594 	return (error);
595 }
596 
597 static int
598 kqueue_scan(struct file *fp, int maxevents, struct kevent *ulistp,
599 	const struct timespec *tsp, struct thread *td)
600 {
601 	struct kqueue *kq = (struct kqueue *)fp->f_data;
602 	struct kevent *kevp;
603 	struct timeval atv, rtv, ttv;
604 	struct knote *kn, marker;
605 	int s, count, timeout, nkev = 0, error = 0;
606 
607 	count = maxevents;
608 	if (count == 0)
609 		goto done;
610 
611 	if (tsp != NULL) {
612 		TIMESPEC_TO_TIMEVAL(&atv, tsp);
613 		if (itimerfix(&atv)) {
614 			error = EINVAL;
615 			goto done;
616 		}
617 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
618 			timeout = -1;
619 		else
620 			timeout = atv.tv_sec > 24 * 60 * 60 ?
621 			    24 * 60 * 60 * hz : tvtohz(&atv);
622 		getmicrouptime(&rtv);
623 		timevaladd(&atv, &rtv);
624 	} else {
625 		atv.tv_sec = 0;
626 		atv.tv_usec = 0;
627 		timeout = 0;
628 	}
629 	goto start;
630 
631 retry:
632 	if (atv.tv_sec || atv.tv_usec) {
633 		getmicrouptime(&rtv);
634 		if (timevalcmp(&rtv, &atv, >=))
635 			goto done;
636 		ttv = atv;
637 		timevalsub(&ttv, &rtv);
638 		timeout = ttv.tv_sec > 24 * 60 * 60 ?
639 			24 * 60 * 60 * hz : tvtohz(&ttv);
640 	}
641 
642 start:
643 	kevp = kq->kq_kev;
644 	s = splhigh();
645 	if (kq->kq_count == 0) {
646 		if (timeout < 0) {
647 			error = EWOULDBLOCK;
648 		} else {
649 			kq->kq_state |= KQ_SLEEP;
650 			error = tsleep(kq, PSOCK | PCATCH, "kqread", timeout);
651 		}
652 		splx(s);
653 		if (error == 0)
654 			goto retry;
655 		/* don't restart after signals... */
656 		if (error == ERESTART)
657 			error = EINTR;
658 		else if (error == EWOULDBLOCK)
659 			error = 0;
660 		goto done;
661 	}
662 
663 	TAILQ_INSERT_TAIL(&kq->kq_head, &marker, kn_tqe);
664 	while (count) {
665 		kn = TAILQ_FIRST(&kq->kq_head);
666 		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
667 		if (kn == &marker) {
668 			splx(s);
669 			if (count == maxevents)
670 				goto retry;
671 			goto done;
672 		}
673 		if (kn->kn_status & KN_DISABLED) {
674 			kn->kn_status &= ~KN_QUEUED;
675 			kq->kq_count--;
676 			continue;
677 		}
678 		if ((kn->kn_flags & EV_ONESHOT) == 0 &&
679 		    kn->kn_fop->f_event(kn, 0) == 0) {
680 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
681 			kq->kq_count--;
682 			continue;
683 		}
684 		*kevp = kn->kn_kevent;
685 		kevp++;
686 		nkev++;
687 		if (kn->kn_flags & EV_ONESHOT) {
688 			kn->kn_status &= ~KN_QUEUED;
689 			kq->kq_count--;
690 			splx(s);
691 			kn->kn_fop->f_detach(kn);
692 			knote_drop(kn, td);
693 			s = splhigh();
694 		} else if (kn->kn_flags & EV_CLEAR) {
695 			kn->kn_data = 0;
696 			kn->kn_fflags = 0;
697 			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
698 			kq->kq_count--;
699 		} else {
700 			TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
701 		}
702 		count--;
703 		if (nkev == KQ_NEVENTS) {
704 			splx(s);
705 			error = copyout((caddr_t)&kq->kq_kev, (caddr_t)ulistp,
706 			    sizeof(struct kevent) * nkev);
707 			ulistp += nkev;
708 			nkev = 0;
709 			kevp = kq->kq_kev;
710 			s = splhigh();
711 			if (error)
712 				break;
713 		}
714 	}
715 	TAILQ_REMOVE(&kq->kq_head, &marker, kn_tqe);
716 	splx(s);
717 done:
718 	if (nkev != 0)
719 		error = copyout((caddr_t)&kq->kq_kev, (caddr_t)ulistp,
720 		    sizeof(struct kevent) * nkev);
721         td->td_retval[0] = maxevents - count;
722 	return (error);
723 }
724 
725 /*
726  * XXX
727  * This could be expanded to call kqueue_scan, if desired.
728  */
729 /*ARGSUSED*/
730 static int
731 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred,
732 	int flags, struct thread *td)
733 {
734 	return (ENXIO);
735 }
736 
737 /*ARGSUSED*/
738 static int
739 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred,
740 	 int flags, struct thread *td)
741 {
742 	return (ENXIO);
743 }
744 
745 /*ARGSUSED*/
746 static int
747 kqueue_ioctl(struct file *fp, u_long com, caddr_t data, struct thread *td)
748 {
749 	return (ENOTTY);
750 }
751 
752 /*ARGSUSED*/
753 static int
754 kqueue_poll(struct file *fp, int events, struct ucred *cred, struct thread *td)
755 {
756 	struct kqueue *kq = (struct kqueue *)fp->f_data;
757 	int revents = 0;
758 	int s = splnet();
759 
760         if (events & (POLLIN | POLLRDNORM)) {
761                 if (kq->kq_count) {
762                         revents |= events & (POLLIN | POLLRDNORM);
763 		} else {
764                         selrecord(td, &kq->kq_sel);
765 			kq->kq_state |= KQ_SEL;
766 		}
767 	}
768 	splx(s);
769 	return (revents);
770 }
771 
772 /*ARGSUSED*/
773 static int
774 kqueue_stat(struct file *fp, struct stat *st, struct thread *td)
775 {
776 	struct kqueue *kq = (struct kqueue *)fp->f_data;
777 
778 	bzero((void *)st, sizeof(*st));
779 	st->st_size = kq->kq_count;
780 	st->st_blksize = sizeof(struct kevent);
781 	st->st_mode = S_IFIFO;
782 	return (0);
783 }
784 
785 /*ARGSUSED*/
786 static int
787 kqueue_close(struct file *fp, struct thread *td)
788 {
789 	struct kqueue *kq = (struct kqueue *)fp->f_data;
790 	struct filedesc *fdp = td->td_proc->p_fd;
791 	struct knote **knp, *kn, *kn0;
792 	int i;
793 
794 	for (i = 0; i < fdp->fd_knlistsize; i++) {
795 		knp = &SLIST_FIRST(&fdp->fd_knlist[i]);
796 		kn = *knp;
797 		while (kn != NULL) {
798 			kn0 = SLIST_NEXT(kn, kn_link);
799 			if (kq == kn->kn_kq) {
800 				kn->kn_fop->f_detach(kn);
801 				fdrop(kn->kn_fp, td);
802 				knote_free(kn);
803 				*knp = kn0;
804 			} else {
805 				knp = &SLIST_NEXT(kn, kn_link);
806 			}
807 			kn = kn0;
808 		}
809 	}
810 	if (fdp->fd_knhashmask != 0) {
811 		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
812 			knp = &SLIST_FIRST(&fdp->fd_knhash[i]);
813 			kn = *knp;
814 			while (kn != NULL) {
815 				kn0 = SLIST_NEXT(kn, kn_link);
816 				if (kq == kn->kn_kq) {
817 					kn->kn_fop->f_detach(kn);
818 		/* XXX non-fd release of kn->kn_ptr */
819 					knote_free(kn);
820 					*knp = kn0;
821 				} else {
822 					knp = &SLIST_NEXT(kn, kn_link);
823 				}
824 				kn = kn0;
825 			}
826 		}
827 	}
828 	free(kq, M_KQUEUE);
829 	fp->f_data = NULL;
830 
831 	return (0);
832 }
833 
834 static void
835 kqueue_wakeup(struct kqueue *kq)
836 {
837 
838 	if (kq->kq_state & KQ_SLEEP) {
839 		kq->kq_state &= ~KQ_SLEEP;
840 		wakeup(kq);
841 	}
842 	if (kq->kq_state & KQ_SEL) {
843 		kq->kq_state &= ~KQ_SEL;
844 		selwakeup(&kq->kq_sel);
845 	}
846 	KNOTE(&kq->kq_sel.si_note, 0);
847 }
848 
849 /*
850  * walk down a list of knotes, activating them if their event has triggered.
851  */
852 void
853 knote(struct klist *list, long hint)
854 {
855 	struct knote *kn;
856 
857 	SLIST_FOREACH(kn, list, kn_selnext)
858 		if (kn->kn_fop->f_event(kn, hint))
859 			KNOTE_ACTIVATE(kn);
860 }
861 
862 /*
863  * remove all knotes from a specified klist
864  */
865 void
866 knote_remove(struct thread *td, struct klist *list)
867 {
868 	struct knote *kn;
869 
870 	while ((kn = SLIST_FIRST(list)) != NULL) {
871 		kn->kn_fop->f_detach(kn);
872 		knote_drop(kn, td);
873 	}
874 }
875 
876 /*
877  * remove all knotes referencing a specified fd
878  */
879 void
880 knote_fdclose(struct thread *td, int fd)
881 {
882 	struct filedesc *fdp = td->td_proc->p_fd;
883 	struct klist *list = &fdp->fd_knlist[fd];
884 
885 	knote_remove(td, list);
886 }
887 
888 static void
889 knote_attach(struct knote *kn, struct filedesc *fdp)
890 {
891 	struct klist *list;
892 	int size;
893 
894 	if (! kn->kn_fop->f_isfd) {
895 		if (fdp->fd_knhashmask == 0)
896 			fdp->fd_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
897 			    &fdp->fd_knhashmask);
898 		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
899 		goto done;
900 	}
901 
902 	if (fdp->fd_knlistsize <= kn->kn_id) {
903 		size = fdp->fd_knlistsize;
904 		while (size <= kn->kn_id)
905 			size += KQEXTENT;
906 		MALLOC(list, struct klist *,
907 		    size * sizeof(struct klist *), M_KQUEUE, M_WAITOK);
908 		bcopy((caddr_t)fdp->fd_knlist, (caddr_t)list,
909 		    fdp->fd_knlistsize * sizeof(struct klist *));
910 		bzero((caddr_t)list +
911 		    fdp->fd_knlistsize * sizeof(struct klist *),
912 		    (size - fdp->fd_knlistsize) * sizeof(struct klist *));
913 		if (fdp->fd_knlist != NULL)
914 			FREE(fdp->fd_knlist, M_KQUEUE);
915 		fdp->fd_knlistsize = size;
916 		fdp->fd_knlist = list;
917 	}
918 	list = &fdp->fd_knlist[kn->kn_id];
919 done:
920 	SLIST_INSERT_HEAD(list, kn, kn_link);
921 	kn->kn_status = 0;
922 }
923 
924 /*
925  * should be called at spl == 0, since we don't want to hold spl
926  * while calling fdrop and free.
927  */
928 static void
929 knote_drop(struct knote *kn, struct thread *td)
930 {
931         struct filedesc *fdp = td->td_proc->p_fd;
932 	struct klist *list;
933 
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