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