kernel - kqueue select support
[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.10 2004/04/04 07:03:14 cperciva Exp $
27  * $DragonFly: src/sys/kern/kern_event.c,v 1.33 2007/02/03 17:05:57 corecode 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/lock.h>
38 #include <sys/fcntl.h>
39 #include <sys/select.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 #include <sys/signalvar.h>
52 #include <sys/filio.h>
53 #include <sys/ktr.h>
54
55 #include <sys/thread2.h>
56 #include <sys/file2.h>
57 #include <sys/mplock2.h>
58
59 #include <vm/vm_zone.h>
60
61 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
62
63 struct kevent_copyin_args {
64         struct kevent_args      *ka;
65         int                     pchanges;
66 };
67
68 static int      kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
69                     struct timespec *tsp, int *errorp);
70 static int      kqueue_read(struct file *fp, struct uio *uio,
71                     struct ucred *cred, int flags);
72 static int      kqueue_write(struct file *fp, struct uio *uio,
73                     struct ucred *cred, int flags);
74 static int      kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
75                     struct ucred *cred, struct sysmsg *msg);
76 static int      kqueue_poll(struct file *fp, int events, struct ucred *cred);
77 static int      kqueue_kqfilter(struct file *fp, struct knote *kn);
78 static int      kqueue_stat(struct file *fp, struct stat *st,
79                     struct ucred *cred);
80 static int      kqueue_close(struct file *fp);
81
82 /*
83  * MPSAFE
84  */
85 static struct fileops kqueueops = {
86         .fo_read = kqueue_read,
87         .fo_write = kqueue_write,
88         .fo_ioctl = kqueue_ioctl,
89         .fo_poll = kqueue_poll,
90         .fo_kqfilter = kqueue_kqfilter,
91         .fo_stat = kqueue_stat,
92         .fo_close = kqueue_close,
93         .fo_shutdown = nofo_shutdown
94 };
95
96 static void     knote_attach(struct knote *kn);
97 static void     knote_drop(struct knote *kn);
98 static void     knote_enqueue(struct knote *kn);
99 static void     knote_dequeue(struct knote *kn);
100 static void     knote_init(void);
101 static struct   knote *knote_alloc(void);
102 static void     knote_free(struct knote *kn);
103
104 static void     filt_kqdetach(struct knote *kn);
105 static int      filt_kqueue(struct knote *kn, long hint);
106 static int      filt_procattach(struct knote *kn);
107 static void     filt_procdetach(struct knote *kn);
108 static int      filt_proc(struct knote *kn, long hint);
109 static int      filt_fileattach(struct knote *kn);
110 static void     filt_timerexpire(void *knx);
111 static int      filt_timerattach(struct knote *kn);
112 static void     filt_timerdetach(struct knote *kn);
113 static int      filt_timer(struct knote *kn, long hint);
114
115 static struct filterops file_filtops =
116         { 1, filt_fileattach, NULL, NULL };
117 static struct filterops kqread_filtops =
118         { 1, NULL, filt_kqdetach, filt_kqueue };
119 static struct filterops proc_filtops =
120         { 0, filt_procattach, filt_procdetach, filt_proc };
121 static struct filterops timer_filtops =
122         { 0, filt_timerattach, filt_timerdetach, filt_timer };
123
124 static vm_zone_t        knote_zone;
125 static int              kq_ncallouts = 0;
126 static int              kq_calloutmax = (4 * 1024);
127 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
128     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
129
130 #define KNOTE_ACTIVATE(kn) do {                                         \
131         kn->kn_status |= KN_ACTIVE;                                     \
132         if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)           \
133                 knote_enqueue(kn);                                      \
134 } while(0)
135
136 #define KN_HASHSIZE             64              /* XXX should be tunable */
137 #define KN_HASH(val, mask)      (((val) ^ (val >> 8)) & (mask))
138
139 extern struct filterops aio_filtops;
140 extern struct filterops sig_filtops;
141
142 /*
143  * Table for for all system-defined filters.
144  */
145 static struct filterops *sysfilt_ops[] = {
146         &file_filtops,                  /* EVFILT_READ */
147         &file_filtops,                  /* EVFILT_WRITE */
148         &aio_filtops,                   /* EVFILT_AIO */
149         &file_filtops,                  /* EVFILT_VNODE */
150         &proc_filtops,                  /* EVFILT_PROC */
151         &sig_filtops,                   /* EVFILT_SIGNAL */
152         &timer_filtops,                 /* EVFILT_TIMER */
153 };
154
155 static int
156 filt_fileattach(struct knote *kn)
157 {
158         return (fo_kqfilter(kn->kn_fp, kn));
159 }
160
161 /*
162  * MPALMOSTSAFE - acquires mplock
163  */
164 static int
165 kqueue_kqfilter(struct file *fp, struct knote *kn)
166 {
167         struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
168
169         get_mplock();
170         if (kn->kn_filter != EVFILT_READ) {
171                 rel_mplock();
172                 return (1);
173         }
174
175         kn->kn_fop = &kqread_filtops;
176         SLIST_INSERT_HEAD(&kq->kq_sel.si_note, kn, kn_selnext);
177         rel_mplock();
178         return (0);
179 }
180
181 static void
182 filt_kqdetach(struct knote *kn)
183 {
184         struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
185
186         SLIST_REMOVE(&kq->kq_sel.si_note, kn, knote, kn_selnext);
187 }
188
189 /*ARGSUSED*/
190 static int
191 filt_kqueue(struct knote *kn, long hint)
192 {
193         struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
194
195         kn->kn_data = kq->kq_count;
196         return (kn->kn_data > 0);
197 }
198
199 static int
200 filt_procattach(struct knote *kn)
201 {
202         struct proc *p;
203         int immediate;
204
205         immediate = 0;
206         lwkt_gettoken(&proc_token);
207         p = pfind(kn->kn_id);
208         if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
209                 p = zpfind(kn->kn_id);
210                 immediate = 1;
211         }
212         if (p == NULL) {
213                 lwkt_reltoken(&proc_token);
214                 return (ESRCH);
215         }
216         if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
217                 lwkt_reltoken(&proc_token);
218                 return (EACCES);
219         }
220
221         kn->kn_ptr.p_proc = p;
222         kn->kn_flags |= EV_CLEAR;               /* automatically set */
223
224         /*
225          * internal flag indicating registration done by kernel
226          */
227         if (kn->kn_flags & EV_FLAG1) {
228                 kn->kn_data = kn->kn_sdata;             /* ppid */
229                 kn->kn_fflags = NOTE_CHILD;
230                 kn->kn_flags &= ~EV_FLAG1;
231         }
232
233         /* XXX lock the proc here while adding to the list? */
234         SLIST_INSERT_HEAD(&p->p_klist, kn, kn_selnext);
235
236         /*
237          * Immediately activate any exit notes if the target process is a
238          * zombie.  This is necessary to handle the case where the target
239          * process, e.g. a child, dies before the kevent is registered.
240          */
241         if (immediate && filt_proc(kn, NOTE_EXIT))
242                 KNOTE_ACTIVATE(kn);
243         lwkt_reltoken(&proc_token);
244
245         return (0);
246 }
247
248 /*
249  * The knote may be attached to a different process, which may exit,
250  * leaving nothing for the knote to be attached to.  So when the process
251  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
252  * it will be deleted when read out.  However, as part of the knote deletion,
253  * this routine is called, so a check is needed to avoid actually performing
254  * a detach, because the original process does not exist any more.
255  */
256 static void
257 filt_procdetach(struct knote *kn)
258 {
259         struct proc *p;
260
261         if (kn->kn_status & KN_DETACHED)
262                 return;
263         /* XXX locking?  this might modify another process. */
264         p = kn->kn_ptr.p_proc;
265         SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
266 }
267
268 static int
269 filt_proc(struct knote *kn, long hint)
270 {
271         u_int event;
272
273         /*
274          * mask off extra data
275          */
276         event = (u_int)hint & NOTE_PCTRLMASK;
277
278         /*
279          * if the user is interested in this event, record it.
280          */
281         if (kn->kn_sfflags & event)
282                 kn->kn_fflags |= event;
283
284         /*
285          * Process is gone, so flag the event as finished.  Detach the
286          * knote from the process now because the process will be poof,
287          * gone later on.
288          */
289         if (event == NOTE_EXIT) {
290                 struct proc *p = kn->kn_ptr.p_proc;
291                 if ((kn->kn_status & KN_DETACHED) == 0) {
292                         SLIST_REMOVE(&p->p_klist, kn, knote, kn_selnext);
293                         kn->kn_status |= KN_DETACHED;
294                         kn->kn_data = p->p_xstat;
295                         kn->kn_ptr.p_proc = NULL;
296                 }
297                 kn->kn_flags |= (EV_EOF | EV_ONESHOT); 
298                 return (1);
299         }
300
301         /*
302          * process forked, and user wants to track the new process,
303          * so attach a new knote to it, and immediately report an
304          * event with the parent's pid.
305          */
306         if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
307                 struct kevent kev;
308                 int error;
309
310                 /*
311                  * register knote with new process.
312                  */
313                 kev.ident = hint & NOTE_PDATAMASK;      /* pid */
314                 kev.filter = kn->kn_filter;
315                 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
316                 kev.fflags = kn->kn_sfflags;
317                 kev.data = kn->kn_id;                   /* parent */
318                 kev.udata = kn->kn_kevent.udata;        /* preserve udata */
319                 error = kqueue_register(kn->kn_kq, &kev);
320                 if (error)
321                         kn->kn_fflags |= NOTE_TRACKERR;
322         }
323
324         return (kn->kn_fflags != 0);
325 }
326
327 static void
328 filt_timerexpire(void *knx)
329 {
330         struct knote *kn = knx;
331         struct callout *calloutp;
332         struct timeval tv;
333         int tticks;
334
335         kn->kn_data++;
336         KNOTE_ACTIVATE(kn);
337
338         if ((kn->kn_flags & EV_ONESHOT) == 0) {
339                 tv.tv_sec = kn->kn_sdata / 1000;
340                 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
341                 tticks = tvtohz_high(&tv);
342                 calloutp = (struct callout *)kn->kn_hook;
343                 callout_reset(calloutp, tticks, filt_timerexpire, kn);
344         }
345 }
346
347 /*
348  * data contains amount of time to sleep, in milliseconds
349  */ 
350 static int
351 filt_timerattach(struct knote *kn)
352 {
353         struct callout *calloutp;
354         struct timeval tv;
355         int tticks;
356
357         if (kq_ncallouts >= kq_calloutmax)
358                 return (ENOMEM);
359         kq_ncallouts++;
360
361         tv.tv_sec = kn->kn_sdata / 1000;
362         tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
363         tticks = tvtohz_high(&tv);
364
365         kn->kn_flags |= EV_CLEAR;               /* automatically set */
366         MALLOC(calloutp, struct callout *, sizeof(*calloutp),
367             M_KQUEUE, M_WAITOK);
368         callout_init(calloutp);
369         kn->kn_hook = (caddr_t)calloutp;
370         callout_reset(calloutp, tticks, filt_timerexpire, kn);
371
372         return (0);
373 }
374
375 static void
376 filt_timerdetach(struct knote *kn)
377 {
378         struct callout *calloutp;
379
380         calloutp = (struct callout *)kn->kn_hook;
381         callout_stop(calloutp);
382         FREE(calloutp, M_KQUEUE);
383         kq_ncallouts--;
384 }
385
386 static int
387 filt_timer(struct knote *kn, long hint)
388 {
389
390         return (kn->kn_data != 0);
391 }
392
393 /*
394  * Initialize a kqueue.
395  *
396  * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
397  *
398  * MPSAFE
399  */
400 void
401 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
402 {
403         TAILQ_INIT(&kq->kq_knpend);
404         TAILQ_INIT(&kq->kq_knlist);
405         kq->kq_fdp = fdp;
406 }
407
408 /*
409  * Terminate a kqueue.  Freeing the actual kq itself is left up to the
410  * caller (it might be embedded in a lwp so we don't do it here).
411  */
412 void
413 kqueue_terminate(struct kqueue *kq)
414 {
415         struct knote *kn;
416         struct klist *list;
417         int hv;
418
419         while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
420                 kn->kn_fop->f_detach(kn);
421                 if (kn->kn_fop->f_isfd) {
422                         list = &kn->kn_fp->f_klist;
423                         SLIST_REMOVE(list, kn, knote, kn_link);
424                         fdrop(kn->kn_fp);
425                         kn->kn_fp = NULL;
426                 } else {
427                         hv = KN_HASH(kn->kn_id, kq->kq_knhashmask);
428                         list = &kq->kq_knhash[hv];
429                         SLIST_REMOVE(list, kn, knote, kn_link);
430                 }
431                 TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
432                 if (kn->kn_status & KN_QUEUED)
433                         knote_dequeue(kn);
434                 knote_free(kn);
435         }
436
437         if (kq->kq_knhash) {
438                 kfree(kq->kq_knhash, M_KQUEUE);
439                 kq->kq_knhash = NULL;
440                 kq->kq_knhashmask = 0;
441         }
442 }
443
444 /*
445  * MPSAFE
446  */
447 int
448 sys_kqueue(struct kqueue_args *uap)
449 {
450         struct thread *td = curthread;
451         struct kqueue *kq;
452         struct file *fp;
453         int fd, error;
454
455         error = falloc(td->td_lwp, &fp, &fd);
456         if (error)
457                 return (error);
458         fp->f_flag = FREAD | FWRITE;
459         fp->f_type = DTYPE_KQUEUE;
460         fp->f_ops = &kqueueops;
461
462         kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
463         kqueue_init(kq, td->td_proc->p_fd);
464         fp->f_data = kq;
465
466         fsetfd(kq->kq_fdp, fp, fd);
467         uap->sysmsg_result = fd;
468         fdrop(fp);
469         return (error);
470 }
471
472 /*
473  * Copy 'count' items into the destination list pointed to by uap->eventlist.
474  */
475 static int
476 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
477 {
478         struct kevent_copyin_args *kap;
479         int error;
480
481         kap = (struct kevent_copyin_args *)arg;
482
483         error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
484         if (error == 0) {
485                 kap->ka->eventlist += count;
486                 *res += count;
487         } else {
488                 *res = -1;
489         }
490
491         return (error);
492 }
493
494 /*
495  * Copy at most 'max' items from the list pointed to by kap->changelist,
496  * return number of items in 'events'.
497  */
498 static int
499 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
500 {
501         struct kevent_copyin_args *kap;
502         int error, count;
503
504         kap = (struct kevent_copyin_args *)arg;
505
506         count = min(kap->ka->nchanges - kap->pchanges, max);
507         error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
508         if (error == 0) {
509                 kap->ka->changelist += count;
510                 kap->pchanges += count;
511                 *events = count;
512         }
513
514         return (error);
515 }
516
517 /*
518  * MPALMOSTSAFE
519  */
520 int
521 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
522             k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
523             struct timespec *tsp_in)
524 {
525         struct kevent *kevp;
526         struct timespec ts;
527         struct timespec *tsp;
528         int i, n, total, error, nerrors = 0;
529         struct kevent kev[KQ_NEVENTS];
530
531         tsp = tsp_in;
532         *res = 0;
533
534         get_mplock();
535         for ( ;; ) {
536                 n = 0;
537                 error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
538                 if (error)
539                         goto done;
540                 if (n == 0)
541                         break;
542                 for (i = 0; i < n; i++) {
543                         kevp = &kev[i];
544                         kevp->flags &= ~EV_SYSFLAGS;
545                         error = kqueue_register(kq, kevp);
546                         if (error) {
547                                 if (nevents != 0) {
548                                         kevp->flags = EV_ERROR;
549                                         kevp->data = error;
550                                         kevent_copyoutfn(uap, kevp, 1, res);
551                                         nevents--;
552                                         nerrors++;
553                                 } else {
554                                         goto done;
555                                 }
556                         }
557                 }
558         }
559         if (nerrors) {
560                 error = 0;
561                 goto done;
562         }
563
564         /*
565          * Acquire/wait for events - setup timeout
566          */
567         if (tsp != NULL) {
568                 struct timespec ats;
569
570                 if (tsp->tv_sec || tsp->tv_nsec) {
571                         nanouptime(&ats);
572                         timespecadd(tsp, &ats);         /* tsp = target time */
573                 }
574         }
575
576         /*
577          * Loop as required.
578          *
579          * Collect as many events as we can.  The timeout on successive
580          * loops is disabled (kqueue_scan() becomes non-blocking).
581          *
582          * The loop stops if an error occurs or all events have been
583          * scanned.  The copyoutfn function does not have to increment
584          * (*res) in order for the loop to continue.
585          */
586         total = 0;
587         error = 0;
588         while ((n = nevents - total) > 0) {
589                 if (n > KQ_NEVENTS)
590                         n = KQ_NEVENTS;
591                 i = kqueue_scan(kq, kev, n, tsp, &error);
592                 if (i == 0)
593                         break;
594                 error = kevent_copyoutfn(uap, kev, i, res);
595                 total += i;
596                 if (error || i < n)
597                         break;
598
599                 /*
600                  * successive loops are non-blocking only if (*res)
601                  * is non-zero.
602                  */
603                 if (*res) {
604                         tsp = &ts;
605                         tsp->tv_sec = 0;
606                         tsp->tv_nsec = 0;
607                 }
608         }
609
610 done:
611         rel_mplock();
612         return (error);
613 }
614
615 /*
616  * MPALMOSTSAFE
617  */
618 int
619 sys_kevent(struct kevent_args *uap)
620 {
621         struct thread *td = curthread;
622         struct proc *p = td->td_proc;
623         struct timespec ts, *tsp;
624         struct kqueue *kq;
625         struct file *fp = NULL;
626         struct kevent_copyin_args *kap, ka;
627         int error;
628
629         if (uap->timeout) {
630                 error = copyin(uap->timeout, &ts, sizeof(ts));
631                 if (error)
632                         return (error);
633                 tsp = &ts;
634         } else {
635                 tsp = NULL;
636         }
637
638         fp = holdfp(p->p_fd, uap->fd, -1);
639         if (fp == NULL)
640                 return (EBADF);
641         if (fp->f_type != DTYPE_KQUEUE) {
642                 fdrop(fp);
643                 return (EBADF);
644         }
645
646         kq = (struct kqueue *)fp->f_data;
647
648         kap = &ka;
649         kap->ka = uap;
650         kap->pchanges = 0;
651
652         error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
653                             kevent_copyin, kevent_copyout, tsp);
654
655         fdrop(fp);
656
657         return (error);
658 }
659
660 int
661 kqueue_register(struct kqueue *kq, struct kevent *kev)
662 {
663         struct filedesc *fdp = kq->kq_fdp;
664         struct filterops *fops;
665         struct file *fp = NULL;
666         struct knote *kn = NULL;
667         int error = 0;
668
669         if (kev->filter < 0) {
670                 if (kev->filter + EVFILT_SYSCOUNT < 0)
671                         return (EINVAL);
672                 fops = sysfilt_ops[~kev->filter];       /* to 0-base index */
673         } else {
674                 /*
675                  * XXX
676                  * filter attach routine is responsible for insuring that
677                  * the identifier can be attached to it.
678                  */
679                 kprintf("unknown filter: %d\n", kev->filter);
680                 return (EINVAL);
681         }
682
683         if (fops->f_isfd) {
684                 /* validate descriptor */
685                 fp = holdfp(fdp, kev->ident, -1);
686                 if (fp == NULL)
687                         return (EBADF);
688
689                 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
690                         if (kn->kn_kq == kq &&
691                             kn->kn_filter == kev->filter &&
692                             kn->kn_id == kev->ident) {
693                                 break;
694                         }
695                 }
696         } else {
697                 if (kq->kq_knhashmask) {
698                         struct klist *list;
699                         
700                         list = &kq->kq_knhash[
701                             KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
702                         SLIST_FOREACH(kn, list, kn_link) {
703                                 if (kn->kn_id == kev->ident &&
704                                     kn->kn_filter == kev->filter)
705                                         break;
706                         }
707                 }
708         }
709
710         if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
711                 error = ENOENT;
712                 goto done;
713         }
714
715         /*
716          * kn now contains the matching knote, or NULL if no match
717          */
718         if (kev->flags & EV_ADD) {
719                 if (kn == NULL) {
720                         kn = knote_alloc();
721                         if (kn == NULL) {
722                                 error = ENOMEM;
723                                 goto done;
724                         }
725                         kn->kn_fp = fp;
726                         kn->kn_kq = kq;
727                         kn->kn_fop = fops;
728
729                         /*
730                          * apply reference count to knote structure, and
731                          * do not release it at the end of this routine.
732                          */
733                         fp = NULL;
734
735                         kn->kn_sfflags = kev->fflags;
736                         kn->kn_sdata = kev->data;
737                         kev->fflags = 0;
738                         kev->data = 0;
739                         kn->kn_kevent = *kev;
740
741                         knote_attach(kn);
742                         if ((error = fops->f_attach(kn)) != 0) {
743                                 knote_drop(kn);
744                                 goto done;
745                         }
746                 } else {
747                         /*
748                          * The user may change some filter values after the
749                          * initial EV_ADD, but doing so will not reset any 
750                          * filter which have already been triggered.
751                          */
752                         kn->kn_sfflags = kev->fflags;
753                         kn->kn_sdata = kev->data;
754                         kn->kn_kevent.udata = kev->udata;
755                 }
756
757                 crit_enter();
758                 if (kn->kn_fop->f_event(kn, 0))
759                         KNOTE_ACTIVATE(kn);
760                 crit_exit();
761         } else if (kev->flags & EV_DELETE) {
762                 kn->kn_fop->f_detach(kn);
763                 knote_drop(kn);
764                 goto done;
765         }
766
767         if ((kev->flags & EV_DISABLE) &&
768             ((kn->kn_status & KN_DISABLED) == 0)) {
769                 crit_enter();
770                 kn->kn_status |= KN_DISABLED;
771                 crit_exit();
772         }
773
774         if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
775                 crit_enter();
776                 kn->kn_status &= ~KN_DISABLED;
777                 if ((kn->kn_status & KN_ACTIVE) &&
778                     ((kn->kn_status & KN_QUEUED) == 0))
779                         knote_enqueue(kn);
780                 crit_exit();
781         }
782
783 done:
784         if (fp != NULL)
785                 fdrop(fp);
786         return (error);
787 }
788
789 /*
790  * Scan the kqueue, blocking if necessary until the target time is reached.
791  * If tsp is NULL we block indefinitely.  If tsp->ts_secs/nsecs are both
792  * 0 we do not block at all.
793  */
794 static int
795 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
796             struct timespec *tsp, int *errorp)
797 {
798         struct knote *kn, marker;
799         int total;
800
801         total = 0;
802 again:
803         crit_enter();
804         if (kq->kq_count == 0) {
805                 if (tsp == NULL) {
806                         kq->kq_state |= KQ_SLEEP;
807                         *errorp = tsleep(kq, PCATCH, "kqread", 0);
808                 } else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
809                         *errorp = EWOULDBLOCK;
810                 } else {
811                         struct timespec ats;
812                         struct timespec atx = *tsp;
813                         int timeout;
814
815                         nanouptime(&ats);
816                         timespecsub(&atx, &ats);
817                         if (ats.tv_sec < 0) {
818                                 *errorp = EWOULDBLOCK;
819                         } else {
820                                 timeout = atx.tv_sec > 24 * 60 * 60 ?
821                                         24 * 60 * 60 * hz : tstohz_high(&atx);
822                                 kq->kq_state |= KQ_SLEEP;
823                                 *errorp = tsleep(kq, PCATCH, "kqread", timeout);
824                         }
825                 }
826                 crit_exit();
827                 if (*errorp == 0)
828                         goto again;
829                 /* don't restart after signals... */
830                 if (*errorp == ERESTART)
831                         *errorp = EINTR;
832                 else if (*errorp == EWOULDBLOCK)
833                         *errorp = 0;
834                 goto done;
835         }
836
837         /*
838          * Collect events.  Continuous mode events may get recycled
839          * past the marker so we stop when we hit it unless no events
840          * have been collected.
841          */
842         TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
843         while (count) {
844                 kn = TAILQ_FIRST(&kq->kq_knpend);
845                 if (kn == &marker)
846                         break;
847                 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
848                 if (kn->kn_status & KN_DISABLED) {
849                         kn->kn_status &= ~KN_QUEUED;
850                         kq->kq_count--;
851                         continue;
852                 }
853                 if ((kn->kn_flags & EV_ONESHOT) == 0 &&
854                     kn->kn_fop->f_event(kn, 0) == 0) {
855                         kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
856                         kq->kq_count--;
857                         continue;
858                 }
859                 *kevp++ = kn->kn_kevent;
860                 ++total;
861                 --count;
862
863                 /*
864                  * Post-event action on the note
865                  */
866                 if (kn->kn_flags & EV_ONESHOT) {
867                         kn->kn_status &= ~KN_QUEUED;
868                         kq->kq_count--;
869                         crit_exit();
870                         kn->kn_fop->f_detach(kn);
871                         knote_drop(kn);
872                         crit_enter();
873                 } else if (kn->kn_flags & EV_CLEAR) {
874                         kn->kn_data = 0;
875                         kn->kn_fflags = 0;
876                         kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
877                         kq->kq_count--;
878                 } else {
879                         TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
880                 }
881         }
882         TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
883         crit_exit();
884         if (total == 0)
885                 goto again;
886 done:
887         return (total);
888 }
889
890 /*
891  * XXX
892  * This could be expanded to call kqueue_scan, if desired.
893  *
894  * MPSAFE
895  */
896 static int
897 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
898 {
899         return (ENXIO);
900 }
901
902 /*
903  * MPSAFE
904  */
905 static int
906 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
907 {
908         return (ENXIO);
909 }
910
911 /*
912  * MPALMOSTSAFE
913  */
914 static int
915 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
916              struct ucred *cred, struct sysmsg *msg)
917 {
918         struct kqueue *kq;
919         int error;
920
921         get_mplock();
922         kq = (struct kqueue *)fp->f_data;
923
924         switch(com) {
925         case FIOASYNC:
926                 if (*(int *)data)
927                         kq->kq_state |= KQ_ASYNC;
928                 else
929                         kq->kq_state &= ~KQ_ASYNC;
930                 error = 0;
931                 break;
932         case FIOSETOWN:
933                 error = fsetown(*(int *)data, &kq->kq_sigio);
934                 break;
935         default:
936                 error = ENOTTY;
937                 break;
938         }
939         rel_mplock();
940         return (error);
941 }
942
943 /*
944  * MPALMOSTSAFE - acquires mplock
945  */
946 static int
947 kqueue_poll(struct file *fp, int events, struct ucred *cred)
948 {
949         struct kqueue *kq = (struct kqueue *)fp->f_data;
950         int revents = 0;
951
952         get_mplock();
953         crit_enter();
954         if (events & (POLLIN | POLLRDNORM)) {
955                 if (kq->kq_count) {
956                         revents |= events & (POLLIN | POLLRDNORM);
957                 } else {
958                         selrecord(curthread, &kq->kq_sel);
959                         kq->kq_state |= KQ_SEL;
960                 }
961         }
962         crit_exit();
963         rel_mplock();
964         return (revents);
965 }
966
967 /*
968  * MPSAFE
969  */
970 static int
971 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
972 {
973         struct kqueue *kq = (struct kqueue *)fp->f_data;
974
975         bzero((void *)st, sizeof(*st));
976         st->st_size = kq->kq_count;
977         st->st_blksize = sizeof(struct kevent);
978         st->st_mode = S_IFIFO;
979         return (0);
980 }
981
982 /*
983  * MPALMOSTSAFE - acquires mplock
984  */
985 static int
986 kqueue_close(struct file *fp)
987 {
988         struct kqueue *kq = (struct kqueue *)fp->f_data;
989
990         get_mplock();
991
992         kqueue_terminate(kq);
993
994         fp->f_data = NULL;
995         funsetown(kq->kq_sigio);
996         rel_mplock();
997
998         kfree(kq, M_KQUEUE);
999         return (0);
1000 }
1001
1002 void
1003 kqueue_wakeup(struct kqueue *kq)
1004 {
1005         if (kq->kq_state & KQ_SLEEP) {
1006                 kq->kq_state &= ~KQ_SLEEP;
1007                 wakeup(kq);
1008         }
1009         if (kq->kq_state & KQ_SEL) {
1010                 kq->kq_state &= ~KQ_SEL;
1011                 selwakeup(&kq->kq_sel);
1012         }
1013         KNOTE(&kq->kq_sel.si_note, 0);
1014 }
1015
1016 /*
1017  * walk down a list of knotes, activating them if their event has triggered.
1018  */
1019 void
1020 knote(struct klist *list, long hint)
1021 {
1022         struct knote *kn;
1023
1024         SLIST_FOREACH(kn, list, kn_selnext)
1025                 if (kn->kn_fop->f_event(kn, hint))
1026                         KNOTE_ACTIVATE(kn);
1027 }
1028
1029 /*
1030  * remove all knotes from a specified klist
1031  */
1032 void
1033 knote_remove(struct klist *list)
1034 {
1035         struct knote *kn;
1036
1037         while ((kn = SLIST_FIRST(list)) != NULL) {
1038                 kn->kn_fop->f_detach(kn);
1039                 knote_drop(kn);
1040         }
1041 }
1042
1043 /*
1044  * remove all knotes referencing a specified fd
1045  */
1046 void
1047 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1048 {
1049         struct knote *kn;
1050
1051 restart:
1052         SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1053                 if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1054                         kn->kn_fop->f_detach(kn);
1055                         knote_drop(kn);
1056                         goto restart;
1057                 }
1058         }
1059 }
1060
1061 static void
1062 knote_attach(struct knote *kn)
1063 {
1064         struct klist *list;
1065         struct kqueue *kq = kn->kn_kq;
1066
1067         if (kn->kn_fop->f_isfd) {
1068                 KKASSERT(kn->kn_fp);
1069                 list = &kn->kn_fp->f_klist;
1070         } else {
1071                 if (kq->kq_knhashmask == 0)
1072                         kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1073                                                  &kq->kq_knhashmask);
1074                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1075         }
1076         SLIST_INSERT_HEAD(list, kn, kn_link);
1077         TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1078         kn->kn_status = 0;
1079 }
1080
1081 /*
1082  * should be called outside of a critical section, since we don't want to
1083  * hold a critical section while calling fdrop and free.
1084  */
1085 static void
1086 knote_drop(struct knote *kn)
1087 {
1088         struct kqueue *kq;
1089         struct klist *list;
1090
1091         kq = kn->kn_kq;
1092
1093         if (kn->kn_fop->f_isfd)
1094                 list = &kn->kn_fp->f_klist;
1095         else
1096                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1097
1098         SLIST_REMOVE(list, kn, knote, kn_link);
1099         TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1100         if (kn->kn_status & KN_QUEUED)
1101                 knote_dequeue(kn);
1102         if (kn->kn_fop->f_isfd)
1103                 fdrop(kn->kn_fp);
1104         knote_free(kn);
1105 }
1106
1107
1108 static void
1109 knote_enqueue(struct knote *kn)
1110 {
1111         struct kqueue *kq = kn->kn_kq;
1112
1113         crit_enter();
1114         KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1115
1116         TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1117         kn->kn_status |= KN_QUEUED;
1118         ++kq->kq_count;
1119
1120         /*
1121          * Send SIGIO on request (typically set up as a mailbox signal)
1122          */
1123         if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1124                 pgsigio(kq->kq_sigio, SIGIO, 0);
1125         crit_exit();
1126         kqueue_wakeup(kq);
1127 }
1128
1129 static void
1130 knote_dequeue(struct knote *kn)
1131 {
1132         struct kqueue *kq = kn->kn_kq;
1133
1134         KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1135         crit_enter();
1136
1137         TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1138         kn->kn_status &= ~KN_QUEUED;
1139         kq->kq_count--;
1140         crit_exit();
1141 }
1142
1143 static void
1144 knote_init(void)
1145 {
1146         knote_zone = zinit("KNOTE", sizeof(struct knote), 0, 0, 1);
1147 }
1148 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1149
1150 static struct knote *
1151 knote_alloc(void)
1152 {
1153         return ((struct knote *)zalloc(knote_zone));
1154 }
1155
1156 static void
1157 knote_free(struct knote *kn)
1158 {
1159         zfree(knote_zone, kn);
1160 }