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 #include "opt_ktrace.h"
33 #include "opt_kqueue.h"
35 #ifdef COMPAT_FREEBSD11
36 #define _WANT_FREEBSD11_KEVENT
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/capsicum.h>
42 #include <sys/kernel.h>
43 #include <sys/limits.h>
45 #include <sys/mutex.h>
47 #include <sys/malloc.h>
48 #include <sys/unistd.h>
50 #include <sys/filedesc.h>
51 #include <sys/filio.h>
52 #include <sys/fcntl.h>
53 #include <sys/kthread.h>
54 #include <sys/selinfo.h>
55 #include <sys/queue.h>
56 #include <sys/event.h>
57 #include <sys/eventvar.h>
59 #include <sys/protosw.h>
60 #include <sys/resourcevar.h>
61 #include <sys/sigio.h>
62 #include <sys/signalvar.h>
63 #include <sys/socket.h>
64 #include <sys/socketvar.h>
66 #include <sys/sysctl.h>
67 #include <sys/sysproto.h>
68 #include <sys/syscallsubr.h>
69 #include <sys/taskqueue.h>
73 #include <sys/ktrace.h>
75 #include <machine/atomic.h>
79 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
82 * This lock is used if multiple kq locks are required. This possibly
83 * should be made into a per proc lock.
85 static struct mtx kq_global;
86 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
87 #define KQ_GLOBAL_LOCK(lck, haslck) do { \
92 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
98 TASKQUEUE_DEFINE_THREAD(kqueue_ctx);
100 static int kevent_copyout(void *arg, struct kevent *kevp, int count);
101 static int kevent_copyin(void *arg, struct kevent *kevp, int count);
102 static int kqueue_register(struct kqueue *kq, struct kevent *kev,
103 struct thread *td, int mflag);
104 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
105 static void kqueue_release(struct kqueue *kq, int locked);
106 static void kqueue_destroy(struct kqueue *kq);
107 static void kqueue_drain(struct kqueue *kq, struct thread *td);
108 static int kqueue_expand(struct kqueue *kq, const struct filterops *fops,
109 uintptr_t ident, int mflag);
110 static void kqueue_task(void *arg, int pending);
111 static int kqueue_scan(struct kqueue *kq, int maxevents,
112 struct kevent_copyops *k_ops,
113 const struct timespec *timeout,
114 struct kevent *keva, struct thread *td);
115 static void kqueue_wakeup(struct kqueue *kq);
116 static const struct filterops *kqueue_fo_find(int filt);
117 static void kqueue_fo_release(int filt);
118 struct g_kevent_args;
119 static int kern_kevent_generic(struct thread *td,
120 struct g_kevent_args *uap,
121 struct kevent_copyops *k_ops, const char *struct_name);
123 static fo_ioctl_t kqueue_ioctl;
124 static fo_poll_t kqueue_poll;
125 static fo_kqfilter_t kqueue_kqfilter;
126 static fo_stat_t kqueue_stat;
127 static fo_close_t kqueue_close;
128 static fo_fill_kinfo_t kqueue_fill_kinfo;
130 static struct fileops kqueueops = {
131 .fo_read = invfo_rdwr,
132 .fo_write = invfo_rdwr,
133 .fo_truncate = invfo_truncate,
134 .fo_ioctl = kqueue_ioctl,
135 .fo_poll = kqueue_poll,
136 .fo_kqfilter = kqueue_kqfilter,
137 .fo_stat = kqueue_stat,
138 .fo_close = kqueue_close,
139 .fo_chmod = invfo_chmod,
140 .fo_chown = invfo_chown,
141 .fo_sendfile = invfo_sendfile,
142 .fo_fill_kinfo = kqueue_fill_kinfo,
145 static int knote_attach(struct knote *kn, struct kqueue *kq);
146 static void knote_drop(struct knote *kn, struct thread *td);
147 static void knote_drop_detached(struct knote *kn, struct thread *td);
148 static void knote_enqueue(struct knote *kn);
149 static void knote_dequeue(struct knote *kn);
150 static void knote_init(void);
151 static struct knote *knote_alloc(int mflag);
152 static void knote_free(struct knote *kn);
154 static void filt_kqdetach(struct knote *kn);
155 static int filt_kqueue(struct knote *kn, long hint);
156 static int filt_procattach(struct knote *kn);
157 static void filt_procdetach(struct knote *kn);
158 static int filt_proc(struct knote *kn, long hint);
159 static int filt_fileattach(struct knote *kn);
160 static void filt_timerexpire(void *knx);
161 static void filt_timerexpire_l(struct knote *kn, bool proc_locked);
162 static int filt_timerattach(struct knote *kn);
163 static void filt_timerdetach(struct knote *kn);
164 static void filt_timerstart(struct knote *kn, sbintime_t to);
165 static void filt_timertouch(struct knote *kn, struct kevent *kev,
167 static int filt_timervalidate(struct knote *kn, sbintime_t *to);
168 static int filt_timer(struct knote *kn, long hint);
169 static int filt_userattach(struct knote *kn);
170 static void filt_userdetach(struct knote *kn);
171 static int filt_user(struct knote *kn, long hint);
172 static void filt_usertouch(struct knote *kn, struct kevent *kev,
175 static struct filterops file_filtops = {
177 .f_attach = filt_fileattach,
179 static struct filterops kqread_filtops = {
181 .f_detach = filt_kqdetach,
182 .f_event = filt_kqueue,
184 /* XXX - move to kern_proc.c? */
185 static struct filterops proc_filtops = {
187 .f_attach = filt_procattach,
188 .f_detach = filt_procdetach,
189 .f_event = filt_proc,
191 static struct filterops timer_filtops = {
193 .f_attach = filt_timerattach,
194 .f_detach = filt_timerdetach,
195 .f_event = filt_timer,
196 .f_touch = filt_timertouch,
198 static struct filterops user_filtops = {
199 .f_attach = filt_userattach,
200 .f_detach = filt_userdetach,
201 .f_event = filt_user,
202 .f_touch = filt_usertouch,
205 static uma_zone_t knote_zone;
206 static unsigned int __exclusive_cache_line kq_ncallouts;
207 static unsigned int kq_calloutmax = 4 * 1024;
208 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
209 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
211 /* XXX - ensure not influx ? */
212 #define KNOTE_ACTIVATE(kn, islock) do { \
214 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
216 KQ_LOCK((kn)->kn_kq); \
217 (kn)->kn_status |= KN_ACTIVE; \
218 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
219 knote_enqueue((kn)); \
221 KQ_UNLOCK((kn)->kn_kq); \
223 #define KQ_LOCK(kq) do { \
224 mtx_lock(&(kq)->kq_lock); \
226 #define KQ_FLUX_WAKEUP(kq) do { \
227 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
228 (kq)->kq_state &= ~KQ_FLUXWAIT; \
232 #define KQ_UNLOCK_FLUX(kq) do { \
233 KQ_FLUX_WAKEUP(kq); \
234 mtx_unlock(&(kq)->kq_lock); \
236 #define KQ_UNLOCK(kq) do { \
237 mtx_unlock(&(kq)->kq_lock); \
239 #define KQ_OWNED(kq) do { \
240 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
242 #define KQ_NOTOWNED(kq) do { \
243 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
246 static struct knlist *
247 kn_list_lock(struct knote *kn)
253 knl->kl_lock(knl->kl_lockarg);
258 kn_list_unlock(struct knlist *knl)
264 do_free = knl->kl_autodestroy && knlist_empty(knl);
265 knl->kl_unlock(knl->kl_lockarg);
273 kn_in_flux(struct knote *kn)
276 return (kn->kn_influx > 0);
280 kn_enter_flux(struct knote *kn)
284 MPASS(kn->kn_influx < INT_MAX);
289 kn_leave_flux(struct knote *kn)
293 MPASS(kn->kn_influx > 0);
295 return (kn->kn_influx == 0);
298 #define KNL_ASSERT_LOCK(knl, islocked) do { \
300 KNL_ASSERT_LOCKED(knl); \
302 KNL_ASSERT_UNLOCKED(knl); \
305 #define KNL_ASSERT_LOCKED(knl) do { \
306 knl->kl_assert_lock((knl)->kl_lockarg, LA_LOCKED); \
308 #define KNL_ASSERT_UNLOCKED(knl) do { \
309 knl->kl_assert_lock((knl)->kl_lockarg, LA_UNLOCKED); \
311 #else /* !INVARIANTS */
312 #define KNL_ASSERT_LOCKED(knl) do {} while (0)
313 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
314 #endif /* INVARIANTS */
317 #define KN_HASHSIZE 64 /* XXX should be tunable */
320 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
323 filt_nullattach(struct knote *kn)
329 struct filterops null_filtops = {
331 .f_attach = filt_nullattach,
334 /* XXX - make SYSINIT to add these, and move into respective modules. */
335 extern struct filterops sig_filtops;
336 extern struct filterops fs_filtops;
339 * Table for all system-defined filters.
341 static struct mtx filterops_lock;
342 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops", MTX_DEF);
344 const struct filterops *for_fop;
347 } sysfilt_ops[EVFILT_SYSCOUNT] = {
348 { &file_filtops, 1 }, /* EVFILT_READ */
349 { &file_filtops, 1 }, /* EVFILT_WRITE */
350 { &null_filtops }, /* EVFILT_AIO */
351 { &file_filtops, 1 }, /* EVFILT_VNODE */
352 { &proc_filtops, 1 }, /* EVFILT_PROC */
353 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
354 { &timer_filtops, 1 }, /* EVFILT_TIMER */
355 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
356 { &fs_filtops, 1 }, /* EVFILT_FS */
357 { &null_filtops }, /* EVFILT_LIO */
358 { &user_filtops, 1 }, /* EVFILT_USER */
359 { &null_filtops }, /* EVFILT_SENDFILE */
360 { &file_filtops, 1 }, /* EVFILT_EMPTY */
364 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
368 filt_fileattach(struct knote *kn)
371 return (fo_kqfilter(kn->kn_fp, kn));
376 kqueue_kqfilter(struct file *fp, struct knote *kn)
378 struct kqueue *kq = kn->kn_fp->f_data;
380 if (kn->kn_filter != EVFILT_READ)
383 kn->kn_status |= KN_KQUEUE;
384 kn->kn_fop = &kqread_filtops;
385 knlist_add(&kq->kq_sel.si_note, kn, 0);
391 filt_kqdetach(struct knote *kn)
393 struct kqueue *kq = kn->kn_fp->f_data;
395 knlist_remove(&kq->kq_sel.si_note, kn, 0);
400 filt_kqueue(struct knote *kn, long hint)
402 struct kqueue *kq = kn->kn_fp->f_data;
404 kn->kn_data = kq->kq_count;
405 return (kn->kn_data > 0);
408 /* XXX - move to kern_proc.c? */
410 filt_procattach(struct knote *kn)
414 bool exiting, immediate;
416 exiting = immediate = false;
417 if (kn->kn_sfflags & NOTE_EXIT)
418 p = pfind_any(kn->kn_id);
420 p = pfind(kn->kn_id);
423 if (p->p_flag & P_WEXIT)
426 if ((error = p_cansee(curthread, p))) {
431 kn->kn_ptr.p_proc = p;
432 kn->kn_flags |= EV_CLEAR; /* automatically set */
435 * Internal flag indicating registration done by kernel for the
436 * purposes of getting a NOTE_CHILD notification.
438 if (kn->kn_flags & EV_FLAG2) {
439 kn->kn_flags &= ~EV_FLAG2;
440 kn->kn_data = kn->kn_sdata; /* ppid */
441 kn->kn_fflags = NOTE_CHILD;
442 kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
443 immediate = true; /* Force immediate activation of child note. */
446 * Internal flag indicating registration done by kernel (for other than
449 if (kn->kn_flags & EV_FLAG1) {
450 kn->kn_flags &= ~EV_FLAG1;
453 knlist_add(p->p_klist, kn, 1);
456 * Immediately activate any child notes or, in the case of a zombie
457 * target process, exit notes. The latter is necessary to handle the
458 * case where the target process, e.g. a child, dies before the kevent
461 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
462 KNOTE_ACTIVATE(kn, 0);
470 * The knote may be attached to a different process, which may exit,
471 * leaving nothing for the knote to be attached to. So when the process
472 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
473 * it will be deleted when read out. However, as part of the knote deletion,
474 * this routine is called, so a check is needed to avoid actually performing
475 * a detach, because the original process does not exist any more.
477 /* XXX - move to kern_proc.c? */
479 filt_procdetach(struct knote *kn)
482 knlist_remove(kn->kn_knlist, kn, 0);
483 kn->kn_ptr.p_proc = NULL;
486 /* XXX - move to kern_proc.c? */
488 filt_proc(struct knote *kn, long hint)
493 p = kn->kn_ptr.p_proc;
494 if (p == NULL) /* already activated, from attach filter */
497 /* Mask off extra data. */
498 event = (u_int)hint & NOTE_PCTRLMASK;
500 /* If the user is interested in this event, record it. */
501 if (kn->kn_sfflags & event)
502 kn->kn_fflags |= event;
504 /* Process is gone, so flag the event as finished. */
505 if (event == NOTE_EXIT) {
506 kn->kn_flags |= EV_EOF | EV_ONESHOT;
507 kn->kn_ptr.p_proc = NULL;
508 if (kn->kn_fflags & NOTE_EXIT)
509 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
510 if (kn->kn_fflags == 0)
511 kn->kn_flags |= EV_DROP;
515 return (kn->kn_fflags != 0);
519 * Called when the process forked. It mostly does the same as the
520 * knote(), activating all knotes registered to be activated when the
521 * process forked. Additionally, for each knote attached to the
522 * parent, check whether user wants to track the new process. If so
523 * attach a new knote to it, and immediately report an event with the
527 knote_fork(struct knlist *list, int pid)
535 KNL_ASSERT_LOCKED(list);
536 if (SLIST_EMPTY(&list->kl_list))
539 memset(&kev, 0, sizeof(kev));
540 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
543 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
549 * The same as knote(), activate the event.
551 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
552 if (kn->kn_fop->f_event(kn, NOTE_FORK))
553 KNOTE_ACTIVATE(kn, 1);
559 * The NOTE_TRACK case. In addition to the activation
560 * of the event, we need to register new events to
561 * track the child. Drop the locks in preparation for
562 * the call to kqueue_register().
566 list->kl_unlock(list->kl_lockarg);
569 * Activate existing knote and register tracking knotes with
572 * First register a knote to get just the child notice. This
573 * must be a separate note from a potential NOTE_EXIT
574 * notification since both NOTE_CHILD and NOTE_EXIT are defined
575 * to use the data field (in conflicting ways).
578 kev.filter = kn->kn_filter;
579 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
581 kev.fflags = kn->kn_sfflags;
582 kev.data = kn->kn_id; /* parent */
583 kev.udata = kn->kn_kevent.udata;/* preserve udata */
584 error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
586 kn->kn_fflags |= NOTE_TRACKERR;
589 * Then register another knote to track other potential events
590 * from the new process.
593 kev.filter = kn->kn_filter;
594 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
595 kev.fflags = kn->kn_sfflags;
596 kev.data = kn->kn_id; /* parent */
597 kev.udata = kn->kn_kevent.udata;/* preserve udata */
598 error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
600 kn->kn_fflags |= NOTE_TRACKERR;
601 if (kn->kn_fop->f_event(kn, NOTE_FORK))
602 KNOTE_ACTIVATE(kn, 0);
603 list->kl_lock(list->kl_lockarg);
611 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
612 * interval timer support code.
615 #define NOTE_TIMER_PRECMASK \
616 (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
619 timer2sbintime(int64_t data, int flags)
624 * Macros for converting to the fractional second portion of an
625 * sbintime_t using 64bit multiplication to improve precision.
627 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
628 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
629 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
630 switch (flags & NOTE_TIMER_PRECMASK) {
633 if (data > (SBT_MAX / SBT_1S))
636 return ((sbintime_t)data << 32);
637 case NOTE_MSECONDS: /* FALLTHROUGH */
642 if (secs > (SBT_MAX / SBT_1S))
645 return (secs << 32 | MS_TO_SBT(data % 1000));
647 return (MS_TO_SBT(data));
649 if (data >= 1000000) {
650 secs = data / 1000000;
652 if (secs > (SBT_MAX / SBT_1S))
655 return (secs << 32 | US_TO_SBT(data % 1000000));
657 return (US_TO_SBT(data));
659 if (data >= 1000000000) {
660 secs = data / 1000000000;
662 if (secs > (SBT_MAX / SBT_1S))
665 return (secs << 32 | NS_TO_SBT(data % 1000000000));
667 return (NS_TO_SBT(data));
674 struct kq_timer_cb_data {
680 TAILQ_ENTRY(kq_timer_cb_data) link;
681 sbintime_t next; /* next timer event fires at */
682 sbintime_t to; /* precalculated timer period, 0 for abs */
685 #define KQ_TIMER_CB_ENQUEUED 0x01
688 kqtimer_sched_callout(struct kq_timer_cb_data *kc)
690 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kc->kn,
691 kc->cpuid, C_ABSOLUTE);
695 kqtimer_proc_continue(struct proc *p)
697 struct kq_timer_cb_data *kc, *kc1;
701 PROC_LOCK_ASSERT(p, MA_OWNED);
706 TAILQ_FOREACH_SAFE(kc, &p->p_kqtim_stop, link, kc1) {
707 TAILQ_REMOVE(&p->p_kqtim_stop, kc, link);
708 kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
710 filt_timerexpire_l(kc->kn, true);
712 kqtimer_sched_callout(kc);
717 filt_timerexpire_l(struct knote *kn, bool proc_locked)
719 struct kq_timer_cb_data *kc;
726 if ((kn->kn_flags & EV_ONESHOT) != 0 || kc->to == 0) {
728 KNOTE_ACTIVATE(kn, 0);
733 if (now >= kc->next) {
734 delta = (now - kc->next) / kc->to;
737 kn->kn_data += delta;
738 kc->next += delta * kc->to;
739 if (now >= kc->next) /* overflow */
740 kc->next = now + kc->to;
741 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
745 * Initial check for stopped kc->p is racy. It is fine to
746 * miss the set of the stop flags, at worst we would schedule
747 * one more callout. On the other hand, it is not fine to not
748 * schedule when we we missed clearing of the flags, we
749 * recheck them under the lock and observe consistent state.
752 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
755 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
756 if ((kc->flags & KQ_TIMER_CB_ENQUEUED) == 0) {
757 kc->flags |= KQ_TIMER_CB_ENQUEUED;
758 TAILQ_INSERT_TAIL(&p->p_kqtim_stop, kc, link);
767 kqtimer_sched_callout(kc);
771 filt_timerexpire(void *knx)
773 filt_timerexpire_l(knx, false);
777 * data contains amount of time to sleep
780 filt_timervalidate(struct knote *kn, sbintime_t *to)
785 if (kn->kn_sdata < 0)
787 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
790 * The only fflags values supported are the timer unit
791 * (precision) and the absolute time indicator.
793 if ((kn->kn_sfflags & ~(NOTE_TIMER_PRECMASK | NOTE_ABSTIME)) != 0)
796 *to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
799 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
802 *to = MAX(0, *to - sbt);
808 filt_timerattach(struct knote *kn)
810 struct kq_timer_cb_data *kc;
815 error = filt_timervalidate(kn, &to);
818 KASSERT(to > 0 || (kn->kn_flags & EV_ONESHOT) != 0 ||
819 (kn->kn_sfflags & NOTE_ABSTIME) != 0,
820 ("%s: periodic timer has a calculated zero timeout", __func__));
822 ("%s: timer has a calculated negative timeout", __func__));
824 if (atomic_fetchadd_int(&kq_ncallouts, 1) + 1 > kq_calloutmax) {
825 atomic_subtract_int(&kq_ncallouts, 1);
829 if ((kn->kn_sfflags & NOTE_ABSTIME) == 0)
830 kn->kn_flags |= EV_CLEAR; /* automatically set */
831 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
832 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
835 kc->cpuid = PCPU_GET(cpuid);
837 callout_init(&kc->c, 1);
838 filt_timerstart(kn, to);
844 filt_timerstart(struct knote *kn, sbintime_t to)
846 struct kq_timer_cb_data *kc;
849 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
853 kc->next = to + sbinuptime();
856 kqtimer_sched_callout(kc);
860 filt_timerdetach(struct knote *kn)
862 struct kq_timer_cb_data *kc;
863 unsigned int old __unused;
868 callout_drain(&kc->c);
871 * kqtimer_proc_continue() might have rescheduled this callout.
872 * Double-check, using the process mutex as an interlock.
875 if ((kc->flags & KQ_TIMER_CB_ENQUEUED) != 0) {
876 kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
877 TAILQ_REMOVE(&kc->p->p_kqtim_stop, kc, link);
879 pending = callout_pending(&kc->c);
883 old = atomic_fetchadd_int(&kq_ncallouts, -1);
884 KASSERT(old > 0, ("Number of callouts cannot become negative"));
885 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
889 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
891 struct kq_timer_cb_data *kc;
898 /* Handle re-added timers that update data/fflags */
899 if (kev->flags & EV_ADD) {
902 /* Drain any existing callout. */
903 callout_drain(&kc->c);
905 /* Throw away any existing undelivered record
906 * of the timer expiration. This is done under
907 * the presumption that if a process is
908 * re-adding this timer with new parameters,
909 * it is no longer interested in what may have
910 * happened under the old parameters. If it is
911 * interested, it can wait for the expiration,
912 * delete the old timer definition, and then
915 * This has to be done while the kq is locked:
916 * - if enqueued, dequeue
917 * - make it no longer active
918 * - clear the count of expiration events
922 if (kn->kn_status & KN_QUEUED)
925 kn->kn_status &= ~KN_ACTIVE;
929 /* Reschedule timer based on new data/fflags */
930 kn->kn_sfflags = kev->fflags;
931 kn->kn_sdata = kev->data;
932 error = filt_timervalidate(kn, &to);
934 kn->kn_flags |= EV_ERROR;
937 filt_timerstart(kn, to);
942 *kev = kn->kn_kevent;
943 if (kn->kn_flags & EV_CLEAR) {
950 panic("filt_timertouch() - invalid type (%ld)", type);
956 filt_timer(struct knote *kn, long hint)
959 return (kn->kn_data != 0);
963 filt_userattach(struct knote *kn)
967 * EVFILT_USER knotes are not attached to anything in the kernel.
970 if (kn->kn_fflags & NOTE_TRIGGER)
978 filt_userdetach(__unused struct knote *kn)
982 * EVFILT_USER knotes are not attached to anything in the kernel.
987 filt_user(struct knote *kn, __unused long hint)
990 return (kn->kn_hookid);
994 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
1000 if (kev->fflags & NOTE_TRIGGER)
1003 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
1004 kev->fflags &= NOTE_FFLAGSMASK;
1010 kn->kn_sfflags &= kev->fflags;
1014 kn->kn_sfflags |= kev->fflags;
1018 kn->kn_sfflags = kev->fflags;
1022 /* XXX Return error? */
1025 kn->kn_sdata = kev->data;
1026 if (kev->flags & EV_CLEAR) {
1034 *kev = kn->kn_kevent;
1035 kev->fflags = kn->kn_sfflags;
1036 kev->data = kn->kn_sdata;
1037 if (kn->kn_flags & EV_CLEAR) {
1045 panic("filt_usertouch() - invalid type (%ld)", type);
1051 sys_kqueue(struct thread *td, struct kqueue_args *uap)
1054 return (kern_kqueue(td, 0, NULL));
1058 sys_kqueuex(struct thread *td, struct kqueuex_args *uap)
1062 if ((uap->flags & ~(KQUEUE_CLOEXEC)) != 0)
1065 if ((uap->flags & KQUEUE_CLOEXEC) != 0)
1067 return (kern_kqueue(td, flags, NULL));
1071 kqueue_init(struct kqueue *kq)
1074 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
1075 TAILQ_INIT(&kq->kq_head);
1076 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
1077 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
1081 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
1083 struct filedesc *fdp;
1089 fdp = td->td_proc->p_fd;
1090 cred = td->td_ucred;
1091 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
1094 error = falloc_caps(td, &fp, &fd, flags, fcaps);
1096 chgkqcnt(cred->cr_ruidinfo, -1, 0);
1100 /* An extra reference on `fp' has been held for us by falloc(). */
1101 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
1104 kq->kq_cred = crhold(cred);
1106 FILEDESC_XLOCK(fdp);
1107 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
1108 FILEDESC_XUNLOCK(fdp);
1110 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
1113 td->td_retval[0] = fd;
1117 struct g_kevent_args {
1119 const void *changelist;
1123 const struct timespec *timeout;
1127 sys_kevent(struct thread *td, struct kevent_args *uap)
1129 struct kevent_copyops k_ops = {
1131 .k_copyout = kevent_copyout,
1132 .k_copyin = kevent_copyin,
1133 .kevent_size = sizeof(struct kevent),
1135 struct g_kevent_args gk_args = {
1137 .changelist = uap->changelist,
1138 .nchanges = uap->nchanges,
1139 .eventlist = uap->eventlist,
1140 .nevents = uap->nevents,
1141 .timeout = uap->timeout,
1144 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent"));
1148 kern_kevent_generic(struct thread *td, struct g_kevent_args *uap,
1149 struct kevent_copyops *k_ops, const char *struct_name)
1151 struct timespec ts, *tsp;
1153 struct kevent *eventlist = uap->eventlist;
1157 if (uap->timeout != NULL) {
1158 error = copyin(uap->timeout, &ts, sizeof(ts));
1166 if (KTRPOINT(td, KTR_STRUCT_ARRAY))
1167 ktrstructarray(struct_name, UIO_USERSPACE, uap->changelist,
1168 uap->nchanges, k_ops->kevent_size);
1171 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1175 if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1176 ktrstructarray(struct_name, UIO_USERSPACE, eventlist,
1177 td->td_retval[0], k_ops->kevent_size);
1184 * Copy 'count' items into the destination list pointed to by uap->eventlist.
1187 kevent_copyout(void *arg, struct kevent *kevp, int count)
1189 struct kevent_args *uap;
1192 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1193 uap = (struct kevent_args *)arg;
1195 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1197 uap->eventlist += count;
1202 * Copy 'count' items from the list pointed to by uap->changelist.
1205 kevent_copyin(void *arg, struct kevent *kevp, int count)
1207 struct kevent_args *uap;
1210 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1211 uap = (struct kevent_args *)arg;
1213 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1215 uap->changelist += count;
1219 #ifdef COMPAT_FREEBSD11
1221 kevent11_copyout(void *arg, struct kevent *kevp, int count)
1223 struct freebsd11_kevent_args *uap;
1224 struct freebsd11_kevent kev11;
1227 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1228 uap = (struct freebsd11_kevent_args *)arg;
1230 for (i = 0; i < count; i++) {
1231 kev11.ident = kevp->ident;
1232 kev11.filter = kevp->filter;
1233 kev11.flags = kevp->flags;
1234 kev11.fflags = kevp->fflags;
1235 kev11.data = kevp->data;
1236 kev11.udata = kevp->udata;
1237 error = copyout(&kev11, uap->eventlist, sizeof(kev11));
1247 * Copy 'count' items from the list pointed to by uap->changelist.
1250 kevent11_copyin(void *arg, struct kevent *kevp, int count)
1252 struct freebsd11_kevent_args *uap;
1253 struct freebsd11_kevent kev11;
1256 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1257 uap = (struct freebsd11_kevent_args *)arg;
1259 for (i = 0; i < count; i++) {
1260 error = copyin(uap->changelist, &kev11, sizeof(kev11));
1263 kevp->ident = kev11.ident;
1264 kevp->filter = kev11.filter;
1265 kevp->flags = kev11.flags;
1266 kevp->fflags = kev11.fflags;
1267 kevp->data = (uintptr_t)kev11.data;
1268 kevp->udata = kev11.udata;
1269 bzero(&kevp->ext, sizeof(kevp->ext));
1277 freebsd11_kevent(struct thread *td, struct freebsd11_kevent_args *uap)
1279 struct kevent_copyops k_ops = {
1281 .k_copyout = kevent11_copyout,
1282 .k_copyin = kevent11_copyin,
1283 .kevent_size = sizeof(struct freebsd11_kevent),
1285 struct g_kevent_args gk_args = {
1287 .changelist = uap->changelist,
1288 .nchanges = uap->nchanges,
1289 .eventlist = uap->eventlist,
1290 .nevents = uap->nevents,
1291 .timeout = uap->timeout,
1294 return (kern_kevent_generic(td, &gk_args, &k_ops, "freebsd11_kevent"));
1299 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1300 struct kevent_copyops *k_ops, const struct timespec *timeout)
1302 cap_rights_t rights;
1306 cap_rights_init_zero(&rights);
1308 cap_rights_set_one(&rights, CAP_KQUEUE_CHANGE);
1310 cap_rights_set_one(&rights, CAP_KQUEUE_EVENT);
1311 error = fget(td, fd, &rights, &fp);
1315 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1322 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1323 struct kevent_copyops *k_ops, const struct timespec *timeout)
1325 struct kevent keva[KQ_NEVENTS];
1326 struct kevent *kevp, *changes;
1327 int i, n, nerrors, error;
1333 while (nchanges > 0) {
1334 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1335 error = k_ops->k_copyin(k_ops->arg, keva, n);
1339 for (i = 0; i < n; i++) {
1343 kevp->flags &= ~EV_SYSFLAGS;
1344 error = kqueue_register(kq, kevp, td, M_WAITOK);
1345 if (error || (kevp->flags & EV_RECEIPT)) {
1348 kevp->flags = EV_ERROR;
1350 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1358 td->td_retval[0] = nerrors;
1362 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1366 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1367 struct kevent_copyops *k_ops, const struct timespec *timeout)
1372 error = kqueue_acquire(fp, &kq);
1375 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1376 kqueue_release(kq, 0);
1381 * Performs a kevent() call on a temporarily created kqueue. This can be
1382 * used to perform one-shot polling, similar to poll() and select().
1385 kern_kevent_anonymous(struct thread *td, int nevents,
1386 struct kevent_copyops *k_ops)
1388 struct kqueue kq = {};
1393 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1394 kqueue_drain(&kq, td);
1395 kqueue_destroy(&kq);
1400 kqueue_add_filteropts(int filt, const struct filterops *filtops)
1405 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1407 "trying to add a filterop that is out of range: %d is beyond %d\n",
1408 ~filt, EVFILT_SYSCOUNT);
1411 mtx_lock(&filterops_lock);
1412 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1413 sysfilt_ops[~filt].for_fop != NULL)
1416 sysfilt_ops[~filt].for_fop = filtops;
1417 sysfilt_ops[~filt].for_refcnt = 0;
1419 mtx_unlock(&filterops_lock);
1425 kqueue_del_filteropts(int filt)
1430 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1433 mtx_lock(&filterops_lock);
1434 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1435 sysfilt_ops[~filt].for_fop == NULL)
1437 else if (sysfilt_ops[~filt].for_refcnt != 0)
1440 sysfilt_ops[~filt].for_fop = &null_filtops;
1441 sysfilt_ops[~filt].for_refcnt = 0;
1443 mtx_unlock(&filterops_lock);
1448 static const struct filterops *
1449 kqueue_fo_find(int filt)
1452 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1455 if (sysfilt_ops[~filt].for_nolock)
1456 return sysfilt_ops[~filt].for_fop;
1458 mtx_lock(&filterops_lock);
1459 sysfilt_ops[~filt].for_refcnt++;
1460 if (sysfilt_ops[~filt].for_fop == NULL)
1461 sysfilt_ops[~filt].for_fop = &null_filtops;
1462 mtx_unlock(&filterops_lock);
1464 return sysfilt_ops[~filt].for_fop;
1468 kqueue_fo_release(int filt)
1471 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1474 if (sysfilt_ops[~filt].for_nolock)
1477 mtx_lock(&filterops_lock);
1478 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1479 ("filter object refcount not valid on release"));
1480 sysfilt_ops[~filt].for_refcnt--;
1481 mtx_unlock(&filterops_lock);
1485 * A ref to kq (obtained via kqueue_acquire) must be held.
1488 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td,
1491 const struct filterops *fops;
1493 struct knote *kn, *tkn;
1495 int error, filt, event;
1496 int haskqglobal, filedesc_unlock;
1498 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1506 filedesc_unlock = 0;
1509 fops = kqueue_fo_find(filt);
1513 if (kev->flags & EV_ADD) {
1514 /* Reject an invalid flag pair early */
1515 if (kev->flags & EV_KEEPUDATA) {
1522 * Prevent waiting with locks. Non-sleepable
1523 * allocation failures are handled in the loop, only
1524 * if the spare knote appears to be actually required.
1526 tkn = knote_alloc(mflag);
1533 KASSERT(td != NULL, ("td is NULL"));
1534 if (kev->ident > INT_MAX)
1537 error = fget(td, kev->ident, &cap_event_rights, &fp);
1541 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1542 kev->ident, M_NOWAIT) != 0) {
1546 error = kqueue_expand(kq, fops, kev->ident, mflag);
1552 if (fp->f_type == DTYPE_KQUEUE) {
1554 * If we add some intelligence about what we are doing,
1555 * we should be able to support events on ourselves.
1556 * We need to know when we are doing this to prevent
1557 * getting both the knlist lock and the kq lock since
1558 * they are the same thing.
1560 if (fp->f_data == kq) {
1566 * Pre-lock the filedesc before the global
1567 * lock mutex, see the comment in
1570 FILEDESC_XLOCK(td->td_proc->p_fd);
1571 filedesc_unlock = 1;
1572 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1576 if (kev->ident < kq->kq_knlistsize) {
1577 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1578 if (kev->filter == kn->kn_filter)
1582 if ((kev->flags & EV_ADD) == EV_ADD) {
1583 error = kqueue_expand(kq, fops, kev->ident, mflag);
1591 * If possible, find an existing knote to use for this kevent.
1593 if (kev->filter == EVFILT_PROC &&
1594 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1595 /* This is an internal creation of a process tracking
1596 * note. Don't attempt to coalesce this with an
1600 } else if (kq->kq_knhashmask != 0) {
1603 list = &kq->kq_knhash[
1604 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1605 SLIST_FOREACH(kn, list, kn_link)
1606 if (kev->ident == kn->kn_id &&
1607 kev->filter == kn->kn_filter)
1612 /* knote is in the process of changing, wait for it to stabilize. */
1613 if (kn != NULL && kn_in_flux(kn)) {
1614 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1615 if (filedesc_unlock) {
1616 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1617 filedesc_unlock = 0;
1619 kq->kq_state |= KQ_FLUXWAIT;
1620 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1629 * kn now contains the matching knote, or NULL if no match
1632 if (kev->flags & EV_ADD) {
1644 * apply reference counts to knote structure, and
1645 * do not release it at the end of this routine.
1650 kn->kn_sfflags = kev->fflags;
1651 kn->kn_sdata = kev->data;
1654 kn->kn_kevent = *kev;
1655 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1656 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1657 kn->kn_status = KN_DETACHED;
1658 if ((kev->flags & EV_DISABLE) != 0)
1659 kn->kn_status |= KN_DISABLED;
1662 error = knote_attach(kn, kq);
1669 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1670 knote_drop_detached(kn, td);
1673 knl = kn_list_lock(kn);
1676 /* No matching knote and the EV_ADD flag is not set. */
1683 if (kev->flags & EV_DELETE) {
1690 if (kev->flags & EV_FORCEONESHOT) {
1691 kn->kn_flags |= EV_ONESHOT;
1692 KNOTE_ACTIVATE(kn, 1);
1695 if ((kev->flags & EV_ENABLE) != 0)
1696 kn->kn_status &= ~KN_DISABLED;
1697 else if ((kev->flags & EV_DISABLE) != 0)
1698 kn->kn_status |= KN_DISABLED;
1701 * The user may change some filter values after the initial EV_ADD,
1702 * but doing so will not reset any filter which has already been
1705 kn->kn_status |= KN_SCAN;
1708 knl = kn_list_lock(kn);
1709 if ((kev->flags & EV_KEEPUDATA) == 0)
1710 kn->kn_kevent.udata = kev->udata;
1711 if (!fops->f_isfd && fops->f_touch != NULL) {
1712 fops->f_touch(kn, kev, EVENT_REGISTER);
1714 kn->kn_sfflags = kev->fflags;
1715 kn->kn_sdata = kev->data;
1720 * We can get here with kn->kn_knlist == NULL. This can happen when
1721 * the initial attach event decides that the event is "completed"
1722 * already, e.g., filt_procattach() is called on a zombie process. It
1723 * will call filt_proc() which will remove it from the list, and NULL
1726 * KN_DISABLED will be stable while the knote is in flux, so the
1727 * unlocked read will not race with an update.
1729 if ((kn->kn_status & KN_DISABLED) == 0)
1730 event = kn->kn_fop->f_event(kn, 0);
1736 kn->kn_status |= KN_ACTIVE;
1737 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1740 kn->kn_status &= ~KN_SCAN;
1742 kn_list_unlock(knl);
1746 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1747 if (filedesc_unlock)
1748 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1753 kqueue_fo_release(filt);
1758 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1766 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1770 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1781 kqueue_release(struct kqueue *kq, int locked)
1788 if (kq->kq_refcnt == 1)
1789 wakeup(&kq->kq_refcnt);
1795 ast_kqueue(struct thread *td, int tda __unused)
1797 taskqueue_quiesce(taskqueue_kqueue_ctx);
1801 kqueue_schedtask(struct kqueue *kq)
1804 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1805 ("scheduling kqueue task while draining"));
1807 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1808 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1809 kq->kq_state |= KQ_TASKSCHED;
1810 ast_sched(curthread, TDA_KQUEUE);
1815 * Expand the kq to make sure we have storage for fops/ident pair.
1817 * Return 0 on success (or no work necessary), return errno on failure.
1820 kqueue_expand(struct kqueue *kq, const struct filterops *fops, uintptr_t ident,
1823 struct klist *list, *tmp_knhash, *to_free;
1824 u_long tmp_knhashmask;
1825 int error, fd, size;
1833 if (kq->kq_knlistsize <= fd) {
1834 size = kq->kq_knlistsize;
1837 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1841 if ((kq->kq_state & KQ_CLOSING) != 0) {
1844 } else if (kq->kq_knlistsize > fd) {
1847 if (kq->kq_knlist != NULL) {
1848 bcopy(kq->kq_knlist, list,
1849 kq->kq_knlistsize * sizeof(*list));
1850 to_free = kq->kq_knlist;
1851 kq->kq_knlist = NULL;
1853 bzero((caddr_t)list +
1854 kq->kq_knlistsize * sizeof(*list),
1855 (size - kq->kq_knlistsize) * sizeof(*list));
1856 kq->kq_knlistsize = size;
1857 kq->kq_knlist = list;
1862 if (kq->kq_knhashmask == 0) {
1863 tmp_knhash = hashinit_flags(KN_HASHSIZE, M_KQUEUE,
1864 &tmp_knhashmask, (mflag & M_WAITOK) != 0 ?
1865 HASH_WAITOK : HASH_NOWAIT);
1866 if (tmp_knhash == NULL)
1869 if ((kq->kq_state & KQ_CLOSING) != 0) {
1870 to_free = tmp_knhash;
1872 } else if (kq->kq_knhashmask == 0) {
1873 kq->kq_knhash = tmp_knhash;
1874 kq->kq_knhashmask = tmp_knhashmask;
1876 to_free = tmp_knhash;
1881 free(to_free, M_KQUEUE);
1888 kqueue_task(void *arg, int pending)
1896 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1899 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1901 kq->kq_state &= ~KQ_TASKSCHED;
1902 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1903 wakeup(&kq->kq_state);
1906 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1910 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1911 * We treat KN_MARKER knotes as if they are in flux.
1914 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1915 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1917 struct kevent *kevp;
1918 struct knote *kn, *marker;
1920 sbintime_t asbt, rsbt;
1921 int count, error, haskqglobal, influx, nkev, touch;
1930 if (maxevents < 0) {
1937 if (!timespecvalid_interval(tsp)) {
1941 if (timespecisset(tsp)) {
1942 if (tsp->tv_sec <= INT32_MAX) {
1943 rsbt = tstosbt(*tsp);
1944 if (TIMESEL(&asbt, rsbt))
1945 asbt += tc_tick_sbt;
1946 if (asbt <= SBT_MAX - rsbt)
1950 rsbt >>= tc_precexp;
1957 marker = knote_alloc(M_WAITOK);
1958 marker->kn_status = KN_MARKER;
1963 if (kq->kq_count == 0) {
1965 error = EWOULDBLOCK;
1967 kq->kq_state |= KQ_SLEEP;
1968 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1969 "kqread", asbt, rsbt, C_ABSOLUTE);
1973 /* don't restart after signals... */
1974 if (error == ERESTART)
1976 else if (error == EWOULDBLOCK)
1981 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1985 kn = TAILQ_FIRST(&kq->kq_head);
1987 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1993 kq->kq_state |= KQ_FLUXWAIT;
1994 error = msleep(kq, &kq->kq_lock, PSOCK,
1999 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2000 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
2001 kn->kn_status &= ~KN_QUEUED;
2007 if (count == maxevents)
2011 KASSERT(!kn_in_flux(kn),
2012 ("knote %p is unexpectedly in flux", kn));
2014 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
2015 kn->kn_status &= ~KN_QUEUED;
2020 * We don't need to lock the list since we've
2021 * marked it as in flux.
2026 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
2027 kn->kn_status &= ~KN_QUEUED;
2032 * We don't need to lock the list since we've
2033 * marked the knote as being in flux.
2035 *kevp = kn->kn_kevent;
2040 kn->kn_status |= KN_SCAN;
2043 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
2044 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
2045 knl = kn_list_lock(kn);
2046 if (kn->kn_fop->f_event(kn, 0) == 0) {
2048 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2049 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
2053 kn_list_unlock(knl);
2057 touch = (!kn->kn_fop->f_isfd &&
2058 kn->kn_fop->f_touch != NULL);
2060 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
2062 *kevp = kn->kn_kevent;
2064 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2065 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
2067 * Manually clear knotes who weren't
2070 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
2074 if (kn->kn_flags & EV_DISPATCH)
2075 kn->kn_status |= KN_DISABLED;
2076 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
2079 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2081 kn->kn_status &= ~KN_SCAN;
2083 kn_list_unlock(knl);
2087 /* we are returning a copy to the user */
2092 if (nkev == KQ_NEVENTS) {
2095 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2103 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
2111 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2112 td->td_retval[0] = maxevents - count;
2118 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
2119 struct ucred *active_cred, struct thread *td)
2122 * Enabling sigio causes two major problems:
2123 * 1) infinite recursion:
2124 * Synopsys: kevent is being used to track signals and have FIOASYNC
2125 * set. On receipt of a signal this will cause a kqueue to recurse
2126 * into itself over and over. Sending the sigio causes the kqueue
2127 * to become ready, which in turn posts sigio again, forever.
2128 * Solution: this can be solved by setting a flag in the kqueue that
2129 * we have a SIGIO in progress.
2130 * 2) locking problems:
2131 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
2132 * us above the proc and pgrp locks.
2133 * Solution: Post a signal using an async mechanism, being sure to
2134 * record a generation count in the delivery so that we do not deliver
2135 * a signal to the wrong process.
2137 * Note, these two mechanisms are somewhat mutually exclusive!
2146 kq->kq_state |= KQ_ASYNC;
2148 kq->kq_state &= ~KQ_ASYNC;
2153 return (fsetown(*(int *)data, &kq->kq_sigio));
2156 *(int *)data = fgetown(&kq->kq_sigio);
2166 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
2173 if ((error = kqueue_acquire(fp, &kq)))
2177 if (events & (POLLIN | POLLRDNORM)) {
2179 revents |= events & (POLLIN | POLLRDNORM);
2181 selrecord(td, &kq->kq_sel);
2182 if (SEL_WAITING(&kq->kq_sel))
2183 kq->kq_state |= KQ_SEL;
2186 kqueue_release(kq, 1);
2193 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred)
2196 bzero((void *)st, sizeof *st);
2198 * We no longer return kq_count because the unlocked value is useless.
2199 * If you spent all this time getting the count, why not spend your
2200 * syscall better by calling kevent?
2202 * XXX - This is needed for libc_r.
2204 st->st_mode = S_IFIFO;
2209 kqueue_drain(struct kqueue *kq, struct thread *td)
2216 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
2217 ("kqueue already closing"));
2218 kq->kq_state |= KQ_CLOSING;
2219 if (kq->kq_refcnt > 1)
2220 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
2222 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
2224 KASSERT(knlist_empty(&kq->kq_sel.si_note),
2225 ("kqueue's knlist not empty"));
2227 for (i = 0; i < kq->kq_knlistsize; i++) {
2228 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
2229 if (kn_in_flux(kn)) {
2230 kq->kq_state |= KQ_FLUXWAIT;
2231 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
2240 if (kq->kq_knhashmask != 0) {
2241 for (i = 0; i <= kq->kq_knhashmask; i++) {
2242 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
2243 if (kn_in_flux(kn)) {
2244 kq->kq_state |= KQ_FLUXWAIT;
2245 msleep(kq, &kq->kq_lock, PSOCK,
2257 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
2258 kq->kq_state |= KQ_TASKDRAIN;
2259 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2262 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2263 selwakeuppri(&kq->kq_sel, PSOCK);
2264 if (!SEL_WAITING(&kq->kq_sel))
2265 kq->kq_state &= ~KQ_SEL;
2272 kqueue_destroy(struct kqueue *kq)
2275 KASSERT(kq->kq_fdp == NULL,
2276 ("kqueue still attached to a file descriptor"));
2277 seldrain(&kq->kq_sel);
2278 knlist_destroy(&kq->kq_sel.si_note);
2279 mtx_destroy(&kq->kq_lock);
2281 if (kq->kq_knhash != NULL)
2282 free(kq->kq_knhash, M_KQUEUE);
2283 if (kq->kq_knlist != NULL)
2284 free(kq->kq_knlist, M_KQUEUE);
2286 funsetown(&kq->kq_sigio);
2291 kqueue_close(struct file *fp, struct thread *td)
2293 struct kqueue *kq = fp->f_data;
2294 struct filedesc *fdp;
2296 int filedesc_unlock;
2298 if ((error = kqueue_acquire(fp, &kq)))
2300 kqueue_drain(kq, td);
2303 * We could be called due to the knote_drop() doing fdrop(),
2304 * called from kqueue_register(). In this case the global
2305 * lock is owned, and filedesc sx is locked before, to not
2306 * take the sleepable lock after non-sleepable.
2310 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2311 FILEDESC_XLOCK(fdp);
2312 filedesc_unlock = 1;
2314 filedesc_unlock = 0;
2315 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2316 if (filedesc_unlock)
2317 FILEDESC_XUNLOCK(fdp);
2320 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2321 crfree(kq->kq_cred);
2329 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2331 struct kqueue *kq = fp->f_data;
2333 kif->kf_type = KF_TYPE_KQUEUE;
2334 kif->kf_un.kf_kqueue.kf_kqueue_addr = (uintptr_t)kq;
2335 kif->kf_un.kf_kqueue.kf_kqueue_count = kq->kq_count;
2336 kif->kf_un.kf_kqueue.kf_kqueue_state = kq->kq_state;
2341 kqueue_wakeup(struct kqueue *kq)
2345 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2346 kq->kq_state &= ~KQ_SLEEP;
2349 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2350 selwakeuppri(&kq->kq_sel, PSOCK);
2351 if (!SEL_WAITING(&kq->kq_sel))
2352 kq->kq_state &= ~KQ_SEL;
2354 if (!knlist_empty(&kq->kq_sel.si_note))
2355 kqueue_schedtask(kq);
2356 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2357 pgsigio(&kq->kq_sigio, SIGIO, 0);
2362 * Walk down a list of knotes, activating them if their event has triggered.
2364 * There is a possibility to optimize in the case of one kq watching another.
2365 * Instead of scheduling a task to wake it up, you could pass enough state
2366 * down the chain to make up the parent kqueue. Make this code functional
2370 knote(struct knlist *list, long hint, int lockflags)
2373 struct knote *kn, *tkn;
2379 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2381 if ((lockflags & KNF_LISTLOCKED) == 0)
2382 list->kl_lock(list->kl_lockarg);
2385 * If we unlock the list lock (and enter influx), we can
2386 * eliminate the kqueue scheduling, but this will introduce
2387 * four lock/unlock's for each knote to test. Also, marker
2388 * would be needed to keep iteration position, since filters
2389 * or other threads could remove events.
2391 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2394 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2396 * Do not process the influx notes, except for
2397 * the influx coming from the kq unlock in the
2398 * kqueue_scan(). In the later case, we do
2399 * not interfere with the scan, since the code
2400 * fragment in kqueue_scan() locks the knlist,
2401 * and cannot proceed until we finished.
2404 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2407 error = kn->kn_fop->f_event(kn, hint);
2411 KNOTE_ACTIVATE(kn, 1);
2414 if (kn->kn_fop->f_event(kn, hint))
2415 KNOTE_ACTIVATE(kn, 1);
2419 if ((lockflags & KNF_LISTLOCKED) == 0)
2420 list->kl_unlock(list->kl_lockarg);
2424 * add a knote to a knlist
2427 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2430 KNL_ASSERT_LOCK(knl, islocked);
2431 KQ_NOTOWNED(kn->kn_kq);
2432 KASSERT(kn_in_flux(kn), ("knote %p not in flux", kn));
2433 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2434 ("knote %p was not detached", kn));
2436 knl->kl_lock(knl->kl_lockarg);
2437 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2439 knl->kl_unlock(knl->kl_lockarg);
2441 kn->kn_knlist = knl;
2442 kn->kn_status &= ~KN_DETACHED;
2443 KQ_UNLOCK(kn->kn_kq);
2447 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2451 KASSERT(!kqislocked || knlislocked, ("kq locked w/o knl locked"));
2452 KNL_ASSERT_LOCK(knl, knlislocked);
2453 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2454 KASSERT(kqislocked || kn_in_flux(kn), ("knote %p not in flux", kn));
2455 KASSERT((kn->kn_status & KN_DETACHED) == 0,
2456 ("knote %p was already detached", kn));
2458 knl->kl_lock(knl->kl_lockarg);
2459 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2460 kn->kn_knlist = NULL;
2462 kn_list_unlock(knl);
2465 kn->kn_status |= KN_DETACHED;
2467 KQ_UNLOCK(kn->kn_kq);
2471 * remove knote from the specified knlist
2474 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2477 knlist_remove_kq(knl, kn, islocked, 0);
2481 knlist_empty(struct knlist *knl)
2484 KNL_ASSERT_LOCKED(knl);
2485 return (SLIST_EMPTY(&knl->kl_list));
2488 static struct mtx knlist_lock;
2489 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2491 static void knlist_mtx_lock(void *arg);
2492 static void knlist_mtx_unlock(void *arg);
2495 knlist_mtx_lock(void *arg)
2498 mtx_lock((struct mtx *)arg);
2502 knlist_mtx_unlock(void *arg)
2505 mtx_unlock((struct mtx *)arg);
2509 knlist_mtx_assert_lock(void *arg, int what)
2512 if (what == LA_LOCKED)
2513 mtx_assert((struct mtx *)arg, MA_OWNED);
2515 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2519 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2520 void (*kl_unlock)(void *),
2521 void (*kl_assert_lock)(void *, int))
2525 knl->kl_lockarg = &knlist_lock;
2527 knl->kl_lockarg = lock;
2529 if (kl_lock == NULL)
2530 knl->kl_lock = knlist_mtx_lock;
2532 knl->kl_lock = kl_lock;
2533 if (kl_unlock == NULL)
2534 knl->kl_unlock = knlist_mtx_unlock;
2536 knl->kl_unlock = kl_unlock;
2537 if (kl_assert_lock == NULL)
2538 knl->kl_assert_lock = knlist_mtx_assert_lock;
2540 knl->kl_assert_lock = kl_assert_lock;
2542 knl->kl_autodestroy = 0;
2543 SLIST_INIT(&knl->kl_list);
2547 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2550 knlist_init(knl, lock, NULL, NULL, NULL);
2554 knlist_alloc(struct mtx *lock)
2558 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2559 knlist_init_mtx(knl, lock);
2564 knlist_destroy(struct knlist *knl)
2567 KASSERT(KNLIST_EMPTY(knl),
2568 ("destroying knlist %p with knotes on it", knl));
2572 knlist_detach(struct knlist *knl)
2575 KNL_ASSERT_LOCKED(knl);
2576 knl->kl_autodestroy = 1;
2577 if (knlist_empty(knl)) {
2578 knlist_destroy(knl);
2579 free(knl, M_KQUEUE);
2584 * Even if we are locked, we may need to drop the lock to allow any influx
2585 * knotes time to "settle".
2588 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2590 struct knote *kn, *kn2;
2593 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2595 KNL_ASSERT_LOCKED(knl);
2597 KNL_ASSERT_UNLOCKED(knl);
2598 again: /* need to reacquire lock since we have dropped it */
2599 knl->kl_lock(knl->kl_lockarg);
2602 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2605 if (kn_in_flux(kn)) {
2609 knlist_remove_kq(knl, kn, 1, 1);
2613 knote_drop_detached(kn, td);
2615 /* Make sure cleared knotes disappear soon */
2616 kn->kn_flags |= EV_EOF | EV_ONESHOT;
2622 if (!SLIST_EMPTY(&knl->kl_list)) {
2623 /* there are still in flux knotes remaining */
2624 kn = SLIST_FIRST(&knl->kl_list);
2627 KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2628 knl->kl_unlock(knl->kl_lockarg);
2629 kq->kq_state |= KQ_FLUXWAIT;
2630 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2636 KNL_ASSERT_LOCKED(knl);
2638 knl->kl_unlock(knl->kl_lockarg);
2639 KNL_ASSERT_UNLOCKED(knl);
2644 * Remove all knotes referencing a specified fd must be called with FILEDESC
2645 * lock. This prevents a race where a new fd comes along and occupies the
2646 * entry and we attach a knote to the fd.
2649 knote_fdclose(struct thread *td, int fd)
2651 struct filedesc *fdp = td->td_proc->p_fd;
2656 FILEDESC_XLOCK_ASSERT(fdp);
2659 * We shouldn't have to worry about new kevents appearing on fd
2660 * since filedesc is locked.
2662 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2667 while (kq->kq_knlistsize > fd &&
2668 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2669 if (kn_in_flux(kn)) {
2670 /* someone else might be waiting on our knote */
2673 kq->kq_state |= KQ_FLUXWAIT;
2674 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2688 knote_attach(struct knote *kn, struct kqueue *kq)
2692 KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2695 if ((kq->kq_state & KQ_CLOSING) != 0)
2697 if (kn->kn_fop->f_isfd) {
2698 if (kn->kn_id >= kq->kq_knlistsize)
2700 list = &kq->kq_knlist[kn->kn_id];
2702 if (kq->kq_knhash == NULL)
2704 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2706 SLIST_INSERT_HEAD(list, kn, kn_link);
2711 knote_drop(struct knote *kn, struct thread *td)
2714 if ((kn->kn_status & KN_DETACHED) == 0)
2715 kn->kn_fop->f_detach(kn);
2716 knote_drop_detached(kn, td);
2720 knote_drop_detached(struct knote *kn, struct thread *td)
2727 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2728 ("knote %p still attached", kn));
2732 KASSERT(kn->kn_influx == 1,
2733 ("knote_drop called on %p with influx %d", kn, kn->kn_influx));
2735 if (kn->kn_fop->f_isfd)
2736 list = &kq->kq_knlist[kn->kn_id];
2738 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2740 if (!SLIST_EMPTY(list))
2741 SLIST_REMOVE(list, kn, knote, kn_link);
2742 if (kn->kn_status & KN_QUEUED)
2746 if (kn->kn_fop->f_isfd) {
2747 fdrop(kn->kn_fp, td);
2750 kqueue_fo_release(kn->kn_kevent.filter);
2756 knote_enqueue(struct knote *kn)
2758 struct kqueue *kq = kn->kn_kq;
2760 KQ_OWNED(kn->kn_kq);
2761 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2763 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2764 kn->kn_status |= KN_QUEUED;
2770 knote_dequeue(struct knote *kn)
2772 struct kqueue *kq = kn->kn_kq;
2774 KQ_OWNED(kn->kn_kq);
2775 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2777 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2778 kn->kn_status &= ~KN_QUEUED;
2786 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2787 NULL, NULL, UMA_ALIGN_PTR, 0);
2788 ast_register(TDA_KQUEUE, ASTR_ASTF_REQUIRED, 0, ast_kqueue);
2790 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2792 static struct knote *
2793 knote_alloc(int mflag)
2796 return (uma_zalloc(knote_zone, mflag | M_ZERO));
2800 knote_free(struct knote *kn)
2803 uma_zfree(knote_zone, kn);
2807 * Register the kev w/ the kq specified by fd.
2810 kqfd_register(int fd, struct kevent *kev, struct thread *td, int mflag)
2814 cap_rights_t rights;
2817 error = fget(td, fd, cap_rights_init_one(&rights, CAP_KQUEUE_CHANGE),
2821 if ((error = kqueue_acquire(fp, &kq)) != 0)
2824 error = kqueue_register(kq, kev, td, mflag);
2825 kqueue_release(kq, 0);