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