2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include "opt_ktrace.h"
35 #include "opt_kqueue.h"
37 #ifdef COMPAT_FREEBSD11
38 #define _WANT_FREEBSD11_KEVENT
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>
47 #include <sys/mutex.h>
48 #include <sys/rwlock.h>
50 #include <sys/malloc.h>
51 #include <sys/unistd.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>
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>
69 #include <sys/sysctl.h>
70 #include <sys/sysproto.h>
71 #include <sys/syscallsubr.h>
72 #include <sys/taskqueue.h>
76 #include <sys/ktrace.h>
78 #include <machine/atomic.h>
82 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
85 * This lock is used if multiple kq locks are required. This possibly
86 * should be made into a per proc lock.
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 { \
95 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
101 TASKQUEUE_DEFINE_THREAD(kqueue_ctx);
103 static int kevent_copyout(void *arg, struct kevent *kevp, int count);
104 static int kevent_copyin(void *arg, struct kevent *kevp, int count);
105 static int kqueue_register(struct kqueue *kq, struct kevent *kev,
106 struct thread *td, int mflag);
107 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
108 static void kqueue_release(struct kqueue *kq, int locked);
109 static void kqueue_destroy(struct kqueue *kq);
110 static void kqueue_drain(struct kqueue *kq, struct thread *td);
111 static int kqueue_expand(struct kqueue *kq, struct filterops *fops,
112 uintptr_t ident, int mflag);
113 static void kqueue_task(void *arg, int pending);
114 static int kqueue_scan(struct kqueue *kq, int maxevents,
115 struct kevent_copyops *k_ops,
116 const struct timespec *timeout,
117 struct kevent *keva, struct thread *td);
118 static void kqueue_wakeup(struct kqueue *kq);
119 static struct filterops *kqueue_fo_find(int filt);
120 static void kqueue_fo_release(int filt);
121 struct g_kevent_args;
122 static int kern_kevent_generic(struct thread *td,
123 struct g_kevent_args *uap,
124 struct kevent_copyops *k_ops, const char *struct_name);
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;
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,
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);
157 static void filt_kqdetach(struct knote *kn);
158 static int filt_kqueue(struct knote *kn, long hint);
159 static int filt_procattach(struct knote *kn);
160 static void filt_procdetach(struct knote *kn);
161 static int filt_proc(struct knote *kn, long hint);
162 static int filt_fileattach(struct knote *kn);
163 static void filt_timerexpire(void *knx);
164 static int filt_timerattach(struct knote *kn);
165 static void filt_timerdetach(struct knote *kn);
166 static void filt_timerstart(struct knote *kn, sbintime_t to);
167 static void filt_timertouch(struct knote *kn, struct kevent *kev,
169 static int filt_timervalidate(struct knote *kn, sbintime_t *to);
170 static int filt_timer(struct knote *kn, long hint);
171 static int filt_userattach(struct knote *kn);
172 static void filt_userdetach(struct knote *kn);
173 static int filt_user(struct knote *kn, long hint);
174 static void filt_usertouch(struct knote *kn, struct kevent *kev,
177 static struct filterops file_filtops = {
179 .f_attach = filt_fileattach,
181 static struct filterops kqread_filtops = {
183 .f_detach = filt_kqdetach,
184 .f_event = filt_kqueue,
186 /* XXX - move to kern_proc.c? */
187 static struct filterops proc_filtops = {
189 .f_attach = filt_procattach,
190 .f_detach = filt_procdetach,
191 .f_event = filt_proc,
193 static struct filterops timer_filtops = {
195 .f_attach = filt_timerattach,
196 .f_detach = filt_timerdetach,
197 .f_event = filt_timer,
198 .f_touch = filt_timertouch,
200 static struct filterops user_filtops = {
201 .f_attach = filt_userattach,
202 .f_detach = filt_userdetach,
203 .f_event = filt_user,
204 .f_touch = filt_usertouch,
207 static uma_zone_t knote_zone;
208 static unsigned int kq_ncallouts = 0;
209 static unsigned int kq_calloutmax = 4 * 1024;
210 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
211 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
213 /* XXX - ensure not influx ? */
214 #define KNOTE_ACTIVATE(kn, islock) do { \
216 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
218 KQ_LOCK((kn)->kn_kq); \
219 (kn)->kn_status |= KN_ACTIVE; \
220 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
221 knote_enqueue((kn)); \
223 KQ_UNLOCK((kn)->kn_kq); \
225 #define KQ_LOCK(kq) do { \
226 mtx_lock(&(kq)->kq_lock); \
228 #define KQ_FLUX_WAKEUP(kq) do { \
229 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
230 (kq)->kq_state &= ~KQ_FLUXWAIT; \
234 #define KQ_UNLOCK_FLUX(kq) do { \
235 KQ_FLUX_WAKEUP(kq); \
236 mtx_unlock(&(kq)->kq_lock); \
238 #define KQ_UNLOCK(kq) do { \
239 mtx_unlock(&(kq)->kq_lock); \
241 #define KQ_OWNED(kq) do { \
242 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
244 #define KQ_NOTOWNED(kq) do { \
245 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
248 static struct knlist *
249 kn_list_lock(struct knote *kn)
255 knl->kl_lock(knl->kl_lockarg);
260 kn_list_unlock(struct knlist *knl)
266 do_free = knl->kl_autodestroy && knlist_empty(knl);
267 knl->kl_unlock(knl->kl_lockarg);
275 kn_in_flux(struct knote *kn)
278 return (kn->kn_influx > 0);
282 kn_enter_flux(struct knote *kn)
286 MPASS(kn->kn_influx < INT_MAX);
291 kn_leave_flux(struct knote *kn)
295 MPASS(kn->kn_influx > 0);
297 return (kn->kn_influx == 0);
300 #define KNL_ASSERT_LOCK(knl, islocked) do { \
302 KNL_ASSERT_LOCKED(knl); \
304 KNL_ASSERT_UNLOCKED(knl); \
307 #define KNL_ASSERT_LOCKED(knl) do { \
308 knl->kl_assert_lock((knl)->kl_lockarg, LA_LOCKED); \
310 #define KNL_ASSERT_UNLOCKED(knl) do { \
311 knl->kl_assert_lock((knl)->kl_lockarg, LA_UNLOCKED); \
313 #else /* !INVARIANTS */
314 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
315 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
316 #endif /* INVARIANTS */
319 #define KN_HASHSIZE 64 /* XXX should be tunable */
322 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
325 filt_nullattach(struct knote *kn)
331 struct filterops null_filtops = {
333 .f_attach = filt_nullattach,
336 /* XXX - make SYSINIT to add these, and move into respective modules. */
337 extern struct filterops sig_filtops;
338 extern struct filterops fs_filtops;
341 * Table for for all system-defined filters.
343 static struct mtx filterops_lock;
344 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
347 struct filterops *for_fop;
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 */
367 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
371 filt_fileattach(struct knote *kn)
374 return (fo_kqfilter(kn->kn_fp, kn));
379 kqueue_kqfilter(struct file *fp, struct knote *kn)
381 struct kqueue *kq = kn->kn_fp->f_data;
383 if (kn->kn_filter != EVFILT_READ)
386 kn->kn_status |= KN_KQUEUE;
387 kn->kn_fop = &kqread_filtops;
388 knlist_add(&kq->kq_sel.si_note, kn, 0);
394 filt_kqdetach(struct knote *kn)
396 struct kqueue *kq = kn->kn_fp->f_data;
398 knlist_remove(&kq->kq_sel.si_note, kn, 0);
403 filt_kqueue(struct knote *kn, long hint)
405 struct kqueue *kq = kn->kn_fp->f_data;
407 kn->kn_data = kq->kq_count;
408 return (kn->kn_data > 0);
411 /* XXX - move to kern_proc.c? */
413 filt_procattach(struct knote *kn)
417 bool exiting, immediate;
419 exiting = immediate = false;
420 if (kn->kn_sfflags & NOTE_EXIT)
421 p = pfind_any(kn->kn_id);
423 p = pfind(kn->kn_id);
426 if (p->p_flag & P_WEXIT)
429 if ((error = p_cansee(curthread, p))) {
434 kn->kn_ptr.p_proc = p;
435 kn->kn_flags |= EV_CLEAR; /* automatically set */
438 * Internal flag indicating registration done by kernel for the
439 * purposes of getting a NOTE_CHILD notification.
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. */
449 * Internal flag indicating registration done by kernel (for other than
452 if (kn->kn_flags & EV_FLAG1) {
453 kn->kn_flags &= ~EV_FLAG1;
456 knlist_add(p->p_klist, kn, 1);
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
464 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
465 KNOTE_ACTIVATE(kn, 0);
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.
480 /* XXX - move to kern_proc.c? */
482 filt_procdetach(struct knote *kn)
485 knlist_remove(kn->kn_knlist, kn, 0);
486 kn->kn_ptr.p_proc = NULL;
489 /* XXX - move to kern_proc.c? */
491 filt_proc(struct knote *kn, long hint)
496 p = kn->kn_ptr.p_proc;
497 if (p == NULL) /* already activated, from attach filter */
500 /* Mask off extra data. */
501 event = (u_int)hint & NOTE_PCTRLMASK;
503 /* If the user is interested in this event, record it. */
504 if (kn->kn_sfflags & event)
505 kn->kn_fflags |= event;
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;
518 return (kn->kn_fflags != 0);
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
530 knote_fork(struct knlist *list, int pid)
538 KNL_ASSERT_LOCKED(list);
539 if (SLIST_EMPTY(&list->kl_list))
542 memset(&kev, 0, sizeof(kev));
543 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
546 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
552 * The same as knote(), activate the event.
554 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
555 if (kn->kn_fop->f_event(kn, NOTE_FORK))
556 KNOTE_ACTIVATE(kn, 1);
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().
569 list->kl_unlock(list->kl_lockarg);
572 * Activate existing knote and register tracking knotes with
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).
581 kev.filter = kn->kn_filter;
582 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
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);
589 kn->kn_fflags |= NOTE_TRACKERR;
592 * Then register another knote to track other potential events
593 * from the new process.
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);
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);
614 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
615 * interval timer support code.
618 #define NOTE_TIMER_PRECMASK \
619 (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
622 timer2sbintime(int64_t data, int flags)
627 * Macros for converting to the fractional second portion of an
628 * sbintime_t using 64bit multiplication to improve precision.
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) {
636 if (data > (SBT_MAX / SBT_1S))
639 return ((sbintime_t)data << 32);
640 case NOTE_MSECONDS: /* FALLTHROUGH */
645 if (secs > (SBT_MAX / SBT_1S))
648 return (secs << 32 | MS_TO_SBT(data % 1000));
650 return (MS_TO_SBT(data));
652 if (data >= 1000000) {
653 secs = data / 1000000;
655 if (secs > (SBT_MAX / SBT_1S))
658 return (secs << 32 | US_TO_SBT(data % 1000000));
660 return (US_TO_SBT(data));
662 if (data >= 1000000000) {
663 secs = data / 1000000000;
665 if (secs > (SBT_MAX / SBT_1S))
668 return (secs << 32 | US_TO_SBT(data % 1000000000));
670 return (NS_TO_SBT(data));
677 struct kq_timer_cb_data {
679 sbintime_t next; /* next timer event fires at */
680 sbintime_t to; /* precalculated timer period, 0 for abs */
684 filt_timerexpire(void *knx)
687 struct kq_timer_cb_data *kc;
691 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
693 if ((kn->kn_flags & EV_ONESHOT) != 0)
699 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
700 PCPU_GET(cpuid), C_ABSOLUTE);
704 * data contains amount of time to sleep
707 filt_timervalidate(struct knote *kn, sbintime_t *to)
712 if (kn->kn_sdata < 0)
714 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
717 * The only fflags values supported are the timer unit
718 * (precision) and the absolute time indicator.
720 if ((kn->kn_sfflags & ~(NOTE_TIMER_PRECMASK | NOTE_ABSTIME)) != 0)
723 *to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
724 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
735 filt_timerattach(struct knote *kn)
737 struct kq_timer_cb_data *kc;
739 unsigned int ncallouts;
742 error = filt_timervalidate(kn, &to);
747 ncallouts = kq_ncallouts;
748 if (ncallouts >= kq_calloutmax)
750 } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
752 if ((kn->kn_sfflags & NOTE_ABSTIME) == 0)
753 kn->kn_flags |= EV_CLEAR; /* automatically set */
754 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
755 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
756 callout_init(&kc->c, 1);
757 filt_timerstart(kn, to);
763 filt_timerstart(struct knote *kn, sbintime_t to)
765 struct kq_timer_cb_data *kc;
768 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
772 kc->next = to + sbinuptime();
775 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
776 PCPU_GET(cpuid), C_ABSOLUTE);
780 filt_timerdetach(struct knote *kn)
782 struct kq_timer_cb_data *kc;
783 unsigned int old __unused;
786 callout_drain(&kc->c);
788 old = atomic_fetchadd_int(&kq_ncallouts, -1);
789 KASSERT(old > 0, ("Number of callouts cannot become negative"));
790 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
794 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
796 struct kq_timer_cb_data *kc;
803 /* Handle re-added timers that update data/fflags */
804 if (kev->flags & EV_ADD) {
807 /* Drain any existing callout. */
808 callout_drain(&kc->c);
810 /* Throw away any existing undelivered record
811 * of the timer expiration. This is done under
812 * the presumption that if a process is
813 * re-adding this timer with new parameters,
814 * it is no longer interested in what may have
815 * happened under the old parameters. If it is
816 * interested, it can wait for the expiration,
817 * delete the old timer definition, and then
820 * This has to be done while the kq is locked:
821 * - if enqueued, dequeue
822 * - make it no longer active
823 * - clear the count of expiration events
827 if (kn->kn_status & KN_QUEUED)
830 kn->kn_status &= ~KN_ACTIVE;
834 /* Reschedule timer based on new data/fflags */
835 kn->kn_sfflags = kev->fflags;
836 kn->kn_sdata = kev->data;
837 error = filt_timervalidate(kn, &to);
839 kn->kn_flags |= EV_ERROR;
842 filt_timerstart(kn, to);
847 *kev = kn->kn_kevent;
848 if (kn->kn_flags & EV_CLEAR) {
855 panic("filt_timertouch() - invalid type (%ld)", type);
861 filt_timer(struct knote *kn, long hint)
864 return (kn->kn_data != 0);
868 filt_userattach(struct knote *kn)
872 * EVFILT_USER knotes are not attached to anything in the kernel.
875 if (kn->kn_fflags & NOTE_TRIGGER)
883 filt_userdetach(__unused struct knote *kn)
887 * EVFILT_USER knotes are not attached to anything in the kernel.
892 filt_user(struct knote *kn, __unused long hint)
895 return (kn->kn_hookid);
899 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
905 if (kev->fflags & NOTE_TRIGGER)
908 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
909 kev->fflags &= NOTE_FFLAGSMASK;
915 kn->kn_sfflags &= kev->fflags;
919 kn->kn_sfflags |= kev->fflags;
923 kn->kn_sfflags = kev->fflags;
927 /* XXX Return error? */
930 kn->kn_sdata = kev->data;
931 if (kev->flags & EV_CLEAR) {
939 *kev = kn->kn_kevent;
940 kev->fflags = kn->kn_sfflags;
941 kev->data = kn->kn_sdata;
942 if (kn->kn_flags & EV_CLEAR) {
950 panic("filt_usertouch() - invalid type (%ld)", type);
956 sys_kqueue(struct thread *td, struct kqueue_args *uap)
959 return (kern_kqueue(td, 0, NULL));
963 kqueue_init(struct kqueue *kq)
966 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
967 TAILQ_INIT(&kq->kq_head);
968 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
969 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
973 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
975 struct filedesc *fdp;
981 fdp = td->td_proc->p_fd;
983 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
986 error = falloc_caps(td, &fp, &fd, flags, fcaps);
988 chgkqcnt(cred->cr_ruidinfo, -1, 0);
992 /* An extra reference on `fp' has been held for us by falloc(). */
993 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
996 kq->kq_cred = crhold(cred);
999 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
1000 FILEDESC_XUNLOCK(fdp);
1002 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
1005 td->td_retval[0] = fd;
1009 struct g_kevent_args {
1015 const struct timespec *timeout;
1019 sys_kevent(struct thread *td, struct kevent_args *uap)
1021 struct kevent_copyops k_ops = {
1023 .k_copyout = kevent_copyout,
1024 .k_copyin = kevent_copyin,
1025 .kevent_size = sizeof(struct kevent),
1027 struct g_kevent_args gk_args = {
1029 .changelist = uap->changelist,
1030 .nchanges = uap->nchanges,
1031 .eventlist = uap->eventlist,
1032 .nevents = uap->nevents,
1033 .timeout = uap->timeout,
1036 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent"));
1040 kern_kevent_generic(struct thread *td, struct g_kevent_args *uap,
1041 struct kevent_copyops *k_ops, const char *struct_name)
1043 struct timespec ts, *tsp;
1045 struct kevent *eventlist = uap->eventlist;
1049 if (uap->timeout != NULL) {
1050 error = copyin(uap->timeout, &ts, sizeof(ts));
1058 if (KTRPOINT(td, KTR_STRUCT_ARRAY))
1059 ktrstructarray(struct_name, UIO_USERSPACE, uap->changelist,
1060 uap->nchanges, k_ops->kevent_size);
1063 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1067 if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1068 ktrstructarray(struct_name, UIO_USERSPACE, eventlist,
1069 td->td_retval[0], k_ops->kevent_size);
1076 * Copy 'count' items into the destination list pointed to by uap->eventlist.
1079 kevent_copyout(void *arg, struct kevent *kevp, int count)
1081 struct kevent_args *uap;
1084 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1085 uap = (struct kevent_args *)arg;
1087 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1089 uap->eventlist += count;
1094 * Copy 'count' items from the list pointed to by uap->changelist.
1097 kevent_copyin(void *arg, struct kevent *kevp, int count)
1099 struct kevent_args *uap;
1102 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1103 uap = (struct kevent_args *)arg;
1105 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1107 uap->changelist += count;
1111 #ifdef COMPAT_FREEBSD11
1113 kevent11_copyout(void *arg, struct kevent *kevp, int count)
1115 struct freebsd11_kevent_args *uap;
1116 struct kevent_freebsd11 kev11;
1119 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1120 uap = (struct freebsd11_kevent_args *)arg;
1122 for (i = 0; i < count; i++) {
1123 kev11.ident = kevp->ident;
1124 kev11.filter = kevp->filter;
1125 kev11.flags = kevp->flags;
1126 kev11.fflags = kevp->fflags;
1127 kev11.data = kevp->data;
1128 kev11.udata = kevp->udata;
1129 error = copyout(&kev11, uap->eventlist, sizeof(kev11));
1139 * Copy 'count' items from the list pointed to by uap->changelist.
1142 kevent11_copyin(void *arg, struct kevent *kevp, int count)
1144 struct freebsd11_kevent_args *uap;
1145 struct kevent_freebsd11 kev11;
1148 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1149 uap = (struct freebsd11_kevent_args *)arg;
1151 for (i = 0; i < count; i++) {
1152 error = copyin(uap->changelist, &kev11, sizeof(kev11));
1155 kevp->ident = kev11.ident;
1156 kevp->filter = kev11.filter;
1157 kevp->flags = kev11.flags;
1158 kevp->fflags = kev11.fflags;
1159 kevp->data = (uintptr_t)kev11.data;
1160 kevp->udata = kev11.udata;
1161 bzero(&kevp->ext, sizeof(kevp->ext));
1169 freebsd11_kevent(struct thread *td, struct freebsd11_kevent_args *uap)
1171 struct kevent_copyops k_ops = {
1173 .k_copyout = kevent11_copyout,
1174 .k_copyin = kevent11_copyin,
1175 .kevent_size = sizeof(struct kevent_freebsd11),
1177 struct g_kevent_args gk_args = {
1179 .changelist = uap->changelist,
1180 .nchanges = uap->nchanges,
1181 .eventlist = uap->eventlist,
1182 .nevents = uap->nevents,
1183 .timeout = uap->timeout,
1186 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent_freebsd11"));
1191 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1192 struct kevent_copyops *k_ops, const struct timespec *timeout)
1194 cap_rights_t rights;
1198 cap_rights_init_zero(&rights);
1200 cap_rights_set_one(&rights, CAP_KQUEUE_CHANGE);
1202 cap_rights_set_one(&rights, CAP_KQUEUE_EVENT);
1203 error = fget(td, fd, &rights, &fp);
1207 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1214 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1215 struct kevent_copyops *k_ops, const struct timespec *timeout)
1217 struct kevent keva[KQ_NEVENTS];
1218 struct kevent *kevp, *changes;
1219 int i, n, nerrors, error;
1222 while (nchanges > 0) {
1223 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1224 error = k_ops->k_copyin(k_ops->arg, keva, n);
1228 for (i = 0; i < n; i++) {
1232 kevp->flags &= ~EV_SYSFLAGS;
1233 error = kqueue_register(kq, kevp, td, M_WAITOK);
1234 if (error || (kevp->flags & EV_RECEIPT)) {
1237 kevp->flags = EV_ERROR;
1239 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1247 td->td_retval[0] = nerrors;
1251 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1255 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1256 struct kevent_copyops *k_ops, const struct timespec *timeout)
1261 error = kqueue_acquire(fp, &kq);
1264 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1265 kqueue_release(kq, 0);
1270 * Performs a kevent() call on a temporarily created kqueue. This can be
1271 * used to perform one-shot polling, similar to poll() and select().
1274 kern_kevent_anonymous(struct thread *td, int nevents,
1275 struct kevent_copyops *k_ops)
1277 struct kqueue kq = {};
1282 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1283 kqueue_drain(&kq, td);
1284 kqueue_destroy(&kq);
1289 kqueue_add_filteropts(int filt, struct filterops *filtops)
1294 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1296 "trying to add a filterop that is out of range: %d is beyond %d\n",
1297 ~filt, EVFILT_SYSCOUNT);
1300 mtx_lock(&filterops_lock);
1301 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1302 sysfilt_ops[~filt].for_fop != NULL)
1305 sysfilt_ops[~filt].for_fop = filtops;
1306 sysfilt_ops[~filt].for_refcnt = 0;
1308 mtx_unlock(&filterops_lock);
1314 kqueue_del_filteropts(int filt)
1319 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1322 mtx_lock(&filterops_lock);
1323 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1324 sysfilt_ops[~filt].for_fop == NULL)
1326 else if (sysfilt_ops[~filt].for_refcnt != 0)
1329 sysfilt_ops[~filt].for_fop = &null_filtops;
1330 sysfilt_ops[~filt].for_refcnt = 0;
1332 mtx_unlock(&filterops_lock);
1337 static struct filterops *
1338 kqueue_fo_find(int filt)
1341 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1344 if (sysfilt_ops[~filt].for_nolock)
1345 return sysfilt_ops[~filt].for_fop;
1347 mtx_lock(&filterops_lock);
1348 sysfilt_ops[~filt].for_refcnt++;
1349 if (sysfilt_ops[~filt].for_fop == NULL)
1350 sysfilt_ops[~filt].for_fop = &null_filtops;
1351 mtx_unlock(&filterops_lock);
1353 return sysfilt_ops[~filt].for_fop;
1357 kqueue_fo_release(int filt)
1360 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1363 if (sysfilt_ops[~filt].for_nolock)
1366 mtx_lock(&filterops_lock);
1367 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1368 ("filter object refcount not valid on release"));
1369 sysfilt_ops[~filt].for_refcnt--;
1370 mtx_unlock(&filterops_lock);
1374 * A ref to kq (obtained via kqueue_acquire) must be held.
1377 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td,
1380 struct filterops *fops;
1382 struct knote *kn, *tkn;
1384 int error, filt, event;
1385 int haskqglobal, filedesc_unlock;
1387 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1395 filedesc_unlock = 0;
1398 fops = kqueue_fo_find(filt);
1402 if (kev->flags & EV_ADD) {
1404 * Prevent waiting with locks. Non-sleepable
1405 * allocation failures are handled in the loop, only
1406 * if the spare knote appears to be actually required.
1408 tkn = knote_alloc(mflag);
1415 KASSERT(td != NULL, ("td is NULL"));
1416 if (kev->ident > INT_MAX)
1419 error = fget(td, kev->ident, &cap_event_rights, &fp);
1423 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1424 kev->ident, M_NOWAIT) != 0) {
1428 error = kqueue_expand(kq, fops, kev->ident, mflag);
1434 if (fp->f_type == DTYPE_KQUEUE) {
1436 * If we add some intelligence about what we are doing,
1437 * we should be able to support events on ourselves.
1438 * We need to know when we are doing this to prevent
1439 * getting both the knlist lock and the kq lock since
1440 * they are the same thing.
1442 if (fp->f_data == kq) {
1448 * Pre-lock the filedesc before the global
1449 * lock mutex, see the comment in
1452 FILEDESC_XLOCK(td->td_proc->p_fd);
1453 filedesc_unlock = 1;
1454 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1458 if (kev->ident < kq->kq_knlistsize) {
1459 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1460 if (kev->filter == kn->kn_filter)
1464 if ((kev->flags & EV_ADD) == EV_ADD) {
1465 error = kqueue_expand(kq, fops, kev->ident, mflag);
1473 * If possible, find an existing knote to use for this kevent.
1475 if (kev->filter == EVFILT_PROC &&
1476 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1477 /* This is an internal creation of a process tracking
1478 * note. Don't attempt to coalesce this with an
1482 } else if (kq->kq_knhashmask != 0) {
1485 list = &kq->kq_knhash[
1486 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1487 SLIST_FOREACH(kn, list, kn_link)
1488 if (kev->ident == kn->kn_id &&
1489 kev->filter == kn->kn_filter)
1494 /* knote is in the process of changing, wait for it to stabilize. */
1495 if (kn != NULL && kn_in_flux(kn)) {
1496 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1497 if (filedesc_unlock) {
1498 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1499 filedesc_unlock = 0;
1501 kq->kq_state |= KQ_FLUXWAIT;
1502 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1511 * kn now contains the matching knote, or NULL if no match
1514 if (kev->flags & EV_ADD) {
1526 * apply reference counts to knote structure, and
1527 * do not release it at the end of this routine.
1532 kn->kn_sfflags = kev->fflags;
1533 kn->kn_sdata = kev->data;
1536 kn->kn_kevent = *kev;
1537 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1538 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1539 kn->kn_status = KN_DETACHED;
1540 if ((kev->flags & EV_DISABLE) != 0)
1541 kn->kn_status |= KN_DISABLED;
1544 error = knote_attach(kn, kq);
1551 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1552 knote_drop_detached(kn, td);
1555 knl = kn_list_lock(kn);
1558 /* No matching knote and the EV_ADD flag is not set. */
1565 if (kev->flags & EV_DELETE) {
1572 if (kev->flags & EV_FORCEONESHOT) {
1573 kn->kn_flags |= EV_ONESHOT;
1574 KNOTE_ACTIVATE(kn, 1);
1577 if ((kev->flags & EV_ENABLE) != 0)
1578 kn->kn_status &= ~KN_DISABLED;
1579 else if ((kev->flags & EV_DISABLE) != 0)
1580 kn->kn_status |= KN_DISABLED;
1583 * The user may change some filter values after the initial EV_ADD,
1584 * but doing so will not reset any filter which has already been
1587 kn->kn_status |= KN_SCAN;
1590 knl = kn_list_lock(kn);
1591 kn->kn_kevent.udata = kev->udata;
1592 if (!fops->f_isfd && fops->f_touch != NULL) {
1593 fops->f_touch(kn, kev, EVENT_REGISTER);
1595 kn->kn_sfflags = kev->fflags;
1596 kn->kn_sdata = kev->data;
1601 * We can get here with kn->kn_knlist == NULL. This can happen when
1602 * the initial attach event decides that the event is "completed"
1603 * already, e.g., filt_procattach() is called on a zombie process. It
1604 * will call filt_proc() which will remove it from the list, and NULL
1607 * KN_DISABLED will be stable while the knote is in flux, so the
1608 * unlocked read will not race with an update.
1610 if ((kn->kn_status & KN_DISABLED) == 0)
1611 event = kn->kn_fop->f_event(kn, 0);
1617 kn->kn_status |= KN_ACTIVE;
1618 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1621 kn->kn_status &= ~KN_SCAN;
1623 kn_list_unlock(knl);
1627 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1628 if (filedesc_unlock)
1629 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1634 kqueue_fo_release(filt);
1639 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1647 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1651 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1662 kqueue_release(struct kqueue *kq, int locked)
1669 if (kq->kq_refcnt == 1)
1670 wakeup(&kq->kq_refcnt);
1676 kqueue_schedtask(struct kqueue *kq)
1680 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1681 ("scheduling kqueue task while draining"));
1683 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1684 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1685 kq->kq_state |= KQ_TASKSCHED;
1690 * Expand the kq to make sure we have storage for fops/ident pair.
1692 * Return 0 on success (or no work necessary), return errno on failure.
1695 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1698 struct klist *list, *tmp_knhash, *to_free;
1699 u_long tmp_knhashmask;
1700 int error, fd, size;
1708 if (kq->kq_knlistsize <= fd) {
1709 size = kq->kq_knlistsize;
1712 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1716 if ((kq->kq_state & KQ_CLOSING) != 0) {
1719 } else if (kq->kq_knlistsize > fd) {
1722 if (kq->kq_knlist != NULL) {
1723 bcopy(kq->kq_knlist, list,
1724 kq->kq_knlistsize * sizeof(*list));
1725 to_free = kq->kq_knlist;
1726 kq->kq_knlist = NULL;
1728 bzero((caddr_t)list +
1729 kq->kq_knlistsize * sizeof(*list),
1730 (size - kq->kq_knlistsize) * sizeof(*list));
1731 kq->kq_knlistsize = size;
1732 kq->kq_knlist = list;
1737 if (kq->kq_knhashmask == 0) {
1738 tmp_knhash = hashinit_flags(KN_HASHSIZE, M_KQUEUE,
1739 &tmp_knhashmask, (mflag & M_WAITOK) != 0 ?
1740 HASH_WAITOK : HASH_NOWAIT);
1741 if (tmp_knhash == NULL)
1744 if ((kq->kq_state & KQ_CLOSING) != 0) {
1745 to_free = tmp_knhash;
1747 } else if (kq->kq_knhashmask == 0) {
1748 kq->kq_knhash = tmp_knhash;
1749 kq->kq_knhashmask = tmp_knhashmask;
1751 to_free = tmp_knhash;
1756 free(to_free, M_KQUEUE);
1763 kqueue_task(void *arg, int pending)
1771 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1774 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1776 kq->kq_state &= ~KQ_TASKSCHED;
1777 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1778 wakeup(&kq->kq_state);
1781 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1785 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1786 * We treat KN_MARKER knotes as if they are in flux.
1789 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1790 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1792 struct kevent *kevp;
1793 struct knote *kn, *marker;
1795 sbintime_t asbt, rsbt;
1796 int count, error, haskqglobal, influx, nkev, touch;
1808 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1809 tsp->tv_nsec >= 1000000000) {
1813 if (timespecisset(tsp)) {
1814 if (tsp->tv_sec <= INT32_MAX) {
1815 rsbt = tstosbt(*tsp);
1816 if (TIMESEL(&asbt, rsbt))
1817 asbt += tc_tick_sbt;
1818 if (asbt <= SBT_MAX - rsbt)
1822 rsbt >>= tc_precexp;
1829 marker = knote_alloc(M_WAITOK);
1830 marker->kn_status = KN_MARKER;
1835 if (kq->kq_count == 0) {
1837 error = EWOULDBLOCK;
1839 kq->kq_state |= KQ_SLEEP;
1840 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1841 "kqread", asbt, rsbt, C_ABSOLUTE);
1845 /* don't restart after signals... */
1846 if (error == ERESTART)
1848 else if (error == EWOULDBLOCK)
1853 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1857 kn = TAILQ_FIRST(&kq->kq_head);
1859 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1865 kq->kq_state |= KQ_FLUXWAIT;
1866 error = msleep(kq, &kq->kq_lock, PSOCK,
1871 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1872 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1873 kn->kn_status &= ~KN_QUEUED;
1879 if (count == maxevents)
1883 KASSERT(!kn_in_flux(kn),
1884 ("knote %p is unexpectedly in flux", kn));
1886 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1887 kn->kn_status &= ~KN_QUEUED;
1892 * We don't need to lock the list since we've
1893 * marked it as in flux.
1898 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1899 kn->kn_status &= ~KN_QUEUED;
1904 * We don't need to lock the list since we've
1905 * marked the knote as being in flux.
1907 *kevp = kn->kn_kevent;
1912 kn->kn_status |= KN_SCAN;
1915 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1916 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1917 knl = kn_list_lock(kn);
1918 if (kn->kn_fop->f_event(kn, 0) == 0) {
1920 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1921 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
1925 kn_list_unlock(knl);
1929 touch = (!kn->kn_fop->f_isfd &&
1930 kn->kn_fop->f_touch != NULL);
1932 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1934 *kevp = kn->kn_kevent;
1936 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1937 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1939 * Manually clear knotes who weren't
1942 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1946 if (kn->kn_flags & EV_DISPATCH)
1947 kn->kn_status |= KN_DISABLED;
1948 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1951 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1953 kn->kn_status &= ~KN_SCAN;
1955 kn_list_unlock(knl);
1959 /* we are returning a copy to the user */
1964 if (nkev == KQ_NEVENTS) {
1967 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1975 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1983 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1984 td->td_retval[0] = maxevents - count;
1990 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1991 struct ucred *active_cred, struct thread *td)
1994 * Enabling sigio causes two major problems:
1995 * 1) infinite recursion:
1996 * Synopsys: kevent is being used to track signals and have FIOASYNC
1997 * set. On receipt of a signal this will cause a kqueue to recurse
1998 * into itself over and over. Sending the sigio causes the kqueue
1999 * to become ready, which in turn posts sigio again, forever.
2000 * Solution: this can be solved by setting a flag in the kqueue that
2001 * we have a SIGIO in progress.
2002 * 2) locking problems:
2003 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
2004 * us above the proc and pgrp locks.
2005 * Solution: Post a signal using an async mechanism, being sure to
2006 * record a generation count in the delivery so that we do not deliver
2007 * a signal to the wrong process.
2009 * Note, these two mechanisms are somewhat mutually exclusive!
2018 kq->kq_state |= KQ_ASYNC;
2020 kq->kq_state &= ~KQ_ASYNC;
2025 return (fsetown(*(int *)data, &kq->kq_sigio));
2028 *(int *)data = fgetown(&kq->kq_sigio);
2038 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
2045 if ((error = kqueue_acquire(fp, &kq)))
2049 if (events & (POLLIN | POLLRDNORM)) {
2051 revents |= events & (POLLIN | POLLRDNORM);
2053 selrecord(td, &kq->kq_sel);
2054 if (SEL_WAITING(&kq->kq_sel))
2055 kq->kq_state |= KQ_SEL;
2058 kqueue_release(kq, 1);
2065 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
2069 bzero((void *)st, sizeof *st);
2071 * We no longer return kq_count because the unlocked value is useless.
2072 * If you spent all this time getting the count, why not spend your
2073 * syscall better by calling kevent?
2075 * XXX - This is needed for libc_r.
2077 st->st_mode = S_IFIFO;
2082 kqueue_drain(struct kqueue *kq, struct thread *td)
2089 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
2090 ("kqueue already closing"));
2091 kq->kq_state |= KQ_CLOSING;
2092 if (kq->kq_refcnt > 1)
2093 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
2095 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
2097 KASSERT(knlist_empty(&kq->kq_sel.si_note),
2098 ("kqueue's knlist not empty"));
2100 for (i = 0; i < kq->kq_knlistsize; i++) {
2101 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
2102 if (kn_in_flux(kn)) {
2103 kq->kq_state |= KQ_FLUXWAIT;
2104 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
2113 if (kq->kq_knhashmask != 0) {
2114 for (i = 0; i <= kq->kq_knhashmask; i++) {
2115 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
2116 if (kn_in_flux(kn)) {
2117 kq->kq_state |= KQ_FLUXWAIT;
2118 msleep(kq, &kq->kq_lock, PSOCK,
2130 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
2131 kq->kq_state |= KQ_TASKDRAIN;
2132 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2135 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2136 selwakeuppri(&kq->kq_sel, PSOCK);
2137 if (!SEL_WAITING(&kq->kq_sel))
2138 kq->kq_state &= ~KQ_SEL;
2145 kqueue_destroy(struct kqueue *kq)
2148 KASSERT(kq->kq_fdp == NULL,
2149 ("kqueue still attached to a file descriptor"));
2150 seldrain(&kq->kq_sel);
2151 knlist_destroy(&kq->kq_sel.si_note);
2152 mtx_destroy(&kq->kq_lock);
2154 if (kq->kq_knhash != NULL)
2155 free(kq->kq_knhash, M_KQUEUE);
2156 if (kq->kq_knlist != NULL)
2157 free(kq->kq_knlist, M_KQUEUE);
2159 funsetown(&kq->kq_sigio);
2164 kqueue_close(struct file *fp, struct thread *td)
2166 struct kqueue *kq = fp->f_data;
2167 struct filedesc *fdp;
2169 int filedesc_unlock;
2171 if ((error = kqueue_acquire(fp, &kq)))
2173 kqueue_drain(kq, td);
2176 * We could be called due to the knote_drop() doing fdrop(),
2177 * called from kqueue_register(). In this case the global
2178 * lock is owned, and filedesc sx is locked before, to not
2179 * take the sleepable lock after non-sleepable.
2183 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2184 FILEDESC_XLOCK(fdp);
2185 filedesc_unlock = 1;
2187 filedesc_unlock = 0;
2188 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2189 if (filedesc_unlock)
2190 FILEDESC_XUNLOCK(fdp);
2193 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2194 crfree(kq->kq_cred);
2202 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2205 kif->kf_type = KF_TYPE_KQUEUE;
2210 kqueue_wakeup(struct kqueue *kq)
2214 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2215 kq->kq_state &= ~KQ_SLEEP;
2218 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2219 selwakeuppri(&kq->kq_sel, PSOCK);
2220 if (!SEL_WAITING(&kq->kq_sel))
2221 kq->kq_state &= ~KQ_SEL;
2223 if (!knlist_empty(&kq->kq_sel.si_note))
2224 kqueue_schedtask(kq);
2225 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2226 pgsigio(&kq->kq_sigio, SIGIO, 0);
2231 * Walk down a list of knotes, activating them if their event has triggered.
2233 * There is a possibility to optimize in the case of one kq watching another.
2234 * Instead of scheduling a task to wake it up, you could pass enough state
2235 * down the chain to make up the parent kqueue. Make this code functional
2239 knote(struct knlist *list, long hint, int lockflags)
2242 struct knote *kn, *tkn;
2248 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2250 if ((lockflags & KNF_LISTLOCKED) == 0)
2251 list->kl_lock(list->kl_lockarg);
2254 * If we unlock the list lock (and enter influx), we can
2255 * eliminate the kqueue scheduling, but this will introduce
2256 * four lock/unlock's for each knote to test. Also, marker
2257 * would be needed to keep iteration position, since filters
2258 * or other threads could remove events.
2260 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2263 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2265 * Do not process the influx notes, except for
2266 * the influx coming from the kq unlock in the
2267 * kqueue_scan(). In the later case, we do
2268 * not interfere with the scan, since the code
2269 * fragment in kqueue_scan() locks the knlist,
2270 * and cannot proceed until we finished.
2273 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2276 error = kn->kn_fop->f_event(kn, hint);
2280 KNOTE_ACTIVATE(kn, 1);
2283 if (kn->kn_fop->f_event(kn, hint))
2284 KNOTE_ACTIVATE(kn, 1);
2288 if ((lockflags & KNF_LISTLOCKED) == 0)
2289 list->kl_unlock(list->kl_lockarg);
2293 * add a knote to a knlist
2296 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2299 KNL_ASSERT_LOCK(knl, islocked);
2300 KQ_NOTOWNED(kn->kn_kq);
2301 KASSERT(kn_in_flux(kn), ("knote %p not in flux", kn));
2302 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2303 ("knote %p was not detached", kn));
2305 knl->kl_lock(knl->kl_lockarg);
2306 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2308 knl->kl_unlock(knl->kl_lockarg);
2310 kn->kn_knlist = knl;
2311 kn->kn_status &= ~KN_DETACHED;
2312 KQ_UNLOCK(kn->kn_kq);
2316 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2320 KASSERT(!kqislocked || knlislocked, ("kq locked w/o knl locked"));
2321 KNL_ASSERT_LOCK(knl, knlislocked);
2322 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2323 KASSERT(kqislocked || kn_in_flux(kn), ("knote %p not in flux", kn));
2324 KASSERT((kn->kn_status & KN_DETACHED) == 0,
2325 ("knote %p was already detached", kn));
2327 knl->kl_lock(knl->kl_lockarg);
2328 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2329 kn->kn_knlist = NULL;
2331 kn_list_unlock(knl);
2334 kn->kn_status |= KN_DETACHED;
2336 KQ_UNLOCK(kn->kn_kq);
2340 * remove knote from the specified knlist
2343 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2346 knlist_remove_kq(knl, kn, islocked, 0);
2350 knlist_empty(struct knlist *knl)
2353 KNL_ASSERT_LOCKED(knl);
2354 return (SLIST_EMPTY(&knl->kl_list));
2357 static struct mtx knlist_lock;
2358 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2360 static void knlist_mtx_lock(void *arg);
2361 static void knlist_mtx_unlock(void *arg);
2364 knlist_mtx_lock(void *arg)
2367 mtx_lock((struct mtx *)arg);
2371 knlist_mtx_unlock(void *arg)
2374 mtx_unlock((struct mtx *)arg);
2378 knlist_mtx_assert_lock(void *arg, int what)
2381 if (what == LA_LOCKED)
2382 mtx_assert((struct mtx *)arg, MA_OWNED);
2384 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2388 knlist_rw_rlock(void *arg)
2391 rw_rlock((struct rwlock *)arg);
2395 knlist_rw_runlock(void *arg)
2398 rw_runlock((struct rwlock *)arg);
2402 knlist_rw_assert_lock(void *arg, int what)
2405 if (what == LA_LOCKED)
2406 rw_assert((struct rwlock *)arg, RA_LOCKED);
2408 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2412 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2413 void (*kl_unlock)(void *),
2414 void (*kl_assert_lock)(void *, int))
2418 knl->kl_lockarg = &knlist_lock;
2420 knl->kl_lockarg = lock;
2422 if (kl_lock == NULL)
2423 knl->kl_lock = knlist_mtx_lock;
2425 knl->kl_lock = kl_lock;
2426 if (kl_unlock == NULL)
2427 knl->kl_unlock = knlist_mtx_unlock;
2429 knl->kl_unlock = kl_unlock;
2430 if (kl_assert_lock == NULL)
2431 knl->kl_assert_lock = knlist_mtx_assert_lock;
2433 knl->kl_assert_lock = kl_assert_lock;
2435 knl->kl_autodestroy = 0;
2436 SLIST_INIT(&knl->kl_list);
2440 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2443 knlist_init(knl, lock, NULL, NULL, NULL);
2447 knlist_alloc(struct mtx *lock)
2451 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2452 knlist_init_mtx(knl, lock);
2457 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2460 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2461 knlist_rw_assert_lock);
2465 knlist_destroy(struct knlist *knl)
2468 KASSERT(KNLIST_EMPTY(knl),
2469 ("destroying knlist %p with knotes on it", knl));
2473 knlist_detach(struct knlist *knl)
2476 KNL_ASSERT_LOCKED(knl);
2477 knl->kl_autodestroy = 1;
2478 if (knlist_empty(knl)) {
2479 knlist_destroy(knl);
2480 free(knl, M_KQUEUE);
2485 * Even if we are locked, we may need to drop the lock to allow any influx
2486 * knotes time to "settle".
2489 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2491 struct knote *kn, *kn2;
2494 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2496 KNL_ASSERT_LOCKED(knl);
2498 KNL_ASSERT_UNLOCKED(knl);
2499 again: /* need to reacquire lock since we have dropped it */
2500 knl->kl_lock(knl->kl_lockarg);
2503 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2506 if (kn_in_flux(kn)) {
2510 knlist_remove_kq(knl, kn, 1, 1);
2514 knote_drop_detached(kn, td);
2516 /* Make sure cleared knotes disappear soon */
2517 kn->kn_flags |= EV_EOF | EV_ONESHOT;
2523 if (!SLIST_EMPTY(&knl->kl_list)) {
2524 /* there are still in flux knotes remaining */
2525 kn = SLIST_FIRST(&knl->kl_list);
2528 KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2529 knl->kl_unlock(knl->kl_lockarg);
2530 kq->kq_state |= KQ_FLUXWAIT;
2531 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2537 KNL_ASSERT_LOCKED(knl);
2539 knl->kl_unlock(knl->kl_lockarg);
2540 KNL_ASSERT_UNLOCKED(knl);
2545 * Remove all knotes referencing a specified fd must be called with FILEDESC
2546 * lock. This prevents a race where a new fd comes along and occupies the
2547 * entry and we attach a knote to the fd.
2550 knote_fdclose(struct thread *td, int fd)
2552 struct filedesc *fdp = td->td_proc->p_fd;
2557 FILEDESC_XLOCK_ASSERT(fdp);
2560 * We shouldn't have to worry about new kevents appearing on fd
2561 * since filedesc is locked.
2563 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2568 while (kq->kq_knlistsize > fd &&
2569 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2570 if (kn_in_flux(kn)) {
2571 /* someone else might be waiting on our knote */
2574 kq->kq_state |= KQ_FLUXWAIT;
2575 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2589 knote_attach(struct knote *kn, struct kqueue *kq)
2593 KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2596 if ((kq->kq_state & KQ_CLOSING) != 0)
2598 if (kn->kn_fop->f_isfd) {
2599 if (kn->kn_id >= kq->kq_knlistsize)
2601 list = &kq->kq_knlist[kn->kn_id];
2603 if (kq->kq_knhash == NULL)
2605 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2607 SLIST_INSERT_HEAD(list, kn, kn_link);
2612 knote_drop(struct knote *kn, struct thread *td)
2615 if ((kn->kn_status & KN_DETACHED) == 0)
2616 kn->kn_fop->f_detach(kn);
2617 knote_drop_detached(kn, td);
2621 knote_drop_detached(struct knote *kn, struct thread *td)
2628 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2629 ("knote %p still attached", kn));
2633 KASSERT(kn->kn_influx == 1,
2634 ("knote_drop called on %p with influx %d", kn, kn->kn_influx));
2636 if (kn->kn_fop->f_isfd)
2637 list = &kq->kq_knlist[kn->kn_id];
2639 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2641 if (!SLIST_EMPTY(list))
2642 SLIST_REMOVE(list, kn, knote, kn_link);
2643 if (kn->kn_status & KN_QUEUED)
2647 if (kn->kn_fop->f_isfd) {
2648 fdrop(kn->kn_fp, td);
2651 kqueue_fo_release(kn->kn_kevent.filter);
2657 knote_enqueue(struct knote *kn)
2659 struct kqueue *kq = kn->kn_kq;
2661 KQ_OWNED(kn->kn_kq);
2662 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2664 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2665 kn->kn_status |= KN_QUEUED;
2671 knote_dequeue(struct knote *kn)
2673 struct kqueue *kq = kn->kn_kq;
2675 KQ_OWNED(kn->kn_kq);
2676 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2678 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2679 kn->kn_status &= ~KN_QUEUED;
2687 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2688 NULL, NULL, UMA_ALIGN_PTR, 0);
2690 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2692 static struct knote *
2693 knote_alloc(int mflag)
2696 return (uma_zalloc(knote_zone, mflag | M_ZERO));
2700 knote_free(struct knote *kn)
2703 uma_zfree(knote_zone, kn);
2707 * Register the kev w/ the kq specified by fd.
2710 kqfd_register(int fd, struct kevent *kev, struct thread *td, int mflag)
2714 cap_rights_t rights;
2717 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2720 if ((error = kqueue_acquire(fp, &kq)) != 0)
2723 error = kqueue_register(kq, kev, td, mflag);
2724 kqueue_release(kq, 0);