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