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