]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_event.c
This commit was generated by cvs2svn to compensate for changes in r147001,
[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(void *arg, struct kevent *kevp, int count);
85 static int      kevent_copyin(void *arg, 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_copyops *k_ops,
93                     const struct timespec *timeout,
94                     struct kevent *keva, 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         struct kevent_copyops k_ops = { uap,
540                                         kevent_copyout,
541                                         kevent_copyin};
542         int error;
543
544         if (uap->timeout != NULL) {
545                 error = copyin(uap->timeout, &ts, sizeof(ts));
546                 if (error)
547                         return (error);
548                 tsp = &ts;
549         } else
550                 tsp = NULL;
551
552         return (kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
553             &k_ops, tsp));
554 }
555
556 /*
557  * Copy 'count' items into the destination list pointed to by uap->eventlist.
558  */
559 static int
560 kevent_copyout(void *arg, struct kevent *kevp, int count)
561 {
562         struct kevent_args *uap;
563         int error;
564
565         KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
566         uap = (struct kevent_args *)arg;
567
568         error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
569         if (error == 0)
570                 uap->eventlist += count;
571         return (error);
572 }
573
574 /*
575  * Copy 'count' items from the list pointed to by uap->changelist.
576  */
577 static int
578 kevent_copyin(void *arg, struct kevent *kevp, int count)
579 {
580         struct kevent_args *uap;
581         int error;
582
583         KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
584         uap = (struct kevent_args *)arg;
585
586         error = copyin(uap->changelist, kevp, count * sizeof *kevp);
587         if (error == 0)
588                 uap->changelist += count;
589         return (error);
590 }
591
592 int
593 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
594     struct kevent_copyops *k_ops, const struct timespec *timeout)
595 {
596         struct kevent keva[KQ_NEVENTS];
597         struct kevent *kevp, *changes;
598         struct kqueue *kq;
599         struct file *fp;
600         int i, n, nerrors, error;
601
602         if ((error = fget(td, fd, &fp)) != 0)
603                 return (error);
604         if ((error = kqueue_aquire(fp, &kq)) != 0)
605                 goto done_norel;
606
607         nerrors = 0;
608
609         while (nchanges > 0) {
610                 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
611                 error = k_ops->k_copyin(k_ops->arg, keva, n);
612                 if (error)
613                         goto done;
614                 changes = keva;
615                 for (i = 0; i < n; i++) {
616                         kevp = &changes[i];
617                         kevp->flags &= ~EV_SYSFLAGS;
618                         error = kqueue_register(kq, kevp, td, 1);
619                         if (error) {
620                                 if (nevents != 0) {
621                                         kevp->flags = EV_ERROR;
622                                         kevp->data = error;
623                                         (void) k_ops->k_copyout(k_ops->arg,
624                                             kevp, 1);
625                                         nevents--;
626                                         nerrors++;
627                                 } else {
628                                         goto done;
629                                 }
630                         }
631                 }
632                 nchanges -= n;
633         }
634         if (nerrors) {
635                 td->td_retval[0] = nerrors;
636                 error = 0;
637                 goto done;
638         }
639
640         error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
641 done:
642         kqueue_release(kq, 0);
643 done_norel:
644         if (fp != NULL)
645                 fdrop(fp, td);
646         return (error);
647 }
648
649 int
650 kqueue_add_filteropts(int filt, struct filterops *filtops)
651 {
652         int error;
653
654         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
655                 printf(
656 "trying to add a filterop that is out of range: %d is beyond %d\n",
657                     ~filt, EVFILT_SYSCOUNT);
658                 return EINVAL;
659         }
660         mtx_lock(&filterops_lock);
661         if (sysfilt_ops[~filt].for_fop != &null_filtops &&
662             sysfilt_ops[~filt].for_fop != NULL)
663                 error = EEXIST;
664         else {
665                 sysfilt_ops[~filt].for_fop = filtops;
666                 sysfilt_ops[~filt].for_refcnt = 0;
667         }
668         mtx_unlock(&filterops_lock);
669
670         return (0);
671 }
672
673 int
674 kqueue_del_filteropts(int filt)
675 {
676         int error;
677
678         error = 0;
679         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
680                 return EINVAL;
681
682         mtx_lock(&filterops_lock);
683         if (sysfilt_ops[~filt].for_fop == &null_filtops ||
684             sysfilt_ops[~filt].for_fop == NULL)
685                 error = EINVAL;
686         else if (sysfilt_ops[~filt].for_refcnt != 0)
687                 error = EBUSY;
688         else {
689                 sysfilt_ops[~filt].for_fop = &null_filtops;
690                 sysfilt_ops[~filt].for_refcnt = 0;
691         }
692         mtx_unlock(&filterops_lock);
693
694         return error;
695 }
696
697 static struct filterops *
698 kqueue_fo_find(int filt)
699 {
700
701         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
702                 return NULL;
703
704         mtx_lock(&filterops_lock);
705         sysfilt_ops[~filt].for_refcnt++;
706         if (sysfilt_ops[~filt].for_fop == NULL)
707                 sysfilt_ops[~filt].for_fop = &null_filtops;
708         mtx_unlock(&filterops_lock);
709
710         return sysfilt_ops[~filt].for_fop;
711 }
712
713 static void
714 kqueue_fo_release(int filt)
715 {
716
717         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
718                 return;
719
720         mtx_lock(&filterops_lock);
721         KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
722             ("filter object refcount not valid on release"));
723         sysfilt_ops[~filt].for_refcnt--;
724         mtx_unlock(&filterops_lock);
725 }
726
727 /*
728  * A ref to kq (obtained via kqueue_aquire) should be held.  waitok will
729  * influence if memory allocation should wait.  Make sure it is 0 if you
730  * hold any mutexes.
731  */
732 int
733 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
734 {
735         struct filedesc *fdp;
736         struct filterops *fops;
737         struct file *fp;
738         struct knote *kn, *tkn;
739         int error, filt, event;
740         int haskqglobal;
741         int fd;
742
743         fdp = NULL;
744         fp = NULL;
745         kn = NULL;
746         error = 0;
747         haskqglobal = 0;
748
749         filt = kev->filter;
750         fops = kqueue_fo_find(filt);
751         if (fops == NULL)
752                 return EINVAL;
753
754         tkn = knote_alloc(waitok);              /* prevent waiting with locks */
755
756 findkn:
757         if (fops->f_isfd) {
758                 KASSERT(td != NULL, ("td is NULL"));
759                 fdp = td->td_proc->p_fd;
760                 FILEDESC_LOCK(fdp);
761                 /* validate descriptor */
762                 fd = kev->ident;
763                 if (fd < 0 || fd >= fdp->fd_nfiles ||
764                     (fp = fdp->fd_ofiles[fd]) == NULL) {
765                         FILEDESC_UNLOCK(fdp);
766                         error = EBADF;
767                         goto done;
768                 }
769                 fhold(fp);
770
771                 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
772                     kev->ident, 0) != 0) {
773                         /* unlock and try again */
774                         FILEDESC_UNLOCK(fdp);
775                         fdrop(fp, td);
776                         fp = NULL;
777                         error = kqueue_expand(kq, fops, kev->ident, waitok);
778                         if (error)
779                                 goto done;
780                         goto findkn;
781                 }
782
783                 if (fp->f_type == DTYPE_KQUEUE) {
784                         /*
785                          * if we add some inteligence about what we are doing,
786                          * we should be able to support events on ourselves.
787                          * We need to know when we are doing this to prevent
788                          * getting both the knlist lock and the kq lock since
789                          * they are the same thing.
790                          */
791                         if (fp->f_data == kq) {
792                                 FILEDESC_UNLOCK(fdp);
793                                 error = EINVAL;
794                                 goto done_noglobal;
795                         }
796
797                         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
798                 }
799
800                 FILEDESC_UNLOCK(fdp);
801                 KQ_LOCK(kq);
802                 if (kev->ident < kq->kq_knlistsize) {
803                         SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
804                                 if (kev->filter == kn->kn_filter)
805                                         break;
806                 }
807         } else {
808                 if ((kev->flags & EV_ADD) == EV_ADD)
809                         kqueue_expand(kq, fops, kev->ident, waitok);
810
811                 KQ_LOCK(kq);
812                 if (kq->kq_knhashmask != 0) {
813                         struct klist *list;
814
815                         list = &kq->kq_knhash[
816                             KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
817                         SLIST_FOREACH(kn, list, kn_link)
818                                 if (kev->ident == kn->kn_id &&
819                                     kev->filter == kn->kn_filter)
820                                         break;
821                 }
822         }
823
824         /* knote is in the process of changing, wait for it to stablize. */
825         if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
826                 if (fp != NULL) {
827                         fdrop(fp, td);
828                         fp = NULL;
829                 }
830                 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
831                 kq->kq_state |= KQ_FLUXWAIT;
832                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
833                 goto findkn;
834         }
835
836         if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
837                 KQ_UNLOCK(kq);
838                 error = ENOENT;
839                 goto done;
840         }
841
842         /*
843          * kn now contains the matching knote, or NULL if no match
844          */
845         if (kev->flags & EV_ADD) {
846                 if (kn == NULL) {
847                         kn = tkn;
848                         tkn = NULL;
849                         if (kn == NULL) {
850                                 error = ENOMEM;
851                                 goto done;
852                         }
853                         kn->kn_fp = fp;
854                         kn->kn_kq = kq;
855                         kn->kn_fop = fops;
856                         /*
857                          * apply reference counts to knote structure, and
858                          * do not release it at the end of this routine.
859                          */
860                         fops = NULL;
861                         fp = NULL;
862
863                         kn->kn_sfflags = kev->fflags;
864                         kn->kn_sdata = kev->data;
865                         kev->fflags = 0;
866                         kev->data = 0;
867                         kn->kn_kevent = *kev;
868                         kn->kn_status = KN_INFLUX|KN_DETACHED;
869
870                         error = knote_attach(kn, kq);
871                         KQ_UNLOCK(kq);
872                         if (error != 0) {
873                                 tkn = kn;
874                                 goto done;
875                         }
876
877                         if ((error = kn->kn_fop->f_attach(kn)) != 0) {
878                                 knote_drop(kn, td);
879                                 goto done;
880                         }
881                         KN_LIST_LOCK(kn);
882                 } else {
883                         /*
884                          * The user may change some filter values after the
885                          * initial EV_ADD, but doing so will not reset any
886                          * filter which has already been triggered.
887                          */
888                         kn->kn_status |= KN_INFLUX;
889                         KQ_UNLOCK(kq);
890                         KN_LIST_LOCK(kn);
891                         kn->kn_sfflags = kev->fflags;
892                         kn->kn_sdata = kev->data;
893                         kn->kn_kevent.udata = kev->udata;
894                 }
895
896                 /*
897                  * We can get here with kn->kn_knlist == NULL.
898                  * This can happen when the initial attach event decides that
899                  * the event is "completed" already.  i.e. filt_procattach
900                  * is called on a zombie process.  It will call filt_proc
901                  * which will remove it from the list, and NULL kn_knlist.
902                  */
903                 event = kn->kn_fop->f_event(kn, 0);
904                 KN_LIST_UNLOCK(kn);
905                 KQ_LOCK(kq);
906                 if (event)
907                         KNOTE_ACTIVATE(kn, 1);
908                 kn->kn_status &= ~KN_INFLUX;
909         } else if (kev->flags & EV_DELETE) {
910                 kn->kn_status |= KN_INFLUX;
911                 KQ_UNLOCK(kq);
912                 if (!(kn->kn_status & KN_DETACHED))
913                         kn->kn_fop->f_detach(kn);
914                 knote_drop(kn, td);
915                 goto done;
916         }
917
918         if ((kev->flags & EV_DISABLE) &&
919             ((kn->kn_status & KN_DISABLED) == 0)) {
920                 kn->kn_status |= KN_DISABLED;
921         }
922
923         if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
924                 kn->kn_status &= ~KN_DISABLED;
925                 if ((kn->kn_status & KN_ACTIVE) &&
926                     ((kn->kn_status & KN_QUEUED) == 0))
927                         knote_enqueue(kn);
928         }
929         KQ_UNLOCK_FLUX(kq);
930
931 done:
932         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
933 done_noglobal:
934         if (fp != NULL)
935                 fdrop(fp, td);
936         if (tkn != NULL)
937                 knote_free(tkn);
938         if (fops != NULL)
939                 kqueue_fo_release(filt);
940         return (error);
941 }
942
943 static int
944 kqueue_aquire(struct file *fp, struct kqueue **kqp)
945 {
946         int error;
947         struct kqueue *kq;
948
949         error = 0;
950
951         FILE_LOCK(fp);
952         do {
953                 kq = fp->f_data;
954                 if (fp->f_type != DTYPE_KQUEUE || kq == NULL) {
955                         error = EBADF;
956                         break;
957                 }
958                 *kqp = kq;
959                 KQ_LOCK(kq);
960                 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
961                         KQ_UNLOCK(kq);
962                         error = EBADF;
963                         break;
964                 }
965                 kq->kq_refcnt++;
966                 KQ_UNLOCK(kq);
967         } while (0);
968         FILE_UNLOCK(fp);
969
970         return error;
971 }
972
973 static void
974 kqueue_release(struct kqueue *kq, int locked)
975 {
976         if (locked)
977                 KQ_OWNED(kq);
978         else
979                 KQ_LOCK(kq);
980         kq->kq_refcnt--;
981         if (kq->kq_refcnt == 1)
982                 wakeup(&kq->kq_refcnt);
983         if (!locked)
984                 KQ_UNLOCK(kq);
985 }
986
987 static void
988 kqueue_schedtask(struct kqueue *kq)
989 {
990
991         KQ_OWNED(kq);
992         KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
993             ("scheduling kqueue task while draining"));
994
995         if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
996                 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
997                 kq->kq_state |= KQ_TASKSCHED;
998         }
999 }
1000
1001 /*
1002  * Expand the kq to make sure we have storage for fops/ident pair.
1003  *
1004  * Return 0 on success (or no work necessary), return errno on failure.
1005  *
1006  * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1007  * If kqueue_register is called from a non-fd context, there usually/should
1008  * be no locks held.
1009  */
1010 static int
1011 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1012         int waitok)
1013 {
1014         struct klist *list, *tmp_knhash;
1015         u_long tmp_knhashmask;
1016         int size;
1017         int fd;
1018         int mflag = waitok ? M_WAITOK : M_NOWAIT;
1019
1020         KQ_NOTOWNED(kq);
1021
1022         if (fops->f_isfd) {
1023                 fd = ident;
1024                 if (kq->kq_knlistsize <= fd) {
1025                         size = kq->kq_knlistsize;
1026                         while (size <= fd)
1027                                 size += KQEXTENT;
1028                         MALLOC(list, struct klist *,
1029                             size * sizeof list, M_KQUEUE, mflag);
1030                         if (list == NULL)
1031                                 return ENOMEM;
1032                         KQ_LOCK(kq);
1033                         if (kq->kq_knlistsize > fd) {
1034                                 FREE(list, M_KQUEUE);
1035                                 list = NULL;
1036                         } else {
1037                                 if (kq->kq_knlist != NULL) {
1038                                         bcopy(kq->kq_knlist, list,
1039                                             kq->kq_knlistsize * sizeof list);
1040                                         FREE(kq->kq_knlist, M_KQUEUE);
1041                                         kq->kq_knlist = NULL;
1042                                 }
1043                                 bzero((caddr_t)list +
1044                                     kq->kq_knlistsize * sizeof list,
1045                                     (size - kq->kq_knlistsize) * sizeof list);
1046                                 kq->kq_knlistsize = size;
1047                                 kq->kq_knlist = list;
1048                         }
1049                         KQ_UNLOCK(kq);
1050                 }
1051         } else {
1052                 if (kq->kq_knhashmask == 0) {
1053                         tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1054                             &tmp_knhashmask);
1055                         if (tmp_knhash == NULL)
1056                                 return ENOMEM;
1057                         KQ_LOCK(kq);
1058                         if (kq->kq_knhashmask == 0) {
1059                                 kq->kq_knhash = tmp_knhash;
1060                                 kq->kq_knhashmask = tmp_knhashmask;
1061                         } else {
1062                                 free(tmp_knhash, M_KQUEUE);
1063                         }
1064                         KQ_UNLOCK(kq);
1065                 }
1066         }
1067
1068         KQ_NOTOWNED(kq);
1069         return 0;
1070 }
1071
1072 static void
1073 kqueue_task(void *arg, int pending)
1074 {
1075         struct kqueue *kq;
1076         int haskqglobal;
1077
1078         haskqglobal = 0;
1079         kq = arg;
1080
1081         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1082         KQ_LOCK(kq);
1083
1084         KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1085
1086         kq->kq_state &= ~KQ_TASKSCHED;
1087         if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1088                 wakeup(&kq->kq_state);
1089         }
1090         KQ_UNLOCK(kq);
1091         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1092 }
1093
1094 /*
1095  * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1096  * We treat KN_MARKER knotes as if they are INFLUX.
1097  */
1098 static int
1099 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1100     const struct timespec *tsp, struct kevent *keva, struct thread *td)
1101 {
1102         struct kevent *kevp;
1103         struct timeval atv, rtv, ttv;
1104         struct knote *kn, *marker;
1105         int count, timeout, nkev, error;
1106         int haskqglobal;
1107
1108         count = maxevents;
1109         nkev = 0;
1110         error = 0;
1111         haskqglobal = 0;
1112
1113         if (maxevents == 0)
1114                 goto done_nl;
1115
1116         if (tsp != NULL) {
1117                 TIMESPEC_TO_TIMEVAL(&atv, tsp);
1118                 if (itimerfix(&atv)) {
1119                         error = EINVAL;
1120                         goto done_nl;
1121                 }
1122                 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1123                         timeout = -1;
1124                 else
1125                         timeout = atv.tv_sec > 24 * 60 * 60 ?
1126                             24 * 60 * 60 * hz : tvtohz(&atv);
1127                 getmicrouptime(&rtv);
1128                 timevaladd(&atv, &rtv);
1129         } else {
1130                 atv.tv_sec = 0;
1131                 atv.tv_usec = 0;
1132                 timeout = 0;
1133         }
1134         marker = knote_alloc(1);
1135         if (marker == NULL) {
1136                 error = ENOMEM;
1137                 goto done_nl;
1138         }
1139         marker->kn_status = KN_MARKER;
1140         KQ_LOCK(kq);
1141         goto start;
1142
1143 retry:
1144         if (atv.tv_sec || atv.tv_usec) {
1145                 getmicrouptime(&rtv);
1146                 if (timevalcmp(&rtv, &atv, >=))
1147                         goto done;
1148                 ttv = atv;
1149                 timevalsub(&ttv, &rtv);
1150                 timeout = ttv.tv_sec > 24 * 60 * 60 ?
1151                         24 * 60 * 60 * hz : tvtohz(&ttv);
1152         }
1153
1154 start:
1155         kevp = keva;
1156         if (kq->kq_count == 0) {
1157                 if (timeout < 0) {
1158                         error = EWOULDBLOCK;
1159                 } else {
1160                         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1161                         kq->kq_state |= KQ_SLEEP;
1162                         error = msleep(kq, &kq->kq_lock, PSOCK | PCATCH,
1163                             "kqread", timeout);
1164                 }
1165                 if (error == 0)
1166                         goto retry;
1167                 /* don't restart after signals... */
1168                 if (error == ERESTART)
1169                         error = EINTR;
1170                 else if (error == EWOULDBLOCK)
1171                         error = 0;
1172                 goto done;
1173         }
1174
1175         TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1176         while (count) {
1177                 KQ_OWNED(kq);
1178                 kn = TAILQ_FIRST(&kq->kq_head);
1179
1180                 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1181                     (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1182                         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1183                         kq->kq_state |= KQ_FLUXWAIT;
1184                         error = msleep(kq, &kq->kq_lock, PSOCK,
1185                             "kqflxwt", 0);
1186                         continue;
1187                 }
1188
1189                 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1190                 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1191                         kn->kn_status &= ~KN_QUEUED;
1192                         kq->kq_count--;
1193                         continue;
1194                 }
1195                 if (kn == marker) {
1196                         KQ_FLUX_WAKEUP(kq);
1197                         if (count == maxevents)
1198                                 goto retry;
1199                         goto done;
1200                 }
1201                 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1202                     ("KN_INFLUX set when not suppose to be"));
1203
1204                 if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1205                         kn->kn_status &= ~KN_QUEUED;
1206                         kn->kn_status |= KN_INFLUX;
1207                         kq->kq_count--;
1208                         KQ_UNLOCK(kq);
1209                         /*
1210                          * We don't need to lock the list since we've marked
1211                          * it _INFLUX.
1212                          */
1213                         *kevp = kn->kn_kevent;
1214                         if (!(kn->kn_status & KN_DETACHED))
1215                                 kn->kn_fop->f_detach(kn);
1216                         knote_drop(kn, td);
1217                         KQ_LOCK(kq);
1218                         kn = NULL;
1219                 } else {
1220                         kn->kn_status |= KN_INFLUX;
1221                         KQ_UNLOCK(kq);
1222                         if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1223                                 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1224                         KN_LIST_LOCK(kn);
1225                         if (kn->kn_fop->f_event(kn, 0) == 0) {
1226                                 KN_LIST_UNLOCK(kn);
1227                                 KQ_LOCK(kq);
1228                                 kn->kn_status &=
1229                                     ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX);
1230                                 kq->kq_count--;
1231                                 continue;
1232                         }
1233                         *kevp = kn->kn_kevent;
1234                         KQ_LOCK(kq);
1235                         if (kn->kn_flags & EV_CLEAR) {
1236                                 kn->kn_data = 0;
1237                                 kn->kn_fflags = 0;
1238                                 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1239                                 kq->kq_count--;
1240                         } else
1241                                 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1242                         KN_LIST_UNLOCK(kn);
1243                         kn->kn_status &= ~(KN_INFLUX);
1244                 }
1245
1246                 /* we are returning a copy to the user */
1247                 kevp++;
1248                 nkev++;
1249                 count--;
1250
1251                 if (nkev == KQ_NEVENTS) {
1252                         KQ_UNLOCK_FLUX(kq);
1253                         error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1254                         nkev = 0;
1255                         kevp = keva;
1256                         KQ_LOCK(kq);
1257                         if (error)
1258                                 break;
1259                 }
1260         }
1261         TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1262 done:
1263         KQ_OWNED(kq);
1264         KQ_UNLOCK_FLUX(kq);
1265         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1266         knote_free(marker);
1267 done_nl:
1268         KQ_NOTOWNED(kq);
1269         if (nkev != 0)
1270                 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1271         td->td_retval[0] = maxevents - count;
1272         return (error);
1273 }
1274
1275 /*
1276  * XXX
1277  * This could be expanded to call kqueue_scan, if desired.
1278  */
1279 /*ARGSUSED*/
1280 static int
1281 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1282         int flags, struct thread *td)
1283 {
1284         return (ENXIO);
1285 }
1286
1287 /*ARGSUSED*/
1288 static int
1289 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1290          int flags, struct thread *td)
1291 {
1292         return (ENXIO);
1293 }
1294
1295 /*ARGSUSED*/
1296 static int
1297 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1298         struct ucred *active_cred, struct thread *td)
1299 {
1300         /*
1301          * Enabling sigio causes two major problems:
1302          * 1) infinite recursion:
1303          * Synopsys: kevent is being used to track signals and have FIOASYNC
1304          * set.  On receipt of a signal this will cause a kqueue to recurse
1305          * into itself over and over.  Sending the sigio causes the kqueue
1306          * to become ready, which in turn posts sigio again, forever.
1307          * Solution: this can be solved by setting a flag in the kqueue that
1308          * we have a SIGIO in progress.
1309          * 2) locking problems:
1310          * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1311          * us above the proc and pgrp locks.
1312          * Solution: Post a signal using an async mechanism, being sure to
1313          * record a generation count in the delivery so that we do not deliver
1314          * a signal to the wrong process.
1315          *
1316          * Note, these two mechanisms are somewhat mutually exclusive!
1317          */
1318 #if 0
1319         struct kqueue *kq;
1320
1321         kq = fp->f_data;
1322         switch (cmd) {
1323         case FIOASYNC:
1324                 if (*(int *)data) {
1325                         kq->kq_state |= KQ_ASYNC;
1326                 } else {
1327                         kq->kq_state &= ~KQ_ASYNC;
1328                 }
1329                 return (0);
1330
1331         case FIOSETOWN:
1332                 return (fsetown(*(int *)data, &kq->kq_sigio));
1333
1334         case FIOGETOWN:
1335                 *(int *)data = fgetown(&kq->kq_sigio);
1336                 return (0);
1337         }
1338 #endif
1339
1340         return (ENOTTY);
1341 }
1342
1343 /*ARGSUSED*/
1344 static int
1345 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1346         struct thread *td)
1347 {
1348         struct kqueue *kq;
1349         int revents = 0;
1350         int error;
1351
1352         if ((error = kqueue_aquire(fp, &kq)))
1353                 return POLLERR;
1354
1355         KQ_LOCK(kq);
1356         if (events & (POLLIN | POLLRDNORM)) {
1357                 if (kq->kq_count) {
1358                         revents |= events & (POLLIN | POLLRDNORM);
1359                 } else {
1360                         selrecord(td, &kq->kq_sel);
1361                         kq->kq_state |= KQ_SEL;
1362                 }
1363         }
1364         kqueue_release(kq, 1);
1365         KQ_UNLOCK(kq);
1366         return (revents);
1367 }
1368
1369 /*ARGSUSED*/
1370 static int
1371 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1372         struct thread *td)
1373 {
1374
1375         bzero((void *)st, sizeof *st);
1376         /*
1377          * We no longer return kq_count because the unlocked value is useless.
1378          * If you spent all this time getting the count, why not spend your
1379          * syscall better by calling kevent?
1380          *
1381          * XXX - This is needed for libc_r.
1382          */
1383         st->st_mode = S_IFIFO;
1384         return (0);
1385 }
1386
1387 /*ARGSUSED*/
1388 static int
1389 kqueue_close(struct file *fp, struct thread *td)
1390 {
1391         struct kqueue *kq = fp->f_data;
1392         struct filedesc *fdp;
1393         struct knote *kn;
1394         int i;
1395         int error;
1396
1397         if ((error = kqueue_aquire(fp, &kq)))
1398                 return error;
1399
1400         KQ_LOCK(kq);
1401
1402         KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1403             ("kqueue already closing"));
1404         kq->kq_state |= KQ_CLOSING;
1405         if (kq->kq_refcnt > 1)
1406                 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1407
1408         KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1409         fdp = kq->kq_fdp;
1410
1411         KASSERT(knlist_empty(&kq->kq_sel.si_note),
1412             ("kqueue's knlist not empty"));
1413
1414         for (i = 0; i < kq->kq_knlistsize; i++) {
1415                 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1416                         KASSERT((kn->kn_status & KN_INFLUX) == 0,
1417                             ("KN_INFLUX set when not suppose to be"));
1418                         kn->kn_status |= KN_INFLUX;
1419                         KQ_UNLOCK(kq);
1420                         if (!(kn->kn_status & KN_DETACHED))
1421                                 kn->kn_fop->f_detach(kn);
1422                         knote_drop(kn, td);
1423                         KQ_LOCK(kq);
1424                 }
1425         }
1426         if (kq->kq_knhashmask != 0) {
1427                 for (i = 0; i <= kq->kq_knhashmask; i++) {
1428                         while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1429                                 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1430                                     ("KN_INFLUX set when not suppose to be"));
1431                                 kn->kn_status |= KN_INFLUX;
1432                                 KQ_UNLOCK(kq);
1433                                 if (!(kn->kn_status & KN_DETACHED))
1434                                         kn->kn_fop->f_detach(kn);
1435                                 knote_drop(kn, td);
1436                                 KQ_LOCK(kq);
1437                         }
1438                 }
1439         }
1440
1441         if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1442                 kq->kq_state |= KQ_TASKDRAIN;
1443                 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1444         }
1445
1446         if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1447                 kq->kq_state &= ~KQ_SEL;
1448                 selwakeuppri(&kq->kq_sel, PSOCK);
1449         }
1450
1451         KQ_UNLOCK(kq);
1452
1453         FILEDESC_LOCK_FAST(fdp);
1454         SLIST_REMOVE(&fdp->fd_kqlist, kq, kqueue, kq_list);
1455         FILEDESC_UNLOCK_FAST(fdp);
1456
1457         knlist_destroy(&kq->kq_sel.si_note);
1458         mtx_destroy(&kq->kq_lock);
1459         kq->kq_fdp = NULL;
1460
1461         if (kq->kq_knhash != NULL)
1462                 free(kq->kq_knhash, M_KQUEUE);
1463         if (kq->kq_knlist != NULL)
1464                 free(kq->kq_knlist, M_KQUEUE);
1465
1466         funsetown(&kq->kq_sigio);
1467         free(kq, M_KQUEUE);
1468         fp->f_data = NULL;
1469
1470         return (0);
1471 }
1472
1473 static void
1474 kqueue_wakeup(struct kqueue *kq)
1475 {
1476         KQ_OWNED(kq);
1477
1478         if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1479                 kq->kq_state &= ~KQ_SLEEP;
1480                 wakeup(kq);
1481         }
1482         if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1483                 kq->kq_state &= ~KQ_SEL;
1484                 selwakeuppri(&kq->kq_sel, PSOCK);
1485         }
1486         if (!knlist_empty(&kq->kq_sel.si_note))
1487                 kqueue_schedtask(kq);
1488         if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1489                 pgsigio(&kq->kq_sigio, SIGIO, 0);
1490         }
1491 }
1492
1493 /*
1494  * Walk down a list of knotes, activating them if their event has triggered.
1495  *
1496  * There is a possibility to optimize in the case of one kq watching another.
1497  * Instead of scheduling a task to wake it up, you could pass enough state
1498  * down the chain to make up the parent kqueue.  Make this code functional
1499  * first.
1500  */
1501 void
1502 knote(struct knlist *list, long hint, int islocked)
1503 {
1504         struct kqueue *kq;
1505         struct knote *kn;
1506
1507         if (list == NULL)
1508                 return;
1509
1510         mtx_assert(list->kl_lock, islocked ? MA_OWNED : MA_NOTOWNED);
1511         if (!islocked)
1512                 mtx_lock(list->kl_lock);
1513         /*
1514          * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1515          * the kqueue scheduling, but this will introduce four
1516          * lock/unlock's for each knote to test.  If we do, continue to use
1517          * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1518          * only safe if you want to remove the current item, which we are
1519          * not doing.
1520          */
1521         SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1522                 kq = kn->kn_kq;
1523                 if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1524                         KQ_LOCK(kq);
1525                         if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1526                                 kn->kn_status |= KN_HASKQLOCK;
1527                                 if (kn->kn_fop->f_event(kn, hint))
1528                                         KNOTE_ACTIVATE(kn, 1);
1529                                 kn->kn_status &= ~KN_HASKQLOCK;
1530                         }
1531                         KQ_UNLOCK(kq);
1532                 }
1533                 kq = NULL;
1534         }
1535         if (!islocked)
1536                 mtx_unlock(list->kl_lock);
1537 }
1538
1539 /*
1540  * add a knote to a knlist
1541  */
1542 void
1543 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1544 {
1545         mtx_assert(knl->kl_lock, islocked ? MA_OWNED : MA_NOTOWNED);
1546         KQ_NOTOWNED(kn->kn_kq);
1547         KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1548             (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1549         if (!islocked)
1550                 mtx_lock(knl->kl_lock);
1551         SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1552         if (!islocked)
1553                 mtx_unlock(knl->kl_lock);
1554         KQ_LOCK(kn->kn_kq);
1555         kn->kn_knlist = knl;
1556         kn->kn_status &= ~KN_DETACHED;
1557         KQ_UNLOCK(kn->kn_kq);
1558 }
1559
1560 static void
1561 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1562 {
1563         KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1564         mtx_assert(knl->kl_lock, knlislocked ? MA_OWNED : MA_NOTOWNED);
1565         mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1566         if (!kqislocked)
1567                 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1568     ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1569         if (!knlislocked)
1570                 mtx_lock(knl->kl_lock);
1571         SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1572         kn->kn_knlist = NULL;
1573         if (!knlislocked)
1574                 mtx_unlock(knl->kl_lock);
1575         if (!kqislocked)
1576                 KQ_LOCK(kn->kn_kq);
1577         kn->kn_status |= KN_DETACHED;
1578         if (!kqislocked)
1579                 KQ_UNLOCK(kn->kn_kq);
1580 }
1581
1582 /*
1583  * remove all knotes from a specified klist
1584  */
1585 void
1586 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1587 {
1588
1589         knlist_remove_kq(knl, kn, islocked, 0);
1590 }
1591
1592 /*
1593  * remove knote from a specified klist while in f_event handler.
1594  */
1595 void
1596 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1597 {
1598
1599         knlist_remove_kq(knl, kn, 1,
1600             (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1601 }
1602
1603 int
1604 knlist_empty(struct knlist *knl)
1605 {
1606
1607         mtx_assert(knl->kl_lock, MA_OWNED);
1608         return SLIST_EMPTY(&knl->kl_list);
1609 }
1610
1611 static struct mtx       knlist_lock;
1612 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1613         MTX_DEF);
1614
1615 void
1616 knlist_init(struct knlist *knl, struct mtx *mtx)
1617 {
1618
1619         if (mtx == NULL)
1620                 knl->kl_lock = &knlist_lock;
1621         else
1622                 knl->kl_lock = mtx;
1623
1624         SLIST_INIT(&knl->kl_list);
1625 }
1626
1627 void
1628 knlist_destroy(struct knlist *knl)
1629 {
1630
1631 #ifdef INVARIANTS
1632         /*
1633          * if we run across this error, we need to find the offending
1634          * driver and have it call knlist_clear.
1635          */
1636         if (!SLIST_EMPTY(&knl->kl_list))
1637                 printf("WARNING: destroying knlist w/ knotes on it!\n");
1638 #endif
1639
1640         knl->kl_lock = NULL;
1641         SLIST_INIT(&knl->kl_list);
1642 }
1643
1644 /*
1645  * Even if we are locked, we may need to drop the lock to allow any influx
1646  * knotes time to "settle".
1647  */
1648 void
1649 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
1650 {
1651         struct knote *kn;
1652         struct kqueue *kq;
1653
1654         if (islocked)
1655                 mtx_assert(knl->kl_lock, MA_OWNED);
1656         else {
1657                 mtx_assert(knl->kl_lock, MA_NOTOWNED);
1658 again:          /* need to reaquire lock since we have dropped it */
1659                 mtx_lock(knl->kl_lock);
1660         }
1661
1662         SLIST_FOREACH(kn, &knl->kl_list, kn_selnext) {
1663                 kq = kn->kn_kq;
1664                 KQ_LOCK(kq);
1665                 if ((kn->kn_status & KN_INFLUX)) {
1666                         KQ_UNLOCK(kq);
1667                         continue;
1668                 }
1669                 knlist_remove_kq(knl, kn, 1, 1);
1670                 if (killkn) {
1671                         kn->kn_status |= KN_INFLUX | KN_DETACHED;
1672                         KQ_UNLOCK(kq);
1673                         knote_drop(kn, td);
1674                 } else {
1675                         /* Make sure cleared knotes disappear soon */
1676                         kn->kn_flags |= (EV_EOF | EV_ONESHOT);
1677                         KQ_UNLOCK(kq);
1678                 }
1679                 kq = NULL;
1680         }
1681
1682         if (!SLIST_EMPTY(&knl->kl_list)) {
1683                 /* there are still KN_INFLUX remaining */
1684                 kn = SLIST_FIRST(&knl->kl_list);
1685                 kq = kn->kn_kq;
1686                 KQ_LOCK(kq);
1687                 KASSERT(kn->kn_status & KN_INFLUX,
1688                     ("knote removed w/o list lock"));
1689                 mtx_unlock(knl->kl_lock);
1690                 kq->kq_state |= KQ_FLUXWAIT;
1691                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
1692                 kq = NULL;
1693                 goto again;
1694         }
1695
1696         if (islocked)
1697                 mtx_assert(knl->kl_lock, MA_OWNED);
1698         else {
1699                 mtx_unlock(knl->kl_lock);
1700                 mtx_assert(knl->kl_lock, MA_NOTOWNED);
1701         }
1702 }
1703
1704 /*
1705  * remove all knotes referencing a specified fd
1706  * must be called with FILEDESC lock.  This prevents a race where a new fd
1707  * comes along and occupies the entry and we attach a knote to the fd.
1708  */
1709 void
1710 knote_fdclose(struct thread *td, int fd)
1711 {
1712         struct filedesc *fdp = td->td_proc->p_fd;
1713         struct kqueue *kq;
1714         struct knote *kn;
1715         int influx;
1716
1717         FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1718
1719         /*
1720          * We shouldn't have to worry about new kevents appearing on fd
1721          * since filedesc is locked.
1722          */
1723         SLIST_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
1724                 KQ_LOCK(kq);
1725
1726 again:
1727                 influx = 0;
1728                 while (kq->kq_knlistsize > fd &&
1729                     (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
1730                         if (kn->kn_status & KN_INFLUX) {
1731                                 /* someone else might be waiting on our knote */
1732                                 if (influx)
1733                                         wakeup(kq);
1734                                 kq->kq_state |= KQ_FLUXWAIT;
1735                                 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
1736                                 goto again;
1737                         }
1738                         kn->kn_status |= KN_INFLUX;
1739                         KQ_UNLOCK(kq);
1740                         if (!(kn->kn_status & KN_DETACHED))
1741                                 kn->kn_fop->f_detach(kn);
1742                         knote_drop(kn, td);
1743                         influx = 1;
1744                         KQ_LOCK(kq);
1745                 }
1746                 KQ_UNLOCK_FLUX(kq);
1747         }
1748 }
1749
1750 static int
1751 knote_attach(struct knote *kn, struct kqueue *kq)
1752 {
1753         struct klist *list;
1754
1755         KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
1756         KQ_OWNED(kq);
1757
1758         if (kn->kn_fop->f_isfd) {
1759                 if (kn->kn_id >= kq->kq_knlistsize)
1760                         return ENOMEM;
1761                 list = &kq->kq_knlist[kn->kn_id];
1762         } else {
1763                 if (kq->kq_knhash == NULL)
1764                         return ENOMEM;
1765                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1766         }
1767
1768         SLIST_INSERT_HEAD(list, kn, kn_link);
1769
1770         return 0;
1771 }
1772
1773 /*
1774  * knote must already have been detatched using the f_detach method.
1775  * no lock need to be held, it is assumed that the KN_INFLUX flag is set
1776  * to prevent other removal.
1777  */
1778 static void
1779 knote_drop(struct knote *kn, struct thread *td)
1780 {
1781         struct kqueue *kq;
1782         struct klist *list;
1783
1784         kq = kn->kn_kq;
1785
1786         KQ_NOTOWNED(kq);
1787         KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
1788             ("knote_drop called without KN_INFLUX set in kn_status"));
1789
1790         KQ_LOCK(kq);
1791         if (kn->kn_fop->f_isfd)
1792                 list = &kq->kq_knlist[kn->kn_id];
1793         else
1794                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1795
1796         SLIST_REMOVE(list, kn, knote, kn_link);
1797         if (kn->kn_status & KN_QUEUED)
1798                 knote_dequeue(kn);
1799         KQ_UNLOCK_FLUX(kq);
1800
1801         if (kn->kn_fop->f_isfd) {
1802                 fdrop(kn->kn_fp, td);
1803                 kn->kn_fp = NULL;
1804         }
1805         kqueue_fo_release(kn->kn_kevent.filter);
1806         kn->kn_fop = NULL;
1807         knote_free(kn);
1808 }
1809
1810 static void
1811 knote_enqueue(struct knote *kn)
1812 {
1813         struct kqueue *kq = kn->kn_kq;
1814
1815         KQ_OWNED(kn->kn_kq);
1816         KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1817
1818         TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1819         kn->kn_status |= KN_QUEUED;
1820         kq->kq_count++;
1821         kqueue_wakeup(kq);
1822 }
1823
1824 static void
1825 knote_dequeue(struct knote *kn)
1826 {
1827         struct kqueue *kq = kn->kn_kq;
1828
1829         KQ_OWNED(kn->kn_kq);
1830         KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1831
1832         TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1833         kn->kn_status &= ~KN_QUEUED;
1834         kq->kq_count--;
1835 }
1836
1837 static void
1838 knote_init(void)
1839 {
1840
1841         knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
1842             NULL, NULL, UMA_ALIGN_PTR, 0);
1843 }
1844 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1845
1846 static struct knote *
1847 knote_alloc(int waitok)
1848 {
1849         return ((struct knote *)uma_zalloc(knote_zone,
1850             (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
1851 }
1852
1853 static void
1854 knote_free(struct knote *kn)
1855 {
1856         if (kn != NULL)
1857                 uma_zfree(knote_zone, kn);
1858 }