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