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