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_compat.h"
35 #include "opt_ktrace.h"
36 #include "opt_kqueue.h"
38 #ifdef COMPAT_FREEBSD11
39 #define _WANT_FREEBSD11_KEVENT
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/capsicum.h>
45 #include <sys/kernel.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 waitok);
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 waitok);
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 waitok);
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 int filt_timer(struct knote *kn, long hint);
167 static int filt_userattach(struct knote *kn);
168 static void filt_userdetach(struct knote *kn);
169 static int filt_user(struct knote *kn, long hint);
170 static void filt_usertouch(struct knote *kn, struct kevent *kev,
173 static struct filterops file_filtops = {
175 .f_attach = filt_fileattach,
177 static struct filterops kqread_filtops = {
179 .f_detach = filt_kqdetach,
180 .f_event = filt_kqueue,
182 /* XXX - move to kern_proc.c? */
183 static struct filterops proc_filtops = {
185 .f_attach = filt_procattach,
186 .f_detach = filt_procdetach,
187 .f_event = filt_proc,
189 static struct filterops timer_filtops = {
191 .f_attach = filt_timerattach,
192 .f_detach = filt_timerdetach,
193 .f_event = filt_timer,
195 static struct filterops user_filtops = {
196 .f_attach = filt_userattach,
197 .f_detach = filt_userdetach,
198 .f_event = filt_user,
199 .f_touch = filt_usertouch,
202 static uma_zone_t knote_zone;
203 static unsigned int kq_ncallouts = 0;
204 static unsigned int kq_calloutmax = 4 * 1024;
205 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
206 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
208 /* XXX - ensure not influx ? */
209 #define KNOTE_ACTIVATE(kn, islock) do { \
211 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
213 KQ_LOCK((kn)->kn_kq); \
214 (kn)->kn_status |= KN_ACTIVE; \
215 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
216 knote_enqueue((kn)); \
218 KQ_UNLOCK((kn)->kn_kq); \
220 #define KQ_LOCK(kq) do { \
221 mtx_lock(&(kq)->kq_lock); \
223 #define KQ_FLUX_WAKEUP(kq) do { \
224 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
225 (kq)->kq_state &= ~KQ_FLUXWAIT; \
229 #define KQ_UNLOCK_FLUX(kq) do { \
230 KQ_FLUX_WAKEUP(kq); \
231 mtx_unlock(&(kq)->kq_lock); \
233 #define KQ_UNLOCK(kq) do { \
234 mtx_unlock(&(kq)->kq_lock); \
236 #define KQ_OWNED(kq) do { \
237 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
239 #define KQ_NOTOWNED(kq) do { \
240 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
243 static struct knlist *
244 kn_list_lock(struct knote *kn)
250 knl->kl_lock(knl->kl_lockarg);
255 kn_list_unlock(struct knlist *knl)
261 do_free = knl->kl_autodestroy && knlist_empty(knl);
262 knl->kl_unlock(knl->kl_lockarg);
270 kn_in_flux(struct knote *kn)
273 return (kn->kn_influx > 0);
277 kn_enter_flux(struct knote *kn)
281 MPASS(kn->kn_influx < INT_MAX);
286 kn_leave_flux(struct knote *kn)
290 MPASS(kn->kn_influx > 0);
292 return (kn->kn_influx == 0);
295 #define KNL_ASSERT_LOCK(knl, islocked) do { \
297 KNL_ASSERT_LOCKED(knl); \
299 KNL_ASSERT_UNLOCKED(knl); \
302 #define KNL_ASSERT_LOCKED(knl) do { \
303 knl->kl_assert_locked((knl)->kl_lockarg); \
305 #define KNL_ASSERT_UNLOCKED(knl) do { \
306 knl->kl_assert_unlocked((knl)->kl_lockarg); \
308 #else /* !INVARIANTS */
309 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
310 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
311 #endif /* INVARIANTS */
314 #define KN_HASHSIZE 64 /* XXX should be tunable */
317 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
320 filt_nullattach(struct knote *kn)
326 struct filterops null_filtops = {
328 .f_attach = filt_nullattach,
331 /* XXX - make SYSINIT to add these, and move into respective modules. */
332 extern struct filterops sig_filtops;
333 extern struct filterops fs_filtops;
336 * Table for for all system-defined filters.
338 static struct mtx filterops_lock;
339 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
342 struct filterops *for_fop;
345 } sysfilt_ops[EVFILT_SYSCOUNT] = {
346 { &file_filtops, 1 }, /* EVFILT_READ */
347 { &file_filtops, 1 }, /* EVFILT_WRITE */
348 { &null_filtops }, /* EVFILT_AIO */
349 { &file_filtops, 1 }, /* EVFILT_VNODE */
350 { &proc_filtops, 1 }, /* EVFILT_PROC */
351 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
352 { &timer_filtops, 1 }, /* EVFILT_TIMER */
353 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
354 { &fs_filtops, 1 }, /* EVFILT_FS */
355 { &null_filtops }, /* EVFILT_LIO */
356 { &user_filtops, 1 }, /* EVFILT_USER */
357 { &null_filtops }, /* EVFILT_SENDFILE */
358 { &file_filtops, 1 }, /* EVFILT_EMPTY */
362 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
366 filt_fileattach(struct knote *kn)
369 return (fo_kqfilter(kn->kn_fp, kn));
374 kqueue_kqfilter(struct file *fp, struct knote *kn)
376 struct kqueue *kq = kn->kn_fp->f_data;
378 if (kn->kn_filter != EVFILT_READ)
381 kn->kn_status |= KN_KQUEUE;
382 kn->kn_fop = &kqread_filtops;
383 knlist_add(&kq->kq_sel.si_note, kn, 0);
389 filt_kqdetach(struct knote *kn)
391 struct kqueue *kq = kn->kn_fp->f_data;
393 knlist_remove(&kq->kq_sel.si_note, kn, 0);
398 filt_kqueue(struct knote *kn, long hint)
400 struct kqueue *kq = kn->kn_fp->f_data;
402 kn->kn_data = kq->kq_count;
403 return (kn->kn_data > 0);
406 /* XXX - move to kern_proc.c? */
408 filt_procattach(struct knote *kn)
412 bool exiting, immediate;
414 exiting = immediate = false;
415 if (kn->kn_sfflags & NOTE_EXIT)
416 p = pfind_any(kn->kn_id);
418 p = pfind(kn->kn_id);
421 if (p->p_flag & P_WEXIT)
424 if ((error = p_cansee(curthread, p))) {
429 kn->kn_ptr.p_proc = p;
430 kn->kn_flags |= EV_CLEAR; /* automatically set */
433 * Internal flag indicating registration done by kernel for the
434 * purposes of getting a NOTE_CHILD notification.
436 if (kn->kn_flags & EV_FLAG2) {
437 kn->kn_flags &= ~EV_FLAG2;
438 kn->kn_data = kn->kn_sdata; /* ppid */
439 kn->kn_fflags = NOTE_CHILD;
440 kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
441 immediate = true; /* Force immediate activation of child note. */
444 * Internal flag indicating registration done by kernel (for other than
447 if (kn->kn_flags & EV_FLAG1) {
448 kn->kn_flags &= ~EV_FLAG1;
451 knlist_add(p->p_klist, kn, 1);
454 * Immediately activate any child notes or, in the case of a zombie
455 * target process, exit notes. The latter is necessary to handle the
456 * case where the target process, e.g. a child, dies before the kevent
459 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
460 KNOTE_ACTIVATE(kn, 0);
468 * The knote may be attached to a different process, which may exit,
469 * leaving nothing for the knote to be attached to. So when the process
470 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
471 * it will be deleted when read out. However, as part of the knote deletion,
472 * this routine is called, so a check is needed to avoid actually performing
473 * a detach, because the original process does not exist any more.
475 /* XXX - move to kern_proc.c? */
477 filt_procdetach(struct knote *kn)
480 knlist_remove(kn->kn_knlist, kn, 0);
481 kn->kn_ptr.p_proc = NULL;
484 /* XXX - move to kern_proc.c? */
486 filt_proc(struct knote *kn, long hint)
491 p = kn->kn_ptr.p_proc;
492 if (p == NULL) /* already activated, from attach filter */
495 /* Mask off extra data. */
496 event = (u_int)hint & NOTE_PCTRLMASK;
498 /* If the user is interested in this event, record it. */
499 if (kn->kn_sfflags & event)
500 kn->kn_fflags |= event;
502 /* Process is gone, so flag the event as finished. */
503 if (event == NOTE_EXIT) {
504 kn->kn_flags |= EV_EOF | EV_ONESHOT;
505 kn->kn_ptr.p_proc = NULL;
506 if (kn->kn_fflags & NOTE_EXIT)
507 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
508 if (kn->kn_fflags == 0)
509 kn->kn_flags |= EV_DROP;
513 return (kn->kn_fflags != 0);
517 * Called when the process forked. It mostly does the same as the
518 * knote(), activating all knotes registered to be activated when the
519 * process forked. Additionally, for each knote attached to the
520 * parent, check whether user wants to track the new process. If so
521 * attach a new knote to it, and immediately report an event with the
525 knote_fork(struct knlist *list, int pid)
534 list->kl_lock(list->kl_lockarg);
536 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
539 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
545 * The same as knote(), activate the event.
547 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
548 kn->kn_status |= KN_HASKQLOCK;
549 if (kn->kn_fop->f_event(kn, NOTE_FORK))
550 KNOTE_ACTIVATE(kn, 1);
551 kn->kn_status &= ~KN_HASKQLOCK;
557 * The NOTE_TRACK case. In addition to the activation
558 * of the event, we need to register new events to
559 * track the child. Drop the locks in preparation for
560 * the call to kqueue_register().
564 list->kl_unlock(list->kl_lockarg);
567 * Activate existing knote and register tracking knotes with
570 * First register a knote to get just the child notice. This
571 * must be a separate note from a potential NOTE_EXIT
572 * notification since both NOTE_CHILD and NOTE_EXIT are defined
573 * to use the data field (in conflicting ways).
576 kev.filter = kn->kn_filter;
577 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
579 kev.fflags = kn->kn_sfflags;
580 kev.data = kn->kn_id; /* parent */
581 kev.udata = kn->kn_kevent.udata;/* preserve udata */
582 error = kqueue_register(kq, &kev, NULL, 0);
584 kn->kn_fflags |= NOTE_TRACKERR;
587 * Then register another knote to track other potential events
588 * from the new process.
591 kev.filter = kn->kn_filter;
592 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
593 kev.fflags = kn->kn_sfflags;
594 kev.data = kn->kn_id; /* parent */
595 kev.udata = kn->kn_kevent.udata;/* preserve udata */
596 error = kqueue_register(kq, &kev, NULL, 0);
598 kn->kn_fflags |= NOTE_TRACKERR;
599 if (kn->kn_fop->f_event(kn, NOTE_FORK))
600 KNOTE_ACTIVATE(kn, 0);
604 list->kl_lock(list->kl_lockarg);
606 list->kl_unlock(list->kl_lockarg);
610 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
611 * interval timer support code.
614 #define NOTE_TIMER_PRECMASK \
615 (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
618 timer2sbintime(intptr_t data, int flags)
623 * Macros for converting to the fractional second portion of an
624 * sbintime_t using 64bit multiplication to improve precision.
626 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
627 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
628 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
629 switch (flags & NOTE_TIMER_PRECMASK) {
632 if (data > (SBT_MAX / SBT_1S))
635 return ((sbintime_t)data << 32);
636 case NOTE_MSECONDS: /* FALLTHROUGH */
641 if (secs > (SBT_MAX / SBT_1S))
644 return (secs << 32 | MS_TO_SBT(data % 1000));
646 return (MS_TO_SBT(data));
648 if (data >= 1000000) {
649 secs = data / 1000000;
651 if (secs > (SBT_MAX / SBT_1S))
654 return (secs << 32 | US_TO_SBT(data % 1000000));
656 return (US_TO_SBT(data));
658 if (data >= 1000000000) {
659 secs = data / 1000000000;
661 if (secs > (SBT_MAX / SBT_1S))
664 return (secs << 32 | US_TO_SBT(data % 1000000000));
666 return (NS_TO_SBT(data));
673 struct kq_timer_cb_data {
675 sbintime_t next; /* next timer event fires at */
676 sbintime_t to; /* precalculated timer period, 0 for abs */
680 filt_timerexpire(void *knx)
683 struct kq_timer_cb_data *kc;
687 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
689 if ((kn->kn_flags & EV_ONESHOT) != 0)
695 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
696 PCPU_GET(cpuid), C_ABSOLUTE);
700 * data contains amount of time to sleep
703 filt_timerattach(struct knote *kn)
705 struct kq_timer_cb_data *kc;
708 unsigned int ncallouts;
710 if (kn->kn_sdata < 0)
712 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
714 /* Only precision unit are supported in flags so far */
715 if ((kn->kn_sfflags & ~(NOTE_TIMER_PRECMASK | NOTE_ABSTIME)) != 0)
718 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
719 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
728 ncallouts = kq_ncallouts;
729 if (ncallouts >= kq_calloutmax)
731 } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
733 if ((kn->kn_sfflags & NOTE_ABSTIME) == 0)
734 kn->kn_flags |= EV_CLEAR; /* automatically set */
735 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
736 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
737 callout_init(&kc->c, 1);
738 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
742 kc->next = to + sbinuptime();
745 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
746 PCPU_GET(cpuid), C_ABSOLUTE);
752 filt_timerdetach(struct knote *kn)
754 struct kq_timer_cb_data *kc;
758 callout_drain(&kc->c);
760 old = atomic_fetchadd_int(&kq_ncallouts, -1);
761 KASSERT(old > 0, ("Number of callouts cannot become negative"));
762 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
766 filt_timer(struct knote *kn, long hint)
769 return (kn->kn_data != 0);
773 filt_userattach(struct knote *kn)
777 * EVFILT_USER knotes are not attached to anything in the kernel.
780 if (kn->kn_fflags & NOTE_TRIGGER)
788 filt_userdetach(__unused struct knote *kn)
792 * EVFILT_USER knotes are not attached to anything in the kernel.
797 filt_user(struct knote *kn, __unused long hint)
800 return (kn->kn_hookid);
804 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
810 if (kev->fflags & NOTE_TRIGGER)
813 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
814 kev->fflags &= NOTE_FFLAGSMASK;
820 kn->kn_sfflags &= kev->fflags;
824 kn->kn_sfflags |= kev->fflags;
828 kn->kn_sfflags = kev->fflags;
832 /* XXX Return error? */
835 kn->kn_sdata = kev->data;
836 if (kev->flags & EV_CLEAR) {
844 *kev = kn->kn_kevent;
845 kev->fflags = kn->kn_sfflags;
846 kev->data = kn->kn_sdata;
847 if (kn->kn_flags & EV_CLEAR) {
855 panic("filt_usertouch() - invalid type (%ld)", type);
861 sys_kqueue(struct thread *td, struct kqueue_args *uap)
864 return (kern_kqueue(td, 0, NULL));
868 kqueue_init(struct kqueue *kq)
871 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
872 TAILQ_INIT(&kq->kq_head);
873 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
874 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
878 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
880 struct filedesc *fdp;
886 fdp = td->td_proc->p_fd;
888 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
891 error = falloc_caps(td, &fp, &fd, flags, fcaps);
893 chgkqcnt(cred->cr_ruidinfo, -1, 0);
897 /* An extra reference on `fp' has been held for us by falloc(). */
898 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
901 kq->kq_cred = crhold(cred);
904 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
905 FILEDESC_XUNLOCK(fdp);
907 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
910 td->td_retval[0] = fd;
914 struct g_kevent_args {
920 const struct timespec *timeout;
924 sys_kevent(struct thread *td, struct kevent_args *uap)
926 struct kevent_copyops k_ops = {
928 .k_copyout = kevent_copyout,
929 .k_copyin = kevent_copyin,
930 .kevent_size = sizeof(struct kevent),
932 struct g_kevent_args gk_args = {
934 .changelist = uap->changelist,
935 .nchanges = uap->nchanges,
936 .eventlist = uap->eventlist,
937 .nevents = uap->nevents,
938 .timeout = uap->timeout,
941 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent"));
945 kern_kevent_generic(struct thread *td, struct g_kevent_args *uap,
946 struct kevent_copyops *k_ops, const char *struct_name)
948 struct timespec ts, *tsp;
950 struct kevent *eventlist = uap->eventlist;
954 if (uap->timeout != NULL) {
955 error = copyin(uap->timeout, &ts, sizeof(ts));
963 if (KTRPOINT(td, KTR_STRUCT_ARRAY))
964 ktrstructarray(struct_name, UIO_USERSPACE, uap->changelist,
965 uap->nchanges, k_ops->kevent_size);
968 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
972 if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
973 ktrstructarray(struct_name, UIO_USERSPACE, eventlist,
974 td->td_retval[0], k_ops->kevent_size);
981 * Copy 'count' items into the destination list pointed to by uap->eventlist.
984 kevent_copyout(void *arg, struct kevent *kevp, int count)
986 struct kevent_args *uap;
989 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
990 uap = (struct kevent_args *)arg;
992 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
994 uap->eventlist += count;
999 * Copy 'count' items from the list pointed to by uap->changelist.
1002 kevent_copyin(void *arg, struct kevent *kevp, int count)
1004 struct kevent_args *uap;
1007 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1008 uap = (struct kevent_args *)arg;
1010 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1012 uap->changelist += count;
1016 #ifdef COMPAT_FREEBSD11
1018 kevent11_copyout(void *arg, struct kevent *kevp, int count)
1020 struct freebsd11_kevent_args *uap;
1021 struct kevent_freebsd11 kev11;
1024 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1025 uap = (struct freebsd11_kevent_args *)arg;
1027 for (i = 0; i < count; i++) {
1028 kev11.ident = kevp->ident;
1029 kev11.filter = kevp->filter;
1030 kev11.flags = kevp->flags;
1031 kev11.fflags = kevp->fflags;
1032 kev11.data = kevp->data;
1033 kev11.udata = kevp->udata;
1034 error = copyout(&kev11, uap->eventlist, sizeof(kev11));
1044 * Copy 'count' items from the list pointed to by uap->changelist.
1047 kevent11_copyin(void *arg, struct kevent *kevp, int count)
1049 struct freebsd11_kevent_args *uap;
1050 struct kevent_freebsd11 kev11;
1053 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1054 uap = (struct freebsd11_kevent_args *)arg;
1056 for (i = 0; i < count; i++) {
1057 error = copyin(uap->changelist, &kev11, sizeof(kev11));
1060 kevp->ident = kev11.ident;
1061 kevp->filter = kev11.filter;
1062 kevp->flags = kev11.flags;
1063 kevp->fflags = kev11.fflags;
1064 kevp->data = (uintptr_t)kev11.data;
1065 kevp->udata = kev11.udata;
1066 bzero(&kevp->ext, sizeof(kevp->ext));
1074 freebsd11_kevent(struct thread *td, struct freebsd11_kevent_args *uap)
1076 struct kevent_copyops k_ops = {
1078 .k_copyout = kevent11_copyout,
1079 .k_copyin = kevent11_copyin,
1080 .kevent_size = sizeof(struct kevent_freebsd11),
1082 struct g_kevent_args gk_args = {
1084 .changelist = uap->changelist,
1085 .nchanges = uap->nchanges,
1086 .eventlist = uap->eventlist,
1087 .nevents = uap->nevents,
1088 .timeout = uap->timeout,
1091 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent_freebsd11"));
1096 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1097 struct kevent_copyops *k_ops, const struct timespec *timeout)
1099 cap_rights_t rights;
1103 cap_rights_init(&rights);
1105 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
1107 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
1108 error = fget(td, fd, &rights, &fp);
1112 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1119 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1120 struct kevent_copyops *k_ops, const struct timespec *timeout)
1122 struct kevent keva[KQ_NEVENTS];
1123 struct kevent *kevp, *changes;
1124 int i, n, nerrors, error;
1127 while (nchanges > 0) {
1128 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1129 error = k_ops->k_copyin(k_ops->arg, keva, n);
1133 for (i = 0; i < n; i++) {
1137 kevp->flags &= ~EV_SYSFLAGS;
1138 error = kqueue_register(kq, kevp, td, 1);
1139 if (error || (kevp->flags & EV_RECEIPT)) {
1142 kevp->flags = EV_ERROR;
1144 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1152 td->td_retval[0] = nerrors;
1156 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1160 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1161 struct kevent_copyops *k_ops, const struct timespec *timeout)
1166 error = kqueue_acquire(fp, &kq);
1169 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1170 kqueue_release(kq, 0);
1175 * Performs a kevent() call on a temporarily created kqueue. This can be
1176 * used to perform one-shot polling, similar to poll() and select().
1179 kern_kevent_anonymous(struct thread *td, int nevents,
1180 struct kevent_copyops *k_ops)
1182 struct kqueue kq = {};
1187 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1188 kqueue_drain(&kq, td);
1189 kqueue_destroy(&kq);
1194 kqueue_add_filteropts(int filt, struct filterops *filtops)
1199 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1201 "trying to add a filterop that is out of range: %d is beyond %d\n",
1202 ~filt, EVFILT_SYSCOUNT);
1205 mtx_lock(&filterops_lock);
1206 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1207 sysfilt_ops[~filt].for_fop != NULL)
1210 sysfilt_ops[~filt].for_fop = filtops;
1211 sysfilt_ops[~filt].for_refcnt = 0;
1213 mtx_unlock(&filterops_lock);
1219 kqueue_del_filteropts(int filt)
1224 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1227 mtx_lock(&filterops_lock);
1228 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1229 sysfilt_ops[~filt].for_fop == NULL)
1231 else if (sysfilt_ops[~filt].for_refcnt != 0)
1234 sysfilt_ops[~filt].for_fop = &null_filtops;
1235 sysfilt_ops[~filt].for_refcnt = 0;
1237 mtx_unlock(&filterops_lock);
1242 static struct filterops *
1243 kqueue_fo_find(int filt)
1246 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1249 if (sysfilt_ops[~filt].for_nolock)
1250 return sysfilt_ops[~filt].for_fop;
1252 mtx_lock(&filterops_lock);
1253 sysfilt_ops[~filt].for_refcnt++;
1254 if (sysfilt_ops[~filt].for_fop == NULL)
1255 sysfilt_ops[~filt].for_fop = &null_filtops;
1256 mtx_unlock(&filterops_lock);
1258 return sysfilt_ops[~filt].for_fop;
1262 kqueue_fo_release(int filt)
1265 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1268 if (sysfilt_ops[~filt].for_nolock)
1271 mtx_lock(&filterops_lock);
1272 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1273 ("filter object refcount not valid on release"));
1274 sysfilt_ops[~filt].for_refcnt--;
1275 mtx_unlock(&filterops_lock);
1279 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1280 * influence if memory allocation should wait. Make sure it is 0 if you
1284 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1286 struct filterops *fops;
1288 struct knote *kn, *tkn;
1290 cap_rights_t rights;
1291 int error, filt, event;
1292 int haskqglobal, filedesc_unlock;
1294 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1302 filedesc_unlock = 0;
1305 fops = kqueue_fo_find(filt);
1309 if (kev->flags & EV_ADD) {
1311 * Prevent waiting with locks. Non-sleepable
1312 * allocation failures are handled in the loop, only
1313 * if the spare knote appears to be actually required.
1315 tkn = knote_alloc(waitok);
1322 KASSERT(td != NULL, ("td is NULL"));
1323 if (kev->ident > INT_MAX)
1326 error = fget(td, kev->ident,
1327 cap_rights_init(&rights, CAP_EVENT), &fp);
1331 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1332 kev->ident, 0) != 0) {
1336 error = kqueue_expand(kq, fops, kev->ident, waitok);
1342 if (fp->f_type == DTYPE_KQUEUE) {
1344 * If we add some intelligence about what we are doing,
1345 * we should be able to support events on ourselves.
1346 * We need to know when we are doing this to prevent
1347 * getting both the knlist lock and the kq lock since
1348 * they are the same thing.
1350 if (fp->f_data == kq) {
1356 * Pre-lock the filedesc before the global
1357 * lock mutex, see the comment in
1360 FILEDESC_XLOCK(td->td_proc->p_fd);
1361 filedesc_unlock = 1;
1362 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1366 if (kev->ident < kq->kq_knlistsize) {
1367 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1368 if (kev->filter == kn->kn_filter)
1372 if ((kev->flags & EV_ADD) == EV_ADD)
1373 kqueue_expand(kq, fops, kev->ident, waitok);
1378 * If possible, find an existing knote to use for this kevent.
1380 if (kev->filter == EVFILT_PROC &&
1381 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1382 /* This is an internal creation of a process tracking
1383 * note. Don't attempt to coalesce this with an
1387 } else if (kq->kq_knhashmask != 0) {
1390 list = &kq->kq_knhash[
1391 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1392 SLIST_FOREACH(kn, list, kn_link)
1393 if (kev->ident == kn->kn_id &&
1394 kev->filter == kn->kn_filter)
1399 /* knote is in the process of changing, wait for it to stabilize. */
1400 if (kn != NULL && kn_in_flux(kn)) {
1401 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1402 if (filedesc_unlock) {
1403 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1404 filedesc_unlock = 0;
1406 kq->kq_state |= KQ_FLUXWAIT;
1407 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1416 * kn now contains the matching knote, or NULL if no match
1419 if (kev->flags & EV_ADD) {
1431 * apply reference counts to knote structure, and
1432 * do not release it at the end of this routine.
1437 kn->kn_sfflags = kev->fflags;
1438 kn->kn_sdata = kev->data;
1441 kn->kn_kevent = *kev;
1442 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1443 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1444 kn->kn_status = KN_DETACHED;
1447 error = knote_attach(kn, kq);
1454 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1455 knote_drop_detached(kn, td);
1458 knl = kn_list_lock(kn);
1461 /* No matching knote and the EV_ADD flag is not set. */
1468 if (kev->flags & EV_DELETE) {
1475 if (kev->flags & EV_FORCEONESHOT) {
1476 kn->kn_flags |= EV_ONESHOT;
1477 KNOTE_ACTIVATE(kn, 1);
1481 * The user may change some filter values after the initial EV_ADD,
1482 * but doing so will not reset any filter which has already been
1485 kn->kn_status |= KN_SCAN;
1488 knl = kn_list_lock(kn);
1489 kn->kn_kevent.udata = kev->udata;
1490 if (!fops->f_isfd && fops->f_touch != NULL) {
1491 fops->f_touch(kn, kev, EVENT_REGISTER);
1493 kn->kn_sfflags = kev->fflags;
1494 kn->kn_sdata = kev->data;
1498 * We can get here with kn->kn_knlist == NULL. This can happen when
1499 * the initial attach event decides that the event is "completed"
1500 * already. i.e. filt_procattach is called on a zombie process. It
1501 * will call filt_proc which will remove it from the list, and NULL
1505 if ((kev->flags & EV_ENABLE) != 0)
1506 kn->kn_status &= ~KN_DISABLED;
1507 else if ((kev->flags & EV_DISABLE) != 0)
1508 kn->kn_status |= KN_DISABLED;
1510 if ((kn->kn_status & KN_DISABLED) == 0)
1511 event = kn->kn_fop->f_event(kn, 0);
1517 kn->kn_status |= KN_ACTIVE;
1518 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1521 kn->kn_status &= ~KN_SCAN;
1523 kn_list_unlock(knl);
1527 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1528 if (filedesc_unlock)
1529 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1534 kqueue_fo_release(filt);
1539 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1547 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1551 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1562 kqueue_release(struct kqueue *kq, int locked)
1569 if (kq->kq_refcnt == 1)
1570 wakeup(&kq->kq_refcnt);
1576 kqueue_schedtask(struct kqueue *kq)
1580 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1581 ("scheduling kqueue task while draining"));
1583 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1584 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1585 kq->kq_state |= KQ_TASKSCHED;
1590 * Expand the kq to make sure we have storage for fops/ident pair.
1592 * Return 0 on success (or no work necessary), return errno on failure.
1594 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1595 * If kqueue_register is called from a non-fd context, there usually/should
1599 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1602 struct klist *list, *tmp_knhash, *to_free;
1603 u_long tmp_knhashmask;
1606 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1613 if (kq->kq_knlistsize <= fd) {
1614 size = kq->kq_knlistsize;
1617 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1621 if (kq->kq_knlistsize > fd) {
1625 if (kq->kq_knlist != NULL) {
1626 bcopy(kq->kq_knlist, list,
1627 kq->kq_knlistsize * sizeof(*list));
1628 to_free = kq->kq_knlist;
1629 kq->kq_knlist = NULL;
1631 bzero((caddr_t)list +
1632 kq->kq_knlistsize * sizeof(*list),
1633 (size - kq->kq_knlistsize) * sizeof(*list));
1634 kq->kq_knlistsize = size;
1635 kq->kq_knlist = list;
1640 if (kq->kq_knhashmask == 0) {
1641 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1643 if (tmp_knhash == NULL)
1646 if (kq->kq_knhashmask == 0) {
1647 kq->kq_knhash = tmp_knhash;
1648 kq->kq_knhashmask = tmp_knhashmask;
1650 to_free = tmp_knhash;
1655 free(to_free, M_KQUEUE);
1662 kqueue_task(void *arg, int pending)
1670 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1673 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1675 kq->kq_state &= ~KQ_TASKSCHED;
1676 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1677 wakeup(&kq->kq_state);
1680 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1684 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1685 * We treat KN_MARKER knotes as if they are in flux.
1688 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1689 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1691 struct kevent *kevp;
1692 struct knote *kn, *marker;
1694 sbintime_t asbt, rsbt;
1695 int count, error, haskqglobal, influx, nkev, touch;
1707 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1708 tsp->tv_nsec >= 1000000000) {
1712 if (timespecisset(tsp)) {
1713 if (tsp->tv_sec <= INT32_MAX) {
1714 rsbt = tstosbt(*tsp);
1715 if (TIMESEL(&asbt, rsbt))
1716 asbt += tc_tick_sbt;
1717 if (asbt <= SBT_MAX - rsbt)
1721 rsbt >>= tc_precexp;
1728 marker = knote_alloc(1);
1729 marker->kn_status = KN_MARKER;
1734 if (kq->kq_count == 0) {
1736 error = EWOULDBLOCK;
1738 kq->kq_state |= KQ_SLEEP;
1739 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1740 "kqread", asbt, rsbt, C_ABSOLUTE);
1744 /* don't restart after signals... */
1745 if (error == ERESTART)
1747 else if (error == EWOULDBLOCK)
1752 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1756 kn = TAILQ_FIRST(&kq->kq_head);
1758 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1764 kq->kq_state |= KQ_FLUXWAIT;
1765 error = msleep(kq, &kq->kq_lock, PSOCK,
1770 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1771 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1772 kn->kn_status &= ~KN_QUEUED;
1778 if (count == maxevents)
1782 KASSERT(!kn_in_flux(kn),
1783 ("knote %p is unexpectedly in flux", kn));
1785 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1786 kn->kn_status &= ~KN_QUEUED;
1791 * We don't need to lock the list since we've
1792 * marked it as in flux.
1797 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1798 kn->kn_status &= ~KN_QUEUED;
1803 * We don't need to lock the list since we've
1804 * marked the knote as being in flux.
1806 *kevp = kn->kn_kevent;
1811 kn->kn_status |= KN_SCAN;
1814 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1815 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1816 knl = kn_list_lock(kn);
1817 if (kn->kn_fop->f_event(kn, 0) == 0) {
1819 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1820 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
1824 kn_list_unlock(knl);
1828 touch = (!kn->kn_fop->f_isfd &&
1829 kn->kn_fop->f_touch != NULL);
1831 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1833 *kevp = kn->kn_kevent;
1835 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1836 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1838 * Manually clear knotes who weren't
1841 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1845 if (kn->kn_flags & EV_DISPATCH)
1846 kn->kn_status |= KN_DISABLED;
1847 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1850 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1852 kn->kn_status &= ~KN_SCAN;
1854 kn_list_unlock(knl);
1858 /* we are returning a copy to the user */
1863 if (nkev == KQ_NEVENTS) {
1866 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1874 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1882 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1883 td->td_retval[0] = maxevents - count;
1889 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1890 struct ucred *active_cred, struct thread *td)
1893 * Enabling sigio causes two major problems:
1894 * 1) infinite recursion:
1895 * Synopsys: kevent is being used to track signals and have FIOASYNC
1896 * set. On receipt of a signal this will cause a kqueue to recurse
1897 * into itself over and over. Sending the sigio causes the kqueue
1898 * to become ready, which in turn posts sigio again, forever.
1899 * Solution: this can be solved by setting a flag in the kqueue that
1900 * we have a SIGIO in progress.
1901 * 2) locking problems:
1902 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1903 * us above the proc and pgrp locks.
1904 * Solution: Post a signal using an async mechanism, being sure to
1905 * record a generation count in the delivery so that we do not deliver
1906 * a signal to the wrong process.
1908 * Note, these two mechanisms are somewhat mutually exclusive!
1917 kq->kq_state |= KQ_ASYNC;
1919 kq->kq_state &= ~KQ_ASYNC;
1924 return (fsetown(*(int *)data, &kq->kq_sigio));
1927 *(int *)data = fgetown(&kq->kq_sigio);
1937 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1944 if ((error = kqueue_acquire(fp, &kq)))
1948 if (events & (POLLIN | POLLRDNORM)) {
1950 revents |= events & (POLLIN | POLLRDNORM);
1952 selrecord(td, &kq->kq_sel);
1953 if (SEL_WAITING(&kq->kq_sel))
1954 kq->kq_state |= KQ_SEL;
1957 kqueue_release(kq, 1);
1964 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1968 bzero((void *)st, sizeof *st);
1970 * We no longer return kq_count because the unlocked value is useless.
1971 * If you spent all this time getting the count, why not spend your
1972 * syscall better by calling kevent?
1974 * XXX - This is needed for libc_r.
1976 st->st_mode = S_IFIFO;
1981 kqueue_drain(struct kqueue *kq, struct thread *td)
1988 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1989 ("kqueue already closing"));
1990 kq->kq_state |= KQ_CLOSING;
1991 if (kq->kq_refcnt > 1)
1992 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1994 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1996 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1997 ("kqueue's knlist not empty"));
1999 for (i = 0; i < kq->kq_knlistsize; i++) {
2000 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
2001 if (kn_in_flux(kn)) {
2002 kq->kq_state |= KQ_FLUXWAIT;
2003 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
2012 if (kq->kq_knhashmask != 0) {
2013 for (i = 0; i <= kq->kq_knhashmask; i++) {
2014 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
2015 if (kn_in_flux(kn)) {
2016 kq->kq_state |= KQ_FLUXWAIT;
2017 msleep(kq, &kq->kq_lock, PSOCK,
2029 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
2030 kq->kq_state |= KQ_TASKDRAIN;
2031 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2034 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2035 selwakeuppri(&kq->kq_sel, PSOCK);
2036 if (!SEL_WAITING(&kq->kq_sel))
2037 kq->kq_state &= ~KQ_SEL;
2044 kqueue_destroy(struct kqueue *kq)
2047 KASSERT(kq->kq_fdp == NULL,
2048 ("kqueue still attached to a file descriptor"));
2049 seldrain(&kq->kq_sel);
2050 knlist_destroy(&kq->kq_sel.si_note);
2051 mtx_destroy(&kq->kq_lock);
2053 if (kq->kq_knhash != NULL)
2054 free(kq->kq_knhash, M_KQUEUE);
2055 if (kq->kq_knlist != NULL)
2056 free(kq->kq_knlist, M_KQUEUE);
2058 funsetown(&kq->kq_sigio);
2063 kqueue_close(struct file *fp, struct thread *td)
2065 struct kqueue *kq = fp->f_data;
2066 struct filedesc *fdp;
2068 int filedesc_unlock;
2070 if ((error = kqueue_acquire(fp, &kq)))
2072 kqueue_drain(kq, td);
2075 * We could be called due to the knote_drop() doing fdrop(),
2076 * called from kqueue_register(). In this case the global
2077 * lock is owned, and filedesc sx is locked before, to not
2078 * take the sleepable lock after non-sleepable.
2082 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2083 FILEDESC_XLOCK(fdp);
2084 filedesc_unlock = 1;
2086 filedesc_unlock = 0;
2087 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2088 if (filedesc_unlock)
2089 FILEDESC_XUNLOCK(fdp);
2092 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2093 crfree(kq->kq_cred);
2101 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2104 kif->kf_type = KF_TYPE_KQUEUE;
2109 kqueue_wakeup(struct kqueue *kq)
2113 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2114 kq->kq_state &= ~KQ_SLEEP;
2117 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2118 selwakeuppri(&kq->kq_sel, PSOCK);
2119 if (!SEL_WAITING(&kq->kq_sel))
2120 kq->kq_state &= ~KQ_SEL;
2122 if (!knlist_empty(&kq->kq_sel.si_note))
2123 kqueue_schedtask(kq);
2124 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2125 pgsigio(&kq->kq_sigio, SIGIO, 0);
2130 * Walk down a list of knotes, activating them if their event has triggered.
2132 * There is a possibility to optimize in the case of one kq watching another.
2133 * Instead of scheduling a task to wake it up, you could pass enough state
2134 * down the chain to make up the parent kqueue. Make this code functional
2138 knote(struct knlist *list, long hint, int lockflags)
2141 struct knote *kn, *tkn;
2147 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2149 if ((lockflags & KNF_LISTLOCKED) == 0)
2150 list->kl_lock(list->kl_lockarg);
2153 * If we unlock the list lock (and enter influx), we can
2154 * eliminate the kqueue scheduling, but this will introduce
2155 * four lock/unlock's for each knote to test. Also, marker
2156 * would be needed to keep iteration position, since filters
2157 * or other threads could remove events.
2159 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2162 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2164 * Do not process the influx notes, except for
2165 * the influx coming from the kq unlock in the
2166 * kqueue_scan(). In the later case, we do
2167 * not interfere with the scan, since the code
2168 * fragment in kqueue_scan() locks the knlist,
2169 * and cannot proceed until we finished.
2172 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2175 error = kn->kn_fop->f_event(kn, hint);
2179 KNOTE_ACTIVATE(kn, 1);
2182 kn->kn_status |= KN_HASKQLOCK;
2183 if (kn->kn_fop->f_event(kn, hint))
2184 KNOTE_ACTIVATE(kn, 1);
2185 kn->kn_status &= ~KN_HASKQLOCK;
2189 if ((lockflags & KNF_LISTLOCKED) == 0)
2190 list->kl_unlock(list->kl_lockarg);
2194 * add a knote to a knlist
2197 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2200 KNL_ASSERT_LOCK(knl, islocked);
2201 KQ_NOTOWNED(kn->kn_kq);
2202 KASSERT(kn_in_flux(kn), ("knote %p not in flux", kn));
2203 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2204 ("knote %p was not detached", kn));
2206 knl->kl_lock(knl->kl_lockarg);
2207 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2209 knl->kl_unlock(knl->kl_lockarg);
2211 kn->kn_knlist = knl;
2212 kn->kn_status &= ~KN_DETACHED;
2213 KQ_UNLOCK(kn->kn_kq);
2217 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2221 KASSERT(!kqislocked || knlislocked, ("kq locked w/o knl locked"));
2222 KNL_ASSERT_LOCK(knl, knlislocked);
2223 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2224 KASSERT(kqislocked || kn_in_flux(kn), ("knote %p not in flux", kn));
2225 KASSERT((kn->kn_status & KN_DETACHED) == 0,
2226 ("knote %p was already detached", kn));
2228 knl->kl_lock(knl->kl_lockarg);
2229 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2230 kn->kn_knlist = NULL;
2232 kn_list_unlock(knl);
2235 kn->kn_status |= KN_DETACHED;
2237 KQ_UNLOCK(kn->kn_kq);
2241 * remove knote from the specified knlist
2244 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2247 knlist_remove_kq(knl, kn, islocked, 0);
2251 knlist_empty(struct knlist *knl)
2254 KNL_ASSERT_LOCKED(knl);
2255 return (SLIST_EMPTY(&knl->kl_list));
2258 static struct mtx knlist_lock;
2259 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2261 static void knlist_mtx_lock(void *arg);
2262 static void knlist_mtx_unlock(void *arg);
2265 knlist_mtx_lock(void *arg)
2268 mtx_lock((struct mtx *)arg);
2272 knlist_mtx_unlock(void *arg)
2275 mtx_unlock((struct mtx *)arg);
2279 knlist_mtx_assert_locked(void *arg)
2282 mtx_assert((struct mtx *)arg, MA_OWNED);
2286 knlist_mtx_assert_unlocked(void *arg)
2289 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2293 knlist_rw_rlock(void *arg)
2296 rw_rlock((struct rwlock *)arg);
2300 knlist_rw_runlock(void *arg)
2303 rw_runlock((struct rwlock *)arg);
2307 knlist_rw_assert_locked(void *arg)
2310 rw_assert((struct rwlock *)arg, RA_LOCKED);
2314 knlist_rw_assert_unlocked(void *arg)
2317 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2321 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2322 void (*kl_unlock)(void *),
2323 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2327 knl->kl_lockarg = &knlist_lock;
2329 knl->kl_lockarg = lock;
2331 if (kl_lock == NULL)
2332 knl->kl_lock = knlist_mtx_lock;
2334 knl->kl_lock = kl_lock;
2335 if (kl_unlock == NULL)
2336 knl->kl_unlock = knlist_mtx_unlock;
2338 knl->kl_unlock = kl_unlock;
2339 if (kl_assert_locked == NULL)
2340 knl->kl_assert_locked = knlist_mtx_assert_locked;
2342 knl->kl_assert_locked = kl_assert_locked;
2343 if (kl_assert_unlocked == NULL)
2344 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2346 knl->kl_assert_unlocked = kl_assert_unlocked;
2348 knl->kl_autodestroy = 0;
2349 SLIST_INIT(&knl->kl_list);
2353 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2356 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2360 knlist_alloc(struct mtx *lock)
2364 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2365 knlist_init_mtx(knl, lock);
2370 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2373 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2374 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2378 knlist_destroy(struct knlist *knl)
2381 KASSERT(KNLIST_EMPTY(knl),
2382 ("destroying knlist %p with knotes on it", knl));
2386 knlist_detach(struct knlist *knl)
2389 KNL_ASSERT_LOCKED(knl);
2390 knl->kl_autodestroy = 1;
2391 if (knlist_empty(knl)) {
2392 knlist_destroy(knl);
2393 free(knl, M_KQUEUE);
2398 * Even if we are locked, we may need to drop the lock to allow any influx
2399 * knotes time to "settle".
2402 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2404 struct knote *kn, *kn2;
2407 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2409 KNL_ASSERT_LOCKED(knl);
2411 KNL_ASSERT_UNLOCKED(knl);
2412 again: /* need to reacquire lock since we have dropped it */
2413 knl->kl_lock(knl->kl_lockarg);
2416 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2419 if (kn_in_flux(kn)) {
2423 knlist_remove_kq(knl, kn, 1, 1);
2427 knote_drop_detached(kn, td);
2429 /* Make sure cleared knotes disappear soon */
2430 kn->kn_flags |= EV_EOF | EV_ONESHOT;
2436 if (!SLIST_EMPTY(&knl->kl_list)) {
2437 /* there are still in flux knotes remaining */
2438 kn = SLIST_FIRST(&knl->kl_list);
2441 KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2442 knl->kl_unlock(knl->kl_lockarg);
2443 kq->kq_state |= KQ_FLUXWAIT;
2444 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2450 KNL_ASSERT_LOCKED(knl);
2452 knl->kl_unlock(knl->kl_lockarg);
2453 KNL_ASSERT_UNLOCKED(knl);
2458 * Remove all knotes referencing a specified fd must be called with FILEDESC
2459 * lock. This prevents a race where a new fd comes along and occupies the
2460 * entry and we attach a knote to the fd.
2463 knote_fdclose(struct thread *td, int fd)
2465 struct filedesc *fdp = td->td_proc->p_fd;
2470 FILEDESC_XLOCK_ASSERT(fdp);
2473 * We shouldn't have to worry about new kevents appearing on fd
2474 * since filedesc is locked.
2476 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2481 while (kq->kq_knlistsize > fd &&
2482 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2483 if (kn_in_flux(kn)) {
2484 /* someone else might be waiting on our knote */
2487 kq->kq_state |= KQ_FLUXWAIT;
2488 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2502 knote_attach(struct knote *kn, struct kqueue *kq)
2506 KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2509 if (kn->kn_fop->f_isfd) {
2510 if (kn->kn_id >= kq->kq_knlistsize)
2512 list = &kq->kq_knlist[kn->kn_id];
2514 if (kq->kq_knhash == NULL)
2516 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2518 SLIST_INSERT_HEAD(list, kn, kn_link);
2523 knote_drop(struct knote *kn, struct thread *td)
2526 if ((kn->kn_status & KN_DETACHED) == 0)
2527 kn->kn_fop->f_detach(kn);
2528 knote_drop_detached(kn, td);
2532 knote_drop_detached(struct knote *kn, struct thread *td)
2539 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2540 ("knote %p still attached", kn));
2544 KASSERT(kn->kn_influx == 1,
2545 ("knote_drop called on %p with influx %d", kn, kn->kn_influx));
2547 if (kn->kn_fop->f_isfd)
2548 list = &kq->kq_knlist[kn->kn_id];
2550 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2552 if (!SLIST_EMPTY(list))
2553 SLIST_REMOVE(list, kn, knote, kn_link);
2554 if (kn->kn_status & KN_QUEUED)
2558 if (kn->kn_fop->f_isfd) {
2559 fdrop(kn->kn_fp, td);
2562 kqueue_fo_release(kn->kn_kevent.filter);
2568 knote_enqueue(struct knote *kn)
2570 struct kqueue *kq = kn->kn_kq;
2572 KQ_OWNED(kn->kn_kq);
2573 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2575 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2576 kn->kn_status |= KN_QUEUED;
2582 knote_dequeue(struct knote *kn)
2584 struct kqueue *kq = kn->kn_kq;
2586 KQ_OWNED(kn->kn_kq);
2587 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2589 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2590 kn->kn_status &= ~KN_QUEUED;
2598 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2599 NULL, NULL, UMA_ALIGN_PTR, 0);
2601 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2603 static struct knote *
2604 knote_alloc(int waitok)
2607 return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2612 knote_free(struct knote *kn)
2615 uma_zfree(knote_zone, kn);
2619 * Register the kev w/ the kq specified by fd.
2622 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2626 cap_rights_t rights;
2629 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2632 if ((error = kqueue_acquire(fp, &kq)) != 0)
2635 error = kqueue_register(kq, kev, td, waitok);
2636 kqueue_release(kq, 0);