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