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