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