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