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