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>
46 #include <sys/mutex.h>
47 #include <sys/rwlock.h>
49 #include <sys/malloc.h>
50 #include <sys/unistd.h>
52 #include <sys/filedesc.h>
53 #include <sys/filio.h>
54 #include <sys/fcntl.h>
55 #include <sys/kthread.h>
56 #include <sys/selinfo.h>
57 #include <sys/queue.h>
58 #include <sys/event.h>
59 #include <sys/eventvar.h>
61 #include <sys/protosw.h>
62 #include <sys/resourcevar.h>
63 #include <sys/sigio.h>
64 #include <sys/signalvar.h>
65 #include <sys/socket.h>
66 #include <sys/socketvar.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysproto.h>
70 #include <sys/syscallsubr.h>
71 #include <sys/taskqueue.h>
75 #include <sys/ktrace.h>
77 #include <machine/atomic.h>
81 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
84 * This lock is used if multiple kq locks are required. This possibly
85 * should be made into a per proc lock.
87 static struct mtx kq_global;
88 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
89 #define KQ_GLOBAL_LOCK(lck, haslck) do { \
94 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
100 TASKQUEUE_DEFINE_THREAD(kqueue_ctx);
102 static int kevent_copyout(void *arg, struct kevent *kevp, int count);
103 static int kevent_copyin(void *arg, struct kevent *kevp, int count);
104 static int kqueue_register(struct kqueue *kq, struct kevent *kev,
105 struct thread *td, int waitok);
106 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
107 static void kqueue_release(struct kqueue *kq, int locked);
108 static void kqueue_destroy(struct kqueue *kq);
109 static void kqueue_drain(struct kqueue *kq, struct thread *td);
110 static int kqueue_expand(struct kqueue *kq, struct filterops *fops,
111 uintptr_t ident, int waitok);
112 static void kqueue_task(void *arg, int pending);
113 static int kqueue_scan(struct kqueue *kq, int maxevents,
114 struct kevent_copyops *k_ops,
115 const struct timespec *timeout,
116 struct kevent *keva, struct thread *td);
117 static void kqueue_wakeup(struct kqueue *kq);
118 static struct filterops *kqueue_fo_find(int filt);
119 static void kqueue_fo_release(int filt);
120 struct g_kevent_args;
121 static int kern_kevent_generic(struct thread *td,
122 struct g_kevent_args *uap,
123 struct kevent_copyops *k_ops, const char *struct_name);
125 static fo_ioctl_t kqueue_ioctl;
126 static fo_poll_t kqueue_poll;
127 static fo_kqfilter_t kqueue_kqfilter;
128 static fo_stat_t kqueue_stat;
129 static fo_close_t kqueue_close;
130 static fo_fill_kinfo_t kqueue_fill_kinfo;
132 static struct fileops kqueueops = {
133 .fo_read = invfo_rdwr,
134 .fo_write = invfo_rdwr,
135 .fo_truncate = invfo_truncate,
136 .fo_ioctl = kqueue_ioctl,
137 .fo_poll = kqueue_poll,
138 .fo_kqfilter = kqueue_kqfilter,
139 .fo_stat = kqueue_stat,
140 .fo_close = kqueue_close,
141 .fo_chmod = invfo_chmod,
142 .fo_chown = invfo_chown,
143 .fo_sendfile = invfo_sendfile,
144 .fo_fill_kinfo = kqueue_fill_kinfo,
147 static int knote_attach(struct knote *kn, struct kqueue *kq);
148 static void knote_drop(struct knote *kn, struct thread *td);
149 static void knote_drop_detached(struct knote *kn, struct thread *td);
150 static void knote_enqueue(struct knote *kn);
151 static void knote_dequeue(struct knote *kn);
152 static void knote_init(void);
153 static struct knote *knote_alloc(int waitok);
154 static void knote_free(struct knote *kn);
156 static void filt_kqdetach(struct knote *kn);
157 static int filt_kqueue(struct knote *kn, long hint);
158 static int filt_procattach(struct knote *kn);
159 static void filt_procdetach(struct knote *kn);
160 static int filt_proc(struct knote *kn, long hint);
161 static int filt_fileattach(struct knote *kn);
162 static void filt_timerexpire(void *knx);
163 static int filt_timerattach(struct knote *kn);
164 static void filt_timerdetach(struct knote *kn);
165 static void filt_timerstart(struct knote *kn, sbintime_t to);
166 static void filt_timertouch(struct knote *kn, struct kevent *kev,
168 static int filt_timervalidate(struct knote *kn, sbintime_t *to);
169 static int filt_timer(struct knote *kn, long hint);
170 static int filt_userattach(struct knote *kn);
171 static void filt_userdetach(struct knote *kn);
172 static int filt_user(struct knote *kn, long hint);
173 static void filt_usertouch(struct knote *kn, struct kevent *kev,
176 static struct filterops file_filtops = {
178 .f_attach = filt_fileattach,
180 static struct filterops kqread_filtops = {
182 .f_detach = filt_kqdetach,
183 .f_event = filt_kqueue,
185 /* XXX - move to kern_proc.c? */
186 static struct filterops proc_filtops = {
188 .f_attach = filt_procattach,
189 .f_detach = filt_procdetach,
190 .f_event = filt_proc,
192 static struct filterops timer_filtops = {
194 .f_attach = filt_timerattach,
195 .f_detach = filt_timerdetach,
196 .f_event = filt_timer,
197 .f_touch = filt_timertouch,
199 static struct filterops user_filtops = {
200 .f_attach = filt_userattach,
201 .f_detach = filt_userdetach,
202 .f_event = filt_user,
203 .f_touch = filt_usertouch,
206 static uma_zone_t knote_zone;
207 static unsigned int kq_ncallouts = 0;
208 static unsigned int kq_calloutmax = 4 * 1024;
209 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
210 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
212 /* XXX - ensure not influx ? */
213 #define KNOTE_ACTIVATE(kn, islock) do { \
215 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
217 KQ_LOCK((kn)->kn_kq); \
218 (kn)->kn_status |= KN_ACTIVE; \
219 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
220 knote_enqueue((kn)); \
222 KQ_UNLOCK((kn)->kn_kq); \
224 #define KQ_LOCK(kq) do { \
225 mtx_lock(&(kq)->kq_lock); \
227 #define KQ_FLUX_WAKEUP(kq) do { \
228 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
229 (kq)->kq_state &= ~KQ_FLUXWAIT; \
233 #define KQ_UNLOCK_FLUX(kq) do { \
234 KQ_FLUX_WAKEUP(kq); \
235 mtx_unlock(&(kq)->kq_lock); \
237 #define KQ_UNLOCK(kq) do { \
238 mtx_unlock(&(kq)->kq_lock); \
240 #define KQ_OWNED(kq) do { \
241 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
243 #define KQ_NOTOWNED(kq) do { \
244 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
247 static struct knlist *
248 kn_list_lock(struct knote *kn)
254 knl->kl_lock(knl->kl_lockarg);
259 kn_list_unlock(struct knlist *knl)
265 do_free = knl->kl_autodestroy && knlist_empty(knl);
266 knl->kl_unlock(knl->kl_lockarg);
274 kn_in_flux(struct knote *kn)
277 return (kn->kn_influx > 0);
281 kn_enter_flux(struct knote *kn)
285 MPASS(kn->kn_influx < INT_MAX);
290 kn_leave_flux(struct knote *kn)
294 MPASS(kn->kn_influx > 0);
296 return (kn->kn_influx == 0);
299 #define KNL_ASSERT_LOCK(knl, islocked) do { \
301 KNL_ASSERT_LOCKED(knl); \
303 KNL_ASSERT_UNLOCKED(knl); \
306 #define KNL_ASSERT_LOCKED(knl) do { \
307 knl->kl_assert_locked((knl)->kl_lockarg); \
309 #define KNL_ASSERT_UNLOCKED(knl) do { \
310 knl->kl_assert_unlocked((knl)->kl_lockarg); \
312 #else /* !INVARIANTS */
313 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
314 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
315 #endif /* INVARIANTS */
318 #define KN_HASHSIZE 64 /* XXX should be tunable */
321 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
324 filt_nullattach(struct knote *kn)
330 struct filterops null_filtops = {
332 .f_attach = filt_nullattach,
335 /* XXX - make SYSINIT to add these, and move into respective modules. */
336 extern struct filterops sig_filtops;
337 extern struct filterops fs_filtops;
340 * Table for for all system-defined filters.
342 static struct mtx filterops_lock;
343 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
346 struct filterops *for_fop;
349 } sysfilt_ops[EVFILT_SYSCOUNT] = {
350 { &file_filtops, 1 }, /* EVFILT_READ */
351 { &file_filtops, 1 }, /* EVFILT_WRITE */
352 { &null_filtops }, /* EVFILT_AIO */
353 { &file_filtops, 1 }, /* EVFILT_VNODE */
354 { &proc_filtops, 1 }, /* EVFILT_PROC */
355 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
356 { &timer_filtops, 1 }, /* EVFILT_TIMER */
357 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
358 { &fs_filtops, 1 }, /* EVFILT_FS */
359 { &null_filtops }, /* EVFILT_LIO */
360 { &user_filtops, 1 }, /* EVFILT_USER */
361 { &null_filtops }, /* EVFILT_SENDFILE */
362 { &file_filtops, 1 }, /* EVFILT_EMPTY */
366 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
370 filt_fileattach(struct knote *kn)
373 return (fo_kqfilter(kn->kn_fp, kn));
378 kqueue_kqfilter(struct file *fp, struct knote *kn)
380 struct kqueue *kq = kn->kn_fp->f_data;
382 if (kn->kn_filter != EVFILT_READ)
385 kn->kn_status |= KN_KQUEUE;
386 kn->kn_fop = &kqread_filtops;
387 knlist_add(&kq->kq_sel.si_note, kn, 0);
393 filt_kqdetach(struct knote *kn)
395 struct kqueue *kq = kn->kn_fp->f_data;
397 knlist_remove(&kq->kq_sel.si_note, kn, 0);
402 filt_kqueue(struct knote *kn, long hint)
404 struct kqueue *kq = kn->kn_fp->f_data;
406 kn->kn_data = kq->kq_count;
407 return (kn->kn_data > 0);
410 /* XXX - move to kern_proc.c? */
412 filt_procattach(struct knote *kn)
416 bool exiting, immediate;
418 exiting = immediate = false;
419 if (kn->kn_sfflags & NOTE_EXIT)
420 p = pfind_any(kn->kn_id);
422 p = pfind(kn->kn_id);
425 if (p->p_flag & P_WEXIT)
428 if ((error = p_cansee(curthread, p))) {
433 kn->kn_ptr.p_proc = p;
434 kn->kn_flags |= EV_CLEAR; /* automatically set */
437 * Internal flag indicating registration done by kernel for the
438 * purposes of getting a NOTE_CHILD notification.
440 if (kn->kn_flags & EV_FLAG2) {
441 kn->kn_flags &= ~EV_FLAG2;
442 kn->kn_data = kn->kn_sdata; /* ppid */
443 kn->kn_fflags = NOTE_CHILD;
444 kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
445 immediate = true; /* Force immediate activation of child note. */
448 * Internal flag indicating registration done by kernel (for other than
451 if (kn->kn_flags & EV_FLAG1) {
452 kn->kn_flags &= ~EV_FLAG1;
455 knlist_add(p->p_klist, kn, 1);
458 * Immediately activate any child notes or, in the case of a zombie
459 * target process, exit notes. The latter is necessary to handle the
460 * case where the target process, e.g. a child, dies before the kevent
463 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
464 KNOTE_ACTIVATE(kn, 0);
472 * The knote may be attached to a different process, which may exit,
473 * leaving nothing for the knote to be attached to. So when the process
474 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
475 * it will be deleted when read out. However, as part of the knote deletion,
476 * this routine is called, so a check is needed to avoid actually performing
477 * a detach, because the original process does not exist any more.
479 /* XXX - move to kern_proc.c? */
481 filt_procdetach(struct knote *kn)
484 knlist_remove(kn->kn_knlist, kn, 0);
485 kn->kn_ptr.p_proc = NULL;
488 /* XXX - move to kern_proc.c? */
490 filt_proc(struct knote *kn, long hint)
495 p = kn->kn_ptr.p_proc;
496 if (p == NULL) /* already activated, from attach filter */
499 /* Mask off extra data. */
500 event = (u_int)hint & NOTE_PCTRLMASK;
502 /* If the user is interested in this event, record it. */
503 if (kn->kn_sfflags & event)
504 kn->kn_fflags |= event;
506 /* Process is gone, so flag the event as finished. */
507 if (event == NOTE_EXIT) {
508 kn->kn_flags |= EV_EOF | EV_ONESHOT;
509 kn->kn_ptr.p_proc = NULL;
510 if (kn->kn_fflags & NOTE_EXIT)
511 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
512 if (kn->kn_fflags == 0)
513 kn->kn_flags |= EV_DROP;
517 return (kn->kn_fflags != 0);
521 * Called when the process forked. It mostly does the same as the
522 * knote(), activating all knotes registered to be activated when the
523 * process forked. Additionally, for each knote attached to the
524 * parent, check whether user wants to track the new process. If so
525 * attach a new knote to it, and immediately report an event with the
529 knote_fork(struct knlist *list, int pid)
539 memset(&kev, 0, sizeof(kev));
540 list->kl_lock(list->kl_lockarg);
541 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
544 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
550 * The same as knote(), activate the event.
552 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
553 kn->kn_status |= KN_HASKQLOCK;
554 if (kn->kn_fop->f_event(kn, NOTE_FORK))
555 KNOTE_ACTIVATE(kn, 1);
556 kn->kn_status &= ~KN_HASKQLOCK;
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, 0);
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, 0);
603 kn->kn_fflags |= NOTE_TRACKERR;
604 if (kn->kn_fop->f_event(kn, NOTE_FORK))
605 KNOTE_ACTIVATE(kn, 0);
609 list->kl_lock(list->kl_lockarg);
611 list->kl_unlock(list->kl_lockarg);
615 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
616 * interval timer support code.
619 #define NOTE_TIMER_PRECMASK \
620 (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
623 timer2sbintime(intptr_t data, int flags)
628 * Macros for converting to the fractional second portion of an
629 * sbintime_t using 64bit multiplication to improve precision.
631 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
632 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
633 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
634 switch (flags & NOTE_TIMER_PRECMASK) {
637 if (data > (SBT_MAX / SBT_1S))
640 return ((sbintime_t)data << 32);
641 case NOTE_MSECONDS: /* FALLTHROUGH */
646 if (secs > (SBT_MAX / SBT_1S))
649 return (secs << 32 | MS_TO_SBT(data % 1000));
651 return (MS_TO_SBT(data));
653 if (data >= 1000000) {
654 secs = data / 1000000;
656 if (secs > (SBT_MAX / SBT_1S))
659 return (secs << 32 | US_TO_SBT(data % 1000000));
661 return (US_TO_SBT(data));
663 if (data >= 1000000000) {
664 secs = data / 1000000000;
666 if (secs > (SBT_MAX / SBT_1S))
669 return (secs << 32 | US_TO_SBT(data % 1000000000));
671 return (NS_TO_SBT(data));
678 struct kq_timer_cb_data {
680 sbintime_t next; /* next timer event fires at */
681 sbintime_t to; /* precalculated timer period, 0 for abs */
685 filt_timerexpire(void *knx)
688 struct kq_timer_cb_data *kc;
692 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
694 if ((kn->kn_flags & EV_ONESHOT) != 0)
700 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
701 PCPU_GET(cpuid), C_ABSOLUTE);
705 * data contains amount of time to sleep
708 filt_timervalidate(struct knote *kn, sbintime_t *to)
713 if (kn->kn_sdata < 0)
715 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
718 * The only fflags values supported are the timer unit
719 * (precision) and the absolute time indicator.
721 if ((kn->kn_sfflags & ~(NOTE_TIMER_PRECMASK | NOTE_ABSTIME)) != 0)
724 *to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
725 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
736 filt_timerattach(struct knote *kn)
738 struct kq_timer_cb_data *kc;
740 unsigned int ncallouts;
743 error = filt_timervalidate(kn, &to);
748 ncallouts = kq_ncallouts;
749 if (ncallouts >= kq_calloutmax)
751 } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
753 if ((kn->kn_sfflags & NOTE_ABSTIME) == 0)
754 kn->kn_flags |= EV_CLEAR; /* automatically set */
755 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
756 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
757 callout_init(&kc->c, 1);
758 filt_timerstart(kn, to);
764 filt_timerstart(struct knote *kn, sbintime_t to)
766 struct kq_timer_cb_data *kc;
769 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
773 kc->next = to + sbinuptime();
776 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
777 PCPU_GET(cpuid), C_ABSOLUTE);
781 filt_timerdetach(struct knote *kn)
783 struct kq_timer_cb_data *kc;
784 unsigned int old __unused;
787 callout_drain(&kc->c);
789 old = atomic_fetchadd_int(&kq_ncallouts, -1);
790 KASSERT(old > 0, ("Number of callouts cannot become negative"));
791 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
795 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
797 struct kq_timer_cb_data *kc;
804 /* Handle re-added timers that update data/fflags */
805 if (kev->flags & EV_ADD) {
808 /* Drain any existing callout. */
809 callout_drain(&kc->c);
811 /* Throw away any existing undelivered record
812 * of the timer expiration. This is done under
813 * the presumption that if a process is
814 * re-adding this timer with new parameters,
815 * it is no longer interested in what may have
816 * happened under the old parameters. If it is
817 * interested, it can wait for the expiration,
818 * delete the old timer definition, and then
821 * This has to be done while the kq is locked:
822 * - if enqueued, dequeue
823 * - make it no longer active
824 * - clear the count of expiration events
828 if (kn->kn_status & KN_QUEUED)
831 kn->kn_status &= ~KN_ACTIVE;
835 /* Reschedule timer based on new data/fflags */
836 kn->kn_sfflags = kev->fflags;
837 kn->kn_sdata = kev->data;
838 error = filt_timervalidate(kn, &to);
840 kn->kn_flags |= EV_ERROR;
843 filt_timerstart(kn, to);
848 *kev = kn->kn_kevent;
849 if (kn->kn_flags & EV_CLEAR) {
856 panic("filt_timertouch() - invalid type (%ld)", type);
862 filt_timer(struct knote *kn, long hint)
865 return (kn->kn_data != 0);
869 filt_userattach(struct knote *kn)
873 * EVFILT_USER knotes are not attached to anything in the kernel.
876 if (kn->kn_fflags & NOTE_TRIGGER)
884 filt_userdetach(__unused struct knote *kn)
888 * EVFILT_USER knotes are not attached to anything in the kernel.
893 filt_user(struct knote *kn, __unused long hint)
896 return (kn->kn_hookid);
900 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
906 if (kev->fflags & NOTE_TRIGGER)
909 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
910 kev->fflags &= NOTE_FFLAGSMASK;
916 kn->kn_sfflags &= kev->fflags;
920 kn->kn_sfflags |= kev->fflags;
924 kn->kn_sfflags = kev->fflags;
928 /* XXX Return error? */
931 kn->kn_sdata = kev->data;
932 if (kev->flags & EV_CLEAR) {
940 *kev = kn->kn_kevent;
941 kev->fflags = kn->kn_sfflags;
942 kev->data = kn->kn_sdata;
943 if (kn->kn_flags & EV_CLEAR) {
951 panic("filt_usertouch() - invalid type (%ld)", type);
957 sys_kqueue(struct thread *td, struct kqueue_args *uap)
960 return (kern_kqueue(td, 0, NULL));
964 kqueue_init(struct kqueue *kq)
967 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
968 TAILQ_INIT(&kq->kq_head);
969 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
970 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
974 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
976 struct filedesc *fdp;
982 fdp = td->td_proc->p_fd;
984 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
987 error = falloc_caps(td, &fp, &fd, flags, fcaps);
989 chgkqcnt(cred->cr_ruidinfo, -1, 0);
993 /* An extra reference on `fp' has been held for us by falloc(). */
994 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
997 kq->kq_cred = crhold(cred);
1000 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
1001 FILEDESC_XUNLOCK(fdp);
1003 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
1006 td->td_retval[0] = fd;
1010 struct g_kevent_args {
1016 const struct timespec *timeout;
1020 sys_kevent(struct thread *td, struct kevent_args *uap)
1022 struct kevent_copyops k_ops = {
1024 .k_copyout = kevent_copyout,
1025 .k_copyin = kevent_copyin,
1026 .kevent_size = sizeof(struct kevent),
1028 struct g_kevent_args gk_args = {
1030 .changelist = uap->changelist,
1031 .nchanges = uap->nchanges,
1032 .eventlist = uap->eventlist,
1033 .nevents = uap->nevents,
1034 .timeout = uap->timeout,
1037 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent"));
1041 kern_kevent_generic(struct thread *td, struct g_kevent_args *uap,
1042 struct kevent_copyops *k_ops, const char *struct_name)
1044 struct timespec ts, *tsp;
1046 struct kevent *eventlist = uap->eventlist;
1050 if (uap->timeout != NULL) {
1051 error = copyin(uap->timeout, &ts, sizeof(ts));
1059 if (KTRPOINT(td, KTR_STRUCT_ARRAY))
1060 ktrstructarray(struct_name, UIO_USERSPACE, uap->changelist,
1061 uap->nchanges, k_ops->kevent_size);
1064 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1068 if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1069 ktrstructarray(struct_name, UIO_USERSPACE, eventlist,
1070 td->td_retval[0], k_ops->kevent_size);
1077 * Copy 'count' items into the destination list pointed to by uap->eventlist.
1080 kevent_copyout(void *arg, struct kevent *kevp, int count)
1082 struct kevent_args *uap;
1085 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1086 uap = (struct kevent_args *)arg;
1088 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1090 uap->eventlist += count;
1095 * Copy 'count' items from the list pointed to by uap->changelist.
1098 kevent_copyin(void *arg, struct kevent *kevp, int count)
1100 struct kevent_args *uap;
1103 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1104 uap = (struct kevent_args *)arg;
1106 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1108 uap->changelist += count;
1112 #ifdef COMPAT_FREEBSD11
1114 kevent11_copyout(void *arg, struct kevent *kevp, int count)
1116 struct freebsd11_kevent_args *uap;
1117 struct kevent_freebsd11 kev11;
1120 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1121 uap = (struct freebsd11_kevent_args *)arg;
1123 for (i = 0; i < count; i++) {
1124 kev11.ident = kevp->ident;
1125 kev11.filter = kevp->filter;
1126 kev11.flags = kevp->flags;
1127 kev11.fflags = kevp->fflags;
1128 kev11.data = kevp->data;
1129 kev11.udata = kevp->udata;
1130 error = copyout(&kev11, uap->eventlist, sizeof(kev11));
1140 * Copy 'count' items from the list pointed to by uap->changelist.
1143 kevent11_copyin(void *arg, struct kevent *kevp, int count)
1145 struct freebsd11_kevent_args *uap;
1146 struct kevent_freebsd11 kev11;
1149 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1150 uap = (struct freebsd11_kevent_args *)arg;
1152 for (i = 0; i < count; i++) {
1153 error = copyin(uap->changelist, &kev11, sizeof(kev11));
1156 kevp->ident = kev11.ident;
1157 kevp->filter = kev11.filter;
1158 kevp->flags = kev11.flags;
1159 kevp->fflags = kev11.fflags;
1160 kevp->data = (uintptr_t)kev11.data;
1161 kevp->udata = kev11.udata;
1162 bzero(&kevp->ext, sizeof(kevp->ext));
1170 freebsd11_kevent(struct thread *td, struct freebsd11_kevent_args *uap)
1172 struct kevent_copyops k_ops = {
1174 .k_copyout = kevent11_copyout,
1175 .k_copyin = kevent11_copyin,
1176 .kevent_size = sizeof(struct kevent_freebsd11),
1178 struct g_kevent_args gk_args = {
1180 .changelist = uap->changelist,
1181 .nchanges = uap->nchanges,
1182 .eventlist = uap->eventlist,
1183 .nevents = uap->nevents,
1184 .timeout = uap->timeout,
1187 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent_freebsd11"));
1192 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1193 struct kevent_copyops *k_ops, const struct timespec *timeout)
1195 cap_rights_t rights;
1199 cap_rights_init(&rights);
1201 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
1203 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
1204 error = fget(td, fd, &rights, &fp);
1208 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1215 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1216 struct kevent_copyops *k_ops, const struct timespec *timeout)
1218 struct kevent keva[KQ_NEVENTS];
1219 struct kevent *kevp, *changes;
1220 int i, n, nerrors, error;
1223 while (nchanges > 0) {
1224 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1225 error = k_ops->k_copyin(k_ops->arg, keva, n);
1229 for (i = 0; i < n; i++) {
1233 kevp->flags &= ~EV_SYSFLAGS;
1234 error = kqueue_register(kq, kevp, td, 1);
1235 if (error || (kevp->flags & EV_RECEIPT)) {
1238 kevp->flags = EV_ERROR;
1240 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1248 td->td_retval[0] = nerrors;
1252 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1256 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1257 struct kevent_copyops *k_ops, const struct timespec *timeout)
1262 error = kqueue_acquire(fp, &kq);
1265 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1266 kqueue_release(kq, 0);
1271 * Performs a kevent() call on a temporarily created kqueue. This can be
1272 * used to perform one-shot polling, similar to poll() and select().
1275 kern_kevent_anonymous(struct thread *td, int nevents,
1276 struct kevent_copyops *k_ops)
1278 struct kqueue kq = {};
1283 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1284 kqueue_drain(&kq, td);
1285 kqueue_destroy(&kq);
1290 kqueue_add_filteropts(int filt, struct filterops *filtops)
1295 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1297 "trying to add a filterop that is out of range: %d is beyond %d\n",
1298 ~filt, EVFILT_SYSCOUNT);
1301 mtx_lock(&filterops_lock);
1302 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1303 sysfilt_ops[~filt].for_fop != NULL)
1306 sysfilt_ops[~filt].for_fop = filtops;
1307 sysfilt_ops[~filt].for_refcnt = 0;
1309 mtx_unlock(&filterops_lock);
1315 kqueue_del_filteropts(int filt)
1320 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1323 mtx_lock(&filterops_lock);
1324 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1325 sysfilt_ops[~filt].for_fop == NULL)
1327 else if (sysfilt_ops[~filt].for_refcnt != 0)
1330 sysfilt_ops[~filt].for_fop = &null_filtops;
1331 sysfilt_ops[~filt].for_refcnt = 0;
1333 mtx_unlock(&filterops_lock);
1338 static struct filterops *
1339 kqueue_fo_find(int filt)
1342 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1345 if (sysfilt_ops[~filt].for_nolock)
1346 return sysfilt_ops[~filt].for_fop;
1348 mtx_lock(&filterops_lock);
1349 sysfilt_ops[~filt].for_refcnt++;
1350 if (sysfilt_ops[~filt].for_fop == NULL)
1351 sysfilt_ops[~filt].for_fop = &null_filtops;
1352 mtx_unlock(&filterops_lock);
1354 return sysfilt_ops[~filt].for_fop;
1358 kqueue_fo_release(int filt)
1361 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1364 if (sysfilt_ops[~filt].for_nolock)
1367 mtx_lock(&filterops_lock);
1368 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1369 ("filter object refcount not valid on release"));
1370 sysfilt_ops[~filt].for_refcnt--;
1371 mtx_unlock(&filterops_lock);
1375 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1376 * influence if memory allocation should wait. Make sure it is 0 if you
1380 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1382 struct filterops *fops;
1384 struct knote *kn, *tkn;
1386 int error, filt, event;
1387 int haskqglobal, filedesc_unlock;
1389 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1397 filedesc_unlock = 0;
1400 fops = kqueue_fo_find(filt);
1404 if (kev->flags & EV_ADD) {
1406 * Prevent waiting with locks. Non-sleepable
1407 * allocation failures are handled in the loop, only
1408 * if the spare knote appears to be actually required.
1410 tkn = knote_alloc(waitok);
1417 KASSERT(td != NULL, ("td is NULL"));
1418 if (kev->ident > INT_MAX)
1421 error = fget(td, kev->ident, &cap_event_rights, &fp);
1425 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1426 kev->ident, 0) != 0) {
1430 error = kqueue_expand(kq, fops, kev->ident, waitok);
1436 if (fp->f_type == DTYPE_KQUEUE) {
1438 * If we add some intelligence about what we are doing,
1439 * we should be able to support events on ourselves.
1440 * We need to know when we are doing this to prevent
1441 * getting both the knlist lock and the kq lock since
1442 * they are the same thing.
1444 if (fp->f_data == kq) {
1450 * Pre-lock the filedesc before the global
1451 * lock mutex, see the comment in
1454 FILEDESC_XLOCK(td->td_proc->p_fd);
1455 filedesc_unlock = 1;
1456 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1460 if (kev->ident < kq->kq_knlistsize) {
1461 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1462 if (kev->filter == kn->kn_filter)
1466 if ((kev->flags & EV_ADD) == EV_ADD)
1467 kqueue_expand(kq, fops, kev->ident, waitok);
1472 * If possible, find an existing knote to use for this kevent.
1474 if (kev->filter == EVFILT_PROC &&
1475 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1476 /* This is an internal creation of a process tracking
1477 * note. Don't attempt to coalesce this with an
1481 } else if (kq->kq_knhashmask != 0) {
1484 list = &kq->kq_knhash[
1485 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1486 SLIST_FOREACH(kn, list, kn_link)
1487 if (kev->ident == kn->kn_id &&
1488 kev->filter == kn->kn_filter)
1493 /* knote is in the process of changing, wait for it to stabilize. */
1494 if (kn != NULL && kn_in_flux(kn)) {
1495 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1496 if (filedesc_unlock) {
1497 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1498 filedesc_unlock = 0;
1500 kq->kq_state |= KQ_FLUXWAIT;
1501 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1510 * kn now contains the matching knote, or NULL if no match
1513 if (kev->flags & EV_ADD) {
1525 * apply reference counts to knote structure, and
1526 * do not release it at the end of this routine.
1531 kn->kn_sfflags = kev->fflags;
1532 kn->kn_sdata = kev->data;
1535 kn->kn_kevent = *kev;
1536 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1537 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1538 kn->kn_status = KN_DETACHED;
1539 if ((kev->flags & EV_DISABLE) != 0)
1540 kn->kn_status |= KN_DISABLED;
1543 error = knote_attach(kn, kq);
1550 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1551 knote_drop_detached(kn, td);
1554 knl = kn_list_lock(kn);
1557 /* No matching knote and the EV_ADD flag is not set. */
1564 if (kev->flags & EV_DELETE) {
1571 if (kev->flags & EV_FORCEONESHOT) {
1572 kn->kn_flags |= EV_ONESHOT;
1573 KNOTE_ACTIVATE(kn, 1);
1576 if ((kev->flags & EV_ENABLE) != 0)
1577 kn->kn_status &= ~KN_DISABLED;
1578 else if ((kev->flags & EV_DISABLE) != 0)
1579 kn->kn_status |= KN_DISABLED;
1582 * The user may change some filter values after the initial EV_ADD,
1583 * but doing so will not reset any filter which has already been
1586 kn->kn_status |= KN_SCAN;
1589 knl = kn_list_lock(kn);
1590 kn->kn_kevent.udata = kev->udata;
1591 if (!fops->f_isfd && fops->f_touch != NULL) {
1592 fops->f_touch(kn, kev, EVENT_REGISTER);
1594 kn->kn_sfflags = kev->fflags;
1595 kn->kn_sdata = kev->data;
1600 * We can get here with kn->kn_knlist == NULL. This can happen when
1601 * the initial attach event decides that the event is "completed"
1602 * already, e.g., filt_procattach() is called on a zombie process. It
1603 * will call filt_proc() which will remove it from the list, and NULL
1606 * KN_DISABLED will be stable while the knote is in flux, so the
1607 * unlocked read will not race with an update.
1609 if ((kn->kn_status & KN_DISABLED) == 0)
1610 event = kn->kn_fop->f_event(kn, 0);
1616 kn->kn_status |= KN_ACTIVE;
1617 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1620 kn->kn_status &= ~KN_SCAN;
1622 kn_list_unlock(knl);
1626 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1627 if (filedesc_unlock)
1628 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1633 kqueue_fo_release(filt);
1638 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1646 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1650 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1661 kqueue_release(struct kqueue *kq, int locked)
1668 if (kq->kq_refcnt == 1)
1669 wakeup(&kq->kq_refcnt);
1675 kqueue_schedtask(struct kqueue *kq)
1679 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1680 ("scheduling kqueue task while draining"));
1682 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1683 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1684 kq->kq_state |= KQ_TASKSCHED;
1689 * Expand the kq to make sure we have storage for fops/ident pair.
1691 * Return 0 on success (or no work necessary), return errno on failure.
1693 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1694 * If kqueue_register is called from a non-fd context, there usually/should
1698 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1701 struct klist *list, *tmp_knhash, *to_free;
1702 u_long tmp_knhashmask;
1705 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1712 if (kq->kq_knlistsize <= fd) {
1713 size = kq->kq_knlistsize;
1716 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1720 if (kq->kq_knlistsize > fd) {
1724 if (kq->kq_knlist != NULL) {
1725 bcopy(kq->kq_knlist, list,
1726 kq->kq_knlistsize * sizeof(*list));
1727 to_free = kq->kq_knlist;
1728 kq->kq_knlist = NULL;
1730 bzero((caddr_t)list +
1731 kq->kq_knlistsize * sizeof(*list),
1732 (size - kq->kq_knlistsize) * sizeof(*list));
1733 kq->kq_knlistsize = size;
1734 kq->kq_knlist = list;
1739 if (kq->kq_knhashmask == 0) {
1740 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1742 if (tmp_knhash == NULL)
1745 if (kq->kq_knhashmask == 0) {
1746 kq->kq_knhash = tmp_knhash;
1747 kq->kq_knhashmask = tmp_knhashmask;
1749 to_free = tmp_knhash;
1754 free(to_free, M_KQUEUE);
1761 kqueue_task(void *arg, int pending)
1769 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1772 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1774 kq->kq_state &= ~KQ_TASKSCHED;
1775 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1776 wakeup(&kq->kq_state);
1779 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1783 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1784 * We treat KN_MARKER knotes as if they are in flux.
1787 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1788 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1790 struct kevent *kevp;
1791 struct knote *kn, *marker;
1793 sbintime_t asbt, rsbt;
1794 int count, error, haskqglobal, influx, nkev, touch;
1806 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1807 tsp->tv_nsec >= 1000000000) {
1811 if (timespecisset(tsp)) {
1812 if (tsp->tv_sec <= INT32_MAX) {
1813 rsbt = tstosbt(*tsp);
1814 if (TIMESEL(&asbt, rsbt))
1815 asbt += tc_tick_sbt;
1816 if (asbt <= SBT_MAX - rsbt)
1820 rsbt >>= tc_precexp;
1827 marker = knote_alloc(1);
1828 marker->kn_status = KN_MARKER;
1833 if (kq->kq_count == 0) {
1835 error = EWOULDBLOCK;
1837 kq->kq_state |= KQ_SLEEP;
1838 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1839 "kqread", asbt, rsbt, C_ABSOLUTE);
1843 /* don't restart after signals... */
1844 if (error == ERESTART)
1846 else if (error == EWOULDBLOCK)
1851 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1855 kn = TAILQ_FIRST(&kq->kq_head);
1857 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1863 kq->kq_state |= KQ_FLUXWAIT;
1864 error = msleep(kq, &kq->kq_lock, PSOCK,
1869 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1870 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1871 kn->kn_status &= ~KN_QUEUED;
1877 if (count == maxevents)
1881 KASSERT(!kn_in_flux(kn),
1882 ("knote %p is unexpectedly in flux", kn));
1884 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1885 kn->kn_status &= ~KN_QUEUED;
1890 * We don't need to lock the list since we've
1891 * marked it as in flux.
1896 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1897 kn->kn_status &= ~KN_QUEUED;
1902 * We don't need to lock the list since we've
1903 * marked the knote as being in flux.
1905 *kevp = kn->kn_kevent;
1910 kn->kn_status |= KN_SCAN;
1913 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1914 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1915 knl = kn_list_lock(kn);
1916 if (kn->kn_fop->f_event(kn, 0) == 0) {
1918 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1919 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
1923 kn_list_unlock(knl);
1927 touch = (!kn->kn_fop->f_isfd &&
1928 kn->kn_fop->f_touch != NULL);
1930 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1932 *kevp = kn->kn_kevent;
1934 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1935 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1937 * Manually clear knotes who weren't
1940 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1944 if (kn->kn_flags & EV_DISPATCH)
1945 kn->kn_status |= KN_DISABLED;
1946 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1949 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1951 kn->kn_status &= ~KN_SCAN;
1953 kn_list_unlock(knl);
1957 /* we are returning a copy to the user */
1962 if (nkev == KQ_NEVENTS) {
1965 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1973 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1981 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1982 td->td_retval[0] = maxevents - count;
1988 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1989 struct ucred *active_cred, struct thread *td)
1992 * Enabling sigio causes two major problems:
1993 * 1) infinite recursion:
1994 * Synopsys: kevent is being used to track signals and have FIOASYNC
1995 * set. On receipt of a signal this will cause a kqueue to recurse
1996 * into itself over and over. Sending the sigio causes the kqueue
1997 * to become ready, which in turn posts sigio again, forever.
1998 * Solution: this can be solved by setting a flag in the kqueue that
1999 * we have a SIGIO in progress.
2000 * 2) locking problems:
2001 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
2002 * us above the proc and pgrp locks.
2003 * Solution: Post a signal using an async mechanism, being sure to
2004 * record a generation count in the delivery so that we do not deliver
2005 * a signal to the wrong process.
2007 * Note, these two mechanisms are somewhat mutually exclusive!
2016 kq->kq_state |= KQ_ASYNC;
2018 kq->kq_state &= ~KQ_ASYNC;
2023 return (fsetown(*(int *)data, &kq->kq_sigio));
2026 *(int *)data = fgetown(&kq->kq_sigio);
2036 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
2043 if ((error = kqueue_acquire(fp, &kq)))
2047 if (events & (POLLIN | POLLRDNORM)) {
2049 revents |= events & (POLLIN | POLLRDNORM);
2051 selrecord(td, &kq->kq_sel);
2052 if (SEL_WAITING(&kq->kq_sel))
2053 kq->kq_state |= KQ_SEL;
2056 kqueue_release(kq, 1);
2063 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
2067 bzero((void *)st, sizeof *st);
2069 * We no longer return kq_count because the unlocked value is useless.
2070 * If you spent all this time getting the count, why not spend your
2071 * syscall better by calling kevent?
2073 * XXX - This is needed for libc_r.
2075 st->st_mode = S_IFIFO;
2080 kqueue_drain(struct kqueue *kq, struct thread *td)
2087 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
2088 ("kqueue already closing"));
2089 kq->kq_state |= KQ_CLOSING;
2090 if (kq->kq_refcnt > 1)
2091 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
2093 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
2095 KASSERT(knlist_empty(&kq->kq_sel.si_note),
2096 ("kqueue's knlist not empty"));
2098 for (i = 0; i < kq->kq_knlistsize; i++) {
2099 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
2100 if (kn_in_flux(kn)) {
2101 kq->kq_state |= KQ_FLUXWAIT;
2102 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
2111 if (kq->kq_knhashmask != 0) {
2112 for (i = 0; i <= kq->kq_knhashmask; i++) {
2113 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
2114 if (kn_in_flux(kn)) {
2115 kq->kq_state |= KQ_FLUXWAIT;
2116 msleep(kq, &kq->kq_lock, PSOCK,
2128 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
2129 kq->kq_state |= KQ_TASKDRAIN;
2130 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2133 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2134 selwakeuppri(&kq->kq_sel, PSOCK);
2135 if (!SEL_WAITING(&kq->kq_sel))
2136 kq->kq_state &= ~KQ_SEL;
2143 kqueue_destroy(struct kqueue *kq)
2146 KASSERT(kq->kq_fdp == NULL,
2147 ("kqueue still attached to a file descriptor"));
2148 seldrain(&kq->kq_sel);
2149 knlist_destroy(&kq->kq_sel.si_note);
2150 mtx_destroy(&kq->kq_lock);
2152 if (kq->kq_knhash != NULL)
2153 free(kq->kq_knhash, M_KQUEUE);
2154 if (kq->kq_knlist != NULL)
2155 free(kq->kq_knlist, M_KQUEUE);
2157 funsetown(&kq->kq_sigio);
2162 kqueue_close(struct file *fp, struct thread *td)
2164 struct kqueue *kq = fp->f_data;
2165 struct filedesc *fdp;
2167 int filedesc_unlock;
2169 if ((error = kqueue_acquire(fp, &kq)))
2171 kqueue_drain(kq, td);
2174 * We could be called due to the knote_drop() doing fdrop(),
2175 * called from kqueue_register(). In this case the global
2176 * lock is owned, and filedesc sx is locked before, to not
2177 * take the sleepable lock after non-sleepable.
2181 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2182 FILEDESC_XLOCK(fdp);
2183 filedesc_unlock = 1;
2185 filedesc_unlock = 0;
2186 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2187 if (filedesc_unlock)
2188 FILEDESC_XUNLOCK(fdp);
2191 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2192 crfree(kq->kq_cred);
2200 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2203 kif->kf_type = KF_TYPE_KQUEUE;
2208 kqueue_wakeup(struct kqueue *kq)
2212 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2213 kq->kq_state &= ~KQ_SLEEP;
2216 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2217 selwakeuppri(&kq->kq_sel, PSOCK);
2218 if (!SEL_WAITING(&kq->kq_sel))
2219 kq->kq_state &= ~KQ_SEL;
2221 if (!knlist_empty(&kq->kq_sel.si_note))
2222 kqueue_schedtask(kq);
2223 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2224 pgsigio(&kq->kq_sigio, SIGIO, 0);
2229 * Walk down a list of knotes, activating them if their event has triggered.
2231 * There is a possibility to optimize in the case of one kq watching another.
2232 * Instead of scheduling a task to wake it up, you could pass enough state
2233 * down the chain to make up the parent kqueue. Make this code functional
2237 knote(struct knlist *list, long hint, int lockflags)
2240 struct knote *kn, *tkn;
2246 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2248 if ((lockflags & KNF_LISTLOCKED) == 0)
2249 list->kl_lock(list->kl_lockarg);
2252 * If we unlock the list lock (and enter influx), we can
2253 * eliminate the kqueue scheduling, but this will introduce
2254 * four lock/unlock's for each knote to test. Also, marker
2255 * would be needed to keep iteration position, since filters
2256 * or other threads could remove events.
2258 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2261 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2263 * Do not process the influx notes, except for
2264 * the influx coming from the kq unlock in the
2265 * kqueue_scan(). In the later case, we do
2266 * not interfere with the scan, since the code
2267 * fragment in kqueue_scan() locks the knlist,
2268 * and cannot proceed until we finished.
2271 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2274 error = kn->kn_fop->f_event(kn, hint);
2278 KNOTE_ACTIVATE(kn, 1);
2281 kn->kn_status |= KN_HASKQLOCK;
2282 if (kn->kn_fop->f_event(kn, hint))
2283 KNOTE_ACTIVATE(kn, 1);
2284 kn->kn_status &= ~KN_HASKQLOCK;
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_locked(void *arg)
2381 mtx_assert((struct mtx *)arg, MA_OWNED);
2385 knlist_mtx_assert_unlocked(void *arg)
2388 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2392 knlist_rw_rlock(void *arg)
2395 rw_rlock((struct rwlock *)arg);
2399 knlist_rw_runlock(void *arg)
2402 rw_runlock((struct rwlock *)arg);
2406 knlist_rw_assert_locked(void *arg)
2409 rw_assert((struct rwlock *)arg, RA_LOCKED);
2413 knlist_rw_assert_unlocked(void *arg)
2416 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2420 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2421 void (*kl_unlock)(void *),
2422 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2426 knl->kl_lockarg = &knlist_lock;
2428 knl->kl_lockarg = lock;
2430 if (kl_lock == NULL)
2431 knl->kl_lock = knlist_mtx_lock;
2433 knl->kl_lock = kl_lock;
2434 if (kl_unlock == NULL)
2435 knl->kl_unlock = knlist_mtx_unlock;
2437 knl->kl_unlock = kl_unlock;
2438 if (kl_assert_locked == NULL)
2439 knl->kl_assert_locked = knlist_mtx_assert_locked;
2441 knl->kl_assert_locked = kl_assert_locked;
2442 if (kl_assert_unlocked == NULL)
2443 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2445 knl->kl_assert_unlocked = kl_assert_unlocked;
2447 knl->kl_autodestroy = 0;
2448 SLIST_INIT(&knl->kl_list);
2452 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2455 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2459 knlist_alloc(struct mtx *lock)
2463 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2464 knlist_init_mtx(knl, lock);
2469 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2472 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2473 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2477 knlist_destroy(struct knlist *knl)
2480 KASSERT(KNLIST_EMPTY(knl),
2481 ("destroying knlist %p with knotes on it", knl));
2485 knlist_detach(struct knlist *knl)
2488 KNL_ASSERT_LOCKED(knl);
2489 knl->kl_autodestroy = 1;
2490 if (knlist_empty(knl)) {
2491 knlist_destroy(knl);
2492 free(knl, M_KQUEUE);
2497 * Even if we are locked, we may need to drop the lock to allow any influx
2498 * knotes time to "settle".
2501 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2503 struct knote *kn, *kn2;
2506 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2508 KNL_ASSERT_LOCKED(knl);
2510 KNL_ASSERT_UNLOCKED(knl);
2511 again: /* need to reacquire lock since we have dropped it */
2512 knl->kl_lock(knl->kl_lockarg);
2515 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2518 if (kn_in_flux(kn)) {
2522 knlist_remove_kq(knl, kn, 1, 1);
2526 knote_drop_detached(kn, td);
2528 /* Make sure cleared knotes disappear soon */
2529 kn->kn_flags |= EV_EOF | EV_ONESHOT;
2535 if (!SLIST_EMPTY(&knl->kl_list)) {
2536 /* there are still in flux knotes remaining */
2537 kn = SLIST_FIRST(&knl->kl_list);
2540 KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2541 knl->kl_unlock(knl->kl_lockarg);
2542 kq->kq_state |= KQ_FLUXWAIT;
2543 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2549 KNL_ASSERT_LOCKED(knl);
2551 knl->kl_unlock(knl->kl_lockarg);
2552 KNL_ASSERT_UNLOCKED(knl);
2557 * Remove all knotes referencing a specified fd must be called with FILEDESC
2558 * lock. This prevents a race where a new fd comes along and occupies the
2559 * entry and we attach a knote to the fd.
2562 knote_fdclose(struct thread *td, int fd)
2564 struct filedesc *fdp = td->td_proc->p_fd;
2569 FILEDESC_XLOCK_ASSERT(fdp);
2572 * We shouldn't have to worry about new kevents appearing on fd
2573 * since filedesc is locked.
2575 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2580 while (kq->kq_knlistsize > fd &&
2581 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2582 if (kn_in_flux(kn)) {
2583 /* someone else might be waiting on our knote */
2586 kq->kq_state |= KQ_FLUXWAIT;
2587 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2601 knote_attach(struct knote *kn, struct kqueue *kq)
2605 KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2608 if (kn->kn_fop->f_isfd) {
2609 if (kn->kn_id >= kq->kq_knlistsize)
2611 list = &kq->kq_knlist[kn->kn_id];
2613 if (kq->kq_knhash == NULL)
2615 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2617 SLIST_INSERT_HEAD(list, kn, kn_link);
2622 knote_drop(struct knote *kn, struct thread *td)
2625 if ((kn->kn_status & KN_DETACHED) == 0)
2626 kn->kn_fop->f_detach(kn);
2627 knote_drop_detached(kn, td);
2631 knote_drop_detached(struct knote *kn, struct thread *td)
2638 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2639 ("knote %p still attached", kn));
2643 KASSERT(kn->kn_influx == 1,
2644 ("knote_drop called on %p with influx %d", kn, kn->kn_influx));
2646 if (kn->kn_fop->f_isfd)
2647 list = &kq->kq_knlist[kn->kn_id];
2649 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2651 if (!SLIST_EMPTY(list))
2652 SLIST_REMOVE(list, kn, knote, kn_link);
2653 if (kn->kn_status & KN_QUEUED)
2657 if (kn->kn_fop->f_isfd) {
2658 fdrop(kn->kn_fp, td);
2661 kqueue_fo_release(kn->kn_kevent.filter);
2667 knote_enqueue(struct knote *kn)
2669 struct kqueue *kq = kn->kn_kq;
2671 KQ_OWNED(kn->kn_kq);
2672 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2674 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2675 kn->kn_status |= KN_QUEUED;
2681 knote_dequeue(struct knote *kn)
2683 struct kqueue *kq = kn->kn_kq;
2685 KQ_OWNED(kn->kn_kq);
2686 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2688 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2689 kn->kn_status &= ~KN_QUEUED;
2697 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2698 NULL, NULL, UMA_ALIGN_PTR, 0);
2700 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2702 static struct knote *
2703 knote_alloc(int waitok)
2706 return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2711 knote_free(struct knote *kn)
2714 uma_zfree(knote_zone, kn);
2718 * Register the kev w/ the kq specified by fd.
2721 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2725 cap_rights_t rights;
2728 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2731 if ((error = kqueue_acquire(fp, &kq)) != 0)
2734 error = kqueue_register(kq, kev, td, waitok);
2735 kqueue_release(kq, 0);