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