2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
5 * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
6 * Copyright (c) 2009 Apple, Inc.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include "opt_ktrace.h"
35 #include "opt_kqueue.h"
37 #ifdef COMPAT_FREEBSD11
38 #define _WANT_FREEBSD11_KEVENT
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/capsicum.h>
44 #include <sys/kernel.h>
45 #include <sys/limits.h>
47 #include <sys/mutex.h>
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 mflag);
106 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
107 static void kqueue_release(struct kqueue *kq, int locked);
108 static void kqueue_destroy(struct kqueue *kq);
109 static void kqueue_drain(struct kqueue *kq, struct thread *td);
110 static int kqueue_expand(struct kqueue *kq, struct filterops *fops,
111 uintptr_t ident, int mflag);
112 static void kqueue_task(void *arg, int pending);
113 static int kqueue_scan(struct kqueue *kq, int maxevents,
114 struct kevent_copyops *k_ops,
115 const struct timespec *timeout,
116 struct kevent *keva, struct thread *td);
117 static void kqueue_wakeup(struct kqueue *kq);
118 static struct filterops *kqueue_fo_find(int filt);
119 static void kqueue_fo_release(int filt);
120 struct g_kevent_args;
121 static int kern_kevent_generic(struct thread *td,
122 struct g_kevent_args *uap,
123 struct kevent_copyops *k_ops, const char *struct_name);
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 mflag);
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 void filt_timerexpire_l(struct knote *kn, bool proc_locked);
164 static int filt_timerattach(struct knote *kn);
165 static void filt_timerdetach(struct knote *kn);
166 static void filt_timerstart(struct knote *kn, sbintime_t to);
167 static void filt_timertouch(struct knote *kn, struct kevent *kev,
169 static int filt_timervalidate(struct knote *kn, sbintime_t *to);
170 static int filt_timer(struct knote *kn, long hint);
171 static int filt_userattach(struct knote *kn);
172 static void filt_userdetach(struct knote *kn);
173 static int filt_user(struct knote *kn, long hint);
174 static void filt_usertouch(struct knote *kn, struct kevent *kev,
177 static struct filterops file_filtops = {
179 .f_attach = filt_fileattach,
181 static struct filterops kqread_filtops = {
183 .f_detach = filt_kqdetach,
184 .f_event = filt_kqueue,
186 /* XXX - move to kern_proc.c? */
187 static struct filterops proc_filtops = {
189 .f_attach = filt_procattach,
190 .f_detach = filt_procdetach,
191 .f_event = filt_proc,
193 static struct filterops timer_filtops = {
195 .f_attach = filt_timerattach,
196 .f_detach = filt_timerdetach,
197 .f_event = filt_timer,
198 .f_touch = filt_timertouch,
200 static struct filterops user_filtops = {
201 .f_attach = filt_userattach,
202 .f_detach = filt_userdetach,
203 .f_event = filt_user,
204 .f_touch = filt_usertouch,
207 static uma_zone_t knote_zone;
208 static unsigned int __exclusive_cache_line kq_ncallouts;
209 static unsigned int kq_calloutmax = 4 * 1024;
210 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
211 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
213 /* XXX - ensure not influx ? */
214 #define KNOTE_ACTIVATE(kn, islock) do { \
216 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
218 KQ_LOCK((kn)->kn_kq); \
219 (kn)->kn_status |= KN_ACTIVE; \
220 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
221 knote_enqueue((kn)); \
223 KQ_UNLOCK((kn)->kn_kq); \
225 #define KQ_LOCK(kq) do { \
226 mtx_lock(&(kq)->kq_lock); \
228 #define KQ_FLUX_WAKEUP(kq) do { \
229 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
230 (kq)->kq_state &= ~KQ_FLUXWAIT; \
234 #define KQ_UNLOCK_FLUX(kq) do { \
235 KQ_FLUX_WAKEUP(kq); \
236 mtx_unlock(&(kq)->kq_lock); \
238 #define KQ_UNLOCK(kq) do { \
239 mtx_unlock(&(kq)->kq_lock); \
241 #define KQ_OWNED(kq) do { \
242 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
244 #define KQ_NOTOWNED(kq) do { \
245 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
248 static struct knlist *
249 kn_list_lock(struct knote *kn)
255 knl->kl_lock(knl->kl_lockarg);
260 kn_list_unlock(struct knlist *knl)
266 do_free = knl->kl_autodestroy && knlist_empty(knl);
267 knl->kl_unlock(knl->kl_lockarg);
275 kn_in_flux(struct knote *kn)
278 return (kn->kn_influx > 0);
282 kn_enter_flux(struct knote *kn)
286 MPASS(kn->kn_influx < INT_MAX);
291 kn_leave_flux(struct knote *kn)
295 MPASS(kn->kn_influx > 0);
297 return (kn->kn_influx == 0);
300 #define KNL_ASSERT_LOCK(knl, islocked) do { \
302 KNL_ASSERT_LOCKED(knl); \
304 KNL_ASSERT_UNLOCKED(knl); \
307 #define KNL_ASSERT_LOCKED(knl) do { \
308 knl->kl_assert_lock((knl)->kl_lockarg, LA_LOCKED); \
310 #define KNL_ASSERT_UNLOCKED(knl) do { \
311 knl->kl_assert_lock((knl)->kl_lockarg, LA_UNLOCKED); \
313 #else /* !INVARIANTS */
314 #define KNL_ASSERT_LOCKED(knl) do {} while (0)
315 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
316 #endif /* INVARIANTS */
319 #define KN_HASHSIZE 64 /* XXX should be tunable */
322 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
325 filt_nullattach(struct knote *kn)
331 struct filterops null_filtops = {
333 .f_attach = filt_nullattach,
336 /* XXX - make SYSINIT to add these, and move into respective modules. */
337 extern struct filterops sig_filtops;
338 extern struct filterops fs_filtops;
341 * Table for all system-defined filters.
343 static struct mtx filterops_lock;
344 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
347 struct filterops *for_fop;
350 } sysfilt_ops[EVFILT_SYSCOUNT] = {
351 { &file_filtops, 1 }, /* EVFILT_READ */
352 { &file_filtops, 1 }, /* EVFILT_WRITE */
353 { &null_filtops }, /* EVFILT_AIO */
354 { &file_filtops, 1 }, /* EVFILT_VNODE */
355 { &proc_filtops, 1 }, /* EVFILT_PROC */
356 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
357 { &timer_filtops, 1 }, /* EVFILT_TIMER */
358 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
359 { &fs_filtops, 1 }, /* EVFILT_FS */
360 { &null_filtops }, /* EVFILT_LIO */
361 { &user_filtops, 1 }, /* EVFILT_USER */
362 { &null_filtops }, /* EVFILT_SENDFILE */
363 { &file_filtops, 1 }, /* EVFILT_EMPTY */
367 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
371 filt_fileattach(struct knote *kn)
374 return (fo_kqfilter(kn->kn_fp, kn));
379 kqueue_kqfilter(struct file *fp, struct knote *kn)
381 struct kqueue *kq = kn->kn_fp->f_data;
383 if (kn->kn_filter != EVFILT_READ)
386 kn->kn_status |= KN_KQUEUE;
387 kn->kn_fop = &kqread_filtops;
388 knlist_add(&kq->kq_sel.si_note, kn, 0);
394 filt_kqdetach(struct knote *kn)
396 struct kqueue *kq = kn->kn_fp->f_data;
398 knlist_remove(&kq->kq_sel.si_note, kn, 0);
403 filt_kqueue(struct knote *kn, long hint)
405 struct kqueue *kq = kn->kn_fp->f_data;
407 kn->kn_data = kq->kq_count;
408 return (kn->kn_data > 0);
411 /* XXX - move to kern_proc.c? */
413 filt_procattach(struct knote *kn)
417 bool exiting, immediate;
419 exiting = immediate = false;
420 if (kn->kn_sfflags & NOTE_EXIT)
421 p = pfind_any(kn->kn_id);
423 p = pfind(kn->kn_id);
426 if (p->p_flag & P_WEXIT)
429 if ((error = p_cansee(curthread, p))) {
434 kn->kn_ptr.p_proc = p;
435 kn->kn_flags |= EV_CLEAR; /* automatically set */
438 * Internal flag indicating registration done by kernel for the
439 * purposes of getting a NOTE_CHILD notification.
441 if (kn->kn_flags & EV_FLAG2) {
442 kn->kn_flags &= ~EV_FLAG2;
443 kn->kn_data = kn->kn_sdata; /* ppid */
444 kn->kn_fflags = NOTE_CHILD;
445 kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
446 immediate = true; /* Force immediate activation of child note. */
449 * Internal flag indicating registration done by kernel (for other than
452 if (kn->kn_flags & EV_FLAG1) {
453 kn->kn_flags &= ~EV_FLAG1;
456 knlist_add(p->p_klist, kn, 1);
459 * Immediately activate any child notes or, in the case of a zombie
460 * target process, exit notes. The latter is necessary to handle the
461 * case where the target process, e.g. a child, dies before the kevent
464 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
465 KNOTE_ACTIVATE(kn, 0);
473 * The knote may be attached to a different process, which may exit,
474 * leaving nothing for the knote to be attached to. So when the process
475 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
476 * it will be deleted when read out. However, as part of the knote deletion,
477 * this routine is called, so a check is needed to avoid actually performing
478 * a detach, because the original process does not exist any more.
480 /* XXX - move to kern_proc.c? */
482 filt_procdetach(struct knote *kn)
485 knlist_remove(kn->kn_knlist, kn, 0);
486 kn->kn_ptr.p_proc = NULL;
489 /* XXX - move to kern_proc.c? */
491 filt_proc(struct knote *kn, long hint)
496 p = kn->kn_ptr.p_proc;
497 if (p == NULL) /* already activated, from attach filter */
500 /* Mask off extra data. */
501 event = (u_int)hint & NOTE_PCTRLMASK;
503 /* If the user is interested in this event, record it. */
504 if (kn->kn_sfflags & event)
505 kn->kn_fflags |= event;
507 /* Process is gone, so flag the event as finished. */
508 if (event == NOTE_EXIT) {
509 kn->kn_flags |= EV_EOF | EV_ONESHOT;
510 kn->kn_ptr.p_proc = NULL;
511 if (kn->kn_fflags & NOTE_EXIT)
512 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
513 if (kn->kn_fflags == 0)
514 kn->kn_flags |= EV_DROP;
518 return (kn->kn_fflags != 0);
522 * Called when the process forked. It mostly does the same as the
523 * knote(), activating all knotes registered to be activated when the
524 * process forked. Additionally, for each knote attached to the
525 * parent, check whether user wants to track the new process. If so
526 * attach a new knote to it, and immediately report an event with the
530 knote_fork(struct knlist *list, int pid)
538 KNL_ASSERT_LOCKED(list);
539 if (SLIST_EMPTY(&list->kl_list))
542 memset(&kev, 0, sizeof(kev));
543 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
546 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
552 * The same as knote(), activate the event.
554 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
555 if (kn->kn_fop->f_event(kn, NOTE_FORK))
556 KNOTE_ACTIVATE(kn, 1);
562 * The NOTE_TRACK case. In addition to the activation
563 * of the event, we need to register new events to
564 * track the child. Drop the locks in preparation for
565 * the call to kqueue_register().
569 list->kl_unlock(list->kl_lockarg);
572 * Activate existing knote and register tracking knotes with
575 * First register a knote to get just the child notice. This
576 * must be a separate note from a potential NOTE_EXIT
577 * notification since both NOTE_CHILD and NOTE_EXIT are defined
578 * to use the data field (in conflicting ways).
581 kev.filter = kn->kn_filter;
582 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
584 kev.fflags = kn->kn_sfflags;
585 kev.data = kn->kn_id; /* parent */
586 kev.udata = kn->kn_kevent.udata;/* preserve udata */
587 error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
589 kn->kn_fflags |= NOTE_TRACKERR;
592 * Then register another knote to track other potential events
593 * from the new process.
596 kev.filter = kn->kn_filter;
597 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
598 kev.fflags = kn->kn_sfflags;
599 kev.data = kn->kn_id; /* parent */
600 kev.udata = kn->kn_kevent.udata;/* preserve udata */
601 error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
603 kn->kn_fflags |= NOTE_TRACKERR;
604 if (kn->kn_fop->f_event(kn, NOTE_FORK))
605 KNOTE_ACTIVATE(kn, 0);
606 list->kl_lock(list->kl_lockarg);
614 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
615 * interval timer support code.
618 #define NOTE_TIMER_PRECMASK \
619 (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
622 timer2sbintime(int64_t data, int flags)
627 * Macros for converting to the fractional second portion of an
628 * sbintime_t using 64bit multiplication to improve precision.
630 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
631 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
632 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
633 switch (flags & NOTE_TIMER_PRECMASK) {
636 if (data > (SBT_MAX / SBT_1S))
639 return ((sbintime_t)data << 32);
640 case NOTE_MSECONDS: /* FALLTHROUGH */
645 if (secs > (SBT_MAX / SBT_1S))
648 return (secs << 32 | MS_TO_SBT(data % 1000));
650 return (MS_TO_SBT(data));
652 if (data >= 1000000) {
653 secs = data / 1000000;
655 if (secs > (SBT_MAX / SBT_1S))
658 return (secs << 32 | US_TO_SBT(data % 1000000));
660 return (US_TO_SBT(data));
662 if (data >= 1000000000) {
663 secs = data / 1000000000;
665 if (secs > (SBT_MAX / SBT_1S))
668 return (secs << 32 | NS_TO_SBT(data % 1000000000));
670 return (NS_TO_SBT(data));
677 struct kq_timer_cb_data {
683 TAILQ_ENTRY(kq_timer_cb_data) link;
684 sbintime_t next; /* next timer event fires at */
685 sbintime_t to; /* precalculated timer period, 0 for abs */
688 #define KQ_TIMER_CB_ENQUEUED 0x01
691 kqtimer_sched_callout(struct kq_timer_cb_data *kc)
693 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kc->kn,
694 kc->cpuid, C_ABSOLUTE);
698 kqtimer_proc_continue(struct proc *p)
700 struct kq_timer_cb_data *kc, *kc1;
704 PROC_LOCK_ASSERT(p, MA_OWNED);
709 TAILQ_FOREACH_SAFE(kc, &p->p_kqtim_stop, link, kc1) {
710 TAILQ_REMOVE(&p->p_kqtim_stop, kc, link);
711 kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
713 filt_timerexpire_l(kc->kn, true);
715 kqtimer_sched_callout(kc);
720 filt_timerexpire_l(struct knote *kn, bool proc_locked)
722 struct kq_timer_cb_data *kc;
729 if ((kn->kn_flags & EV_ONESHOT) != 0 || kc->to == 0) {
731 KNOTE_ACTIVATE(kn, 0);
736 if (now >= kc->next) {
737 delta = (now - kc->next) / kc->to;
740 kn->kn_data += delta;
741 kc->next += delta * kc->to;
742 if (now >= kc->next) /* overflow */
743 kc->next = now + kc->to;
744 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
748 * Initial check for stopped kc->p is racy. It is fine to
749 * miss the set of the stop flags, at worst we would schedule
750 * one more callout. On the other hand, it is not fine to not
751 * schedule when we we missed clearing of the flags, we
752 * recheck them under the lock and observe consistent state.
755 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
758 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
759 if ((kc->flags & KQ_TIMER_CB_ENQUEUED) == 0) {
760 kc->flags |= KQ_TIMER_CB_ENQUEUED;
761 TAILQ_INSERT_TAIL(&p->p_kqtim_stop, kc, link);
770 kqtimer_sched_callout(kc);
774 filt_timerexpire(void *knx)
776 filt_timerexpire_l(knx, false);
780 * data contains amount of time to sleep
783 filt_timervalidate(struct knote *kn, sbintime_t *to)
788 if (kn->kn_sdata < 0)
790 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
793 * The only fflags values supported are the timer unit
794 * (precision) and the absolute time indicator.
796 if ((kn->kn_sfflags & ~(NOTE_TIMER_PRECMASK | NOTE_ABSTIME)) != 0)
799 *to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
802 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
805 *to = MAX(0, *to - sbt);
811 filt_timerattach(struct knote *kn)
813 struct kq_timer_cb_data *kc;
818 error = filt_timervalidate(kn, &to);
821 KASSERT(to > 0 || (kn->kn_flags & EV_ONESHOT) != 0 ||
822 (kn->kn_sfflags & NOTE_ABSTIME) != 0,
823 ("%s: periodic timer has a calculated zero timeout", __func__));
825 ("%s: timer has a calculated negative timeout", __func__));
827 if (atomic_fetchadd_int(&kq_ncallouts, 1) + 1 > kq_calloutmax) {
828 atomic_subtract_int(&kq_ncallouts, 1);
832 if ((kn->kn_sfflags & NOTE_ABSTIME) == 0)
833 kn->kn_flags |= EV_CLEAR; /* automatically set */
834 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
835 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
838 kc->cpuid = PCPU_GET(cpuid);
840 callout_init(&kc->c, 1);
841 filt_timerstart(kn, to);
847 filt_timerstart(struct knote *kn, sbintime_t to)
849 struct kq_timer_cb_data *kc;
852 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
856 kc->next = to + sbinuptime();
859 kqtimer_sched_callout(kc);
863 filt_timerdetach(struct knote *kn)
865 struct kq_timer_cb_data *kc;
866 unsigned int old __unused;
871 callout_drain(&kc->c);
874 * kqtimer_proc_continue() might have rescheduled this callout.
875 * Double-check, using the process mutex as an interlock.
878 if ((kc->flags & KQ_TIMER_CB_ENQUEUED) != 0) {
879 kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
880 TAILQ_REMOVE(&kc->p->p_kqtim_stop, kc, link);
882 pending = callout_pending(&kc->c);
886 old = atomic_fetchadd_int(&kq_ncallouts, -1);
887 KASSERT(old > 0, ("Number of callouts cannot become negative"));
888 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
892 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
894 struct kq_timer_cb_data *kc;
901 /* Handle re-added timers that update data/fflags */
902 if (kev->flags & EV_ADD) {
905 /* Drain any existing callout. */
906 callout_drain(&kc->c);
908 /* Throw away any existing undelivered record
909 * of the timer expiration. This is done under
910 * the presumption that if a process is
911 * re-adding this timer with new parameters,
912 * it is no longer interested in what may have
913 * happened under the old parameters. If it is
914 * interested, it can wait for the expiration,
915 * delete the old timer definition, and then
918 * This has to be done while the kq is locked:
919 * - if enqueued, dequeue
920 * - make it no longer active
921 * - clear the count of expiration events
925 if (kn->kn_status & KN_QUEUED)
928 kn->kn_status &= ~KN_ACTIVE;
932 /* Reschedule timer based on new data/fflags */
933 kn->kn_sfflags = kev->fflags;
934 kn->kn_sdata = kev->data;
935 error = filt_timervalidate(kn, &to);
937 kn->kn_flags |= EV_ERROR;
940 filt_timerstart(kn, to);
945 *kev = kn->kn_kevent;
946 if (kn->kn_flags & EV_CLEAR) {
953 panic("filt_timertouch() - invalid type (%ld)", type);
959 filt_timer(struct knote *kn, long hint)
962 return (kn->kn_data != 0);
966 filt_userattach(struct knote *kn)
970 * EVFILT_USER knotes are not attached to anything in the kernel.
973 if (kn->kn_fflags & NOTE_TRIGGER)
981 filt_userdetach(__unused struct knote *kn)
985 * EVFILT_USER knotes are not attached to anything in the kernel.
990 filt_user(struct knote *kn, __unused long hint)
993 return (kn->kn_hookid);
997 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
1002 case EVENT_REGISTER:
1003 if (kev->fflags & NOTE_TRIGGER)
1006 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
1007 kev->fflags &= NOTE_FFLAGSMASK;
1013 kn->kn_sfflags &= kev->fflags;
1017 kn->kn_sfflags |= kev->fflags;
1021 kn->kn_sfflags = kev->fflags;
1025 /* XXX Return error? */
1028 kn->kn_sdata = kev->data;
1029 if (kev->flags & EV_CLEAR) {
1037 *kev = kn->kn_kevent;
1038 kev->fflags = kn->kn_sfflags;
1039 kev->data = kn->kn_sdata;
1040 if (kn->kn_flags & EV_CLEAR) {
1048 panic("filt_usertouch() - invalid type (%ld)", type);
1054 sys_kqueue(struct thread *td, struct kqueue_args *uap)
1057 return (kern_kqueue(td, 0, NULL));
1061 sys_kqueuex(struct thread *td, struct kqueuex_args *uap)
1065 if ((uap->flags & ~(KQUEUE_CLOEXEC)) != 0)
1068 if ((uap->flags & KQUEUE_CLOEXEC) != 0)
1070 return (kern_kqueue(td, flags, NULL));
1074 kqueue_init(struct kqueue *kq)
1077 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
1078 TAILQ_INIT(&kq->kq_head);
1079 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
1080 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
1084 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
1086 struct filedesc *fdp;
1092 fdp = td->td_proc->p_fd;
1093 cred = td->td_ucred;
1094 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
1097 error = falloc_caps(td, &fp, &fd, flags, fcaps);
1099 chgkqcnt(cred->cr_ruidinfo, -1, 0);
1103 /* An extra reference on `fp' has been held for us by falloc(). */
1104 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
1107 kq->kq_cred = crhold(cred);
1109 FILEDESC_XLOCK(fdp);
1110 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
1111 FILEDESC_XUNLOCK(fdp);
1113 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
1116 td->td_retval[0] = fd;
1120 struct g_kevent_args {
1122 const void *changelist;
1126 const struct timespec *timeout;
1130 sys_kevent(struct thread *td, struct kevent_args *uap)
1132 struct kevent_copyops k_ops = {
1134 .k_copyout = kevent_copyout,
1135 .k_copyin = kevent_copyin,
1136 .kevent_size = sizeof(struct kevent),
1138 struct g_kevent_args gk_args = {
1140 .changelist = uap->changelist,
1141 .nchanges = uap->nchanges,
1142 .eventlist = uap->eventlist,
1143 .nevents = uap->nevents,
1144 .timeout = uap->timeout,
1147 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent"));
1151 kern_kevent_generic(struct thread *td, struct g_kevent_args *uap,
1152 struct kevent_copyops *k_ops, const char *struct_name)
1154 struct timespec ts, *tsp;
1156 struct kevent *eventlist = uap->eventlist;
1160 if (uap->timeout != NULL) {
1161 error = copyin(uap->timeout, &ts, sizeof(ts));
1169 if (KTRPOINT(td, KTR_STRUCT_ARRAY))
1170 ktrstructarray(struct_name, UIO_USERSPACE, uap->changelist,
1171 uap->nchanges, k_ops->kevent_size);
1174 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1178 if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1179 ktrstructarray(struct_name, UIO_USERSPACE, eventlist,
1180 td->td_retval[0], k_ops->kevent_size);
1187 * Copy 'count' items into the destination list pointed to by uap->eventlist.
1190 kevent_copyout(void *arg, struct kevent *kevp, int count)
1192 struct kevent_args *uap;
1195 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1196 uap = (struct kevent_args *)arg;
1198 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1200 uap->eventlist += count;
1205 * Copy 'count' items from the list pointed to by uap->changelist.
1208 kevent_copyin(void *arg, struct kevent *kevp, int count)
1210 struct kevent_args *uap;
1213 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1214 uap = (struct kevent_args *)arg;
1216 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1218 uap->changelist += count;
1222 #ifdef COMPAT_FREEBSD11
1224 kevent11_copyout(void *arg, struct kevent *kevp, int count)
1226 struct freebsd11_kevent_args *uap;
1227 struct freebsd11_kevent kev11;
1230 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1231 uap = (struct freebsd11_kevent_args *)arg;
1233 for (i = 0; i < count; i++) {
1234 kev11.ident = kevp->ident;
1235 kev11.filter = kevp->filter;
1236 kev11.flags = kevp->flags;
1237 kev11.fflags = kevp->fflags;
1238 kev11.data = kevp->data;
1239 kev11.udata = kevp->udata;
1240 error = copyout(&kev11, uap->eventlist, sizeof(kev11));
1250 * Copy 'count' items from the list pointed to by uap->changelist.
1253 kevent11_copyin(void *arg, struct kevent *kevp, int count)
1255 struct freebsd11_kevent_args *uap;
1256 struct freebsd11_kevent kev11;
1259 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1260 uap = (struct freebsd11_kevent_args *)arg;
1262 for (i = 0; i < count; i++) {
1263 error = copyin(uap->changelist, &kev11, sizeof(kev11));
1266 kevp->ident = kev11.ident;
1267 kevp->filter = kev11.filter;
1268 kevp->flags = kev11.flags;
1269 kevp->fflags = kev11.fflags;
1270 kevp->data = (uintptr_t)kev11.data;
1271 kevp->udata = kev11.udata;
1272 bzero(&kevp->ext, sizeof(kevp->ext));
1280 freebsd11_kevent(struct thread *td, struct freebsd11_kevent_args *uap)
1282 struct kevent_copyops k_ops = {
1284 .k_copyout = kevent11_copyout,
1285 .k_copyin = kevent11_copyin,
1286 .kevent_size = sizeof(struct freebsd11_kevent),
1288 struct g_kevent_args gk_args = {
1290 .changelist = uap->changelist,
1291 .nchanges = uap->nchanges,
1292 .eventlist = uap->eventlist,
1293 .nevents = uap->nevents,
1294 .timeout = uap->timeout,
1297 return (kern_kevent_generic(td, &gk_args, &k_ops, "freebsd11_kevent"));
1302 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1303 struct kevent_copyops *k_ops, const struct timespec *timeout)
1305 cap_rights_t rights;
1309 cap_rights_init_zero(&rights);
1311 cap_rights_set_one(&rights, CAP_KQUEUE_CHANGE);
1313 cap_rights_set_one(&rights, CAP_KQUEUE_EVENT);
1314 error = fget(td, fd, &rights, &fp);
1318 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1325 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1326 struct kevent_copyops *k_ops, const struct timespec *timeout)
1328 struct kevent keva[KQ_NEVENTS];
1329 struct kevent *kevp, *changes;
1330 int i, n, nerrors, error;
1336 while (nchanges > 0) {
1337 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1338 error = k_ops->k_copyin(k_ops->arg, keva, n);
1342 for (i = 0; i < n; i++) {
1346 kevp->flags &= ~EV_SYSFLAGS;
1347 error = kqueue_register(kq, kevp, td, M_WAITOK);
1348 if (error || (kevp->flags & EV_RECEIPT)) {
1351 kevp->flags = EV_ERROR;
1353 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1361 td->td_retval[0] = nerrors;
1365 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1369 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1370 struct kevent_copyops *k_ops, const struct timespec *timeout)
1375 error = kqueue_acquire(fp, &kq);
1378 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1379 kqueue_release(kq, 0);
1384 * Performs a kevent() call on a temporarily created kqueue. This can be
1385 * used to perform one-shot polling, similar to poll() and select().
1388 kern_kevent_anonymous(struct thread *td, int nevents,
1389 struct kevent_copyops *k_ops)
1391 struct kqueue kq = {};
1396 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1397 kqueue_drain(&kq, td);
1398 kqueue_destroy(&kq);
1403 kqueue_add_filteropts(int filt, struct filterops *filtops)
1408 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1410 "trying to add a filterop that is out of range: %d is beyond %d\n",
1411 ~filt, EVFILT_SYSCOUNT);
1414 mtx_lock(&filterops_lock);
1415 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1416 sysfilt_ops[~filt].for_fop != NULL)
1419 sysfilt_ops[~filt].for_fop = filtops;
1420 sysfilt_ops[~filt].for_refcnt = 0;
1422 mtx_unlock(&filterops_lock);
1428 kqueue_del_filteropts(int filt)
1433 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1436 mtx_lock(&filterops_lock);
1437 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1438 sysfilt_ops[~filt].for_fop == NULL)
1440 else if (sysfilt_ops[~filt].for_refcnt != 0)
1443 sysfilt_ops[~filt].for_fop = &null_filtops;
1444 sysfilt_ops[~filt].for_refcnt = 0;
1446 mtx_unlock(&filterops_lock);
1451 static struct filterops *
1452 kqueue_fo_find(int filt)
1455 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1458 if (sysfilt_ops[~filt].for_nolock)
1459 return sysfilt_ops[~filt].for_fop;
1461 mtx_lock(&filterops_lock);
1462 sysfilt_ops[~filt].for_refcnt++;
1463 if (sysfilt_ops[~filt].for_fop == NULL)
1464 sysfilt_ops[~filt].for_fop = &null_filtops;
1465 mtx_unlock(&filterops_lock);
1467 return sysfilt_ops[~filt].for_fop;
1471 kqueue_fo_release(int filt)
1474 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1477 if (sysfilt_ops[~filt].for_nolock)
1480 mtx_lock(&filterops_lock);
1481 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1482 ("filter object refcount not valid on release"));
1483 sysfilt_ops[~filt].for_refcnt--;
1484 mtx_unlock(&filterops_lock);
1488 * A ref to kq (obtained via kqueue_acquire) must be held.
1491 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td,
1494 struct filterops *fops;
1496 struct knote *kn, *tkn;
1498 int error, filt, event;
1499 int haskqglobal, filedesc_unlock;
1501 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1509 filedesc_unlock = 0;
1512 fops = kqueue_fo_find(filt);
1516 if (kev->flags & EV_ADD) {
1517 /* Reject an invalid flag pair early */
1518 if (kev->flags & EV_KEEPUDATA) {
1525 * Prevent waiting with locks. Non-sleepable
1526 * allocation failures are handled in the loop, only
1527 * if the spare knote appears to be actually required.
1529 tkn = knote_alloc(mflag);
1536 KASSERT(td != NULL, ("td is NULL"));
1537 if (kev->ident > INT_MAX)
1540 error = fget(td, kev->ident, &cap_event_rights, &fp);
1544 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1545 kev->ident, M_NOWAIT) != 0) {
1549 error = kqueue_expand(kq, fops, kev->ident, mflag);
1555 if (fp->f_type == DTYPE_KQUEUE) {
1557 * If we add some intelligence about what we are doing,
1558 * we should be able to support events on ourselves.
1559 * We need to know when we are doing this to prevent
1560 * getting both the knlist lock and the kq lock since
1561 * they are the same thing.
1563 if (fp->f_data == kq) {
1569 * Pre-lock the filedesc before the global
1570 * lock mutex, see the comment in
1573 FILEDESC_XLOCK(td->td_proc->p_fd);
1574 filedesc_unlock = 1;
1575 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1579 if (kev->ident < kq->kq_knlistsize) {
1580 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1581 if (kev->filter == kn->kn_filter)
1585 if ((kev->flags & EV_ADD) == EV_ADD) {
1586 error = kqueue_expand(kq, fops, kev->ident, mflag);
1594 * If possible, find an existing knote to use for this kevent.
1596 if (kev->filter == EVFILT_PROC &&
1597 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1598 /* This is an internal creation of a process tracking
1599 * note. Don't attempt to coalesce this with an
1603 } else if (kq->kq_knhashmask != 0) {
1606 list = &kq->kq_knhash[
1607 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1608 SLIST_FOREACH(kn, list, kn_link)
1609 if (kev->ident == kn->kn_id &&
1610 kev->filter == kn->kn_filter)
1615 /* knote is in the process of changing, wait for it to stabilize. */
1616 if (kn != NULL && kn_in_flux(kn)) {
1617 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1618 if (filedesc_unlock) {
1619 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1620 filedesc_unlock = 0;
1622 kq->kq_state |= KQ_FLUXWAIT;
1623 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1632 * kn now contains the matching knote, or NULL if no match
1635 if (kev->flags & EV_ADD) {
1647 * apply reference counts to knote structure, and
1648 * do not release it at the end of this routine.
1653 kn->kn_sfflags = kev->fflags;
1654 kn->kn_sdata = kev->data;
1657 kn->kn_kevent = *kev;
1658 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1659 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1660 kn->kn_status = KN_DETACHED;
1661 if ((kev->flags & EV_DISABLE) != 0)
1662 kn->kn_status |= KN_DISABLED;
1665 error = knote_attach(kn, kq);
1672 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1673 knote_drop_detached(kn, td);
1676 knl = kn_list_lock(kn);
1679 /* No matching knote and the EV_ADD flag is not set. */
1686 if (kev->flags & EV_DELETE) {
1693 if (kev->flags & EV_FORCEONESHOT) {
1694 kn->kn_flags |= EV_ONESHOT;
1695 KNOTE_ACTIVATE(kn, 1);
1698 if ((kev->flags & EV_ENABLE) != 0)
1699 kn->kn_status &= ~KN_DISABLED;
1700 else if ((kev->flags & EV_DISABLE) != 0)
1701 kn->kn_status |= KN_DISABLED;
1704 * The user may change some filter values after the initial EV_ADD,
1705 * but doing so will not reset any filter which has already been
1708 kn->kn_status |= KN_SCAN;
1711 knl = kn_list_lock(kn);
1712 if ((kev->flags & EV_KEEPUDATA) == 0)
1713 kn->kn_kevent.udata = kev->udata;
1714 if (!fops->f_isfd && fops->f_touch != NULL) {
1715 fops->f_touch(kn, kev, EVENT_REGISTER);
1717 kn->kn_sfflags = kev->fflags;
1718 kn->kn_sdata = kev->data;
1723 * We can get here with kn->kn_knlist == NULL. This can happen when
1724 * the initial attach event decides that the event is "completed"
1725 * already, e.g., filt_procattach() is called on a zombie process. It
1726 * will call filt_proc() which will remove it from the list, and NULL
1729 * KN_DISABLED will be stable while the knote is in flux, so the
1730 * unlocked read will not race with an update.
1732 if ((kn->kn_status & KN_DISABLED) == 0)
1733 event = kn->kn_fop->f_event(kn, 0);
1739 kn->kn_status |= KN_ACTIVE;
1740 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1743 kn->kn_status &= ~KN_SCAN;
1745 kn_list_unlock(knl);
1749 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1750 if (filedesc_unlock)
1751 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1756 kqueue_fo_release(filt);
1761 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1769 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1773 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1784 kqueue_release(struct kqueue *kq, int locked)
1791 if (kq->kq_refcnt == 1)
1792 wakeup(&kq->kq_refcnt);
1798 ast_kqueue(struct thread *td, int tda __unused)
1800 taskqueue_quiesce(taskqueue_kqueue_ctx);
1804 kqueue_schedtask(struct kqueue *kq)
1807 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1808 ("scheduling kqueue task while draining"));
1810 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1811 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1812 kq->kq_state |= KQ_TASKSCHED;
1813 ast_sched(curthread, TDA_KQUEUE);
1818 * Expand the kq to make sure we have storage for fops/ident pair.
1820 * Return 0 on success (or no work necessary), return errno on failure.
1823 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1826 struct klist *list, *tmp_knhash, *to_free;
1827 u_long tmp_knhashmask;
1828 int error, fd, size;
1836 if (kq->kq_knlistsize <= fd) {
1837 size = kq->kq_knlistsize;
1840 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1844 if ((kq->kq_state & KQ_CLOSING) != 0) {
1847 } else if (kq->kq_knlistsize > fd) {
1850 if (kq->kq_knlist != NULL) {
1851 bcopy(kq->kq_knlist, list,
1852 kq->kq_knlistsize * sizeof(*list));
1853 to_free = kq->kq_knlist;
1854 kq->kq_knlist = NULL;
1856 bzero((caddr_t)list +
1857 kq->kq_knlistsize * sizeof(*list),
1858 (size - kq->kq_knlistsize) * sizeof(*list));
1859 kq->kq_knlistsize = size;
1860 kq->kq_knlist = list;
1865 if (kq->kq_knhashmask == 0) {
1866 tmp_knhash = hashinit_flags(KN_HASHSIZE, M_KQUEUE,
1867 &tmp_knhashmask, (mflag & M_WAITOK) != 0 ?
1868 HASH_WAITOK : HASH_NOWAIT);
1869 if (tmp_knhash == NULL)
1872 if ((kq->kq_state & KQ_CLOSING) != 0) {
1873 to_free = tmp_knhash;
1875 } else if (kq->kq_knhashmask == 0) {
1876 kq->kq_knhash = tmp_knhash;
1877 kq->kq_knhashmask = tmp_knhashmask;
1879 to_free = tmp_knhash;
1884 free(to_free, M_KQUEUE);
1891 kqueue_task(void *arg, int pending)
1899 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1902 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1904 kq->kq_state &= ~KQ_TASKSCHED;
1905 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1906 wakeup(&kq->kq_state);
1909 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1913 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1914 * We treat KN_MARKER knotes as if they are in flux.
1917 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1918 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1920 struct kevent *kevp;
1921 struct knote *kn, *marker;
1923 sbintime_t asbt, rsbt;
1924 int count, error, haskqglobal, influx, nkev, touch;
1933 if (maxevents < 0) {
1940 if (!timespecvalid_interval(tsp)) {
1944 if (timespecisset(tsp)) {
1945 if (tsp->tv_sec <= INT32_MAX) {
1946 rsbt = tstosbt(*tsp);
1947 if (TIMESEL(&asbt, rsbt))
1948 asbt += tc_tick_sbt;
1949 if (asbt <= SBT_MAX - rsbt)
1953 rsbt >>= tc_precexp;
1960 marker = knote_alloc(M_WAITOK);
1961 marker->kn_status = KN_MARKER;
1966 if (kq->kq_count == 0) {
1968 error = EWOULDBLOCK;
1970 kq->kq_state |= KQ_SLEEP;
1971 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1972 "kqread", asbt, rsbt, C_ABSOLUTE);
1976 /* don't restart after signals... */
1977 if (error == ERESTART)
1979 else if (error == EWOULDBLOCK)
1984 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1988 kn = TAILQ_FIRST(&kq->kq_head);
1990 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1996 kq->kq_state |= KQ_FLUXWAIT;
1997 error = msleep(kq, &kq->kq_lock, PSOCK,
2002 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2003 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
2004 kn->kn_status &= ~KN_QUEUED;
2010 if (count == maxevents)
2014 KASSERT(!kn_in_flux(kn),
2015 ("knote %p is unexpectedly in flux", kn));
2017 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
2018 kn->kn_status &= ~KN_QUEUED;
2023 * We don't need to lock the list since we've
2024 * marked it as in flux.
2029 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
2030 kn->kn_status &= ~KN_QUEUED;
2035 * We don't need to lock the list since we've
2036 * marked the knote as being in flux.
2038 *kevp = kn->kn_kevent;
2043 kn->kn_status |= KN_SCAN;
2046 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
2047 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
2048 knl = kn_list_lock(kn);
2049 if (kn->kn_fop->f_event(kn, 0) == 0) {
2051 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2052 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
2056 kn_list_unlock(knl);
2060 touch = (!kn->kn_fop->f_isfd &&
2061 kn->kn_fop->f_touch != NULL);
2063 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
2065 *kevp = kn->kn_kevent;
2067 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2068 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
2070 * Manually clear knotes who weren't
2073 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
2077 if (kn->kn_flags & EV_DISPATCH)
2078 kn->kn_status |= KN_DISABLED;
2079 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
2082 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2084 kn->kn_status &= ~KN_SCAN;
2086 kn_list_unlock(knl);
2090 /* we are returning a copy to the user */
2095 if (nkev == KQ_NEVENTS) {
2098 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2106 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
2114 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2115 td->td_retval[0] = maxevents - count;
2121 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
2122 struct ucred *active_cred, struct thread *td)
2125 * Enabling sigio causes two major problems:
2126 * 1) infinite recursion:
2127 * Synopsys: kevent is being used to track signals and have FIOASYNC
2128 * set. On receipt of a signal this will cause a kqueue to recurse
2129 * into itself over and over. Sending the sigio causes the kqueue
2130 * to become ready, which in turn posts sigio again, forever.
2131 * Solution: this can be solved by setting a flag in the kqueue that
2132 * we have a SIGIO in progress.
2133 * 2) locking problems:
2134 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
2135 * us above the proc and pgrp locks.
2136 * Solution: Post a signal using an async mechanism, being sure to
2137 * record a generation count in the delivery so that we do not deliver
2138 * a signal to the wrong process.
2140 * Note, these two mechanisms are somewhat mutually exclusive!
2149 kq->kq_state |= KQ_ASYNC;
2151 kq->kq_state &= ~KQ_ASYNC;
2156 return (fsetown(*(int *)data, &kq->kq_sigio));
2159 *(int *)data = fgetown(&kq->kq_sigio);
2169 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
2176 if ((error = kqueue_acquire(fp, &kq)))
2180 if (events & (POLLIN | POLLRDNORM)) {
2182 revents |= events & (POLLIN | POLLRDNORM);
2184 selrecord(td, &kq->kq_sel);
2185 if (SEL_WAITING(&kq->kq_sel))
2186 kq->kq_state |= KQ_SEL;
2189 kqueue_release(kq, 1);
2196 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred)
2199 bzero((void *)st, sizeof *st);
2201 * We no longer return kq_count because the unlocked value is useless.
2202 * If you spent all this time getting the count, why not spend your
2203 * syscall better by calling kevent?
2205 * XXX - This is needed for libc_r.
2207 st->st_mode = S_IFIFO;
2212 kqueue_drain(struct kqueue *kq, struct thread *td)
2219 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
2220 ("kqueue already closing"));
2221 kq->kq_state |= KQ_CLOSING;
2222 if (kq->kq_refcnt > 1)
2223 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
2225 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
2227 KASSERT(knlist_empty(&kq->kq_sel.si_note),
2228 ("kqueue's knlist not empty"));
2230 for (i = 0; i < kq->kq_knlistsize; i++) {
2231 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
2232 if (kn_in_flux(kn)) {
2233 kq->kq_state |= KQ_FLUXWAIT;
2234 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
2243 if (kq->kq_knhashmask != 0) {
2244 for (i = 0; i <= kq->kq_knhashmask; i++) {
2245 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
2246 if (kn_in_flux(kn)) {
2247 kq->kq_state |= KQ_FLUXWAIT;
2248 msleep(kq, &kq->kq_lock, PSOCK,
2260 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
2261 kq->kq_state |= KQ_TASKDRAIN;
2262 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2265 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2266 selwakeuppri(&kq->kq_sel, PSOCK);
2267 if (!SEL_WAITING(&kq->kq_sel))
2268 kq->kq_state &= ~KQ_SEL;
2275 kqueue_destroy(struct kqueue *kq)
2278 KASSERT(kq->kq_fdp == NULL,
2279 ("kqueue still attached to a file descriptor"));
2280 seldrain(&kq->kq_sel);
2281 knlist_destroy(&kq->kq_sel.si_note);
2282 mtx_destroy(&kq->kq_lock);
2284 if (kq->kq_knhash != NULL)
2285 free(kq->kq_knhash, M_KQUEUE);
2286 if (kq->kq_knlist != NULL)
2287 free(kq->kq_knlist, M_KQUEUE);
2289 funsetown(&kq->kq_sigio);
2294 kqueue_close(struct file *fp, struct thread *td)
2296 struct kqueue *kq = fp->f_data;
2297 struct filedesc *fdp;
2299 int filedesc_unlock;
2301 if ((error = kqueue_acquire(fp, &kq)))
2303 kqueue_drain(kq, td);
2306 * We could be called due to the knote_drop() doing fdrop(),
2307 * called from kqueue_register(). In this case the global
2308 * lock is owned, and filedesc sx is locked before, to not
2309 * take the sleepable lock after non-sleepable.
2313 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2314 FILEDESC_XLOCK(fdp);
2315 filedesc_unlock = 1;
2317 filedesc_unlock = 0;
2318 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2319 if (filedesc_unlock)
2320 FILEDESC_XUNLOCK(fdp);
2323 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2324 crfree(kq->kq_cred);
2332 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2334 struct kqueue *kq = fp->f_data;
2336 kif->kf_type = KF_TYPE_KQUEUE;
2337 kif->kf_un.kf_kqueue.kf_kqueue_addr = (uintptr_t)kq;
2338 kif->kf_un.kf_kqueue.kf_kqueue_count = kq->kq_count;
2339 kif->kf_un.kf_kqueue.kf_kqueue_state = kq->kq_state;
2344 kqueue_wakeup(struct kqueue *kq)
2348 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2349 kq->kq_state &= ~KQ_SLEEP;
2352 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2353 selwakeuppri(&kq->kq_sel, PSOCK);
2354 if (!SEL_WAITING(&kq->kq_sel))
2355 kq->kq_state &= ~KQ_SEL;
2357 if (!knlist_empty(&kq->kq_sel.si_note))
2358 kqueue_schedtask(kq);
2359 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2360 pgsigio(&kq->kq_sigio, SIGIO, 0);
2365 * Walk down a list of knotes, activating them if their event has triggered.
2367 * There is a possibility to optimize in the case of one kq watching another.
2368 * Instead of scheduling a task to wake it up, you could pass enough state
2369 * down the chain to make up the parent kqueue. Make this code functional
2373 knote(struct knlist *list, long hint, int lockflags)
2376 struct knote *kn, *tkn;
2382 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2384 if ((lockflags & KNF_LISTLOCKED) == 0)
2385 list->kl_lock(list->kl_lockarg);
2388 * If we unlock the list lock (and enter influx), we can
2389 * eliminate the kqueue scheduling, but this will introduce
2390 * four lock/unlock's for each knote to test. Also, marker
2391 * would be needed to keep iteration position, since filters
2392 * or other threads could remove events.
2394 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2397 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2399 * Do not process the influx notes, except for
2400 * the influx coming from the kq unlock in the
2401 * kqueue_scan(). In the later case, we do
2402 * not interfere with the scan, since the code
2403 * fragment in kqueue_scan() locks the knlist,
2404 * and cannot proceed until we finished.
2407 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2410 error = kn->kn_fop->f_event(kn, hint);
2414 KNOTE_ACTIVATE(kn, 1);
2417 if (kn->kn_fop->f_event(kn, hint))
2418 KNOTE_ACTIVATE(kn, 1);
2422 if ((lockflags & KNF_LISTLOCKED) == 0)
2423 list->kl_unlock(list->kl_lockarg);
2427 * add a knote to a knlist
2430 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2433 KNL_ASSERT_LOCK(knl, islocked);
2434 KQ_NOTOWNED(kn->kn_kq);
2435 KASSERT(kn_in_flux(kn), ("knote %p not in flux", kn));
2436 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2437 ("knote %p was not detached", kn));
2439 knl->kl_lock(knl->kl_lockarg);
2440 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2442 knl->kl_unlock(knl->kl_lockarg);
2444 kn->kn_knlist = knl;
2445 kn->kn_status &= ~KN_DETACHED;
2446 KQ_UNLOCK(kn->kn_kq);
2450 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2454 KASSERT(!kqislocked || knlislocked, ("kq locked w/o knl locked"));
2455 KNL_ASSERT_LOCK(knl, knlislocked);
2456 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2457 KASSERT(kqislocked || kn_in_flux(kn), ("knote %p not in flux", kn));
2458 KASSERT((kn->kn_status & KN_DETACHED) == 0,
2459 ("knote %p was already detached", kn));
2461 knl->kl_lock(knl->kl_lockarg);
2462 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2463 kn->kn_knlist = NULL;
2465 kn_list_unlock(knl);
2468 kn->kn_status |= KN_DETACHED;
2470 KQ_UNLOCK(kn->kn_kq);
2474 * remove knote from the specified knlist
2477 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2480 knlist_remove_kq(knl, kn, islocked, 0);
2484 knlist_empty(struct knlist *knl)
2487 KNL_ASSERT_LOCKED(knl);
2488 return (SLIST_EMPTY(&knl->kl_list));
2491 static struct mtx knlist_lock;
2492 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2494 static void knlist_mtx_lock(void *arg);
2495 static void knlist_mtx_unlock(void *arg);
2498 knlist_mtx_lock(void *arg)
2501 mtx_lock((struct mtx *)arg);
2505 knlist_mtx_unlock(void *arg)
2508 mtx_unlock((struct mtx *)arg);
2512 knlist_mtx_assert_lock(void *arg, int what)
2515 if (what == LA_LOCKED)
2516 mtx_assert((struct mtx *)arg, MA_OWNED);
2518 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2522 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2523 void (*kl_unlock)(void *),
2524 void (*kl_assert_lock)(void *, int))
2528 knl->kl_lockarg = &knlist_lock;
2530 knl->kl_lockarg = lock;
2532 if (kl_lock == NULL)
2533 knl->kl_lock = knlist_mtx_lock;
2535 knl->kl_lock = kl_lock;
2536 if (kl_unlock == NULL)
2537 knl->kl_unlock = knlist_mtx_unlock;
2539 knl->kl_unlock = kl_unlock;
2540 if (kl_assert_lock == NULL)
2541 knl->kl_assert_lock = knlist_mtx_assert_lock;
2543 knl->kl_assert_lock = kl_assert_lock;
2545 knl->kl_autodestroy = 0;
2546 SLIST_INIT(&knl->kl_list);
2550 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2553 knlist_init(knl, lock, NULL, NULL, NULL);
2557 knlist_alloc(struct mtx *lock)
2561 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2562 knlist_init_mtx(knl, lock);
2567 knlist_destroy(struct knlist *knl)
2570 KASSERT(KNLIST_EMPTY(knl),
2571 ("destroying knlist %p with knotes on it", knl));
2575 knlist_detach(struct knlist *knl)
2578 KNL_ASSERT_LOCKED(knl);
2579 knl->kl_autodestroy = 1;
2580 if (knlist_empty(knl)) {
2581 knlist_destroy(knl);
2582 free(knl, M_KQUEUE);
2587 * Even if we are locked, we may need to drop the lock to allow any influx
2588 * knotes time to "settle".
2591 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2593 struct knote *kn, *kn2;
2596 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2598 KNL_ASSERT_LOCKED(knl);
2600 KNL_ASSERT_UNLOCKED(knl);
2601 again: /* need to reacquire lock since we have dropped it */
2602 knl->kl_lock(knl->kl_lockarg);
2605 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2608 if (kn_in_flux(kn)) {
2612 knlist_remove_kq(knl, kn, 1, 1);
2616 knote_drop_detached(kn, td);
2618 /* Make sure cleared knotes disappear soon */
2619 kn->kn_flags |= EV_EOF | EV_ONESHOT;
2625 if (!SLIST_EMPTY(&knl->kl_list)) {
2626 /* there are still in flux knotes remaining */
2627 kn = SLIST_FIRST(&knl->kl_list);
2630 KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2631 knl->kl_unlock(knl->kl_lockarg);
2632 kq->kq_state |= KQ_FLUXWAIT;
2633 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2639 KNL_ASSERT_LOCKED(knl);
2641 knl->kl_unlock(knl->kl_lockarg);
2642 KNL_ASSERT_UNLOCKED(knl);
2647 * Remove all knotes referencing a specified fd must be called with FILEDESC
2648 * lock. This prevents a race where a new fd comes along and occupies the
2649 * entry and we attach a knote to the fd.
2652 knote_fdclose(struct thread *td, int fd)
2654 struct filedesc *fdp = td->td_proc->p_fd;
2659 FILEDESC_XLOCK_ASSERT(fdp);
2662 * We shouldn't have to worry about new kevents appearing on fd
2663 * since filedesc is locked.
2665 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2670 while (kq->kq_knlistsize > fd &&
2671 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2672 if (kn_in_flux(kn)) {
2673 /* someone else might be waiting on our knote */
2676 kq->kq_state |= KQ_FLUXWAIT;
2677 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2691 knote_attach(struct knote *kn, struct kqueue *kq)
2695 KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2698 if ((kq->kq_state & KQ_CLOSING) != 0)
2700 if (kn->kn_fop->f_isfd) {
2701 if (kn->kn_id >= kq->kq_knlistsize)
2703 list = &kq->kq_knlist[kn->kn_id];
2705 if (kq->kq_knhash == NULL)
2707 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2709 SLIST_INSERT_HEAD(list, kn, kn_link);
2714 knote_drop(struct knote *kn, struct thread *td)
2717 if ((kn->kn_status & KN_DETACHED) == 0)
2718 kn->kn_fop->f_detach(kn);
2719 knote_drop_detached(kn, td);
2723 knote_drop_detached(struct knote *kn, struct thread *td)
2730 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2731 ("knote %p still attached", kn));
2735 KASSERT(kn->kn_influx == 1,
2736 ("knote_drop called on %p with influx %d", kn, kn->kn_influx));
2738 if (kn->kn_fop->f_isfd)
2739 list = &kq->kq_knlist[kn->kn_id];
2741 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2743 if (!SLIST_EMPTY(list))
2744 SLIST_REMOVE(list, kn, knote, kn_link);
2745 if (kn->kn_status & KN_QUEUED)
2749 if (kn->kn_fop->f_isfd) {
2750 fdrop(kn->kn_fp, td);
2753 kqueue_fo_release(kn->kn_kevent.filter);
2759 knote_enqueue(struct knote *kn)
2761 struct kqueue *kq = kn->kn_kq;
2763 KQ_OWNED(kn->kn_kq);
2764 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2766 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2767 kn->kn_status |= KN_QUEUED;
2773 knote_dequeue(struct knote *kn)
2775 struct kqueue *kq = kn->kn_kq;
2777 KQ_OWNED(kn->kn_kq);
2778 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2780 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2781 kn->kn_status &= ~KN_QUEUED;
2789 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2790 NULL, NULL, UMA_ALIGN_PTR, 0);
2791 ast_register(TDA_KQUEUE, ASTR_ASTF_REQUIRED, 0, ast_kqueue);
2793 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2795 static struct knote *
2796 knote_alloc(int mflag)
2799 return (uma_zalloc(knote_zone, mflag | M_ZERO));
2803 knote_free(struct knote *kn)
2806 uma_zfree(knote_zone, kn);
2810 * Register the kev w/ the kq specified by fd.
2813 kqfd_register(int fd, struct kevent *kev, struct thread *td, int mflag)
2817 cap_rights_t rights;
2820 error = fget(td, fd, cap_rights_init_one(&rights, CAP_KQUEUE_CHANGE),
2824 if ((error = kqueue_acquire(fp, &kq)) != 0)
2827 error = kqueue_register(kq, kev, td, mflag);
2828 kqueue_release(kq, 0);