]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_event.c
This commit was generated by cvs2svn to compensate for changes in r145857,
[FreeBSD/FreeBSD.git] / sys / kern / kern_event.c
1 /*-
2  * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
3  * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/lock.h>
35 #include <sys/mutex.h>
36 #include <sys/proc.h>
37 #include <sys/malloc.h>
38 #include <sys/unistd.h>
39 #include <sys/file.h>
40 #include <sys/filedesc.h>
41 #include <sys/filio.h>
42 #include <sys/fcntl.h>
43 #include <sys/kthread.h>
44 #include <sys/selinfo.h>
45 #include <sys/queue.h>
46 #include <sys/event.h>
47 #include <sys/eventvar.h>
48 #include <sys/poll.h>
49 #include <sys/protosw.h>
50 #include <sys/sigio.h>
51 #include <sys/signalvar.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/stat.h>
55 #include <sys/sysctl.h>
56 #include <sys/sysproto.h>
57 #include <sys/syscallsubr.h>
58 #include <sys/taskqueue.h>
59 #include <sys/uio.h>
60
61 #include <vm/uma.h>
62
63 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
64
65 /*
66  * This lock is used if multiple kq locks are required.  This possibly
67  * should be made into a per proc lock.
68  */
69 static struct mtx       kq_global;
70 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
71 #define KQ_GLOBAL_LOCK(lck, haslck)     do {    \
72         if (!haslck)                            \
73                 mtx_lock(lck);                  \
74         haslck = 1;                             \
75 } while (0)
76 #define KQ_GLOBAL_UNLOCK(lck, haslck)   do {    \
77         if (haslck)                             \
78                 mtx_unlock(lck);                        \
79         haslck = 0;                             \
80 } while (0)
81
82 TASKQUEUE_DEFINE_THREAD(kqueue);
83
84 static int      kevent_copyout(struct kevent **eventlist, enum uio_seg eventseg,
85                     struct kevent *kevp, int count);
86 static int      kqueue_aquire(struct file *fp, struct kqueue **kqp);
87 static void     kqueue_release(struct kqueue *kq, int locked);
88 static int      kqueue_expand(struct kqueue *kq, struct filterops *fops,
89                     uintptr_t ident, int waitok);
90 static void     kqueue_task(void *arg, int pending);
91 static int      kqueue_scan(struct kqueue *kq, int maxevents,
92                     struct kevent *eventlist, enum uio_seg eventseg,
93                     const struct timespec *timeout, struct kevent *keva,
94                     struct thread *td);
95 static void     kqueue_wakeup(struct kqueue *kq);
96 static struct filterops *kqueue_fo_find(int filt);
97 static void     kqueue_fo_release(int filt);
98
99 static fo_rdwr_t        kqueue_read;
100 static fo_rdwr_t        kqueue_write;
101 static fo_ioctl_t       kqueue_ioctl;
102 static fo_poll_t        kqueue_poll;
103 static fo_kqfilter_t    kqueue_kqfilter;
104 static fo_stat_t        kqueue_stat;
105 static fo_close_t       kqueue_close;
106
107 static struct fileops kqueueops = {
108         .fo_read = kqueue_read,
109         .fo_write = kqueue_write,
110         .fo_ioctl = kqueue_ioctl,
111         .fo_poll = kqueue_poll,
112         .fo_kqfilter = kqueue_kqfilter,
113         .fo_stat = kqueue_stat,
114         .fo_close = kqueue_close,
115 };
116
117 static int      knote_attach(struct knote *kn, struct kqueue *kq);
118 static void     knote_drop(struct knote *kn, struct thread *td);
119 static void     knote_enqueue(struct knote *kn);
120 static void     knote_dequeue(struct knote *kn);
121 static void     knote_init(void);
122 static struct   knote *knote_alloc(int waitok);
123 static void     knote_free(struct knote *kn);
124
125 static void     filt_kqdetach(struct knote *kn);
126 static int      filt_kqueue(struct knote *kn, long hint);
127 static int      filt_procattach(struct knote *kn);
128 static void     filt_procdetach(struct knote *kn);
129 static int      filt_proc(struct knote *kn, long hint);
130 static int      filt_fileattach(struct knote *kn);
131 static void     filt_timerexpire(void *knx);
132 static int      filt_timerattach(struct knote *kn);
133 static void     filt_timerdetach(struct knote *kn);
134 static int      filt_timer(struct knote *kn, long hint);
135
136 static struct filterops file_filtops =
137         { 1, filt_fileattach, NULL, NULL };
138 static struct filterops kqread_filtops =
139         { 1, NULL, filt_kqdetach, filt_kqueue };
140 /* XXX - move to kern_proc.c?  */
141 static struct filterops proc_filtops =
142         { 0, filt_procattach, filt_procdetach, filt_proc };
143 static struct filterops timer_filtops =
144         { 0, filt_timerattach, filt_timerdetach, filt_timer };
145
146 static uma_zone_t       knote_zone;
147 static int              kq_ncallouts = 0;
148 static int              kq_calloutmax = (4 * 1024);
149 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
150     &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
151
152 /* XXX - ensure not KN_INFLUX?? */
153 #define KNOTE_ACTIVATE(kn, islock) do {                                 \
154         if ((islock))                                                   \
155                 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED);            \
156         else                                                            \
157                 KQ_LOCK((kn)->kn_kq);                                   \
158         (kn)->kn_status |= KN_ACTIVE;                                   \
159         if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0)         \
160                 knote_enqueue((kn));                                    \
161         if (!(islock))                                                  \
162                 KQ_UNLOCK((kn)->kn_kq);                                 \
163 } while(0)
164 #define KQ_LOCK(kq) do {                                                \
165         mtx_lock(&(kq)->kq_lock);                                       \
166 } while (0)
167 #define KQ_FLUX_WAKEUP(kq) do {                                         \
168         if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) {            \
169                 (kq)->kq_state &= ~KQ_FLUXWAIT;                         \
170                 wakeup((kq));                                           \
171         }                                                               \
172 } while (0)
173 #define KQ_UNLOCK_FLUX(kq) do {                                         \
174         KQ_FLUX_WAKEUP(kq);                                             \
175         mtx_unlock(&(kq)->kq_lock);                                     \
176 } while (0)
177 #define KQ_UNLOCK(kq) do {                                              \
178         mtx_unlock(&(kq)->kq_lock);                                     \
179 } while (0)
180 #define KQ_OWNED(kq) do {                                               \
181         mtx_assert(&(kq)->kq_lock, MA_OWNED);                           \
182 } while (0)
183 #define KQ_NOTOWNED(kq) do {                                            \
184         mtx_assert(&(kq)->kq_lock, MA_NOTOWNED);                        \
185 } while (0)
186 #define KN_LIST_LOCK(kn) do {                                           \
187         if (kn->kn_knlist != NULL)                                      \
188                 mtx_lock(kn->kn_knlist->kl_lock);                       \
189 } while (0)
190 #define KN_LIST_UNLOCK(kn) do {                                         \
191         if (kn->kn_knlist != NULL)                                      \
192                 mtx_unlock(kn->kn_knlist->kl_lock);                     \
193 } while (0)
194
195 #define KN_HASHSIZE             64              /* XXX should be tunable */
196 #define KN_HASH(val, mask)      (((val) ^ (val >> 8)) & (mask))
197
198 static int
199 filt_nullattach(struct knote *kn)
200 {
201
202         return (ENXIO);
203 };
204
205 struct filterops null_filtops =
206         { 0, filt_nullattach, NULL, NULL };
207
208 /* XXX - make SYSINIT to add these, and move into respective modules. */
209 extern struct filterops sig_filtops;
210 extern struct filterops fs_filtops;
211
212 /*
213  * Table for for all system-defined filters.
214  */
215 static struct mtx       filterops_lock;
216 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
217         MTX_DEF);
218 static struct {
219         struct filterops *for_fop;
220         int for_refcnt;
221 } sysfilt_ops[EVFILT_SYSCOUNT] = {
222         { &file_filtops },                      /* EVFILT_READ */
223         { &file_filtops },                      /* EVFILT_WRITE */
224         { &null_filtops },                      /* EVFILT_AIO */
225         { &file_filtops },                      /* EVFILT_VNODE */
226         { &proc_filtops },                      /* EVFILT_PROC */
227         { &sig_filtops },                       /* EVFILT_SIGNAL */
228         { &timer_filtops },                     /* EVFILT_TIMER */
229         { &file_filtops },                      /* EVFILT_NETDEV */
230         { &fs_filtops },                        /* EVFILT_FS */
231 };
232
233 /*
234  * Simple redirection for all cdevsw style objects to call their fo_kqfilter
235  * method.
236  */
237 static int
238 filt_fileattach(struct knote *kn)
239 {
240
241         return (fo_kqfilter(kn->kn_fp, kn));
242 }
243
244 /*ARGSUSED*/
245 static int
246 kqueue_kqfilter(struct file *fp, struct knote *kn)
247 {
248         struct kqueue *kq = kn->kn_fp->f_data;
249
250         if (kn->kn_filter != EVFILT_READ)
251                 return (EINVAL);
252
253         kn->kn_status |= KN_KQUEUE;
254         kn->kn_fop = &kqread_filtops;
255         knlist_add(&kq->kq_sel.si_note, kn, 0);
256
257         return (0);
258 }
259
260 static void
261 filt_kqdetach(struct knote *kn)
262 {
263         struct kqueue *kq = kn->kn_fp->f_data;
264
265         knlist_remove(&kq->kq_sel.si_note, kn, 0);
266 }
267
268 /*ARGSUSED*/
269 static int
270 filt_kqueue(struct knote *kn, long hint)
271 {
272         struct kqueue *kq = kn->kn_fp->f_data;
273
274         kn->kn_data = kq->kq_count;
275         return (kn->kn_data > 0);
276 }
277
278 /* XXX - move to kern_proc.c?  */
279 static int
280 filt_procattach(struct knote *kn)
281 {
282         struct proc *p;
283         int immediate;
284         int error;
285
286         immediate = 0;
287         p = pfind(kn->kn_id);
288         if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
289                 p = zpfind(kn->kn_id);
290                 immediate = 1;
291         } else if (p != NULL && (p->p_flag & P_WEXIT)) {
292                 immediate = 1;
293         }
294
295         if (p == NULL)
296                 return (ESRCH);
297         if ((error = p_cansee(curthread, p)))
298                 return (error);
299
300         kn->kn_ptr.p_proc = p;
301         kn->kn_flags |= EV_CLEAR;               /* automatically set */
302
303         /*
304          * internal flag indicating registration done by kernel
305          */
306         if (kn->kn_flags & EV_FLAG1) {
307                 kn->kn_data = kn->kn_sdata;             /* ppid */
308                 kn->kn_fflags = NOTE_CHILD;
309                 kn->kn_flags &= ~EV_FLAG1;
310         }
311
312         if (immediate == 0)
313                 knlist_add(&p->p_klist, kn, 1);
314
315         /*
316          * Immediately activate any exit notes if the target process is a
317          * zombie.  This is necessary to handle the case where the target
318          * process, e.g. a child, dies before the kevent is registered.
319          */
320         if (immediate && filt_proc(kn, NOTE_EXIT))
321                 KNOTE_ACTIVATE(kn, 0);
322
323         PROC_UNLOCK(p);
324
325         return (0);
326 }
327
328 /*
329  * The knote may be attached to a different process, which may exit,
330  * leaving nothing for the knote to be attached to.  So when the process
331  * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
332  * it will be deleted when read out.  However, as part of the knote deletion,
333  * this routine is called, so a check is needed to avoid actually performing
334  * a detach, because the original process does not exist any more.
335  */
336 /* XXX - move to kern_proc.c?  */
337 static void
338 filt_procdetach(struct knote *kn)
339 {
340         struct proc *p;
341
342         p = kn->kn_ptr.p_proc;
343         knlist_remove(&p->p_klist, kn, 0);
344         kn->kn_ptr.p_proc = NULL;
345 }
346
347 /* XXX - move to kern_proc.c?  */
348 static int
349 filt_proc(struct knote *kn, long hint)
350 {
351         struct proc *p = kn->kn_ptr.p_proc;
352         u_int event;
353
354         /*
355          * mask off extra data
356          */
357         event = (u_int)hint & NOTE_PCTRLMASK;
358
359         /*
360          * if the user is interested in this event, record it.
361          */
362         if (kn->kn_sfflags & event)
363                 kn->kn_fflags |= event;
364
365         /*
366          * process is gone, so flag the event as finished.
367          */
368         if (event == NOTE_EXIT) {
369                 if (!(kn->kn_status & KN_DETACHED))
370                         knlist_remove_inevent(&p->p_klist, kn);
371                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
372                 kn->kn_ptr.p_proc = NULL;
373                 return (1);
374         }
375
376         /*
377          * process forked, and user wants to track the new process,
378          * so attach a new knote to it, and immediately report an
379          * event with the parent's pid.
380          */
381         if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
382                 struct kevent kev;
383                 int error;
384
385                 /*
386                  * register knote with new process.
387                  */
388                 kev.ident = hint & NOTE_PDATAMASK;      /* pid */
389                 kev.filter = kn->kn_filter;
390                 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
391                 kev.fflags = kn->kn_sfflags;
392                 kev.data = kn->kn_id;                   /* parent */
393                 kev.udata = kn->kn_kevent.udata;        /* preserve udata */
394                 error = kqueue_register(kn->kn_kq, &kev, NULL, 0);
395                 if (error)
396                         kn->kn_fflags |= NOTE_TRACKERR;
397         }
398
399         return (kn->kn_fflags != 0);
400 }
401
402 static int
403 timertoticks(intptr_t data)
404 {
405         struct timeval tv;
406         int tticks;
407
408         tv.tv_sec = data / 1000;
409         tv.tv_usec = (data % 1000) * 1000;
410         tticks = tvtohz(&tv);
411
412         return tticks;
413 }
414
415 /* XXX - move to kern_timeout.c? */
416 static void
417 filt_timerexpire(void *knx)
418 {
419         struct knote *kn = knx;
420         struct callout *calloutp;
421
422         kn->kn_data++;
423         KNOTE_ACTIVATE(kn, 0);  /* XXX - handle locking */
424
425         if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
426                 calloutp = (struct callout *)kn->kn_hook;
427                 callout_reset(calloutp, timertoticks(kn->kn_sdata),
428                     filt_timerexpire, kn);
429         }
430 }
431
432 /*
433  * data contains amount of time to sleep, in milliseconds
434  */
435 /* XXX - move to kern_timeout.c? */
436 static int
437 filt_timerattach(struct knote *kn)
438 {
439         struct callout *calloutp;
440
441         atomic_add_int(&kq_ncallouts, 1);
442
443         if (kq_ncallouts >= kq_calloutmax) {
444                 atomic_add_int(&kq_ncallouts, -1);
445                 return (ENOMEM);
446         }
447
448         kn->kn_flags |= EV_CLEAR;               /* automatically set */
449         kn->kn_status &= ~KN_DETACHED;          /* knlist_add usually sets it */
450         MALLOC(calloutp, struct callout *, sizeof(*calloutp),
451             M_KQUEUE, M_WAITOK);
452         callout_init(calloutp, CALLOUT_MPSAFE);
453         kn->kn_hook = calloutp;
454         callout_reset(calloutp, timertoticks(kn->kn_sdata), filt_timerexpire,
455             kn);
456
457         return (0);
458 }
459
460 /* XXX - move to kern_timeout.c? */
461 static void
462 filt_timerdetach(struct knote *kn)
463 {
464         struct callout *calloutp;
465
466         calloutp = (struct callout *)kn->kn_hook;
467         callout_drain(calloutp);
468         FREE(calloutp, M_KQUEUE);
469         atomic_add_int(&kq_ncallouts, -1);
470         kn->kn_status |= KN_DETACHED;   /* knlist_remove usually clears it */
471 }
472
473 /* XXX - move to kern_timeout.c? */
474 static int
475 filt_timer(struct knote *kn, long hint)
476 {
477
478         return (kn->kn_data != 0);
479 }
480
481 /*
482  * MPSAFE
483  */
484 int
485 kqueue(struct thread *td, struct kqueue_args *uap)
486 {
487         struct filedesc *fdp;
488         struct kqueue *kq;
489         struct file *fp;
490         int fd, error;
491
492         fdp = td->td_proc->p_fd;
493         error = falloc(td, &fp, &fd);
494         if (error)
495                 goto done2;
496
497         /* An extra reference on `nfp' has been held for us by falloc(). */
498         kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
499         mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
500         TAILQ_INIT(&kq->kq_head);
501         kq->kq_fdp = fdp;
502         knlist_init(&kq->kq_sel.si_note, &kq->kq_lock);
503         TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
504
505         FILEDESC_LOCK_FAST(fdp);
506         SLIST_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
507         FILEDESC_UNLOCK_FAST(fdp);
508
509         FILE_LOCK(fp);
510         fp->f_flag = FREAD | FWRITE;
511         fp->f_type = DTYPE_KQUEUE;
512         fp->f_ops = &kqueueops;
513         fp->f_data = kq;
514         FILE_UNLOCK(fp);
515         fdrop(fp, td);
516
517         td->td_retval[0] = fd;
518 done2:
519         return (error);
520 }
521
522 #ifndef _SYS_SYSPROTO_H_
523 struct kevent_args {
524         int     fd;
525         const struct kevent *changelist;
526         int     nchanges;
527         struct  kevent *eventlist;
528         int     nevents;
529         const struct timespec *timeout;
530 };
531 #endif
532 /*
533  * MPSAFE
534  */
535 int
536 kevent(struct thread *td, struct kevent_args *uap)
537 {
538         struct timespec ts, *tsp;
539         int error;
540
541         if (uap->timeout != NULL) {
542                 error = copyin(uap->timeout, &ts, sizeof(ts));
543                 if (error)
544                         return (error);
545                 tsp = &ts;
546         } else
547                 tsp = NULL;
548
549         return (kern_kevent(td, uap->fd, uap->changelist, uap->nchanges,
550             UIO_USERSPACE, uap->eventlist, uap->nevents, UIO_USERSPACE, tsp));
551 }
552
553 /*
554  * Copy 'count' items into the destination list pointd to by *eventlist.  The
555  * eventlist and nevents values are updated to point after the copied out
556  * item(s) upon return.
557  */
558 static int
559 kevent_copyout(struct kevent **eventlist, enum uio_seg eventseg,
560     struct kevent *kevp, int count)
561 {
562         int error;
563
564         if (eventseg == UIO_USERSPACE)
565                 error = copyout(kevp, *eventlist,
566                     sizeof(struct kevent) * count);
567         else {
568                 bcopy(kevp, *eventlist, sizeof(struct kevent) * count);
569                 error = 0;
570         }
571         *eventlist += count;
572         return (error);
573 }
574
575 int
576 kern_kevent(struct thread *td, int fd, struct kevent *changelist, int nchanges,
577     enum uio_seg changeseg, struct kevent *eventlist, int nevents,
578     enum uio_seg eventseg, const struct timespec *timeout)
579 {
580         struct kevent keva[KQ_NEVENTS];
581         struct kevent *kevp, *changes;
582         struct kqueue *kq;
583         struct file *fp;
584         int i, n, nerrors, error;
585
586         if ((error = fget(td, fd, &fp)) != 0)
587                 return (error);
588         if ((error = kqueue_aquire(fp, &kq)) != 0)
589                 goto done_norel;
590
591         nerrors = 0;
592
593         while (nchanges > 0) {
594                 if (changeseg == UIO_USERSPACE) {
595                         n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
596                         error = copyin(changelist, keva, n * sizeof *keva);
597                         if (error)
598                                 goto done;
599                         changes = keva;
600                 } else {
601                         changes = changelist;
602                         n = nchanges;
603                 }
604                 for (i = 0; i < n; i++) {
605                         kevp = &changes[i];
606                         kevp->flags &= ~EV_SYSFLAGS;
607                         error = kqueue_register(kq, kevp, td, 1);
608                         if (error) {
609                                 if (nevents != 0) {
610                                         kevp->flags = EV_ERROR;
611                                         kevp->data = error;
612                                         (void) kevent_copyout(&eventlist,
613                                             eventseg, kevp, 1);
614                                         nevents--;
615                                         nerrors++;
616                                 } else {
617                                         goto done;
618                                 }
619                         }
620                 }
621                 nchanges -= n;
622                 changelist += n;
623         }
624         if (nerrors) {
625                 td->td_retval[0] = nerrors;
626                 error = 0;
627                 goto done;
628         }
629
630         error = kqueue_scan(kq, nevents, eventlist, eventseg, timeout,
631             keva, td);
632 done:
633         kqueue_release(kq, 0);
634 done_norel:
635         if (fp != NULL)
636                 fdrop(fp, td);
637         return (error);
638 }
639
640 int
641 kqueue_add_filteropts(int filt, struct filterops *filtops)
642 {
643         int error;
644
645         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
646                 printf(
647 "trying to add a filterop that is out of range: %d is beyond %d\n",
648                     ~filt, EVFILT_SYSCOUNT);
649                 return EINVAL;
650         }
651         mtx_lock(&filterops_lock);
652         if (sysfilt_ops[~filt].for_fop != &null_filtops &&
653             sysfilt_ops[~filt].for_fop != NULL)
654                 error = EEXIST;
655         else {
656                 sysfilt_ops[~filt].for_fop = filtops;
657                 sysfilt_ops[~filt].for_refcnt = 0;
658         }
659         mtx_unlock(&filterops_lock);
660
661         return (0);
662 }
663
664 int
665 kqueue_del_filteropts(int filt)
666 {
667         int error;
668
669         error = 0;
670         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
671                 return EINVAL;
672
673         mtx_lock(&filterops_lock);
674         if (sysfilt_ops[~filt].for_fop == &null_filtops ||
675             sysfilt_ops[~filt].for_fop == NULL)
676                 error = EINVAL;
677         else if (sysfilt_ops[~filt].for_refcnt != 0)
678                 error = EBUSY;
679         else {
680                 sysfilt_ops[~filt].for_fop = &null_filtops;
681                 sysfilt_ops[~filt].for_refcnt = 0;
682         }
683         mtx_unlock(&filterops_lock);
684
685         return error;
686 }
687
688 static struct filterops *
689 kqueue_fo_find(int filt)
690 {
691
692         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
693                 return NULL;
694
695         mtx_lock(&filterops_lock);
696         sysfilt_ops[~filt].for_refcnt++;
697         if (sysfilt_ops[~filt].for_fop == NULL)
698                 sysfilt_ops[~filt].for_fop = &null_filtops;
699         mtx_unlock(&filterops_lock);
700
701         return sysfilt_ops[~filt].for_fop;
702 }
703
704 static void
705 kqueue_fo_release(int filt)
706 {
707
708         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
709                 return;
710
711         mtx_lock(&filterops_lock);
712         KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
713             ("filter object refcount not valid on release"));
714         sysfilt_ops[~filt].for_refcnt--;
715         mtx_unlock(&filterops_lock);
716 }
717
718 /*
719  * A ref to kq (obtained via kqueue_aquire) should be held.  waitok will
720  * influence if memory allocation should wait.  Make sure it is 0 if you
721  * hold any mutexes.
722  */
723 int
724 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
725 {
726         struct filedesc *fdp;
727         struct filterops *fops;
728         struct file *fp;
729         struct knote *kn, *tkn;
730         int error, filt, event;
731         int haskqglobal;
732         int fd;
733
734         fdp = NULL;
735         fp = NULL;
736         kn = NULL;
737         error = 0;
738         haskqglobal = 0;
739
740         filt = kev->filter;
741         fops = kqueue_fo_find(filt);
742         if (fops == NULL)
743                 return EINVAL;
744
745         tkn = knote_alloc(waitok);              /* prevent waiting with locks */
746
747 findkn:
748         if (fops->f_isfd) {
749                 KASSERT(td != NULL, ("td is NULL"));
750                 fdp = td->td_proc->p_fd;
751                 FILEDESC_LOCK(fdp);
752                 /* validate descriptor */
753                 fd = kev->ident;
754                 if (fd < 0 || fd >= fdp->fd_nfiles ||
755                     (fp = fdp->fd_ofiles[fd]) == NULL) {
756                         FILEDESC_UNLOCK(fdp);
757                         error = EBADF;
758                         goto done;
759                 }
760                 fhold(fp);
761
762                 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
763                     kev->ident, 0) != 0) {
764                         /* unlock and try again */
765                         FILEDESC_UNLOCK(fdp);
766                         fdrop(fp, td);
767                         fp = NULL;
768                         error = kqueue_expand(kq, fops, kev->ident, waitok);
769                         if (error)
770                                 goto done;
771                         goto findkn;
772                 }
773
774                 if (fp->f_type == DTYPE_KQUEUE) {
775                         /*
776                          * if we add some inteligence about what we are doing,
777                          * we should be able to support events on ourselves.
778                          * We need to know when we are doing this to prevent
779                          * getting both the knlist lock and the kq lock since
780                          * they are the same thing.
781                          */
782                         if (fp->f_data == kq) {
783                                 FILEDESC_UNLOCK(fdp);
784                                 error = EINVAL;
785                                 goto done_noglobal;
786                         }
787
788                         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
789                 }
790
791                 FILEDESC_UNLOCK(fdp);
792                 KQ_LOCK(kq);
793                 if (kev->ident < kq->kq_knlistsize) {
794                         SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
795                                 if (kev->filter == kn->kn_filter)
796                                         break;
797                 }
798         } else {
799                 if ((kev->flags & EV_ADD) == EV_ADD)
800                         kqueue_expand(kq, fops, kev->ident, waitok);
801
802                 KQ_LOCK(kq);
803                 if (kq->kq_knhashmask != 0) {
804                         struct klist *list;
805
806                         list = &kq->kq_knhash[
807                             KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
808                         SLIST_FOREACH(kn, list, kn_link)
809                                 if (kev->ident == kn->kn_id &&
810                                     kev->filter == kn->kn_filter)
811                                         break;
812                 }
813         }
814
815         /* knote is in the process of changing, wait for it to stablize. */
816         if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
817                 if (fp != NULL) {
818                         fdrop(fp, td);
819                         fp = NULL;
820                 }
821                 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
822                 kq->kq_state |= KQ_FLUXWAIT;
823                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
824                 goto findkn;
825         }
826
827         if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
828                 KQ_UNLOCK(kq);
829                 error = ENOENT;
830                 goto done;
831         }
832
833         /*
834          * kn now contains the matching knote, or NULL if no match
835          */
836         if (kev->flags & EV_ADD) {
837                 if (kn == NULL) {
838                         kn = tkn;
839                         tkn = NULL;
840                         if (kn == NULL) {
841                                 error = ENOMEM;
842                                 goto done;
843                         }
844                         kn->kn_fp = fp;
845                         kn->kn_kq = kq;
846                         kn->kn_fop = fops;
847                         /*
848                          * apply reference counts to knote structure, and
849                          * do not release it at the end of this routine.
850                          */
851                         fops = NULL;
852                         fp = NULL;
853
854                         kn->kn_sfflags = kev->fflags;
855                         kn->kn_sdata = kev->data;
856                         kev->fflags = 0;
857                         kev->data = 0;
858                         kn->kn_kevent = *kev;
859                         kn->kn_status = KN_INFLUX|KN_DETACHED;
860
861                         error = knote_attach(kn, kq);
862                         KQ_UNLOCK(kq);
863                         if (error != 0) {
864                                 tkn = kn;
865                                 goto done;
866                         }
867
868                         if ((error = kn->kn_fop->f_attach(kn)) != 0) {
869                                 knote_drop(kn, td);
870                                 goto done;
871                         }
872                         KN_LIST_LOCK(kn);
873                 } else {
874                         /*
875                          * The user may change some filter values after the
876                          * initial EV_ADD, but doing so will not reset any
877                          * filter which has already been triggered.
878                          */
879                         kn->kn_status |= KN_INFLUX;
880                         KQ_UNLOCK(kq);
881                         KN_LIST_LOCK(kn);
882                         kn->kn_sfflags = kev->fflags;
883                         kn->kn_sdata = kev->data;
884                         kn->kn_kevent.udata = kev->udata;
885                 }
886
887                 /*
888                  * We can get here with kn->kn_knlist == NULL.
889                  * This can happen when the initial attach event decides that
890                  * the event is "completed" already.  i.e. filt_procattach
891                  * is called on a zombie process.  It will call filt_proc
892                  * which will remove it from the list, and NULL kn_knlist.
893                  */
894                 event = kn->kn_fop->f_event(kn, 0);
895                 KN_LIST_UNLOCK(kn);
896                 KQ_LOCK(kq);
897                 if (event)
898                         KNOTE_ACTIVATE(kn, 1);
899                 kn->kn_status &= ~KN_INFLUX;
900         } else if (kev->flags & EV_DELETE) {
901                 kn->kn_status |= KN_INFLUX;
902                 KQ_UNLOCK(kq);
903                 if (!(kn->kn_status & KN_DETACHED))
904                         kn->kn_fop->f_detach(kn);
905                 knote_drop(kn, td);
906                 goto done;
907         }
908
909         if ((kev->flags & EV_DISABLE) &&
910             ((kn->kn_status & KN_DISABLED) == 0)) {
911                 kn->kn_status |= KN_DISABLED;
912         }
913
914         if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
915                 kn->kn_status &= ~KN_DISABLED;
916                 if ((kn->kn_status & KN_ACTIVE) &&
917                     ((kn->kn_status & KN_QUEUED) == 0))
918                         knote_enqueue(kn);
919         }
920         KQ_UNLOCK_FLUX(kq);
921
922 done:
923         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
924 done_noglobal:
925         if (fp != NULL)
926                 fdrop(fp, td);
927         if (tkn != NULL)
928                 knote_free(tkn);
929         if (fops != NULL)
930                 kqueue_fo_release(filt);
931         return (error);
932 }
933
934 static int
935 kqueue_aquire(struct file *fp, struct kqueue **kqp)
936 {
937         int error;
938         struct kqueue *kq;
939
940         error = 0;
941
942         FILE_LOCK(fp);
943         do {
944                 kq = fp->f_data;
945                 if (fp->f_type != DTYPE_KQUEUE || kq == NULL) {
946                         error = EBADF;
947                         break;
948                 }
949                 *kqp = kq;
950                 KQ_LOCK(kq);
951                 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
952                         KQ_UNLOCK(kq);
953                         error = EBADF;
954                         break;
955                 }
956                 kq->kq_refcnt++;
957                 KQ_UNLOCK(kq);
958         } while (0);
959         FILE_UNLOCK(fp);
960
961         return error;
962 }
963
964 static void
965 kqueue_release(struct kqueue *kq, int locked)
966 {
967         if (locked)
968                 KQ_OWNED(kq);
969         else
970                 KQ_LOCK(kq);
971         kq->kq_refcnt--;
972         if (kq->kq_refcnt == 1)
973                 wakeup(&kq->kq_refcnt);
974         if (!locked)
975                 KQ_UNLOCK(kq);
976 }
977
978 static void
979 kqueue_schedtask(struct kqueue *kq)
980 {
981
982         KQ_OWNED(kq);
983         KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
984             ("scheduling kqueue task while draining"));
985
986         if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
987                 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
988                 kq->kq_state |= KQ_TASKSCHED;
989         }
990 }
991
992 /*
993  * Expand the kq to make sure we have storage for fops/ident pair.
994  *
995  * Return 0 on success (or no work necessary), return errno on failure.
996  *
997  * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
998  * If kqueue_register is called from a non-fd context, there usually/should
999  * be no locks held.
1000  */
1001 static int
1002 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1003         int waitok)
1004 {
1005         struct klist *list, *tmp_knhash;
1006         u_long tmp_knhashmask;
1007         int size;
1008         int fd;
1009         int mflag = waitok ? M_WAITOK : M_NOWAIT;
1010
1011         KQ_NOTOWNED(kq);
1012
1013         if (fops->f_isfd) {
1014                 fd = ident;
1015                 if (kq->kq_knlistsize <= fd) {
1016                         size = kq->kq_knlistsize;
1017                         while (size <= fd)
1018                                 size += KQEXTENT;
1019                         MALLOC(list, struct klist *,
1020                             size * sizeof list, M_KQUEUE, mflag);
1021                         if (list == NULL)
1022                                 return ENOMEM;
1023                         KQ_LOCK(kq);
1024                         if (kq->kq_knlistsize > fd) {
1025                                 FREE(list, M_KQUEUE);
1026                                 list = NULL;
1027                         } else {
1028                                 if (kq->kq_knlist != NULL) {
1029                                         bcopy(kq->kq_knlist, list,
1030                                             kq->kq_knlistsize * sizeof list);
1031                                         FREE(kq->kq_knlist, M_KQUEUE);
1032                                         kq->kq_knlist = NULL;
1033                                 }
1034                                 bzero((caddr_t)list +
1035                                     kq->kq_knlistsize * sizeof list,
1036                                     (size - kq->kq_knlistsize) * sizeof list);
1037                                 kq->kq_knlistsize = size;
1038                                 kq->kq_knlist = list;
1039                         }
1040                         KQ_UNLOCK(kq);
1041                 }
1042         } else {
1043                 if (kq->kq_knhashmask == 0) {
1044                         tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1045                             &tmp_knhashmask);
1046                         if (tmp_knhash == NULL)
1047                                 return ENOMEM;
1048                         KQ_LOCK(kq);
1049                         if (kq->kq_knhashmask == 0) {
1050                                 kq->kq_knhash = tmp_knhash;
1051                                 kq->kq_knhashmask = tmp_knhashmask;
1052                         } else {
1053                                 free(tmp_knhash, M_KQUEUE);
1054                         }
1055                         KQ_UNLOCK(kq);
1056                 }
1057         }
1058
1059         KQ_NOTOWNED(kq);
1060         return 0;
1061 }
1062
1063 static void
1064 kqueue_task(void *arg, int pending)
1065 {
1066         struct kqueue *kq;
1067         int haskqglobal;
1068
1069         haskqglobal = 0;
1070         kq = arg;
1071
1072         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1073         KQ_LOCK(kq);
1074
1075         KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1076
1077         kq->kq_state &= ~KQ_TASKSCHED;
1078         if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1079                 wakeup(&kq->kq_state);
1080         }
1081         KQ_UNLOCK(kq);
1082         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1083 }
1084
1085 /*
1086  * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1087  * We treat KN_MARKER knotes as if they are INFLUX.
1088  */
1089 static int
1090 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent *eventlist,
1091     enum uio_seg eventseg, const struct timespec *tsp, struct kevent *keva,
1092     struct thread *td)
1093 {
1094         struct kevent *kevp;
1095         struct timeval atv, rtv, ttv;
1096         struct knote *kn, *marker;
1097         int count, timeout, nkev, error;
1098         int haskqglobal;
1099
1100         count = maxevents;
1101         nkev = 0;
1102         error = 0;
1103         haskqglobal = 0;
1104
1105         if (maxevents == 0)
1106                 goto done_nl;
1107
1108         if (tsp != NULL) {
1109                 TIMESPEC_TO_TIMEVAL(&atv, tsp);
1110                 if (itimerfix(&atv)) {
1111                         error = EINVAL;
1112                         goto done_nl;
1113                 }
1114                 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1115                         timeout = -1;
1116                 else
1117                         timeout = atv.tv_sec > 24 * 60 * 60 ?
1118                             24 * 60 * 60 * hz : tvtohz(&atv);
1119                 getmicrouptime(&rtv);
1120                 timevaladd(&atv, &rtv);
1121         } else {
1122                 atv.tv_sec = 0;
1123                 atv.tv_usec = 0;
1124                 timeout = 0;
1125         }
1126         marker = knote_alloc(1);
1127         if (marker == NULL) {
1128                 error = ENOMEM;
1129                 goto done_nl;
1130         }
1131         marker->kn_status = KN_MARKER;
1132         KQ_LOCK(kq);
1133         goto start;
1134
1135 retry:
1136         if (atv.tv_sec || atv.tv_usec) {
1137                 getmicrouptime(&rtv);
1138                 if (timevalcmp(&rtv, &atv, >=))
1139                         goto done;
1140                 ttv = atv;
1141                 timevalsub(&ttv, &rtv);
1142                 timeout = ttv.tv_sec > 24 * 60 * 60 ?
1143                         24 * 60 * 60 * hz : tvtohz(&ttv);
1144         }
1145
1146 start:
1147         kevp = keva;
1148         if (kq->kq_count == 0) {
1149                 if (timeout < 0) {
1150                         error = EWOULDBLOCK;
1151                 } else {
1152                         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1153                         kq->kq_state |= KQ_SLEEP;
1154                         error = msleep(kq, &kq->kq_lock, PSOCK | PCATCH,
1155                             "kqread", timeout);
1156                 }
1157                 if (error == 0)
1158                         goto retry;
1159                 /* don't restart after signals... */
1160                 if (error == ERESTART)
1161                         error = EINTR;
1162                 else if (error == EWOULDBLOCK)
1163                         error = 0;
1164                 goto done;
1165         }
1166
1167         TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1168         while (count) {
1169                 KQ_OWNED(kq);
1170                 kn = TAILQ_FIRST(&kq->kq_head);
1171
1172                 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1173                     (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1174                         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1175                         kq->kq_state |= KQ_FLUXWAIT;
1176                         error = msleep(kq, &kq->kq_lock, PSOCK,
1177                             "kqflxwt", 0);
1178                         continue;
1179                 }
1180
1181                 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1182                 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1183                         kn->kn_status &= ~KN_QUEUED;
1184                         kq->kq_count--;
1185                         continue;
1186                 }
1187                 if (kn == marker) {
1188                         KQ_FLUX_WAKEUP(kq);
1189                         if (count == maxevents)
1190                                 goto retry;
1191                         goto done;
1192                 }
1193                 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1194                     ("KN_INFLUX set when not suppose to be"));
1195
1196                 if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1197                         kn->kn_status &= ~KN_QUEUED;
1198                         kn->kn_status |= KN_INFLUX;
1199                         kq->kq_count--;
1200                         KQ_UNLOCK(kq);
1201                         /*
1202                          * We don't need to lock the list since we've marked
1203                          * it _INFLUX.
1204                          */
1205                         *kevp = kn->kn_kevent;
1206                         if (!(kn->kn_status & KN_DETACHED))
1207                                 kn->kn_fop->f_detach(kn);
1208                         knote_drop(kn, td);
1209                         KQ_LOCK(kq);
1210                         kn = NULL;
1211                 } else {
1212                         kn->kn_status |= KN_INFLUX;
1213                         KQ_UNLOCK(kq);
1214                         if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1215                                 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1216                         KN_LIST_LOCK(kn);
1217                         if (kn->kn_fop->f_event(kn, 0) == 0) {
1218                                 KN_LIST_UNLOCK(kn);
1219                                 KQ_LOCK(kq);
1220                                 kn->kn_status &=
1221                                     ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX);
1222                                 kq->kq_count--;
1223                                 continue;
1224                         }
1225                         *kevp = kn->kn_kevent;
1226                         KQ_LOCK(kq);
1227                         if (kn->kn_flags & EV_CLEAR) {
1228                                 kn->kn_data = 0;
1229                                 kn->kn_fflags = 0;
1230                                 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1231                                 kq->kq_count--;
1232                         } else
1233                                 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1234                         KN_LIST_UNLOCK(kn);
1235                         kn->kn_status &= ~(KN_INFLUX);
1236                 }
1237
1238                 /* we are returning a copy to the user */
1239                 kevp++;
1240                 nkev++;
1241                 count--;
1242
1243                 if (nkev == KQ_NEVENTS) {
1244                         KQ_UNLOCK_FLUX(kq);
1245                         error = kevent_copyout(&eventlist, eventseg, keva,
1246                             nkev);
1247                         nkev = 0;
1248                         kevp = keva;
1249                         KQ_LOCK(kq);
1250                         if (error)
1251                                 break;
1252                 }
1253         }
1254         TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1255 done:
1256         KQ_OWNED(kq);
1257         KQ_UNLOCK_FLUX(kq);
1258         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1259         knote_free(marker);
1260 done_nl:
1261         KQ_NOTOWNED(kq);
1262         if (nkev != 0)
1263                 error = kevent_copyout(&eventlist, eventseg, keva, nkev);
1264         td->td_retval[0] = maxevents - count;
1265         return (error);
1266 }
1267
1268 /*
1269  * XXX
1270  * This could be expanded to call kqueue_scan, if desired.
1271  */
1272 /*ARGSUSED*/
1273 static int
1274 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1275         int flags, struct thread *td)
1276 {
1277         return (ENXIO);
1278 }
1279
1280 /*ARGSUSED*/
1281 static int
1282 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1283          int flags, struct thread *td)
1284 {
1285         return (ENXIO);
1286 }
1287
1288 /*ARGSUSED*/
1289 static int
1290 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1291         struct ucred *active_cred, struct thread *td)
1292 {
1293         /*
1294          * Enabling sigio causes two major problems:
1295          * 1) infinite recursion:
1296          * Synopsys: kevent is being used to track signals and have FIOASYNC
1297          * set.  On receipt of a signal this will cause a kqueue to recurse
1298          * into itself over and over.  Sending the sigio causes the kqueue
1299          * to become ready, which in turn posts sigio again, forever.
1300          * Solution: this can be solved by setting a flag in the kqueue that
1301          * we have a SIGIO in progress.
1302          * 2) locking problems:
1303          * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1304          * us above the proc and pgrp locks.
1305          * Solution: Post a signal using an async mechanism, being sure to
1306          * record a generation count in the delivery so that we do not deliver
1307          * a signal to the wrong process.
1308          *
1309          * Note, these two mechanisms are somewhat mutually exclusive!
1310          */
1311 #if 0
1312         struct kqueue *kq;
1313
1314         kq = fp->f_data;
1315         switch (cmd) {
1316         case FIOASYNC:
1317                 if (*(int *)data) {
1318                         kq->kq_state |= KQ_ASYNC;
1319                 } else {
1320                         kq->kq_state &= ~KQ_ASYNC;
1321                 }
1322                 return (0);
1323
1324         case FIOSETOWN:
1325                 return (fsetown(*(int *)data, &kq->kq_sigio));
1326
1327         case FIOGETOWN:
1328                 *(int *)data = fgetown(&kq->kq_sigio);
1329                 return (0);
1330         }
1331 #endif
1332
1333         return (ENOTTY);
1334 }
1335
1336 /*ARGSUSED*/
1337 static int
1338 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1339         struct thread *td)
1340 {
1341         struct kqueue *kq;
1342         int revents = 0;
1343         int error;
1344
1345         if ((error = kqueue_aquire(fp, &kq)))
1346                 return POLLERR;
1347
1348         KQ_LOCK(kq);
1349         if (events & (POLLIN | POLLRDNORM)) {
1350                 if (kq->kq_count) {
1351                         revents |= events & (POLLIN | POLLRDNORM);
1352                 } else {
1353                         selrecord(td, &kq->kq_sel);
1354                         kq->kq_state |= KQ_SEL;
1355                 }
1356         }
1357         kqueue_release(kq, 1);
1358         KQ_UNLOCK(kq);
1359         return (revents);
1360 }
1361
1362 /*ARGSUSED*/
1363 static int
1364 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1365         struct thread *td)
1366 {
1367
1368         return (ENXIO);
1369 }
1370
1371 /*ARGSUSED*/
1372 static int
1373 kqueue_close(struct file *fp, struct thread *td)
1374 {
1375         struct kqueue *kq = fp->f_data;
1376         struct filedesc *fdp;
1377         struct knote *kn;
1378         int i;
1379         int error;
1380
1381         if ((error = kqueue_aquire(fp, &kq)))
1382                 return error;
1383
1384         KQ_LOCK(kq);
1385
1386         KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1387             ("kqueue already closing"));
1388         kq->kq_state |= KQ_CLOSING;
1389         if (kq->kq_refcnt > 1)
1390                 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1391
1392         KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1393         fdp = kq->kq_fdp;
1394
1395         KASSERT(knlist_empty(&kq->kq_sel.si_note),
1396             ("kqueue's knlist not empty"));
1397
1398         for (i = 0; i < kq->kq_knlistsize; i++) {
1399                 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1400                         KASSERT((kn->kn_status & KN_INFLUX) == 0,
1401                             ("KN_INFLUX set when not suppose to be"));
1402                         kn->kn_status |= KN_INFLUX;
1403                         KQ_UNLOCK(kq);
1404                         if (!(kn->kn_status & KN_DETACHED))
1405                                 kn->kn_fop->f_detach(kn);
1406                         knote_drop(kn, td);
1407                         KQ_LOCK(kq);
1408                 }
1409         }
1410         if (kq->kq_knhashmask != 0) {
1411                 for (i = 0; i <= kq->kq_knhashmask; i++) {
1412                         while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1413                                 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1414                                     ("KN_INFLUX set when not suppose to be"));
1415                                 kn->kn_status |= KN_INFLUX;
1416                                 KQ_UNLOCK(kq);
1417                                 if (!(kn->kn_status & KN_DETACHED))
1418                                         kn->kn_fop->f_detach(kn);
1419                                 knote_drop(kn, td);
1420                                 KQ_LOCK(kq);
1421                         }
1422                 }
1423         }
1424
1425         if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1426                 kq->kq_state |= KQ_TASKDRAIN;
1427                 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1428         }
1429
1430         if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1431                 kq->kq_state &= ~KQ_SEL;
1432                 selwakeuppri(&kq->kq_sel, PSOCK);
1433         }
1434
1435         KQ_UNLOCK(kq);
1436
1437         FILEDESC_LOCK_FAST(fdp);
1438         SLIST_REMOVE(&fdp->fd_kqlist, kq, kqueue, kq_list);
1439         FILEDESC_UNLOCK_FAST(fdp);
1440
1441         knlist_destroy(&kq->kq_sel.si_note);
1442         mtx_destroy(&kq->kq_lock);
1443         kq->kq_fdp = NULL;
1444
1445         if (kq->kq_knhash != NULL)
1446                 free(kq->kq_knhash, M_KQUEUE);
1447         if (kq->kq_knlist != NULL)
1448                 free(kq->kq_knlist, M_KQUEUE);
1449
1450         funsetown(&kq->kq_sigio);
1451         free(kq, M_KQUEUE);
1452         fp->f_data = NULL;
1453
1454         return (0);
1455 }
1456
1457 static void
1458 kqueue_wakeup(struct kqueue *kq)
1459 {
1460         KQ_OWNED(kq);
1461
1462         if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1463                 kq->kq_state &= ~KQ_SLEEP;
1464                 wakeup(kq);
1465         }
1466         if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1467                 kq->kq_state &= ~KQ_SEL;
1468                 selwakeuppri(&kq->kq_sel, PSOCK);
1469         }
1470         if (!knlist_empty(&kq->kq_sel.si_note))
1471                 kqueue_schedtask(kq);
1472         if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1473                 pgsigio(&kq->kq_sigio, SIGIO, 0);
1474         }
1475 }
1476
1477 /*
1478  * Walk down a list of knotes, activating them if their event has triggered.
1479  *
1480  * There is a possibility to optimize in the case of one kq watching another.
1481  * Instead of scheduling a task to wake it up, you could pass enough state
1482  * down the chain to make up the parent kqueue.  Make this code functional
1483  * first.
1484  */
1485 void
1486 knote(struct knlist *list, long hint, int islocked)
1487 {
1488         struct kqueue *kq;
1489         struct knote *kn;
1490
1491         if (list == NULL)
1492                 return;
1493
1494         mtx_assert(list->kl_lock, islocked ? MA_OWNED : MA_NOTOWNED);
1495         if (!islocked)
1496                 mtx_lock(list->kl_lock);
1497         /*
1498          * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1499          * the kqueue scheduling, but this will introduce four
1500          * lock/unlock's for each knote to test.  If we do, continue to use
1501          * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1502          * only safe if you want to remove the current item, which we are
1503          * not doing.
1504          */
1505         SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1506                 kq = kn->kn_kq;
1507                 if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1508                         KQ_LOCK(kq);
1509                         if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1510                                 kn->kn_status |= KN_HASKQLOCK;
1511                                 if (kn->kn_fop->f_event(kn, hint))
1512                                         KNOTE_ACTIVATE(kn, 1);
1513                                 kn->kn_status &= ~KN_HASKQLOCK;
1514                         }
1515                         KQ_UNLOCK(kq);
1516                 }
1517                 kq = NULL;
1518         }
1519         if (!islocked)
1520                 mtx_unlock(list->kl_lock);
1521 }
1522
1523 /*
1524  * add a knote to a knlist
1525  */
1526 void
1527 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1528 {
1529         mtx_assert(knl->kl_lock, islocked ? MA_OWNED : MA_NOTOWNED);
1530         KQ_NOTOWNED(kn->kn_kq);
1531         KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1532             (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1533         if (!islocked)
1534                 mtx_lock(knl->kl_lock);
1535         SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1536         if (!islocked)
1537                 mtx_unlock(knl->kl_lock);
1538         KQ_LOCK(kn->kn_kq);
1539         kn->kn_knlist = knl;
1540         kn->kn_status &= ~KN_DETACHED;
1541         KQ_UNLOCK(kn->kn_kq);
1542 }
1543
1544 static void
1545 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1546 {
1547         KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1548         mtx_assert(knl->kl_lock, knlislocked ? MA_OWNED : MA_NOTOWNED);
1549         mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1550         if (!kqislocked)
1551                 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1552     ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1553         if (!knlislocked)
1554                 mtx_lock(knl->kl_lock);
1555         SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1556         kn->kn_knlist = NULL;
1557         if (!knlislocked)
1558                 mtx_unlock(knl->kl_lock);
1559         if (!kqislocked)
1560                 KQ_LOCK(kn->kn_kq);
1561         kn->kn_status |= KN_DETACHED;
1562         if (!kqislocked)
1563                 KQ_UNLOCK(kn->kn_kq);
1564 }
1565
1566 /*
1567  * remove all knotes from a specified klist
1568  */
1569 void
1570 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1571 {
1572
1573         knlist_remove_kq(knl, kn, islocked, 0);
1574 }
1575
1576 /*
1577  * remove knote from a specified klist while in f_event handler.
1578  */
1579 void
1580 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1581 {
1582
1583         knlist_remove_kq(knl, kn, 1,
1584             (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1585 }
1586
1587 int
1588 knlist_empty(struct knlist *knl)
1589 {
1590
1591         mtx_assert(knl->kl_lock, MA_OWNED);
1592         return SLIST_EMPTY(&knl->kl_list);
1593 }
1594
1595 static struct mtx       knlist_lock;
1596 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1597         MTX_DEF);
1598
1599 void
1600 knlist_init(struct knlist *knl, struct mtx *mtx)
1601 {
1602
1603         if (mtx == NULL)
1604                 knl->kl_lock = &knlist_lock;
1605         else
1606                 knl->kl_lock = mtx;
1607
1608         SLIST_INIT(&knl->kl_list);
1609 }
1610
1611 void
1612 knlist_destroy(struct knlist *knl)
1613 {
1614
1615 #ifdef INVARIANTS
1616         /*
1617          * if we run across this error, we need to find the offending
1618          * driver and have it call knlist_clear.
1619          */
1620         if (!SLIST_EMPTY(&knl->kl_list))
1621                 printf("WARNING: destroying knlist w/ knotes on it!\n");
1622 #endif
1623
1624         knl->kl_lock = NULL;
1625         SLIST_INIT(&knl->kl_list);
1626 }
1627
1628 /*
1629  * Even if we are locked, we may need to drop the lock to allow any influx
1630  * knotes time to "settle".
1631  */
1632 void
1633 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
1634 {
1635         struct knote *kn;
1636         struct kqueue *kq;
1637
1638         if (islocked)
1639                 mtx_assert(knl->kl_lock, MA_OWNED);
1640         else {
1641                 mtx_assert(knl->kl_lock, MA_NOTOWNED);
1642 again:          /* need to reaquire lock since we have dropped it */
1643                 mtx_lock(knl->kl_lock);
1644         }
1645
1646         SLIST_FOREACH(kn, &knl->kl_list, kn_selnext) {
1647                 kq = kn->kn_kq;
1648                 KQ_LOCK(kq);
1649                 if ((kn->kn_status & KN_INFLUX)) {
1650                         KQ_UNLOCK(kq);
1651                         continue;
1652                 }
1653                 knlist_remove_kq(knl, kn, 1, 1);
1654                 if (killkn) {
1655                         kn->kn_status |= KN_INFLUX | KN_DETACHED;
1656                         KQ_UNLOCK(kq);
1657                         knote_drop(kn, td);
1658                 } else {
1659                         /* Make sure cleared knotes disappear soon */
1660                         kn->kn_flags |= (EV_EOF | EV_ONESHOT);
1661                         KQ_UNLOCK(kq);
1662                 }
1663                 kq = NULL;
1664         }
1665
1666         if (!SLIST_EMPTY(&knl->kl_list)) {
1667                 /* there are still KN_INFLUX remaining */
1668                 kn = SLIST_FIRST(&knl->kl_list);
1669                 kq = kn->kn_kq;
1670                 KQ_LOCK(kq);
1671                 KASSERT(kn->kn_status & KN_INFLUX,
1672                     ("knote removed w/o list lock"));
1673                 mtx_unlock(knl->kl_lock);
1674                 kq->kq_state |= KQ_FLUXWAIT;
1675                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
1676                 kq = NULL;
1677                 goto again;
1678         }
1679
1680         if (islocked)
1681                 mtx_assert(knl->kl_lock, MA_OWNED);
1682         else {
1683                 mtx_unlock(knl->kl_lock);
1684                 mtx_assert(knl->kl_lock, MA_NOTOWNED);
1685         }
1686 }
1687
1688 /*
1689  * remove all knotes referencing a specified fd
1690  * must be called with FILEDESC lock.  This prevents a race where a new fd
1691  * comes along and occupies the entry and we attach a knote to the fd.
1692  */
1693 void
1694 knote_fdclose(struct thread *td, int fd)
1695 {
1696         struct filedesc *fdp = td->td_proc->p_fd;
1697         struct kqueue *kq;
1698         struct knote *kn;
1699         int influx;
1700
1701         FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1702
1703         /*
1704          * We shouldn't have to worry about new kevents appearing on fd
1705          * since filedesc is locked.
1706          */
1707         SLIST_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
1708                 KQ_LOCK(kq);
1709
1710 again:
1711                 influx = 0;
1712                 while (kq->kq_knlistsize > fd &&
1713                     (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
1714                         if (kn->kn_status & KN_INFLUX) {
1715                                 /* someone else might be waiting on our knote */
1716                                 if (influx)
1717                                         wakeup(kq);
1718                                 kq->kq_state |= KQ_FLUXWAIT;
1719                                 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
1720                                 goto again;
1721                         }
1722                         kn->kn_status |= KN_INFLUX;
1723                         KQ_UNLOCK(kq);
1724                         if (!(kn->kn_status & KN_DETACHED))
1725                                 kn->kn_fop->f_detach(kn);
1726                         knote_drop(kn, td);
1727                         influx = 1;
1728                         KQ_LOCK(kq);
1729                 }
1730                 KQ_UNLOCK_FLUX(kq);
1731         }
1732 }
1733
1734 static int
1735 knote_attach(struct knote *kn, struct kqueue *kq)
1736 {
1737         struct klist *list;
1738
1739         KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
1740         KQ_OWNED(kq);
1741
1742         if (kn->kn_fop->f_isfd) {
1743                 if (kn->kn_id >= kq->kq_knlistsize)
1744                         return ENOMEM;
1745                 list = &kq->kq_knlist[kn->kn_id];
1746         } else {
1747                 if (kq->kq_knhash == NULL)
1748                         return ENOMEM;
1749                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1750         }
1751
1752         SLIST_INSERT_HEAD(list, kn, kn_link);
1753
1754         return 0;
1755 }
1756
1757 /*
1758  * knote must already have been detatched using the f_detach method.
1759  * no lock need to be held, it is assumed that the KN_INFLUX flag is set
1760  * to prevent other removal.
1761  */
1762 static void
1763 knote_drop(struct knote *kn, struct thread *td)
1764 {
1765         struct kqueue *kq;
1766         struct klist *list;
1767
1768         kq = kn->kn_kq;
1769
1770         KQ_NOTOWNED(kq);
1771         KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
1772             ("knote_drop called without KN_INFLUX set in kn_status"));
1773
1774         KQ_LOCK(kq);
1775         if (kn->kn_fop->f_isfd)
1776                 list = &kq->kq_knlist[kn->kn_id];
1777         else
1778                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1779
1780         SLIST_REMOVE(list, kn, knote, kn_link);
1781         if (kn->kn_status & KN_QUEUED)
1782                 knote_dequeue(kn);
1783         KQ_UNLOCK_FLUX(kq);
1784
1785         if (kn->kn_fop->f_isfd) {
1786                 fdrop(kn->kn_fp, td);
1787                 kn->kn_fp = NULL;
1788         }
1789         kqueue_fo_release(kn->kn_kevent.filter);
1790         kn->kn_fop = NULL;
1791         knote_free(kn);
1792 }
1793
1794 static void
1795 knote_enqueue(struct knote *kn)
1796 {
1797         struct kqueue *kq = kn->kn_kq;
1798
1799         KQ_OWNED(kn->kn_kq);
1800         KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1801
1802         TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1803         kn->kn_status |= KN_QUEUED;
1804         kq->kq_count++;
1805         kqueue_wakeup(kq);
1806 }
1807
1808 static void
1809 knote_dequeue(struct knote *kn)
1810 {
1811         struct kqueue *kq = kn->kn_kq;
1812
1813         KQ_OWNED(kn->kn_kq);
1814         KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1815
1816         TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1817         kn->kn_status &= ~KN_QUEUED;
1818         kq->kq_count--;
1819 }
1820
1821 static void
1822 knote_init(void)
1823 {
1824
1825         knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
1826             NULL, NULL, UMA_ALIGN_PTR, 0);
1827 }
1828 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1829
1830 static struct knote *
1831 knote_alloc(int waitok)
1832 {
1833         return ((struct knote *)uma_zalloc(knote_zone,
1834             (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
1835 }
1836
1837 static void
1838 knote_free(struct knote *kn)
1839 {
1840         if (kn != NULL)
1841                 uma_zfree(knote_zone, kn);
1842 }