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