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