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