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