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