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