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