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