kern_event.c revision 101941
1208599Srdivacky/*-
2208599Srdivacky * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
3208599Srdivacky * All rights reserved.
4208599Srdivacky *
5208599Srdivacky * Redistribution and use in source and binary forms, with or without
6208599Srdivacky * modification, are permitted provided that the following conditions
7208599Srdivacky * are met:
8208599Srdivacky * 1. Redistributions of source code must retain the above copyright
9208599Srdivacky *    notice, this list of conditions and the following disclaimer.
10208599Srdivacky * 2. Redistributions in binary form must reproduce the above copyright
11208599Srdivacky *    notice, this list of conditions and the following disclaimer in the
12208599Srdivacky *    documentation and/or other materials provided with the distribution.
13208599Srdivacky *
14208599Srdivacky * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15208599Srdivacky * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16208599Srdivacky * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17208599Srdivacky * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18208599Srdivacky * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19208599Srdivacky * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20208599Srdivacky * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21234353Sdim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22208599Srdivacky * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23208599Srdivacky * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24208599Srdivacky * SUCH DAMAGE.
25208599Srdivacky *
26208599Srdivacky * $FreeBSD: head/sys/kern/kern_event.c 101941 2002-08-15 20:55:08Z rwatson $
27208599Srdivacky */
28208599Srdivacky
29208599Srdivacky#include <sys/param.h>
30208599Srdivacky#include <sys/systm.h>
31208599Srdivacky#include <sys/kernel.h>
32208599Srdivacky#include <sys/lock.h>
33208599Srdivacky#include <sys/mutex.h>
34208599Srdivacky#include <sys/proc.h>
35208599Srdivacky#include <sys/malloc.h>
36208599Srdivacky#include <sys/unistd.h>
37208599Srdivacky#include <sys/file.h>
38208599Srdivacky#include <sys/fcntl.h>
39218893Sdim#include <sys/selinfo.h>
40218893Sdim#include <sys/queue.h>
41218893Sdim#include <sys/event.h>
42208599Srdivacky#include <sys/eventvar.h>
43208599Srdivacky#include <sys/poll.h>
44208599Srdivacky#include <sys/protosw.h>
45208599Srdivacky#include <sys/socket.h>
46208599Srdivacky#include <sys/socketvar.h>
47208599Srdivacky#include <sys/stat.h>
48208599Srdivacky#include <sys/sysctl.h>
49208599Srdivacky#include <sys/sysproto.h>
50208599Srdivacky#include <sys/uio.h>
51208599Srdivacky
52208599Srdivacky#include <vm/uma.h>
53208599Srdivacky
54208599SrdivackyMALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
55208599Srdivacky
56208599Srdivackystatic int	kqueue_scan(struct file *fp, int maxevents,
57208599Srdivacky		    struct kevent *ulistp, const struct timespec *timeout,
58208599Srdivacky		    struct thread *td);
59208599Srdivackystatic int 	kqueue_read(struct file *fp, struct uio *uio,
60208599Srdivacky		    struct ucred *active_cred, int flags, struct thread *td);
61208599Srdivackystatic int	kqueue_write(struct file *fp, struct uio *uio,
62218893Sdim		    struct ucred *active_cred, int flags, struct thread *td);
63218893Sdimstatic int	kqueue_ioctl(struct file *fp, u_long com, void *data,
64218893Sdim		    struct thread *td);
65218893Sdimstatic int 	kqueue_poll(struct file *fp, int events, struct ucred *cred,
66218893Sdim		    struct thread *td);
67208599Srdivackystatic int 	kqueue_kqfilter(struct file *fp, struct knote *kn);
68208599Srdivackystatic int 	kqueue_stat(struct file *fp, struct stat *st, struct thread *td);
69208599Srdivackystatic int 	kqueue_close(struct file *fp, struct thread *td);
70208599Srdivackystatic void 	kqueue_wakeup(struct kqueue *kq);
71208599Srdivacky
72208599Srdivackystatic struct fileops kqueueops = {
73208599Srdivacky	kqueue_read,
74208599Srdivacky	kqueue_write,
75208599Srdivacky	kqueue_ioctl,
76208599Srdivacky	kqueue_poll,
77208599Srdivacky	kqueue_kqfilter,
78208599Srdivacky	kqueue_stat,
79208599Srdivacky	kqueue_close
80208599Srdivacky};
81208599Srdivacky
82208599Srdivackystatic void 	knote_attach(struct knote *kn, struct filedesc *fdp);
83208599Srdivackystatic void 	knote_drop(struct knote *kn, struct thread *td);
84208599Srdivackystatic void 	knote_enqueue(struct knote *kn);
85208599Srdivackystatic void 	knote_dequeue(struct knote *kn);
86208599Srdivackystatic void 	knote_init(void);
87208599Srdivackystatic struct 	knote *knote_alloc(void);
88208599Srdivackystatic void 	knote_free(struct knote *kn);
89208599Srdivacky
90208599Srdivackystatic void	filt_kqdetach(struct knote *kn);
91208599Srdivackystatic int	filt_kqueue(struct knote *kn, long hint);
92208599Srdivackystatic int	filt_procattach(struct knote *kn);
93208599Srdivackystatic void	filt_procdetach(struct knote *kn);
94208599Srdivackystatic int	filt_proc(struct knote *kn, long hint);
95208599Srdivackystatic int	filt_fileattach(struct knote *kn);
96208599Srdivackystatic void	filt_timerexpire(void *knx);
97208599Srdivackystatic int	filt_timerattach(struct knote *kn);
98208599Srdivackystatic void	filt_timerdetach(struct knote *kn);
99208599Srdivackystatic int	filt_timer(struct knote *kn, long hint);
100208599Srdivacky
101208599Srdivackystatic struct filterops file_filtops =
102208599Srdivacky	{ 1, filt_fileattach, NULL, NULL };
103208599Srdivackystatic struct filterops kqread_filtops =
104208599Srdivacky	{ 1, NULL, filt_kqdetach, filt_kqueue };
105208599Srdivackystatic struct filterops proc_filtops =
106208599Srdivacky	{ 0, filt_procattach, filt_procdetach, filt_proc };
107208599Srdivackystatic struct filterops timer_filtops =
108208599Srdivacky	{ 0, filt_timerattach, filt_timerdetach, filt_timer };
109208599Srdivacky
110208599Srdivackystatic uma_zone_t	knote_zone;
111208599Srdivackystatic int 		kq_ncallouts = 0;
112208599Srdivackystatic int 		kq_calloutmax = (4 * 1024);
113208599SrdivackySYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
114208599Srdivacky    &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
115208599Srdivacky
116208599Srdivacky#define KNOTE_ACTIVATE(kn) do { 					\
117208599Srdivacky	kn->kn_status |= KN_ACTIVE;					\
118208599Srdivacky	if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)		\
119208599Srdivacky		knote_enqueue(kn);					\
120208599Srdivacky} while(0)
121208599Srdivacky
122208599Srdivacky#define	KN_HASHSIZE		64		/* XXX should be tunable */
123208599Srdivacky#define KN_HASH(val, mask)	(((val) ^ (val >> 8)) & (mask))
124208599Srdivacky
125208599Srdivackystatic int
126208599Srdivackyfilt_nullattach(struct knote *kn)
127208599Srdivacky{
128208599Srdivacky
129208599Srdivacky	return (ENXIO);
130208599Srdivacky};
131208599Srdivacky
132208599Srdivackystruct filterops null_filtops =
133208599Srdivacky	{ 0, filt_nullattach, NULL, NULL };
134208599Srdivacky
135208599Srdivackyextern struct filterops sig_filtops;
136208599Srdivacky
137208599Srdivacky/*
138208599Srdivacky * Table for for all system-defined filters.
139208599Srdivacky */
140208599Srdivackystatic struct filterops *sysfilt_ops[] = {
141208599Srdivacky	&file_filtops,			/* EVFILT_READ */
142208599Srdivacky	&file_filtops,			/* EVFILT_WRITE */
143208599Srdivacky	&null_filtops,			/* EVFILT_AIO */
144208599Srdivacky	&file_filtops,			/* EVFILT_VNODE */
145208599Srdivacky	&proc_filtops,			/* EVFILT_PROC */
146208599Srdivacky	&sig_filtops,			/* EVFILT_SIGNAL */
147208599Srdivacky	&timer_filtops,			/* EVFILT_TIMER */
148208599Srdivacky	&file_filtops,			/* EVFILT_NETDEV */
149208599Srdivacky};
150208599Srdivacky
151208599Srdivackystatic int
152208599Srdivackyfilt_fileattach(struct knote *kn)
153208599Srdivacky{
154208599Srdivacky
155208599Srdivacky	return (fo_kqfilter(kn->kn_fp, kn));
156208599Srdivacky}
157226633Sdim
158226633Sdim/*ARGSUSED*/
159226633Sdimstatic int
160226633Sdimkqueue_kqfilter(struct file *fp, struct knote *kn)
161226633Sdim{
162226633Sdim	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
163208599Srdivacky
164218893Sdim	if (kn->kn_filter != EVFILT_READ)
165208599Srdivacky		return (1);
166208599Srdivacky
167218893Sdim	kn->kn_fop = &kqread_filtops;
168208599Srdivacky	SLIST_INSERT_HEAD(&kq->kq_sel.si_note, kn, kn_selnext);
169208599Srdivacky	return (0);
170208599Srdivacky}
171218893Sdim
172218893Sdimstatic void
173218893Sdimfilt_kqdetach(struct knote *kn)
174218893Sdim{
175208599Srdivacky	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
176208599Srdivacky
177208599Srdivacky	SLIST_REMOVE(&kq->kq_sel.si_note, kn, knote, kn_selnext);
178208599Srdivacky}
179208599Srdivacky
180208599Srdivacky/*ARGSUSED*/
181208599Srdivackystatic int
182208599Srdivackyfilt_kqueue(struct knote *kn, long hint)
183208599Srdivacky{
184208599Srdivacky	struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
185208599Srdivacky
186208599Srdivacky	kn->kn_data = kq->kq_count;
187208599Srdivacky	return (kn->kn_data > 0);
188208599Srdivacky}
189208599Srdivacky
190208599Srdivackystatic int
191208599Srdivackyfilt_procattach(struct knote *kn)
192208599Srdivacky{
193208599Srdivacky	struct proc *p;
194208599Srdivacky	int error;
195208599Srdivacky
196208599Srdivacky	p = pfind(kn->kn_id);
197208599Srdivacky	if (p == NULL)
198208599Srdivacky		return (ESRCH);
199208599Srdivacky	if ((error = p_cansee(curthread, p))) {
200208599Srdivacky		PROC_UNLOCK(p);
201208599Srdivacky		return (error);
202208599Srdivacky	}
203208599Srdivacky
204208599Srdivacky	kn->kn_ptr.p_proc = p;
205208599Srdivacky	kn->kn_flags |= EV_CLEAR;		/* automatically set */
206208599Srdivacky
207208599Srdivacky	/*
208208599Srdivacky	 * internal flag indicating registration done by kernel
209208599Srdivacky	 */
210208599Srdivacky	if (kn->kn_flags & EV_FLAG1) {
211208599Srdivacky		kn->kn_data = kn->kn_sdata;		/* ppid */
212208599Srdivacky		kn->kn_fflags = NOTE_CHILD;
213208599Srdivacky		kn->kn_flags &= ~EV_FLAG1;
214208599Srdivacky	}
215208599Srdivacky
216208599Srdivacky	SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
217208599Srdivacky	PROC_UNLOCK(p);
218208599Srdivacky
219208599Srdivacky	return (0);
220208599Srdivacky}
221208599Srdivacky
222208599Srdivacky/*
223208599Srdivacky * The knote may be attached to a different process, which may exit,
224208599Srdivacky * leaving nothing for the knote to be attached to.  So when the process
225208599Srdivacky * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
226208599Srdivacky * it will be deleted when read out.  However, as part of the knote deletion,
227208599Srdivacky * this routine is called, so a check is needed to avoid actually performing
228208599Srdivacky * a detach, because the original process does not exist any more.
229208599Srdivacky */
230208599Srdivackystatic void
231208599Srdivackyfilt_procdetach(struct knote *kn)
232208599Srdivacky{
233208599Srdivacky	struct proc *p = kn->kn_ptr.p_proc;
234208599Srdivacky
235208599Srdivacky	if (kn->kn_status & KN_DETACHED)
236208599Srdivacky		return;
237208599Srdivacky
238208599Srdivacky	PROC_LOCK(p);
239208599Srdivacky	SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
240208599Srdivacky	PROC_UNLOCK(p);
241208599Srdivacky}
242208599Srdivacky
243208599Srdivackystatic int
244234353Sdimfilt_proc(struct knote *kn, long hint)
245208599Srdivacky{
246208599Srdivacky	u_int event;
247208599Srdivacky
248208599Srdivacky	/*
249208599Srdivacky	 * mask off extra data
250208599Srdivacky	 */
251208599Srdivacky	event = (u_int)hint & NOTE_PCTRLMASK;
252208599Srdivacky
253208599Srdivacky	/*
254208599Srdivacky	 * if the user is interested in this event, record it.
255208599Srdivacky	 */
256208599Srdivacky	if (kn->kn_sfflags & event)
257208599Srdivacky		kn->kn_fflags |= event;
258208599Srdivacky
259208599Srdivacky	/*
260208599Srdivacky	 * process is gone, so flag the event as finished.
261208599Srdivacky	 */
262208599Srdivacky	if (event == NOTE_EXIT) {
263208599Srdivacky		kn->kn_status |= KN_DETACHED;
264208599Srdivacky		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
265208599Srdivacky		return (1);
266208599Srdivacky	}
267208599Srdivacky
268208599Srdivacky	/*
269208599Srdivacky	 * process forked, and user wants to track the new process,
270208599Srdivacky	 * so attach a new knote to it, and immediately report an
271208599Srdivacky	 * event with the parent's pid.
272208599Srdivacky	 */
273208599Srdivacky	if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
274208599Srdivacky		struct kevent kev;
275		int error;
276
277		/*
278		 * register knote with new process.
279		 */
280		kev.ident = hint & NOTE_PDATAMASK;	/* pid */
281		kev.filter = kn->kn_filter;
282		kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
283		kev.fflags = kn->kn_sfflags;
284		kev.data = kn->kn_id;			/* parent */
285		kev.udata = kn->kn_kevent.udata;	/* preserve udata */
286		error = kqueue_register(kn->kn_kq, &kev, NULL);
287		if (error)
288			kn->kn_fflags |= NOTE_TRACKERR;
289	}
290
291	return (kn->kn_fflags != 0);
292}
293
294static void
295filt_timerexpire(void *knx)
296{
297	struct knote *kn = knx;
298	struct callout *calloutp;
299	struct timeval tv;
300	int tticks;
301
302	kn->kn_data++;
303	KNOTE_ACTIVATE(kn);
304
305	if ((kn->kn_flags & EV_ONESHOT) == 0) {
306		tv.tv_sec = kn->kn_sdata / 1000;
307		tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
308		tticks = tvtohz(&tv);
309		calloutp = (struct callout *)kn->kn_hook;
310		callout_reset(calloutp, tticks, filt_timerexpire, kn);
311	}
312}
313
314/*
315 * data contains amount of time to sleep, in milliseconds
316 */
317static int
318filt_timerattach(struct knote *kn)
319{
320	struct callout *calloutp;
321	struct timeval tv;
322	int tticks;
323
324	if (kq_ncallouts >= kq_calloutmax)
325		return (ENOMEM);
326	kq_ncallouts++;
327
328	tv.tv_sec = kn->kn_sdata / 1000;
329	tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
330	tticks = tvtohz(&tv);
331
332	kn->kn_flags |= EV_CLEAR;		/* automatically set */
333	MALLOC(calloutp, struct callout *, sizeof(*calloutp),
334	    M_KQUEUE, M_WAITOK);
335	callout_init(calloutp, 0);
336	callout_reset(calloutp, tticks, filt_timerexpire, kn);
337	kn->kn_hook = calloutp;
338
339	return (0);
340}
341
342static void
343filt_timerdetach(struct knote *kn)
344{
345	struct callout *calloutp;
346
347	calloutp = (struct callout *)kn->kn_hook;
348	callout_stop(calloutp);
349	FREE(calloutp, M_KQUEUE);
350	kq_ncallouts--;
351}
352
353static int
354filt_timer(struct knote *kn, long hint)
355{
356
357	return (kn->kn_data != 0);
358}
359
360/*
361 * MPSAFE
362 */
363int
364kqueue(struct thread *td, struct kqueue_args *uap)
365{
366	struct filedesc *fdp;
367	struct kqueue *kq;
368	struct file *fp;
369	int fd, error;
370
371	mtx_lock(&Giant);
372	fdp = td->td_proc->p_fd;
373	error = falloc(td, &fp, &fd);
374	if (error)
375		goto done2;
376	kq = malloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
377	TAILQ_INIT(&kq->kq_head);
378	FILE_LOCK(fp);
379	fp->f_flag = FREAD | FWRITE;
380	fp->f_type = DTYPE_KQUEUE;
381	fp->f_ops = &kqueueops;
382	TAILQ_INIT(&kq->kq_head);
383	fp->f_data = kq;
384	FILE_UNLOCK(fp);
385	FILEDESC_LOCK(fdp);
386	td->td_retval[0] = fd;
387	if (fdp->fd_knlistsize < 0)
388		fdp->fd_knlistsize = 0;		/* this process has a kq */
389	FILEDESC_UNLOCK(fdp);
390	kq->kq_fdp = fdp;
391done2:
392	mtx_unlock(&Giant);
393	return (error);
394}
395
396#ifndef _SYS_SYSPROTO_H_
397struct kevent_args {
398	int	fd;
399	const struct kevent *changelist;
400	int	nchanges;
401	struct	kevent *eventlist;
402	int	nevents;
403	const struct timespec *timeout;
404};
405#endif
406/*
407 * MPSAFE
408 */
409int
410kevent(struct thread *td, struct kevent_args *uap)
411{
412	struct kevent *kevp;
413	struct kqueue *kq;
414	struct file *fp;
415	struct timespec ts;
416	int i, n, nerrors, error;
417
418	if ((error = fget(td, uap->fd, &fp)) != 0)
419		return (error);
420	if (fp->f_type != DTYPE_KQUEUE) {
421		fdrop(fp, td);
422		return (EBADF);
423	}
424	if (uap->timeout != NULL) {
425		error = copyin(uap->timeout, &ts, sizeof(ts));
426		if (error)
427			goto done_nogiant;
428		uap->timeout = &ts;
429	}
430	mtx_lock(&Giant);
431
432	kq = (struct kqueue *)fp->f_data;
433	nerrors = 0;
434
435	while (uap->nchanges > 0) {
436		n = uap->nchanges > KQ_NEVENTS ? KQ_NEVENTS : uap->nchanges;
437		error = copyin(uap->changelist, kq->kq_kev,
438		    n * sizeof(struct kevent));
439		if (error)
440			goto done;
441		for (i = 0; i < n; i++) {
442			kevp = &kq->kq_kev[i];
443			kevp->flags &= ~EV_SYSFLAGS;
444			error = kqueue_register(kq, kevp, td);
445			if (error) {
446				if (uap->nevents != 0) {
447					kevp->flags = EV_ERROR;
448					kevp->data = error;
449					(void) copyout(kevp,
450					    uap->eventlist,
451					    sizeof(*kevp));
452					uap->eventlist++;
453					uap->nevents--;
454					nerrors++;
455				} else {
456					goto done;
457				}
458			}
459		}
460		uap->nchanges -= n;
461		uap->changelist += n;
462	}
463	if (nerrors) {
464        	td->td_retval[0] = nerrors;
465		error = 0;
466		goto done;
467	}
468
469	error = kqueue_scan(fp, uap->nevents, uap->eventlist, uap->timeout, td);
470done:
471	mtx_unlock(&Giant);
472done_nogiant:
473	if (fp != NULL)
474		fdrop(fp, td);
475	return (error);
476}
477
478int
479kqueue_add_filteropts(int filt, struct filterops *filtops)
480{
481
482	if (filt > 0)
483		panic("filt(%d) > 0", filt);
484	if (filt + EVFILT_SYSCOUNT < 0)
485		panic("filt(%d) + EVFILT_SYSCOUNT(%d) == %d < 0",
486		    filt, EVFILT_SYSCOUNT, filt + EVFILT_SYSCOUNT);
487	if (sysfilt_ops[~filt] != &null_filtops)
488		panic("sysfilt_ops[~filt(%d)] != &null_filtops", filt);
489	sysfilt_ops[~filt] = filtops;
490	return (0);
491}
492
493int
494kqueue_del_filteropts(int filt)
495{
496
497	if (filt > 0)
498		panic("filt(%d) > 0", filt);
499	if (filt + EVFILT_SYSCOUNT < 0)
500		panic("filt(%d) + EVFILT_SYSCOUNT(%d) == %d < 0",
501		    filt, EVFILT_SYSCOUNT, filt + EVFILT_SYSCOUNT);
502	if (sysfilt_ops[~filt] == &null_filtops)
503		panic("sysfilt_ops[~filt(%d)] != &null_filtops", filt);
504	sysfilt_ops[~filt] = &null_filtops;
505	return (0);
506}
507
508int
509kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td)
510{
511	struct filedesc *fdp = kq->kq_fdp;
512	struct filterops *fops;
513	struct file *fp = NULL;
514	struct knote *kn = NULL;
515	int s, error = 0;
516
517	if (kev->filter < 0) {
518		if (kev->filter + EVFILT_SYSCOUNT < 0)
519			return (EINVAL);
520		fops = sysfilt_ops[~kev->filter];	/* to 0-base index */
521	} else {
522		/*
523		 * XXX
524		 * filter attach routine is responsible for insuring that
525		 * the identifier can be attached to it.
526		 */
527		printf("unknown filter: %d\n", kev->filter);
528		return (EINVAL);
529	}
530
531	FILEDESC_LOCK(fdp);
532	if (fops->f_isfd) {
533		/* validate descriptor */
534		if ((u_int)kev->ident >= fdp->fd_nfiles ||
535		    (fp = fdp->fd_ofiles[kev->ident]) == NULL) {
536			FILEDESC_UNLOCK(fdp);
537			return (EBADF);
538		}
539		fhold(fp);
540
541		if (kev->ident < fdp->fd_knlistsize) {
542			SLIST_FOREACH(kn, &fdp->fd_knlist[kev->ident], kn_link)
543				if (kq == kn->kn_kq &&
544				    kev->filter == kn->kn_filter)
545					break;
546		}
547	} else {
548		if (fdp->fd_knhashmask != 0) {
549			struct klist *list;
550
551			list = &fdp->fd_knhash[
552			    KN_HASH((u_long)kev->ident, fdp->fd_knhashmask)];
553			SLIST_FOREACH(kn, list, kn_link)
554				if (kev->ident == kn->kn_id &&
555				    kq == kn->kn_kq &&
556				    kev->filter == kn->kn_filter)
557					break;
558		}
559	}
560	FILEDESC_UNLOCK(fdp);
561
562	if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
563		error = ENOENT;
564		goto done;
565	}
566
567	/*
568	 * kn now contains the matching knote, or NULL if no match
569	 */
570	if (kev->flags & EV_ADD) {
571
572		if (kn == NULL) {
573			kn = knote_alloc();
574			if (kn == NULL) {
575				error = ENOMEM;
576				goto done;
577			}
578			kn->kn_fp = fp;
579			kn->kn_kq = kq;
580			kn->kn_fop = fops;
581
582			/*
583			 * apply reference count to knote structure, and
584			 * do not release it at the end of this routine.
585			 */
586			fp = NULL;
587
588			kn->kn_sfflags = kev->fflags;
589			kn->kn_sdata = kev->data;
590			kev->fflags = 0;
591			kev->data = 0;
592			kn->kn_kevent = *kev;
593
594			knote_attach(kn, fdp);
595			if ((error = fops->f_attach(kn)) != 0) {
596				knote_drop(kn, td);
597				goto done;
598			}
599		} else {
600			/*
601			 * The user may change some filter values after the
602			 * initial EV_ADD, but doing so will not reset any
603			 * filter which have already been triggered.
604			 */
605			kn->kn_sfflags = kev->fflags;
606			kn->kn_sdata = kev->data;
607			kn->kn_kevent.udata = kev->udata;
608		}
609
610		s = splhigh();
611		if (kn->kn_fop->f_event(kn, 0))
612			KNOTE_ACTIVATE(kn);
613		splx(s);
614
615	} else if (kev->flags & EV_DELETE) {
616		kn->kn_fop->f_detach(kn);
617		knote_drop(kn, td);
618		goto done;
619	}
620
621	if ((kev->flags & EV_DISABLE) &&
622	    ((kn->kn_status & KN_DISABLED) == 0)) {
623		s = splhigh();
624		kn->kn_status |= KN_DISABLED;
625		splx(s);
626	}
627
628	if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
629		s = splhigh();
630		kn->kn_status &= ~KN_DISABLED;
631		if ((kn->kn_status & KN_ACTIVE) &&
632		    ((kn->kn_status & KN_QUEUED) == 0))
633			knote_enqueue(kn);
634		splx(s);
635	}
636
637done:
638	if (fp != NULL)
639		fdrop(fp, td);
640	return (error);
641}
642
643static int
644kqueue_scan(struct file *fp, int maxevents, struct kevent *ulistp,
645	const struct timespec *tsp, struct thread *td)
646{
647	struct kqueue *kq;
648	struct kevent *kevp;
649	struct timeval atv, rtv, ttv;
650	struct knote *kn, marker;
651	int s, count, timeout, nkev = 0, error = 0;
652
653	FILE_LOCK_ASSERT(fp, MA_NOTOWNED);
654
655	kq = (struct kqueue *)fp->f_data;
656	count = maxevents;
657	if (count == 0)
658		goto done;
659
660	if (tsp != NULL) {
661		TIMESPEC_TO_TIMEVAL(&atv, tsp);
662		if (itimerfix(&atv)) {
663			error = EINVAL;
664			goto done;
665		}
666		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
667			timeout = -1;
668		else
669			timeout = atv.tv_sec > 24 * 60 * 60 ?
670			    24 * 60 * 60 * hz : tvtohz(&atv);
671		getmicrouptime(&rtv);
672		timevaladd(&atv, &rtv);
673	} else {
674		atv.tv_sec = 0;
675		atv.tv_usec = 0;
676		timeout = 0;
677	}
678	goto start;
679
680retry:
681	if (atv.tv_sec || atv.tv_usec) {
682		getmicrouptime(&rtv);
683		if (timevalcmp(&rtv, &atv, >=))
684			goto done;
685		ttv = atv;
686		timevalsub(&ttv, &rtv);
687		timeout = ttv.tv_sec > 24 * 60 * 60 ?
688			24 * 60 * 60 * hz : tvtohz(&ttv);
689	}
690
691start:
692	kevp = kq->kq_kev;
693	s = splhigh();
694	if (kq->kq_count == 0) {
695		if (timeout < 0) {
696			error = EWOULDBLOCK;
697		} else {
698			kq->kq_state |= KQ_SLEEP;
699			error = tsleep(kq, PSOCK | PCATCH, "kqread", timeout);
700		}
701		splx(s);
702		if (error == 0)
703			goto retry;
704		/* don't restart after signals... */
705		if (error == ERESTART)
706			error = EINTR;
707		else if (error == EWOULDBLOCK)
708			error = 0;
709		goto done;
710	}
711
712	TAILQ_INSERT_TAIL(&kq->kq_head, &marker, kn_tqe);
713	while (count) {
714		kn = TAILQ_FIRST(&kq->kq_head);
715		TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
716		if (kn == &marker) {
717			splx(s);
718			if (count == maxevents)
719				goto retry;
720			goto done;
721		}
722		if (kn->kn_status & KN_DISABLED) {
723			kn->kn_status &= ~KN_QUEUED;
724			kq->kq_count--;
725			continue;
726		}
727		if ((kn->kn_flags & EV_ONESHOT) == 0 &&
728		    kn->kn_fop->f_event(kn, 0) == 0) {
729			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
730			kq->kq_count--;
731			continue;
732		}
733		*kevp = kn->kn_kevent;
734		kevp++;
735		nkev++;
736		if (kn->kn_flags & EV_ONESHOT) {
737			kn->kn_status &= ~KN_QUEUED;
738			kq->kq_count--;
739			splx(s);
740			kn->kn_fop->f_detach(kn);
741			knote_drop(kn, td);
742			s = splhigh();
743		} else if (kn->kn_flags & EV_CLEAR) {
744			kn->kn_data = 0;
745			kn->kn_fflags = 0;
746			kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
747			kq->kq_count--;
748		} else {
749			TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
750		}
751		count--;
752		if (nkev == KQ_NEVENTS) {
753			splx(s);
754			error = copyout(&kq->kq_kev, ulistp,
755			    sizeof(struct kevent) * nkev);
756			ulistp += nkev;
757			nkev = 0;
758			kevp = kq->kq_kev;
759			s = splhigh();
760			if (error)
761				break;
762		}
763	}
764	TAILQ_REMOVE(&kq->kq_head, &marker, kn_tqe);
765	splx(s);
766done:
767	if (nkev != 0)
768		error = copyout(&kq->kq_kev, ulistp,
769		    sizeof(struct kevent) * nkev);
770        td->td_retval[0] = maxevents - count;
771	return (error);
772}
773
774/*
775 * XXX
776 * This could be expanded to call kqueue_scan, if desired.
777 */
778/*ARGSUSED*/
779static int
780kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
781	int flags, struct thread *td)
782{
783	return (ENXIO);
784}
785
786/*ARGSUSED*/
787static int
788kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
789	 int flags, struct thread *td)
790{
791	return (ENXIO);
792}
793
794/*ARGSUSED*/
795static int
796kqueue_ioctl(struct file *fp, u_long com, void *data, struct thread *td)
797{
798	return (ENOTTY);
799}
800
801/*ARGSUSED*/
802static int
803kqueue_poll(struct file *fp, int events, struct ucred *cred, struct thread *td)
804{
805	struct kqueue *kq;
806	int revents = 0;
807	int s = splnet();
808
809	kq = (struct kqueue *)fp->f_data;
810        if (events & (POLLIN | POLLRDNORM)) {
811                if (kq->kq_count) {
812                        revents |= events & (POLLIN | POLLRDNORM);
813		} else {
814                        selrecord(td, &kq->kq_sel);
815			kq->kq_state |= KQ_SEL;
816		}
817	}
818	splx(s);
819	return (revents);
820}
821
822/*ARGSUSED*/
823static int
824kqueue_stat(struct file *fp, struct stat *st, struct thread *td)
825{
826	struct kqueue *kq;
827
828	kq = (struct kqueue *)fp->f_data;
829	bzero((void *)st, sizeof(*st));
830	st->st_size = kq->kq_count;
831	st->st_blksize = sizeof(struct kevent);
832	st->st_mode = S_IFIFO;
833	return (0);
834}
835
836/*ARGSUSED*/
837static int
838kqueue_close(struct file *fp, struct thread *td)
839{
840	struct kqueue *kq = (struct kqueue *)fp->f_data;
841	struct filedesc *fdp = td->td_proc->p_fd;
842	struct knote **knp, *kn, *kn0;
843	int i;
844
845	FILEDESC_LOCK(fdp);
846	for (i = 0; i < fdp->fd_knlistsize; i++) {
847		knp = &SLIST_FIRST(&fdp->fd_knlist[i]);
848		kn = *knp;
849		while (kn != NULL) {
850			kn0 = SLIST_NEXT(kn, kn_link);
851			if (kq == kn->kn_kq) {
852				kn->kn_fop->f_detach(kn);
853				*knp = kn0;
854				FILE_LOCK(kn->kn_fp);
855				FILEDESC_UNLOCK(fdp);
856				fdrop_locked(kn->kn_fp, td);
857				knote_free(kn);
858				FILEDESC_LOCK(fdp);
859			} else {
860				knp = &SLIST_NEXT(kn, kn_link);
861			}
862			kn = kn0;
863		}
864	}
865	if (fdp->fd_knhashmask != 0) {
866		for (i = 0; i < fdp->fd_knhashmask + 1; i++) {
867			knp = &SLIST_FIRST(&fdp->fd_knhash[i]);
868			kn = *knp;
869			while (kn != NULL) {
870				kn0 = SLIST_NEXT(kn, kn_link);
871				if (kq == kn->kn_kq) {
872					kn->kn_fop->f_detach(kn);
873					*knp = kn0;
874		/* XXX non-fd release of kn->kn_ptr */
875					FILEDESC_UNLOCK(fdp);
876					knote_free(kn);
877					FILEDESC_LOCK(fdp);
878				} else {
879					knp = &SLIST_NEXT(kn, kn_link);
880				}
881				kn = kn0;
882			}
883		}
884	}
885	FILEDESC_UNLOCK(fdp);
886	free(kq, M_KQUEUE);
887	fp->f_data = NULL;
888
889	return (0);
890}
891
892static void
893kqueue_wakeup(struct kqueue *kq)
894{
895
896	if (kq->kq_state & KQ_SLEEP) {
897		kq->kq_state &= ~KQ_SLEEP;
898		wakeup(kq);
899	}
900	if (kq->kq_state & KQ_SEL) {
901		kq->kq_state &= ~KQ_SEL;
902		selwakeup(&kq->kq_sel);
903	}
904	KNOTE(&kq->kq_sel.si_note, 0);
905}
906
907/*
908 * walk down a list of knotes, activating them if their event has triggered.
909 */
910void
911knote(struct klist *list, long hint)
912{
913	struct knote *kn;
914
915	SLIST_FOREACH(kn, list, kn_selnext)
916		if (kn->kn_fop->f_event(kn, hint))
917			KNOTE_ACTIVATE(kn);
918}
919
920/*
921 * remove all knotes from a specified klist
922 */
923void
924knote_remove(struct thread *td, struct klist *list)
925{
926	struct knote *kn;
927
928	while ((kn = SLIST_FIRST(list)) != NULL) {
929		kn->kn_fop->f_detach(kn);
930		knote_drop(kn, td);
931	}
932}
933
934/*
935 * remove all knotes referencing a specified fd
936 */
937void
938knote_fdclose(struct thread *td, int fd)
939{
940	struct filedesc *fdp = td->td_proc->p_fd;
941	struct klist *list;
942
943	FILEDESC_LOCK(fdp);
944	list = &fdp->fd_knlist[fd];
945	FILEDESC_UNLOCK(fdp);
946	knote_remove(td, list);
947}
948
949static void
950knote_attach(struct knote *kn, struct filedesc *fdp)
951{
952	struct klist *list, *oldlist;
953	int size, newsize;
954
955	FILEDESC_LOCK(fdp);
956
957	if (! kn->kn_fop->f_isfd) {
958		if (fdp->fd_knhashmask == 0)
959			fdp->fd_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
960			    &fdp->fd_knhashmask);
961		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
962		goto done;
963	}
964
965	if (fdp->fd_knlistsize <= kn->kn_id) {
966retry:
967		size = fdp->fd_knlistsize;
968		while (size <= kn->kn_id)
969			size += KQEXTENT;
970		FILEDESC_UNLOCK(fdp);
971		MALLOC(list, struct klist *,
972		    size * sizeof(struct klist *), M_KQUEUE, M_WAITOK);
973		FILEDESC_LOCK(fdp);
974		newsize = fdp->fd_knlistsize;
975		while (newsize <= kn->kn_id)
976			newsize += KQEXTENT;
977		if (newsize != size) {
978			FILEDESC_UNLOCK(fdp);
979			free(list, M_TEMP);
980			FILEDESC_LOCK(fdp);
981			goto retry;
982		}
983		bcopy(fdp->fd_knlist, list,
984		    fdp->fd_knlistsize * sizeof(struct klist *));
985		bzero((caddr_t)list +
986		    fdp->fd_knlistsize * sizeof(struct klist *),
987		    (size - fdp->fd_knlistsize) * sizeof(struct klist *));
988		if (fdp->fd_knlist != NULL)
989			oldlist = fdp->fd_knlist;
990		else
991			oldlist = NULL;
992		fdp->fd_knlistsize = size;
993		fdp->fd_knlist = list;
994		FILEDESC_UNLOCK(fdp);
995		if (oldlist != NULL)
996			FREE(oldlist, M_KQUEUE);
997		FILEDESC_LOCK(fdp);
998	}
999	list = &fdp->fd_knlist[kn->kn_id];
1000done:
1001	FILEDESC_UNLOCK(fdp);
1002	SLIST_INSERT_HEAD(list, kn, kn_link);
1003	kn->kn_status = 0;
1004}
1005
1006/*
1007 * should be called at spl == 0, since we don't want to hold spl
1008 * while calling fdrop and free.
1009 */
1010static void
1011knote_drop(struct knote *kn, struct thread *td)
1012{
1013        struct filedesc *fdp = td->td_proc->p_fd;
1014	struct klist *list;
1015
1016	FILEDESC_LOCK(fdp);
1017	if (kn->kn_fop->f_isfd)
1018		list = &fdp->fd_knlist[kn->kn_id];
1019	else
1020		list = &fdp->fd_knhash[KN_HASH(kn->kn_id, fdp->fd_knhashmask)];
1021	if (kn->kn_fop->f_isfd)
1022		FILE_LOCK(kn->kn_fp);
1023	FILEDESC_UNLOCK(fdp);
1024
1025	SLIST_REMOVE(list, kn, knote, kn_link);
1026	if (kn->kn_status & KN_QUEUED)
1027		knote_dequeue(kn);
1028	if (kn->kn_fop->f_isfd)
1029		fdrop_locked(kn->kn_fp, td);
1030	knote_free(kn);
1031}
1032
1033
1034static void
1035knote_enqueue(struct knote *kn)
1036{
1037	struct kqueue *kq = kn->kn_kq;
1038	int s = splhigh();
1039
1040	KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1041
1042	TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1043	kn->kn_status |= KN_QUEUED;
1044	kq->kq_count++;
1045	splx(s);
1046	kqueue_wakeup(kq);
1047}
1048
1049static void
1050knote_dequeue(struct knote *kn)
1051{
1052	struct kqueue *kq = kn->kn_kq;
1053	int s = splhigh();
1054
1055	KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1056
1057	TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1058	kn->kn_status &= ~KN_QUEUED;
1059	kq->kq_count--;
1060	splx(s);
1061}
1062
1063static void
1064knote_init(void)
1065{
1066	knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
1067	    NULL, NULL, UMA_ALIGN_PTR, 0);
1068
1069}
1070SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1071
1072static struct knote *
1073knote_alloc(void)
1074{
1075	return ((struct knote *)uma_zalloc(knote_zone, M_WAITOK));
1076}
1077
1078static void
1079knote_free(struct knote *kn)
1080{
1081	uma_zfree(knote_zone, kn);
1082}
1083