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