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