]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/kern/kern_event.c
MFC r368207,368607:
[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                                             \
557     (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
558
559 static sbintime_t
560 timer2sbintime(intptr_t data, int flags)
561 {
562         int64_t secs;
563
564         /*
565          * Macros for converting to the fractional second portion of an
566          * sbintime_t using 64bit multiplication to improve precision.
567          */
568 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
569 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
570 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
571         switch (flags & NOTE_TIMER_PRECMASK) {
572         case NOTE_SECONDS:
573 #ifdef __LP64__
574                 if (data > (SBT_MAX / SBT_1S))
575                         return (SBT_MAX);
576 #endif
577                 return ((sbintime_t)data << 32);
578         case NOTE_MSECONDS: /* FALLTHROUGH */
579         case 0:
580                 if (data >= 1000) {
581                         secs = data / 1000;
582 #ifdef __LP64__
583                         if (secs > (SBT_MAX / SBT_1S))
584                                 return (SBT_MAX);
585 #endif
586                         return (secs << 32 | MS_TO_SBT(data % 1000));
587                 }
588                 return (MS_TO_SBT(data));
589         case NOTE_USECONDS:
590                 if (data >= 1000000) {
591                         secs = data / 1000000;
592 #ifdef __LP64__
593                         if (secs > (SBT_MAX / SBT_1S))
594                                 return (SBT_MAX);
595 #endif
596                         return (secs << 32 | US_TO_SBT(data % 1000000));
597                 }
598                 return (US_TO_SBT(data));
599         case NOTE_NSECONDS:
600                 if (data >= 1000000000) {
601                         secs = data / 1000000000;
602 #ifdef __LP64__
603                         if (secs > (SBT_MAX / SBT_1S))
604                                 return (SBT_MAX);
605 #endif
606                         return (secs << 32 | US_TO_SBT(data % 1000000000));
607                 }
608                 return (NS_TO_SBT(data));
609         default:
610                 break;
611         }
612         return (-1);
613 }
614
615 struct kq_timer_cb_data {
616         struct callout c;
617         sbintime_t next;        /* next timer event fires at */
618         sbintime_t to;          /* precalculated timer period */
619 };
620
621 static void
622 filt_timerexpire(void *knx)
623 {
624         struct knote *kn;
625         struct kq_timer_cb_data *kc;
626
627         kn = knx;
628         kn->kn_data++;
629         KNOTE_ACTIVATE(kn, 0);  /* XXX - handle locking */
630
631         if ((kn->kn_flags & EV_ONESHOT) != 0)
632                 return;
633
634         kc = kn->kn_ptr.p_v;
635         kc->next += kc->to;
636         callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
637             PCPU_GET(cpuid), C_ABSOLUTE);
638 }
639
640 /*
641  * data contains amount of time to sleep
642  */
643 static int
644 filt_timerattach(struct knote *kn)
645 {
646         struct kq_timer_cb_data *kc;
647         sbintime_t to;
648         unsigned int ncallouts;
649
650         if (kn->kn_sdata < 0)
651                 return (EINVAL);
652         if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
653                 kn->kn_sdata = 1;
654         /* Only precision unit are supported in flags so far */
655         if ((kn->kn_sfflags & ~NOTE_TIMER_PRECMASK) != 0)
656                 return (EINVAL);
657
658         to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
659         if (to < 0)
660                 return (EINVAL);
661
662         do {
663                 ncallouts = kq_ncallouts;
664                 if (ncallouts >= kq_calloutmax)
665                         return (ENOMEM);
666         } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
667
668         kn->kn_flags |= EV_CLEAR;               /* automatically set */
669         kn->kn_status &= ~KN_DETACHED;          /* knlist_add clears it */
670         kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
671         callout_init(&kc->c, 1);
672         kc->next = to + sbinuptime();
673         kc->to = to;
674         callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
675             PCPU_GET(cpuid), C_ABSOLUTE);
676
677         return (0);
678 }
679
680 static void
681 filt_timerdetach(struct knote *kn)
682 {
683         struct kq_timer_cb_data *kc;
684         unsigned int old;
685
686         kc = kn->kn_ptr.p_v;
687         callout_drain(&kc->c);
688         free(kc, M_KQUEUE);
689         old = atomic_fetchadd_int(&kq_ncallouts, -1);
690         KASSERT(old > 0, ("Number of callouts cannot become negative"));
691         kn->kn_status |= KN_DETACHED;   /* knlist_remove sets it */
692 }
693
694 static int
695 filt_timer(struct knote *kn, long hint)
696 {
697
698         return (kn->kn_data != 0);
699 }
700
701 static int
702 filt_userattach(struct knote *kn)
703 {
704
705         /* 
706          * EVFILT_USER knotes are not attached to anything in the kernel.
707          */ 
708         kn->kn_hook = NULL;
709         if (kn->kn_fflags & NOTE_TRIGGER)
710                 kn->kn_hookid = 1;
711         else
712                 kn->kn_hookid = 0;
713         return (0);
714 }
715
716 static void
717 filt_userdetach(__unused struct knote *kn)
718 {
719
720         /*
721          * EVFILT_USER knotes are not attached to anything in the kernel.
722          */
723 }
724
725 static int
726 filt_user(struct knote *kn, __unused long hint)
727 {
728
729         return (kn->kn_hookid);
730 }
731
732 static void
733 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
734 {
735         u_int ffctrl;
736
737         switch (type) {
738         case EVENT_REGISTER:
739                 if (kev->fflags & NOTE_TRIGGER)
740                         kn->kn_hookid = 1;
741
742                 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
743                 kev->fflags &= NOTE_FFLAGSMASK;
744                 switch (ffctrl) {
745                 case NOTE_FFNOP:
746                         break;
747
748                 case NOTE_FFAND:
749                         kn->kn_sfflags &= kev->fflags;
750                         break;
751
752                 case NOTE_FFOR:
753                         kn->kn_sfflags |= kev->fflags;
754                         break;
755
756                 case NOTE_FFCOPY:
757                         kn->kn_sfflags = kev->fflags;
758                         break;
759
760                 default:
761                         /* XXX Return error? */
762                         break;
763                 }
764                 kn->kn_sdata = kev->data;
765                 if (kev->flags & EV_CLEAR) {
766                         kn->kn_hookid = 0;
767                         kn->kn_data = 0;
768                         kn->kn_fflags = 0;
769                 }
770                 break;
771
772         case EVENT_PROCESS:
773                 *kev = kn->kn_kevent;
774                 kev->fflags = kn->kn_sfflags;
775                 kev->data = kn->kn_sdata;
776                 if (kn->kn_flags & EV_CLEAR) {
777                         kn->kn_hookid = 0;
778                         kn->kn_data = 0;
779                         kn->kn_fflags = 0;
780                 }
781                 break;
782
783         default:
784                 panic("filt_usertouch() - invalid type (%ld)", type);
785                 break;
786         }
787 }
788
789 int
790 sys_kqueue(struct thread *td, struct kqueue_args *uap)
791 {
792
793         return (kern_kqueue(td, 0));
794 }
795
796 int
797 kern_kqueue(struct thread *td, int flags)
798 {
799         struct filedesc *fdp;
800         struct kqueue *kq;
801         struct file *fp;
802         int fd, error;
803
804         fdp = td->td_proc->p_fd;
805         error = falloc(td, &fp, &fd, flags);
806         if (error)
807                 goto done2;
808
809         /* An extra reference on `fp' has been held for us by falloc(). */
810         kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
811         mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
812         TAILQ_INIT(&kq->kq_head);
813         kq->kq_fdp = fdp;
814         knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
815         TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
816
817         FILEDESC_XLOCK(fdp);
818         TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
819         FILEDESC_XUNLOCK(fdp);
820
821         finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
822         fdrop(fp, td);
823
824         td->td_retval[0] = fd;
825 done2:
826         return (error);
827 }
828
829 #ifdef KTRACE
830 static size_t
831 kev_iovlen(int n, u_int kgio)
832 {
833
834         if (n < 0 || n >= kgio / sizeof(struct kevent))
835                 return (kgio);
836         return (n * sizeof(struct kevent));
837 }
838 #endif
839
840 #ifndef _SYS_SYSPROTO_H_
841 struct kevent_args {
842         int     fd;
843         const struct kevent *changelist;
844         int     nchanges;
845         struct  kevent *eventlist;
846         int     nevents;
847         const struct timespec *timeout;
848 };
849 #endif
850 int
851 sys_kevent(struct thread *td, struct kevent_args *uap)
852 {
853         struct timespec ts, *tsp;
854         struct kevent_copyops k_ops = { uap,
855                                         kevent_copyout,
856                                         kevent_copyin};
857         int error;
858 #ifdef KTRACE
859         struct uio ktruio;
860         struct iovec ktriov;
861         struct uio *ktruioin = NULL;
862         struct uio *ktruioout = NULL;
863         u_int kgio;
864 #endif
865
866         if (uap->timeout != NULL) {
867                 error = copyin(uap->timeout, &ts, sizeof(ts));
868                 if (error)
869                         return (error);
870                 tsp = &ts;
871         } else
872                 tsp = NULL;
873
874 #ifdef KTRACE
875         if (KTRPOINT(td, KTR_GENIO)) {
876                 kgio = ktr_geniosize;
877                 ktriov.iov_base = uap->changelist;
878                 ktriov.iov_len = kev_iovlen(uap->nchanges, kgio);
879                 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
880                     .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
881                     .uio_td = td };
882                 ktruioin = cloneuio(&ktruio);
883                 ktriov.iov_base = uap->eventlist;
884                 ktriov.iov_len = kev_iovlen(uap->nevents, kgio);
885                 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
886                 ktruioout = cloneuio(&ktruio);
887         }
888 #endif
889
890         error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
891             &k_ops, tsp);
892
893 #ifdef KTRACE
894         if (ktruioin != NULL) {
895                 ktruioin->uio_resid = kev_iovlen(uap->nchanges, kgio);
896                 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
897                 ktruioout->uio_resid = kev_iovlen(td->td_retval[0], kgio);
898                 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
899         }
900 #endif
901
902         return (error);
903 }
904
905 /*
906  * Copy 'count' items into the destination list pointed to by uap->eventlist.
907  */
908 static int
909 kevent_copyout(void *arg, struct kevent *kevp, int count)
910 {
911         struct kevent_args *uap;
912         int error;
913
914         KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
915         uap = (struct kevent_args *)arg;
916
917         error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
918         if (error == 0)
919                 uap->eventlist += count;
920         return (error);
921 }
922
923 /*
924  * Copy 'count' items from the list pointed to by uap->changelist.
925  */
926 static int
927 kevent_copyin(void *arg, struct kevent *kevp, int count)
928 {
929         struct kevent_args *uap;
930         int error;
931
932         KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
933         uap = (struct kevent_args *)arg;
934
935         error = copyin(uap->changelist, kevp, count * sizeof *kevp);
936         if (error == 0)
937                 uap->changelist += count;
938         return (error);
939 }
940
941 int
942 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
943     struct kevent_copyops *k_ops, const struct timespec *timeout)
944 {
945         cap_rights_t rights;
946         struct file *fp;
947         int error;
948
949         cap_rights_init(&rights);
950         if (nchanges > 0)
951                 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
952         if (nevents > 0)
953                 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
954         error = fget(td, fd, &rights, &fp);
955         if (error != 0)
956                 return (error);
957
958         error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
959         fdrop(fp, td);
960
961         return (error);
962 }
963
964 int
965 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
966     struct kevent_copyops *k_ops, const struct timespec *timeout)
967 {
968         struct kevent keva[KQ_NEVENTS];
969         struct kevent *kevp, *changes;
970         struct kqueue *kq;
971         int i, n, nerrors, error;
972
973         error = kqueue_acquire(fp, &kq);
974         if (error != 0)
975                 return (error);
976
977         nerrors = 0;
978
979         while (nchanges > 0) {
980                 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
981                 error = k_ops->k_copyin(k_ops->arg, keva, n);
982                 if (error)
983                         goto done;
984                 changes = keva;
985                 for (i = 0; i < n; i++) {
986                         kevp = &changes[i];
987                         if (!kevp->filter)
988                                 continue;
989                         kevp->flags &= ~EV_SYSFLAGS;
990                         error = kqueue_register(kq, kevp, td, 1);
991                         if (error || (kevp->flags & EV_RECEIPT)) {
992                                 if (nevents != 0) {
993                                         kevp->flags = EV_ERROR;
994                                         kevp->data = error;
995                                         (void) k_ops->k_copyout(k_ops->arg,
996                                             kevp, 1);
997                                         nevents--;
998                                         nerrors++;
999                                 } else {
1000                                         goto done;
1001                                 }
1002                         }
1003                 }
1004                 nchanges -= n;
1005         }
1006         if (nerrors) {
1007                 td->td_retval[0] = nerrors;
1008                 error = 0;
1009                 goto done;
1010         }
1011
1012         error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
1013 done:
1014         kqueue_release(kq, 0);
1015         return (error);
1016 }
1017
1018 int
1019 kqueue_add_filteropts(int filt, struct filterops *filtops)
1020 {
1021         int error;
1022
1023         error = 0;
1024         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1025                 printf(
1026 "trying to add a filterop that is out of range: %d is beyond %d\n",
1027                     ~filt, EVFILT_SYSCOUNT);
1028                 return EINVAL;
1029         }
1030         mtx_lock(&filterops_lock);
1031         if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1032             sysfilt_ops[~filt].for_fop != NULL)
1033                 error = EEXIST;
1034         else {
1035                 sysfilt_ops[~filt].for_fop = filtops;
1036                 sysfilt_ops[~filt].for_refcnt = 0;
1037         }
1038         mtx_unlock(&filterops_lock);
1039
1040         return (error);
1041 }
1042
1043 int
1044 kqueue_del_filteropts(int filt)
1045 {
1046         int error;
1047
1048         error = 0;
1049         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1050                 return EINVAL;
1051
1052         mtx_lock(&filterops_lock);
1053         if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1054             sysfilt_ops[~filt].for_fop == NULL)
1055                 error = EINVAL;
1056         else if (sysfilt_ops[~filt].for_refcnt != 0)
1057                 error = EBUSY;
1058         else {
1059                 sysfilt_ops[~filt].for_fop = &null_filtops;
1060                 sysfilt_ops[~filt].for_refcnt = 0;
1061         }
1062         mtx_unlock(&filterops_lock);
1063
1064         return error;
1065 }
1066
1067 static struct filterops *
1068 kqueue_fo_find(int filt)
1069 {
1070
1071         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1072                 return NULL;
1073
1074         mtx_lock(&filterops_lock);
1075         sysfilt_ops[~filt].for_refcnt++;
1076         if (sysfilt_ops[~filt].for_fop == NULL)
1077                 sysfilt_ops[~filt].for_fop = &null_filtops;
1078         mtx_unlock(&filterops_lock);
1079
1080         return sysfilt_ops[~filt].for_fop;
1081 }
1082
1083 static void
1084 kqueue_fo_release(int filt)
1085 {
1086
1087         if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1088                 return;
1089
1090         mtx_lock(&filterops_lock);
1091         KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1092             ("filter object refcount not valid on release"));
1093         sysfilt_ops[~filt].for_refcnt--;
1094         mtx_unlock(&filterops_lock);
1095 }
1096
1097 /*
1098  * A ref to kq (obtained via kqueue_acquire) must be held.  waitok will
1099  * influence if memory allocation should wait.  Make sure it is 0 if you
1100  * hold any mutexes.
1101  */
1102 static int
1103 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1104 {
1105         struct filterops *fops;
1106         struct file *fp;
1107         struct knote *kn, *tkn;
1108         cap_rights_t rights;
1109         int error, filt, event;
1110         int haskqglobal, filedesc_unlock;
1111
1112         fp = NULL;
1113         kn = NULL;
1114         error = 0;
1115         haskqglobal = 0;
1116         filedesc_unlock = 0;
1117
1118         filt = kev->filter;
1119         fops = kqueue_fo_find(filt);
1120         if (fops == NULL)
1121                 return EINVAL;
1122
1123         tkn = knote_alloc(waitok);              /* prevent waiting with locks */
1124
1125 findkn:
1126         if (fops->f_isfd) {
1127                 KASSERT(td != NULL, ("td is NULL"));
1128                 if (kev->ident > INT_MAX)
1129                         error = EBADF;
1130                 else
1131                         error = fget(td, kev->ident,
1132                             cap_rights_init(&rights, CAP_EVENT), &fp);
1133                 if (error)
1134                         goto done;
1135
1136                 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1137                     kev->ident, 0) != 0) {
1138                         /* try again */
1139                         fdrop(fp, td);
1140                         fp = NULL;
1141                         error = kqueue_expand(kq, fops, kev->ident, waitok);
1142                         if (error)
1143                                 goto done;
1144                         goto findkn;
1145                 }
1146
1147                 if (fp->f_type == DTYPE_KQUEUE) {
1148                         /*
1149                          * If we add some intelligence about what we are doing,
1150                          * we should be able to support events on ourselves.
1151                          * We need to know when we are doing this to prevent
1152                          * getting both the knlist lock and the kq lock since
1153                          * they are the same thing.
1154                          */
1155                         if (fp->f_data == kq) {
1156                                 error = EINVAL;
1157                                 goto done;
1158                         }
1159
1160                         /*
1161                          * Pre-lock the filedesc before the global
1162                          * lock mutex, see the comment in
1163                          * kqueue_close().
1164                          */
1165                         FILEDESC_XLOCK(td->td_proc->p_fd);
1166                         filedesc_unlock = 1;
1167                         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1168                 }
1169
1170                 KQ_LOCK(kq);
1171                 if (kev->ident < kq->kq_knlistsize) {
1172                         SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1173                                 if (kev->filter == kn->kn_filter)
1174                                         break;
1175                 }
1176         } else {
1177                 if ((kev->flags & EV_ADD) == EV_ADD)
1178                         kqueue_expand(kq, fops, kev->ident, waitok);
1179
1180                 KQ_LOCK(kq);
1181
1182                 /*
1183                  * If possible, find an existing knote to use for this kevent.
1184                  */
1185                 if (kev->filter == EVFILT_PROC &&
1186                     (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1187                         /* This is an internal creation of a process tracking
1188                          * note. Don't attempt to coalesce this with an
1189                          * existing note.
1190                          */
1191                         ;                       
1192                 } else if (kq->kq_knhashmask != 0) {
1193                         struct klist *list;
1194
1195                         list = &kq->kq_knhash[
1196                             KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1197                         SLIST_FOREACH(kn, list, kn_link)
1198                                 if (kev->ident == kn->kn_id &&
1199                                     kev->filter == kn->kn_filter)
1200                                         break;
1201                 }
1202         }
1203
1204         /* knote is in the process of changing, wait for it to stabilize. */
1205         if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1206                 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1207                 if (filedesc_unlock) {
1208                         FILEDESC_XUNLOCK(td->td_proc->p_fd);
1209                         filedesc_unlock = 0;
1210                 }
1211                 kq->kq_state |= KQ_FLUXWAIT;
1212                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1213                 if (fp != NULL) {
1214                         fdrop(fp, td);
1215                         fp = NULL;
1216                 }
1217                 goto findkn;
1218         }
1219
1220         /*
1221          * kn now contains the matching knote, or NULL if no match
1222          */
1223         if (kn == NULL) {
1224                 if (kev->flags & EV_ADD) {
1225                         kn = tkn;
1226                         tkn = NULL;
1227                         if (kn == NULL) {
1228                                 KQ_UNLOCK(kq);
1229                                 error = ENOMEM;
1230                                 goto done;
1231                         }
1232                         kn->kn_fp = fp;
1233                         kn->kn_kq = kq;
1234                         kn->kn_fop = fops;
1235                         /*
1236                          * apply reference counts to knote structure, and
1237                          * do not release it at the end of this routine.
1238                          */
1239                         fops = NULL;
1240                         fp = NULL;
1241
1242                         kn->kn_sfflags = kev->fflags;
1243                         kn->kn_sdata = kev->data;
1244                         kev->fflags = 0;
1245                         kev->data = 0;
1246                         kn->kn_kevent = *kev;
1247                         kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1248                             EV_ENABLE | EV_DISABLE);
1249                         kn->kn_status = KN_INFLUX|KN_DETACHED;
1250
1251                         error = knote_attach(kn, kq);
1252                         KQ_UNLOCK(kq);
1253                         if (error != 0) {
1254                                 tkn = kn;
1255                                 goto done;
1256                         }
1257
1258                         if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1259                                 knote_drop(kn, td);
1260                                 goto done;
1261                         }
1262                         KN_LIST_LOCK(kn);
1263                         goto done_ev_add;
1264                 } else {
1265                         /* No matching knote and the EV_ADD flag is not set. */
1266                         KQ_UNLOCK(kq);
1267                         error = ENOENT;
1268                         goto done;
1269                 }
1270         }
1271         
1272         if (kev->flags & EV_DELETE) {
1273                 kn->kn_status |= KN_INFLUX;
1274                 KQ_UNLOCK(kq);
1275                 if (!(kn->kn_status & KN_DETACHED))
1276                         kn->kn_fop->f_detach(kn);
1277                 knote_drop(kn, td);
1278                 goto done;
1279         }
1280
1281         /*
1282          * The user may change some filter values after the initial EV_ADD,
1283          * but doing so will not reset any filter which has already been
1284          * triggered.
1285          */
1286         kn->kn_status |= KN_INFLUX | KN_SCAN;
1287         KQ_UNLOCK(kq);
1288         KN_LIST_LOCK(kn);
1289         kn->kn_kevent.udata = kev->udata;
1290         if (!fops->f_isfd && fops->f_touch != NULL) {
1291                 fops->f_touch(kn, kev, EVENT_REGISTER);
1292         } else {
1293                 kn->kn_sfflags = kev->fflags;
1294                 kn->kn_sdata = kev->data;
1295         }
1296
1297         /*
1298          * We can get here with kn->kn_knlist == NULL.  This can happen when
1299          * the initial attach event decides that the event is "completed" 
1300          * already.  i.e. filt_procattach is called on a zombie process.  It
1301          * will call filt_proc which will remove it from the list, and NULL
1302          * kn_knlist.
1303          */
1304 done_ev_add:
1305         event = kn->kn_fop->f_event(kn, 0);
1306         KQ_LOCK(kq);
1307         if (event)
1308                 KNOTE_ACTIVATE(kn, 1);
1309         kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1310         KN_LIST_UNLOCK(kn);
1311
1312         if ((kev->flags & EV_DISABLE) &&
1313             ((kn->kn_status & KN_DISABLED) == 0)) {
1314                 kn->kn_status |= KN_DISABLED;
1315         }
1316
1317         if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1318                 kn->kn_status &= ~KN_DISABLED;
1319                 if ((kn->kn_status & KN_ACTIVE) &&
1320                     ((kn->kn_status & KN_QUEUED) == 0))
1321                         knote_enqueue(kn);
1322         }
1323         KQ_UNLOCK_FLUX(kq);
1324
1325 done:
1326         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1327         if (filedesc_unlock)
1328                 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1329         if (fp != NULL)
1330                 fdrop(fp, td);
1331         if (tkn != NULL)
1332                 knote_free(tkn);
1333         if (fops != NULL)
1334                 kqueue_fo_release(filt);
1335         return (error);
1336 }
1337
1338 static int
1339 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1340 {
1341         int error;
1342         struct kqueue *kq;
1343
1344         error = 0;
1345
1346         kq = fp->f_data;
1347         if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1348                 return (EBADF);
1349         *kqp = kq;
1350         KQ_LOCK(kq);
1351         if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1352                 KQ_UNLOCK(kq);
1353                 return (EBADF);
1354         }
1355         kq->kq_refcnt++;
1356         KQ_UNLOCK(kq);
1357
1358         return error;
1359 }
1360
1361 static void
1362 kqueue_release(struct kqueue *kq, int locked)
1363 {
1364         if (locked)
1365                 KQ_OWNED(kq);
1366         else
1367                 KQ_LOCK(kq);
1368         kq->kq_refcnt--;
1369         if (kq->kq_refcnt == 1)
1370                 wakeup(&kq->kq_refcnt);
1371         if (!locked)
1372                 KQ_UNLOCK(kq);
1373 }
1374
1375 static void
1376 kqueue_schedtask(struct kqueue *kq)
1377 {
1378
1379         KQ_OWNED(kq);
1380         KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1381             ("scheduling kqueue task while draining"));
1382
1383         if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1384                 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1385                 kq->kq_state |= KQ_TASKSCHED;
1386         }
1387 }
1388
1389 /*
1390  * Expand the kq to make sure we have storage for fops/ident pair.
1391  *
1392  * Return 0 on success (or no work necessary), return errno on failure.
1393  *
1394  * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1395  * If kqueue_register is called from a non-fd context, there usually/should
1396  * be no locks held.
1397  */
1398 static int
1399 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1400         int waitok)
1401 {
1402         struct klist *list, *tmp_knhash, *to_free;
1403         u_long tmp_knhashmask;
1404         int size;
1405         int fd;
1406         int mflag = waitok ? M_WAITOK : M_NOWAIT;
1407
1408         KQ_NOTOWNED(kq);
1409
1410         to_free = NULL;
1411         if (fops->f_isfd) {
1412                 fd = ident;
1413                 if (kq->kq_knlistsize <= fd) {
1414                         size = kq->kq_knlistsize;
1415                         while (size <= fd)
1416                                 size += KQEXTENT;
1417                         list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1418                         if (list == NULL)
1419                                 return ENOMEM;
1420                         KQ_LOCK(kq);
1421                         if (kq->kq_knlistsize > fd) {
1422                                 to_free = list;
1423                                 list = NULL;
1424                         } else {
1425                                 if (kq->kq_knlist != NULL) {
1426                                         bcopy(kq->kq_knlist, list,
1427                                             kq->kq_knlistsize * sizeof(*list));
1428                                         to_free = kq->kq_knlist;
1429                                         kq->kq_knlist = NULL;
1430                                 }
1431                                 bzero((caddr_t)list +
1432                                     kq->kq_knlistsize * sizeof(*list),
1433                                     (size - kq->kq_knlistsize) * sizeof(*list));
1434                                 kq->kq_knlistsize = size;
1435                                 kq->kq_knlist = list;
1436                         }
1437                         KQ_UNLOCK(kq);
1438                 }
1439         } else {
1440                 if (kq->kq_knhashmask == 0) {
1441                         tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1442                             &tmp_knhashmask);
1443                         if (tmp_knhash == NULL)
1444                                 return ENOMEM;
1445                         KQ_LOCK(kq);
1446                         if (kq->kq_knhashmask == 0) {
1447                                 kq->kq_knhash = tmp_knhash;
1448                                 kq->kq_knhashmask = tmp_knhashmask;
1449                         } else {
1450                                 to_free = tmp_knhash;
1451                         }
1452                         KQ_UNLOCK(kq);
1453                 }
1454         }
1455         free(to_free, M_KQUEUE);
1456
1457         KQ_NOTOWNED(kq);
1458         return 0;
1459 }
1460
1461 static void
1462 kqueue_task(void *arg, int pending)
1463 {
1464         struct kqueue *kq;
1465         int haskqglobal;
1466
1467         haskqglobal = 0;
1468         kq = arg;
1469
1470         KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1471         KQ_LOCK(kq);
1472
1473         KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1474
1475         kq->kq_state &= ~KQ_TASKSCHED;
1476         if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1477                 wakeup(&kq->kq_state);
1478         }
1479         KQ_UNLOCK(kq);
1480         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1481 }
1482
1483 /*
1484  * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1485  * We treat KN_MARKER knotes as if they are INFLUX.
1486  */
1487 static int
1488 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1489     const struct timespec *tsp, struct kevent *keva, struct thread *td)
1490 {
1491         struct kevent *kevp;
1492         struct knote *kn, *marker;
1493         sbintime_t asbt, rsbt;
1494         int count, error, haskqglobal, influx, nkev, touch;
1495
1496         count = maxevents;
1497         nkev = 0;
1498         error = 0;
1499         haskqglobal = 0;
1500
1501         if (maxevents == 0)
1502                 goto done_nl;
1503
1504         rsbt = 0;
1505         if (tsp != NULL) {
1506                 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1507                     tsp->tv_nsec >= 1000000000) {
1508                         error = EINVAL;
1509                         goto done_nl;
1510                 }
1511                 if (timespecisset(tsp)) {
1512                         if (tsp->tv_sec <= INT32_MAX) {
1513                                 rsbt = tstosbt(*tsp);
1514                                 if (TIMESEL(&asbt, rsbt))
1515                                         asbt += tc_tick_sbt;
1516                                 if (asbt <= SBT_MAX - rsbt)
1517                                         asbt += rsbt;
1518                                 else
1519                                         asbt = 0;
1520                                 rsbt >>= tc_precexp;
1521                         } else
1522                                 asbt = 0;
1523                 } else
1524                         asbt = -1;
1525         } else
1526                 asbt = 0;
1527         marker = knote_alloc(1);
1528         if (marker == NULL) {
1529                 error = ENOMEM;
1530                 goto done_nl;
1531         }
1532         marker->kn_status = KN_MARKER;
1533         KQ_LOCK(kq);
1534
1535 retry:
1536         kevp = keva;
1537         if (kq->kq_count == 0) {
1538                 if (asbt == -1) {
1539                         error = EWOULDBLOCK;
1540                 } else {
1541                         kq->kq_state |= KQ_SLEEP;
1542                         error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1543                             "kqread", asbt, rsbt, C_ABSOLUTE);
1544                 }
1545                 if (error == 0)
1546                         goto retry;
1547                 /* don't restart after signals... */
1548                 if (error == ERESTART)
1549                         error = EINTR;
1550                 else if (error == EWOULDBLOCK)
1551                         error = 0;
1552                 goto done;
1553         }
1554
1555         TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1556         influx = 0;
1557         while (count) {
1558                 KQ_OWNED(kq);
1559                 kn = TAILQ_FIRST(&kq->kq_head);
1560
1561                 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1562                     (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1563                         if (influx) {
1564                                 influx = 0;
1565                                 KQ_FLUX_WAKEUP(kq);
1566                         }
1567                         kq->kq_state |= KQ_FLUXWAIT;
1568                         error = msleep(kq, &kq->kq_lock, PSOCK,
1569                             "kqflxwt", 0);
1570                         continue;
1571                 }
1572
1573                 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1574                 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1575                         kn->kn_status &= ~KN_QUEUED;
1576                         kq->kq_count--;
1577                         continue;
1578                 }
1579                 if (kn == marker) {
1580                         KQ_FLUX_WAKEUP(kq);
1581                         if (count == maxevents)
1582                                 goto retry;
1583                         goto done;
1584                 }
1585                 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1586                     ("KN_INFLUX set when not suppose to be"));
1587
1588                 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1589                         kn->kn_status &= ~KN_QUEUED;
1590                         kn->kn_status |= KN_INFLUX;
1591                         kq->kq_count--;
1592                         KQ_UNLOCK(kq);
1593                         /*
1594                          * We don't need to lock the list since we've marked
1595                          * it _INFLUX.
1596                          */
1597                         if (!(kn->kn_status & KN_DETACHED))
1598                                 kn->kn_fop->f_detach(kn);
1599                         knote_drop(kn, td);
1600                         KQ_LOCK(kq);
1601                         continue;
1602                 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1603                         kn->kn_status &= ~KN_QUEUED;
1604                         kn->kn_status |= KN_INFLUX;
1605                         kq->kq_count--;
1606                         KQ_UNLOCK(kq);
1607                         /*
1608                          * We don't need to lock the list since we've marked
1609                          * it _INFLUX.
1610                          */
1611                         *kevp = kn->kn_kevent;
1612                         if (!(kn->kn_status & KN_DETACHED))
1613                                 kn->kn_fop->f_detach(kn);
1614                         knote_drop(kn, td);
1615                         KQ_LOCK(kq);
1616                         kn = NULL;
1617                 } else {
1618                         kn->kn_status |= KN_INFLUX | KN_SCAN;
1619                         KQ_UNLOCK(kq);
1620                         if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1621                                 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1622                         KN_LIST_LOCK(kn);
1623                         if (kn->kn_fop->f_event(kn, 0) == 0) {
1624                                 KQ_LOCK(kq);
1625                                 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1626                                 kn->kn_status &=
1627                                     ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1628                                     KN_SCAN);
1629                                 kq->kq_count--;
1630                                 KN_LIST_UNLOCK(kn);
1631                                 influx = 1;
1632                                 continue;
1633                         }
1634                         touch = (!kn->kn_fop->f_isfd &&
1635                             kn->kn_fop->f_touch != NULL);
1636                         if (touch)
1637                                 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1638                         else
1639                                 *kevp = kn->kn_kevent;
1640                         KQ_LOCK(kq);
1641                         KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1642                         if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1643                                 /* 
1644                                  * Manually clear knotes who weren't 
1645                                  * 'touch'ed.
1646                                  */
1647                                 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1648                                         kn->kn_data = 0;
1649                                         kn->kn_fflags = 0;
1650                                 }
1651                                 if (kn->kn_flags & EV_DISPATCH)
1652                                         kn->kn_status |= KN_DISABLED;
1653                                 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1654                                 kq->kq_count--;
1655                         } else
1656                                 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1657                         
1658                         kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1659                         KN_LIST_UNLOCK(kn);
1660                         influx = 1;
1661                 }
1662
1663                 /* we are returning a copy to the user */
1664                 kevp++;
1665                 nkev++;
1666                 count--;
1667
1668                 if (nkev == KQ_NEVENTS) {
1669                         influx = 0;
1670                         KQ_UNLOCK_FLUX(kq);
1671                         error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1672                         nkev = 0;
1673                         kevp = keva;
1674                         KQ_LOCK(kq);
1675                         if (error)
1676                                 break;
1677                 }
1678         }
1679         TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1680 done:
1681         KQ_OWNED(kq);
1682         KQ_UNLOCK_FLUX(kq);
1683         knote_free(marker);
1684 done_nl:
1685         KQ_NOTOWNED(kq);
1686         if (nkev != 0)
1687                 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1688         td->td_retval[0] = maxevents - count;
1689         return (error);
1690 }
1691
1692 /*
1693  * XXX
1694  * This could be expanded to call kqueue_scan, if desired.
1695  */
1696 /*ARGSUSED*/
1697 static int
1698 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1699         int flags, struct thread *td)
1700 {
1701         return (ENXIO);
1702 }
1703
1704 /*ARGSUSED*/
1705 static int
1706 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1707          int flags, struct thread *td)
1708 {
1709         return (ENXIO);
1710 }
1711
1712 /*ARGSUSED*/
1713 static int
1714 kqueue_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1715         struct thread *td)
1716 {
1717
1718         return (EINVAL);
1719 }
1720
1721 /*ARGSUSED*/
1722 static int
1723 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1724         struct ucred *active_cred, struct thread *td)
1725 {
1726         /*
1727          * Enabling sigio causes two major problems:
1728          * 1) infinite recursion:
1729          * Synopsys: kevent is being used to track signals and have FIOASYNC
1730          * set.  On receipt of a signal this will cause a kqueue to recurse
1731          * into itself over and over.  Sending the sigio causes the kqueue
1732          * to become ready, which in turn posts sigio again, forever.
1733          * Solution: this can be solved by setting a flag in the kqueue that
1734          * we have a SIGIO in progress.
1735          * 2) locking problems:
1736          * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1737          * us above the proc and pgrp locks.
1738          * Solution: Post a signal using an async mechanism, being sure to
1739          * record a generation count in the delivery so that we do not deliver
1740          * a signal to the wrong process.
1741          *
1742          * Note, these two mechanisms are somewhat mutually exclusive!
1743          */
1744 #if 0
1745         struct kqueue *kq;
1746
1747         kq = fp->f_data;
1748         switch (cmd) {
1749         case FIOASYNC:
1750                 if (*(int *)data) {
1751                         kq->kq_state |= KQ_ASYNC;
1752                 } else {
1753                         kq->kq_state &= ~KQ_ASYNC;
1754                 }
1755                 return (0);
1756
1757         case FIOSETOWN:
1758                 return (fsetown(*(int *)data, &kq->kq_sigio));
1759
1760         case FIOGETOWN:
1761                 *(int *)data = fgetown(&kq->kq_sigio);
1762                 return (0);
1763         }
1764 #endif
1765
1766         return (ENOTTY);
1767 }
1768
1769 /*ARGSUSED*/
1770 static int
1771 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1772         struct thread *td)
1773 {
1774         struct kqueue *kq;
1775         int revents = 0;
1776         int error;
1777
1778         if ((error = kqueue_acquire(fp, &kq)))
1779                 return POLLERR;
1780
1781         KQ_LOCK(kq);
1782         if (events & (POLLIN | POLLRDNORM)) {
1783                 if (kq->kq_count) {
1784                         revents |= events & (POLLIN | POLLRDNORM);
1785                 } else {
1786                         selrecord(td, &kq->kq_sel);
1787                         if (SEL_WAITING(&kq->kq_sel))
1788                                 kq->kq_state |= KQ_SEL;
1789                 }
1790         }
1791         kqueue_release(kq, 1);
1792         KQ_UNLOCK(kq);
1793         return (revents);
1794 }
1795
1796 /*ARGSUSED*/
1797 static int
1798 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1799         struct thread *td)
1800 {
1801
1802         bzero((void *)st, sizeof *st);
1803         /*
1804          * We no longer return kq_count because the unlocked value is useless.
1805          * If you spent all this time getting the count, why not spend your
1806          * syscall better by calling kevent?
1807          *
1808          * XXX - This is needed for libc_r.
1809          */
1810         st->st_mode = S_IFIFO;
1811         return (0);
1812 }
1813
1814 /*ARGSUSED*/
1815 static int
1816 kqueue_close(struct file *fp, struct thread *td)
1817 {
1818         struct kqueue *kq = fp->f_data;
1819         struct filedesc *fdp;
1820         struct knote *kn;
1821         int i;
1822         int error;
1823         int filedesc_unlock;
1824
1825         if ((error = kqueue_acquire(fp, &kq)))
1826                 return error;
1827
1828         filedesc_unlock = 0;
1829         KQ_LOCK(kq);
1830
1831         KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1832             ("kqueue already closing"));
1833         kq->kq_state |= KQ_CLOSING;
1834         if (kq->kq_refcnt > 1)
1835                 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1836
1837         KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1838         fdp = kq->kq_fdp;
1839
1840         KASSERT(knlist_empty(&kq->kq_sel.si_note),
1841             ("kqueue's knlist not empty"));
1842
1843         for (i = 0; i < kq->kq_knlistsize; i++) {
1844                 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1845                         if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1846                                 kq->kq_state |= KQ_FLUXWAIT;
1847                                 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1848                                 continue;
1849                         }
1850                         kn->kn_status |= KN_INFLUX;
1851                         KQ_UNLOCK(kq);
1852                         if (!(kn->kn_status & KN_DETACHED))
1853                                 kn->kn_fop->f_detach(kn);
1854                         knote_drop(kn, td);
1855                         KQ_LOCK(kq);
1856                 }
1857         }
1858         if (kq->kq_knhashmask != 0) {
1859                 for (i = 0; i <= kq->kq_knhashmask; i++) {
1860                         while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1861                                 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1862                                         kq->kq_state |= KQ_FLUXWAIT;
1863                                         msleep(kq, &kq->kq_lock, PSOCK,
1864                                                "kqclo2", 0);
1865                                         continue;
1866                                 }
1867                                 kn->kn_status |= KN_INFLUX;
1868                                 KQ_UNLOCK(kq);
1869                                 if (!(kn->kn_status & KN_DETACHED))
1870                                         kn->kn_fop->f_detach(kn);
1871                                 knote_drop(kn, td);
1872                                 KQ_LOCK(kq);
1873                         }
1874                 }
1875         }
1876
1877         if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1878                 kq->kq_state |= KQ_TASKDRAIN;
1879                 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1880         }
1881
1882         if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1883                 selwakeuppri(&kq->kq_sel, PSOCK);
1884                 if (!SEL_WAITING(&kq->kq_sel))
1885                         kq->kq_state &= ~KQ_SEL;
1886         }
1887
1888         KQ_UNLOCK(kq);
1889
1890         /*
1891          * We could be called due to the knote_drop() doing fdrop(),
1892          * called from kqueue_register().  In this case the global
1893          * lock is owned, and filedesc sx is locked before, to not
1894          * take the sleepable lock after non-sleepable.
1895          */
1896         if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1897                 FILEDESC_XLOCK(fdp);
1898                 filedesc_unlock = 1;
1899         } else
1900                 filedesc_unlock = 0;
1901         TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1902         if (filedesc_unlock)
1903                 FILEDESC_XUNLOCK(fdp);
1904
1905         seldrain(&kq->kq_sel);
1906         knlist_destroy(&kq->kq_sel.si_note);
1907         mtx_destroy(&kq->kq_lock);
1908         kq->kq_fdp = NULL;
1909
1910         if (kq->kq_knhash != NULL)
1911                 free(kq->kq_knhash, M_KQUEUE);
1912         if (kq->kq_knlist != NULL)
1913                 free(kq->kq_knlist, M_KQUEUE);
1914
1915         funsetown(&kq->kq_sigio);
1916         free(kq, M_KQUEUE);
1917         fp->f_data = NULL;
1918
1919         return (0);
1920 }
1921
1922 static void
1923 kqueue_wakeup(struct kqueue *kq)
1924 {
1925         KQ_OWNED(kq);
1926
1927         if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1928                 kq->kq_state &= ~KQ_SLEEP;
1929                 wakeup(kq);
1930         }
1931         if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1932                 selwakeuppri(&kq->kq_sel, PSOCK);
1933                 if (!SEL_WAITING(&kq->kq_sel))
1934                         kq->kq_state &= ~KQ_SEL;
1935         }
1936         if (!knlist_empty(&kq->kq_sel.si_note))
1937                 kqueue_schedtask(kq);
1938         if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1939                 pgsigio(&kq->kq_sigio, SIGIO, 0);
1940         }
1941 }
1942
1943 /*
1944  * Walk down a list of knotes, activating them if their event has triggered.
1945  *
1946  * There is a possibility to optimize in the case of one kq watching another.
1947  * Instead of scheduling a task to wake it up, you could pass enough state
1948  * down the chain to make up the parent kqueue.  Make this code functional
1949  * first.
1950  */
1951 void
1952 knote(struct knlist *list, long hint, int lockflags)
1953 {
1954         struct kqueue *kq;
1955         struct knote *kn, *tkn;
1956         int error;
1957         bool own_influx;
1958
1959         if (list == NULL)
1960                 return;
1961
1962         KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1963
1964         if ((lockflags & KNF_LISTLOCKED) == 0)
1965                 list->kl_lock(list->kl_lockarg); 
1966
1967         /*
1968          * If we unlock the list lock (and set KN_INFLUX), we can
1969          * eliminate the kqueue scheduling, but this will introduce
1970          * four lock/unlock's for each knote to test.  Also, marker
1971          * would be needed to keep iteration position, since filters
1972          * or other threads could remove events.
1973          */
1974         SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
1975                 kq = kn->kn_kq;
1976                 KQ_LOCK(kq);
1977                 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1978                         /*
1979                          * Do not process the influx notes, except for
1980                          * the influx coming from the kq unlock in the
1981                          * kqueue_scan().  In the later case, we do
1982                          * not interfere with the scan, since the code
1983                          * fragment in kqueue_scan() locks the knlist,
1984                          * and cannot proceed until we finished.
1985                          */
1986                         KQ_UNLOCK(kq);
1987                 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1988                         own_influx = (kn->kn_status & KN_INFLUX) == 0;
1989                         if (own_influx)
1990                                 kn->kn_status |= KN_INFLUX;
1991                         KQ_UNLOCK(kq);
1992                         error = kn->kn_fop->f_event(kn, hint);
1993                         KQ_LOCK(kq);
1994                         if (own_influx)
1995                                 kn->kn_status &= ~KN_INFLUX;
1996                         if (error)
1997                                 KNOTE_ACTIVATE(kn, 1);
1998                         KQ_UNLOCK_FLUX(kq);
1999                 } else {
2000                         kn->kn_status |= KN_HASKQLOCK;
2001                         if (kn->kn_fop->f_event(kn, hint))
2002                                 KNOTE_ACTIVATE(kn, 1);
2003                         kn->kn_status &= ~KN_HASKQLOCK;
2004                         KQ_UNLOCK(kq);
2005                 }
2006         }
2007         if ((lockflags & KNF_LISTLOCKED) == 0)
2008                 list->kl_unlock(list->kl_lockarg); 
2009 }
2010
2011 /*
2012  * add a knote to a knlist
2013  */
2014 void
2015 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2016 {
2017         KNL_ASSERT_LOCK(knl, islocked);
2018         KQ_NOTOWNED(kn->kn_kq);
2019         KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
2020             (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
2021         if (!islocked)
2022                 knl->kl_lock(knl->kl_lockarg);
2023         SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2024         if (!islocked)
2025                 knl->kl_unlock(knl->kl_lockarg);
2026         KQ_LOCK(kn->kn_kq);
2027         kn->kn_knlist = knl;
2028         kn->kn_status &= ~KN_DETACHED;
2029         KQ_UNLOCK(kn->kn_kq);
2030 }
2031
2032 static void
2033 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
2034 {
2035         KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2036         KNL_ASSERT_LOCK(knl, knlislocked);
2037         mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2038         if (!kqislocked)
2039                 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2040     ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2041         if (!knlislocked)
2042                 knl->kl_lock(knl->kl_lockarg);
2043         SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2044         kn->kn_knlist = NULL;
2045         if (!knlislocked)
2046                 knl->kl_unlock(knl->kl_lockarg);
2047         if (!kqislocked)
2048                 KQ_LOCK(kn->kn_kq);
2049         kn->kn_status |= KN_DETACHED;
2050         if (!kqislocked)
2051                 KQ_UNLOCK(kn->kn_kq);
2052 }
2053
2054 /*
2055  * remove knote from the specified knlist
2056  */
2057 void
2058 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2059 {
2060
2061         knlist_remove_kq(knl, kn, islocked, 0);
2062 }
2063
2064 /*
2065  * remove knote from the specified knlist while in f_event handler.
2066  */
2067 void
2068 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
2069 {
2070
2071         knlist_remove_kq(knl, kn, 1,
2072             (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
2073 }
2074
2075 int
2076 knlist_empty(struct knlist *knl)
2077 {
2078
2079         KNL_ASSERT_LOCKED(knl);
2080         return (SLIST_EMPTY(&knl->kl_list));
2081 }
2082
2083 static struct mtx knlist_lock;
2084 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2085     MTX_DEF);
2086 static void knlist_mtx_lock(void *arg);
2087 static void knlist_mtx_unlock(void *arg);
2088
2089 static void
2090 knlist_mtx_lock(void *arg)
2091 {
2092
2093         mtx_lock((struct mtx *)arg);
2094 }
2095
2096 static void
2097 knlist_mtx_unlock(void *arg)
2098 {
2099
2100         mtx_unlock((struct mtx *)arg);
2101 }
2102
2103 static void
2104 knlist_mtx_assert_locked(void *arg)
2105 {
2106
2107         mtx_assert((struct mtx *)arg, MA_OWNED);
2108 }
2109
2110 static void
2111 knlist_mtx_assert_unlocked(void *arg)
2112 {
2113
2114         mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2115 }
2116
2117 static void
2118 knlist_rw_rlock(void *arg)
2119 {
2120
2121         rw_rlock((struct rwlock *)arg);
2122 }
2123
2124 static void
2125 knlist_rw_runlock(void *arg)
2126 {
2127
2128         rw_runlock((struct rwlock *)arg);
2129 }
2130
2131 static void
2132 knlist_rw_assert_locked(void *arg)
2133 {
2134
2135         rw_assert((struct rwlock *)arg, RA_LOCKED);
2136 }
2137
2138 static void
2139 knlist_rw_assert_unlocked(void *arg)
2140 {
2141
2142         rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2143 }
2144
2145 void
2146 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2147     void (*kl_unlock)(void *),
2148     void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2149 {
2150
2151         if (lock == NULL)
2152                 knl->kl_lockarg = &knlist_lock;
2153         else
2154                 knl->kl_lockarg = lock;
2155
2156         if (kl_lock == NULL)
2157                 knl->kl_lock = knlist_mtx_lock;
2158         else
2159                 knl->kl_lock = kl_lock;
2160         if (kl_unlock == NULL)
2161                 knl->kl_unlock = knlist_mtx_unlock;
2162         else
2163                 knl->kl_unlock = kl_unlock;
2164         if (kl_assert_locked == NULL)
2165                 knl->kl_assert_locked = knlist_mtx_assert_locked;
2166         else
2167                 knl->kl_assert_locked = kl_assert_locked;
2168         if (kl_assert_unlocked == NULL)
2169                 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2170         else
2171                 knl->kl_assert_unlocked = kl_assert_unlocked;
2172
2173         SLIST_INIT(&knl->kl_list);
2174 }
2175
2176 void
2177 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2178 {
2179
2180         knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2181 }
2182
2183 void
2184 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2185 {
2186
2187         knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2188             knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2189 }
2190
2191 void
2192 knlist_destroy(struct knlist *knl)
2193 {
2194
2195         KASSERT(KNLIST_EMPTY(knl),
2196             ("destroying knlist %p with knotes on it", knl));
2197 }
2198
2199 /*
2200  * Even if we are locked, we may need to drop the lock to allow any influx
2201  * knotes time to "settle".
2202  */
2203 void
2204 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2205 {
2206         struct knote *kn, *kn2;
2207         struct kqueue *kq;
2208
2209         if (islocked)
2210                 KNL_ASSERT_LOCKED(knl);
2211         else {
2212                 KNL_ASSERT_UNLOCKED(knl);
2213 again:          /* need to reacquire lock since we have dropped it */
2214                 knl->kl_lock(knl->kl_lockarg);
2215         }
2216
2217         SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2218                 kq = kn->kn_kq;
2219                 KQ_LOCK(kq);
2220                 if ((kn->kn_status & KN_INFLUX)) {
2221                         KQ_UNLOCK(kq);
2222                         continue;
2223                 }
2224                 knlist_remove_kq(knl, kn, 1, 1);
2225                 if (killkn) {
2226                         kn->kn_status |= KN_INFLUX | KN_DETACHED;
2227                         KQ_UNLOCK(kq);
2228                         knote_drop(kn, td);
2229                 } else {
2230                         /* Make sure cleared knotes disappear soon */
2231                         kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2232                         KQ_UNLOCK(kq);
2233                 }
2234                 kq = NULL;
2235         }
2236
2237         if (!SLIST_EMPTY(&knl->kl_list)) {
2238                 /* there are still KN_INFLUX remaining */
2239                 kn = SLIST_FIRST(&knl->kl_list);
2240                 kq = kn->kn_kq;
2241                 KQ_LOCK(kq);
2242                 KASSERT(kn->kn_status & KN_INFLUX,
2243                     ("knote removed w/o list lock"));
2244                 knl->kl_unlock(knl->kl_lockarg);
2245                 kq->kq_state |= KQ_FLUXWAIT;
2246                 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2247                 kq = NULL;
2248                 goto again;
2249         }
2250
2251         if (islocked)
2252                 KNL_ASSERT_LOCKED(knl);
2253         else {
2254                 knl->kl_unlock(knl->kl_lockarg);
2255                 KNL_ASSERT_UNLOCKED(knl);
2256         }
2257 }
2258
2259 /*
2260  * Remove all knotes referencing a specified fd must be called with FILEDESC
2261  * lock.  This prevents a race where a new fd comes along and occupies the
2262  * entry and we attach a knote to the fd.
2263  */
2264 void
2265 knote_fdclose(struct thread *td, int fd)
2266 {
2267         struct filedesc *fdp = td->td_proc->p_fd;
2268         struct kqueue *kq;
2269         struct knote *kn;
2270         int influx;
2271
2272         FILEDESC_XLOCK_ASSERT(fdp);
2273
2274         /*
2275          * We shouldn't have to worry about new kevents appearing on fd
2276          * since filedesc is locked.
2277          */
2278         TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2279                 KQ_LOCK(kq);
2280
2281 again:
2282                 influx = 0;
2283                 while (kq->kq_knlistsize > fd &&
2284                     (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2285                         if (kn->kn_status & KN_INFLUX) {
2286                                 /* someone else might be waiting on our knote */
2287                                 if (influx)
2288                                         wakeup(kq);
2289                                 kq->kq_state |= KQ_FLUXWAIT;
2290                                 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2291                                 goto again;
2292                         }
2293                         kn->kn_status |= KN_INFLUX;
2294                         KQ_UNLOCK(kq);
2295                         if (!(kn->kn_status & KN_DETACHED))
2296                                 kn->kn_fop->f_detach(kn);
2297                         knote_drop(kn, td);
2298                         influx = 1;
2299                         KQ_LOCK(kq);
2300                 }
2301                 KQ_UNLOCK_FLUX(kq);
2302         }
2303 }
2304
2305 static int
2306 knote_attach(struct knote *kn, struct kqueue *kq)
2307 {
2308         struct klist *list;
2309
2310         KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2311         KQ_OWNED(kq);
2312
2313         if (kn->kn_fop->f_isfd) {
2314                 if (kn->kn_id >= kq->kq_knlistsize)
2315                         return (ENOMEM);
2316                 list = &kq->kq_knlist[kn->kn_id];
2317         } else {
2318                 if (kq->kq_knhash == NULL)
2319                         return (ENOMEM);
2320                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2321         }
2322         SLIST_INSERT_HEAD(list, kn, kn_link);
2323         return (0);
2324 }
2325
2326 /*
2327  * knote must already have been detached using the f_detach method.
2328  * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2329  * to prevent other removal.
2330  */
2331 static void
2332 knote_drop(struct knote *kn, struct thread *td)
2333 {
2334         struct kqueue *kq;
2335         struct klist *list;
2336
2337         kq = kn->kn_kq;
2338
2339         KQ_NOTOWNED(kq);
2340         KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2341             ("knote_drop called without KN_INFLUX set in kn_status"));
2342
2343         KQ_LOCK(kq);
2344         if (kn->kn_fop->f_isfd)
2345                 list = &kq->kq_knlist[kn->kn_id];
2346         else
2347                 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2348
2349         if (!SLIST_EMPTY(list))
2350                 SLIST_REMOVE(list, kn, knote, kn_link);
2351         if (kn->kn_status & KN_QUEUED)
2352                 knote_dequeue(kn);
2353         KQ_UNLOCK_FLUX(kq);
2354
2355         if (kn->kn_fop->f_isfd) {
2356                 fdrop(kn->kn_fp, td);
2357                 kn->kn_fp = NULL;
2358         }
2359         kqueue_fo_release(kn->kn_kevent.filter);
2360         kn->kn_fop = NULL;
2361         knote_free(kn);
2362 }
2363
2364 static void
2365 knote_enqueue(struct knote *kn)
2366 {
2367         struct kqueue *kq = kn->kn_kq;
2368
2369         KQ_OWNED(kn->kn_kq);
2370         KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2371
2372         TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2373         kn->kn_status |= KN_QUEUED;
2374         kq->kq_count++;
2375         kqueue_wakeup(kq);
2376 }
2377
2378 static void
2379 knote_dequeue(struct knote *kn)
2380 {
2381         struct kqueue *kq = kn->kn_kq;
2382
2383         KQ_OWNED(kn->kn_kq);
2384         KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2385
2386         TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2387         kn->kn_status &= ~KN_QUEUED;
2388         kq->kq_count--;
2389 }
2390
2391 static void
2392 knote_init(void)
2393 {
2394
2395         knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2396             NULL, NULL, UMA_ALIGN_PTR, 0);
2397 }
2398 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2399
2400 static struct knote *
2401 knote_alloc(int waitok)
2402 {
2403         return ((struct knote *)uma_zalloc(knote_zone,
2404             (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2405 }
2406
2407 static void
2408 knote_free(struct knote *kn)
2409 {
2410         if (kn != NULL)
2411                 uma_zfree(knote_zone, kn);
2412 }
2413
2414 /*
2415  * Register the kev w/ the kq specified by fd.
2416  */
2417 int 
2418 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2419 {
2420         struct kqueue *kq;
2421         struct file *fp;
2422         cap_rights_t rights;
2423         int error;
2424
2425         error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2426         if (error != 0)
2427                 return (error);
2428         if ((error = kqueue_acquire(fp, &kq)) != 0)
2429                 goto noacquire;
2430
2431         error = kqueue_register(kq, kev, td, waitok);
2432         kqueue_release(kq, 0);
2433
2434 noacquire:
2435         fdrop(fp, td);
2436         return (error);
2437 }