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_cmp = file_kcmp_generic,
143 .fo_fill_kinfo = kqueue_fill_kinfo,
146 static int knote_attach(struct knote *kn, struct kqueue *kq);
147 static void knote_drop(struct knote *kn, struct thread *td);
148 static void knote_drop_detached(struct knote *kn, struct thread *td);
149 static void knote_enqueue(struct knote *kn);
150 static void knote_dequeue(struct knote *kn);
151 static void knote_init(void);
152 static struct knote *knote_alloc(int mflag);
153 static void knote_free(struct knote *kn);
155 static void filt_kqdetach(struct knote *kn);
156 static int filt_kqueue(struct knote *kn, long hint);
157 static int filt_procattach(struct knote *kn);
158 static void filt_procdetach(struct knote *kn);
159 static int filt_proc(struct knote *kn, long hint);
160 static int filt_fileattach(struct knote *kn);
161 static void filt_timerexpire(void *knx);
162 static void filt_timerexpire_l(struct knote *kn, bool proc_locked);
163 static int filt_timerattach(struct knote *kn);
164 static void filt_timerdetach(struct knote *kn);
165 static void filt_timerstart(struct knote *kn, sbintime_t to);
166 static void filt_timertouch(struct knote *kn, struct kevent *kev,
168 static int filt_timervalidate(struct knote *kn, sbintime_t *to);
169 static int filt_timer(struct knote *kn, long hint);
170 static int filt_userattach(struct knote *kn);
171 static void filt_userdetach(struct knote *kn);
172 static int filt_user(struct knote *kn, long hint);
173 static void filt_usertouch(struct knote *kn, struct kevent *kev,
176 static struct filterops file_filtops = {
178 .f_attach = filt_fileattach,
180 static struct filterops kqread_filtops = {
182 .f_detach = filt_kqdetach,
183 .f_event = filt_kqueue,
185 /* XXX - move to kern_proc.c? */
186 static struct filterops proc_filtops = {
188 .f_attach = filt_procattach,
189 .f_detach = filt_procdetach,
190 .f_event = filt_proc,
192 static struct filterops timer_filtops = {
194 .f_attach = filt_timerattach,
195 .f_detach = filt_timerdetach,
196 .f_event = filt_timer,
197 .f_touch = filt_timertouch,
199 static struct filterops user_filtops = {
200 .f_attach = filt_userattach,
201 .f_detach = filt_userdetach,
202 .f_event = filt_user,
203 .f_touch = filt_usertouch,
206 static uma_zone_t knote_zone;
207 static unsigned int __exclusive_cache_line kq_ncallouts;
208 static unsigned int kq_calloutmax = 4 * 1024;
209 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
210 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
212 /* XXX - ensure not influx ? */
213 #define KNOTE_ACTIVATE(kn, islock) do { \
215 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
217 KQ_LOCK((kn)->kn_kq); \
218 (kn)->kn_status |= KN_ACTIVE; \
219 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
220 knote_enqueue((kn)); \
222 KQ_UNLOCK((kn)->kn_kq); \
224 #define KQ_LOCK(kq) do { \
225 mtx_lock(&(kq)->kq_lock); \
227 #define KQ_FLUX_WAKEUP(kq) do { \
228 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
229 (kq)->kq_state &= ~KQ_FLUXWAIT; \
233 #define KQ_UNLOCK_FLUX(kq) do { \
234 KQ_FLUX_WAKEUP(kq); \
235 mtx_unlock(&(kq)->kq_lock); \
237 #define KQ_UNLOCK(kq) do { \
238 mtx_unlock(&(kq)->kq_lock); \
240 #define KQ_OWNED(kq) do { \
241 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
243 #define KQ_NOTOWNED(kq) do { \
244 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
247 static struct knlist *
248 kn_list_lock(struct knote *kn)
254 knl->kl_lock(knl->kl_lockarg);
259 kn_list_unlock(struct knlist *knl)
265 do_free = knl->kl_autodestroy && knlist_empty(knl);
266 knl->kl_unlock(knl->kl_lockarg);
274 kn_in_flux(struct knote *kn)
277 return (kn->kn_influx > 0);
281 kn_enter_flux(struct knote *kn)
285 MPASS(kn->kn_influx < INT_MAX);
290 kn_leave_flux(struct knote *kn)
294 MPASS(kn->kn_influx > 0);
296 return (kn->kn_influx == 0);
299 #define KNL_ASSERT_LOCK(knl, islocked) do { \
301 KNL_ASSERT_LOCKED(knl); \
303 KNL_ASSERT_UNLOCKED(knl); \
306 #define KNL_ASSERT_LOCKED(knl) do { \
307 knl->kl_assert_lock((knl)->kl_lockarg, LA_LOCKED); \
309 #define KNL_ASSERT_UNLOCKED(knl) do { \
310 knl->kl_assert_lock((knl)->kl_lockarg, LA_UNLOCKED); \
312 #else /* !INVARIANTS */
313 #define KNL_ASSERT_LOCKED(knl) do {} while (0)
314 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
315 #endif /* INVARIANTS */
318 #define KN_HASHSIZE 64 /* XXX should be tunable */
321 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
324 filt_nullattach(struct knote *kn)
330 struct filterops null_filtops = {
332 .f_attach = filt_nullattach,
335 /* XXX - make SYSINIT to add these, and move into respective modules. */
336 extern struct filterops sig_filtops;
337 extern struct filterops fs_filtops;
340 * Table for all system-defined filters.
342 static struct mtx filterops_lock;
343 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops", MTX_DEF);
345 const struct filterops *for_fop;
348 } sysfilt_ops[EVFILT_SYSCOUNT] = {
349 { &file_filtops, 1 }, /* EVFILT_READ */
350 { &file_filtops, 1 }, /* EVFILT_WRITE */
351 { &null_filtops }, /* EVFILT_AIO */
352 { &file_filtops, 1 }, /* EVFILT_VNODE */
353 { &proc_filtops, 1 }, /* EVFILT_PROC */
354 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
355 { &timer_filtops, 1 }, /* EVFILT_TIMER */
356 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
357 { &fs_filtops, 1 }, /* EVFILT_FS */
358 { &null_filtops }, /* EVFILT_LIO */
359 { &user_filtops, 1 }, /* EVFILT_USER */
360 { &null_filtops }, /* EVFILT_SENDFILE */
361 { &file_filtops, 1 }, /* EVFILT_EMPTY */
365 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
369 filt_fileattach(struct knote *kn)
372 return (fo_kqfilter(kn->kn_fp, kn));
377 kqueue_kqfilter(struct file *fp, struct knote *kn)
379 struct kqueue *kq = kn->kn_fp->f_data;
381 if (kn->kn_filter != EVFILT_READ)
384 kn->kn_status |= KN_KQUEUE;
385 kn->kn_fop = &kqread_filtops;
386 knlist_add(&kq->kq_sel.si_note, kn, 0);
392 filt_kqdetach(struct knote *kn)
394 struct kqueue *kq = kn->kn_fp->f_data;
396 knlist_remove(&kq->kq_sel.si_note, kn, 0);
401 filt_kqueue(struct knote *kn, long hint)
403 struct kqueue *kq = kn->kn_fp->f_data;
405 kn->kn_data = kq->kq_count;
406 return (kn->kn_data > 0);
409 /* XXX - move to kern_proc.c? */
411 filt_procattach(struct knote *kn)
415 bool exiting, immediate;
417 exiting = immediate = false;
418 if (kn->kn_sfflags & NOTE_EXIT)
419 p = pfind_any(kn->kn_id);
421 p = pfind(kn->kn_id);
424 if (p->p_flag & P_WEXIT)
427 if ((error = p_cansee(curthread, p))) {
432 kn->kn_ptr.p_proc = p;
433 kn->kn_flags |= EV_CLEAR; /* automatically set */
436 * Internal flag indicating registration done by kernel for the
437 * purposes of getting a NOTE_CHILD notification.
439 if (kn->kn_flags & EV_FLAG2) {
440 kn->kn_flags &= ~EV_FLAG2;
441 kn->kn_data = kn->kn_sdata; /* ppid */
442 kn->kn_fflags = NOTE_CHILD;
443 kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
444 immediate = true; /* Force immediate activation of child note. */
447 * Internal flag indicating registration done by kernel (for other than
450 if (kn->kn_flags & EV_FLAG1) {
451 kn->kn_flags &= ~EV_FLAG1;
454 knlist_add(p->p_klist, kn, 1);
457 * Immediately activate any child notes or, in the case of a zombie
458 * target process, exit notes. The latter is necessary to handle the
459 * case where the target process, e.g. a child, dies before the kevent
462 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
463 KNOTE_ACTIVATE(kn, 0);
471 * The knote may be attached to a different process, which may exit,
472 * leaving nothing for the knote to be attached to. So when the process
473 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
474 * it will be deleted when read out. However, as part of the knote deletion,
475 * this routine is called, so a check is needed to avoid actually performing
476 * a detach, because the original process does not exist any more.
478 /* XXX - move to kern_proc.c? */
480 filt_procdetach(struct knote *kn)
483 knlist_remove(kn->kn_knlist, kn, 0);
484 kn->kn_ptr.p_proc = NULL;
487 /* XXX - move to kern_proc.c? */
489 filt_proc(struct knote *kn, long hint)
494 p = kn->kn_ptr.p_proc;
495 if (p == NULL) /* already activated, from attach filter */
498 /* Mask off extra data. */
499 event = (u_int)hint & NOTE_PCTRLMASK;
501 /* If the user is interested in this event, record it. */
502 if (kn->kn_sfflags & event)
503 kn->kn_fflags |= event;
505 /* Process is gone, so flag the event as finished. */
506 if (event == NOTE_EXIT) {
507 kn->kn_flags |= EV_EOF | EV_ONESHOT;
508 kn->kn_ptr.p_proc = NULL;
509 if (kn->kn_fflags & NOTE_EXIT)
510 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
511 if (kn->kn_fflags == 0)
512 kn->kn_flags |= EV_DROP;
516 return (kn->kn_fflags != 0);
520 * Called when the process forked. It mostly does the same as the
521 * knote(), activating all knotes registered to be activated when the
522 * process forked. Additionally, for each knote attached to the
523 * parent, check whether user wants to track the new process. If so
524 * attach a new knote to it, and immediately report an event with the
528 knote_fork(struct knlist *list, int pid)
536 KNL_ASSERT_LOCKED(list);
537 if (SLIST_EMPTY(&list->kl_list))
540 memset(&kev, 0, sizeof(kev));
541 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
544 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
550 * The same as knote(), activate the event.
552 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
553 if (kn->kn_fop->f_event(kn, NOTE_FORK))
554 KNOTE_ACTIVATE(kn, 1);
560 * The NOTE_TRACK case. In addition to the activation
561 * of the event, we need to register new events to
562 * track the child. Drop the locks in preparation for
563 * the call to kqueue_register().
567 list->kl_unlock(list->kl_lockarg);
570 * Activate existing knote and register tracking knotes with
573 * First register a knote to get just the child notice. This
574 * must be a separate note from a potential NOTE_EXIT
575 * notification since both NOTE_CHILD and NOTE_EXIT are defined
576 * to use the data field (in conflicting ways).
579 kev.filter = kn->kn_filter;
580 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
582 kev.fflags = kn->kn_sfflags;
583 kev.data = kn->kn_id; /* parent */
584 kev.udata = kn->kn_kevent.udata;/* preserve udata */
585 error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
587 kn->kn_fflags |= NOTE_TRACKERR;
590 * Then register another knote to track other potential events
591 * from the new process.
594 kev.filter = kn->kn_filter;
595 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
596 kev.fflags = kn->kn_sfflags;
597 kev.data = kn->kn_id; /* parent */
598 kev.udata = kn->kn_kevent.udata;/* preserve udata */
599 error = kqueue_register(kq, &kev, NULL, M_NOWAIT);
601 kn->kn_fflags |= NOTE_TRACKERR;
602 if (kn->kn_fop->f_event(kn, NOTE_FORK))
603 KNOTE_ACTIVATE(kn, 0);
604 list->kl_lock(list->kl_lockarg);
612 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
613 * interval timer support code.
616 #define NOTE_TIMER_PRECMASK \
617 (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
620 timer2sbintime(int64_t data, int flags)
625 * Macros for converting to the fractional second portion of an
626 * sbintime_t using 64bit multiplication to improve precision.
628 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
629 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
630 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
631 switch (flags & NOTE_TIMER_PRECMASK) {
634 if (data > (SBT_MAX / SBT_1S))
637 return ((sbintime_t)data << 32);
638 case NOTE_MSECONDS: /* FALLTHROUGH */
643 if (secs > (SBT_MAX / SBT_1S))
646 return (secs << 32 | MS_TO_SBT(data % 1000));
648 return (MS_TO_SBT(data));
650 if (data >= 1000000) {
651 secs = data / 1000000;
653 if (secs > (SBT_MAX / SBT_1S))
656 return (secs << 32 | US_TO_SBT(data % 1000000));
658 return (US_TO_SBT(data));
660 if (data >= 1000000000) {
661 secs = data / 1000000000;
663 if (secs > (SBT_MAX / SBT_1S))
666 return (secs << 32 | NS_TO_SBT(data % 1000000000));
668 return (NS_TO_SBT(data));
675 struct kq_timer_cb_data {
681 TAILQ_ENTRY(kq_timer_cb_data) link;
682 sbintime_t next; /* next timer event fires at */
683 sbintime_t to; /* precalculated timer period, 0 for abs */
686 #define KQ_TIMER_CB_ENQUEUED 0x01
689 kqtimer_sched_callout(struct kq_timer_cb_data *kc)
691 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kc->kn,
692 kc->cpuid, C_ABSOLUTE);
696 kqtimer_proc_continue(struct proc *p)
698 struct kq_timer_cb_data *kc, *kc1;
702 PROC_LOCK_ASSERT(p, MA_OWNED);
707 TAILQ_FOREACH_SAFE(kc, &p->p_kqtim_stop, link, kc1) {
708 TAILQ_REMOVE(&p->p_kqtim_stop, kc, link);
709 kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
711 filt_timerexpire_l(kc->kn, true);
713 kqtimer_sched_callout(kc);
718 filt_timerexpire_l(struct knote *kn, bool proc_locked)
720 struct kq_timer_cb_data *kc;
727 if ((kn->kn_flags & EV_ONESHOT) != 0 || kc->to == 0) {
729 KNOTE_ACTIVATE(kn, 0);
734 if (now >= kc->next) {
735 delta = (now - kc->next) / kc->to;
738 kn->kn_data += delta;
739 kc->next += delta * kc->to;
740 if (now >= kc->next) /* overflow */
741 kc->next = now + kc->to;
742 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
746 * Initial check for stopped kc->p is racy. It is fine to
747 * miss the set of the stop flags, at worst we would schedule
748 * one more callout. On the other hand, it is not fine to not
749 * schedule when we we missed clearing of the flags, we
750 * recheck them under the lock and observe consistent state.
753 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
756 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
757 if ((kc->flags & KQ_TIMER_CB_ENQUEUED) == 0) {
758 kc->flags |= KQ_TIMER_CB_ENQUEUED;
759 TAILQ_INSERT_TAIL(&p->p_kqtim_stop, kc, link);
768 kqtimer_sched_callout(kc);
772 filt_timerexpire(void *knx)
774 filt_timerexpire_l(knx, false);
778 * data contains amount of time to sleep
781 filt_timervalidate(struct knote *kn, sbintime_t *to)
786 if (kn->kn_sdata < 0)
788 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
791 * The only fflags values supported are the timer unit
792 * (precision) and the absolute time indicator.
794 if ((kn->kn_sfflags & ~(NOTE_TIMER_PRECMASK | NOTE_ABSTIME)) != 0)
797 *to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
800 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
803 *to = MAX(0, *to - sbt);
809 filt_timerattach(struct knote *kn)
811 struct kq_timer_cb_data *kc;
816 error = filt_timervalidate(kn, &to);
819 KASSERT(to > 0 || (kn->kn_flags & EV_ONESHOT) != 0 ||
820 (kn->kn_sfflags & NOTE_ABSTIME) != 0,
821 ("%s: periodic timer has a calculated zero timeout", __func__));
823 ("%s: timer has a calculated negative timeout", __func__));
825 if (atomic_fetchadd_int(&kq_ncallouts, 1) + 1 > kq_calloutmax) {
826 atomic_subtract_int(&kq_ncallouts, 1);
830 if ((kn->kn_sfflags & NOTE_ABSTIME) == 0)
831 kn->kn_flags |= EV_CLEAR; /* automatically set */
832 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
833 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
836 kc->cpuid = PCPU_GET(cpuid);
838 callout_init(&kc->c, 1);
839 filt_timerstart(kn, to);
845 filt_timerstart(struct knote *kn, sbintime_t to)
847 struct kq_timer_cb_data *kc;
850 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
854 kc->next = to + sbinuptime();
857 kqtimer_sched_callout(kc);
861 filt_timerdetach(struct knote *kn)
863 struct kq_timer_cb_data *kc;
864 unsigned int old __unused;
869 callout_drain(&kc->c);
872 * kqtimer_proc_continue() might have rescheduled this callout.
873 * Double-check, using the process mutex as an interlock.
876 if ((kc->flags & KQ_TIMER_CB_ENQUEUED) != 0) {
877 kc->flags &= ~KQ_TIMER_CB_ENQUEUED;
878 TAILQ_REMOVE(&kc->p->p_kqtim_stop, kc, link);
880 pending = callout_pending(&kc->c);
884 old = atomic_fetchadd_int(&kq_ncallouts, -1);
885 KASSERT(old > 0, ("Number of callouts cannot become negative"));
886 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
890 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
892 struct kq_timer_cb_data *kc;
899 /* Handle re-added timers that update data/fflags */
900 if (kev->flags & EV_ADD) {
903 /* Drain any existing callout. */
904 callout_drain(&kc->c);
906 /* Throw away any existing undelivered record
907 * of the timer expiration. This is done under
908 * the presumption that if a process is
909 * re-adding this timer with new parameters,
910 * it is no longer interested in what may have
911 * happened under the old parameters. If it is
912 * interested, it can wait for the expiration,
913 * delete the old timer definition, and then
916 * This has to be done while the kq is locked:
917 * - if enqueued, dequeue
918 * - make it no longer active
919 * - clear the count of expiration events
923 if (kn->kn_status & KN_QUEUED)
926 kn->kn_status &= ~KN_ACTIVE;
930 /* Reschedule timer based on new data/fflags */
931 kn->kn_sfflags = kev->fflags;
932 kn->kn_sdata = kev->data;
933 error = filt_timervalidate(kn, &to);
935 kn->kn_flags |= EV_ERROR;
938 filt_timerstart(kn, to);
943 *kev = kn->kn_kevent;
944 if (kn->kn_flags & EV_CLEAR) {
951 panic("filt_timertouch() - invalid type (%ld)", type);
957 filt_timer(struct knote *kn, long hint)
960 return (kn->kn_data != 0);
964 filt_userattach(struct knote *kn)
968 * EVFILT_USER knotes are not attached to anything in the kernel.
971 if (kn->kn_fflags & NOTE_TRIGGER)
979 filt_userdetach(__unused struct knote *kn)
983 * EVFILT_USER knotes are not attached to anything in the kernel.
988 filt_user(struct knote *kn, __unused long hint)
991 return (kn->kn_hookid);
995 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
1000 case EVENT_REGISTER:
1001 if (kev->fflags & NOTE_TRIGGER)
1004 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
1005 kev->fflags &= NOTE_FFLAGSMASK;
1011 kn->kn_sfflags &= kev->fflags;
1015 kn->kn_sfflags |= kev->fflags;
1019 kn->kn_sfflags = kev->fflags;
1023 /* XXX Return error? */
1026 kn->kn_sdata = kev->data;
1027 if (kev->flags & EV_CLEAR) {
1035 *kev = kn->kn_kevent;
1036 kev->fflags = kn->kn_sfflags;
1037 kev->data = kn->kn_sdata;
1038 if (kn->kn_flags & EV_CLEAR) {
1046 panic("filt_usertouch() - invalid type (%ld)", type);
1052 sys_kqueue(struct thread *td, struct kqueue_args *uap)
1055 return (kern_kqueue(td, 0, NULL));
1059 sys_kqueuex(struct thread *td, struct kqueuex_args *uap)
1063 if ((uap->flags & ~(KQUEUE_CLOEXEC)) != 0)
1066 if ((uap->flags & KQUEUE_CLOEXEC) != 0)
1068 return (kern_kqueue(td, flags, NULL));
1072 kqueue_init(struct kqueue *kq)
1075 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
1076 TAILQ_INIT(&kq->kq_head);
1077 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
1078 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
1082 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
1084 struct filedesc *fdp;
1090 fdp = td->td_proc->p_fd;
1091 cred = td->td_ucred;
1092 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
1095 error = falloc_caps(td, &fp, &fd, flags, fcaps);
1097 chgkqcnt(cred->cr_ruidinfo, -1, 0);
1101 /* An extra reference on `fp' has been held for us by falloc(). */
1102 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
1105 kq->kq_cred = crhold(cred);
1107 FILEDESC_XLOCK(fdp);
1108 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
1109 FILEDESC_XUNLOCK(fdp);
1111 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
1114 td->td_retval[0] = fd;
1118 struct g_kevent_args {
1120 const void *changelist;
1124 const struct timespec *timeout;
1128 sys_kevent(struct thread *td, struct kevent_args *uap)
1130 struct kevent_copyops k_ops = {
1132 .k_copyout = kevent_copyout,
1133 .k_copyin = kevent_copyin,
1134 .kevent_size = sizeof(struct kevent),
1136 struct g_kevent_args gk_args = {
1138 .changelist = uap->changelist,
1139 .nchanges = uap->nchanges,
1140 .eventlist = uap->eventlist,
1141 .nevents = uap->nevents,
1142 .timeout = uap->timeout,
1145 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent"));
1149 kern_kevent_generic(struct thread *td, struct g_kevent_args *uap,
1150 struct kevent_copyops *k_ops, const char *struct_name)
1152 struct timespec ts, *tsp;
1154 struct kevent *eventlist = uap->eventlist;
1158 if (uap->timeout != NULL) {
1159 error = copyin(uap->timeout, &ts, sizeof(ts));
1167 if (KTRPOINT(td, KTR_STRUCT_ARRAY))
1168 ktrstructarray(struct_name, UIO_USERSPACE, uap->changelist,
1169 uap->nchanges, k_ops->kevent_size);
1172 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1176 if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1177 ktrstructarray(struct_name, UIO_USERSPACE, eventlist,
1178 td->td_retval[0], k_ops->kevent_size);
1185 * Copy 'count' items into the destination list pointed to by uap->eventlist.
1188 kevent_copyout(void *arg, struct kevent *kevp, int count)
1190 struct kevent_args *uap;
1193 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1194 uap = (struct kevent_args *)arg;
1196 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1198 uap->eventlist += count;
1203 * Copy 'count' items from the list pointed to by uap->changelist.
1206 kevent_copyin(void *arg, struct kevent *kevp, int count)
1208 struct kevent_args *uap;
1211 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1212 uap = (struct kevent_args *)arg;
1214 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1216 uap->changelist += count;
1220 #ifdef COMPAT_FREEBSD11
1222 kevent11_copyout(void *arg, struct kevent *kevp, int count)
1224 struct freebsd11_kevent_args *uap;
1225 struct freebsd11_kevent kev11;
1228 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1229 uap = (struct freebsd11_kevent_args *)arg;
1231 for (i = 0; i < count; i++) {
1232 kev11.ident = kevp->ident;
1233 kev11.filter = kevp->filter;
1234 kev11.flags = kevp->flags;
1235 kev11.fflags = kevp->fflags;
1236 kev11.data = kevp->data;
1237 kev11.udata = kevp->udata;
1238 error = copyout(&kev11, uap->eventlist, sizeof(kev11));
1248 * Copy 'count' items from the list pointed to by uap->changelist.
1251 kevent11_copyin(void *arg, struct kevent *kevp, int count)
1253 struct freebsd11_kevent_args *uap;
1254 struct freebsd11_kevent kev11;
1257 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1258 uap = (struct freebsd11_kevent_args *)arg;
1260 for (i = 0; i < count; i++) {
1261 error = copyin(uap->changelist, &kev11, sizeof(kev11));
1264 kevp->ident = kev11.ident;
1265 kevp->filter = kev11.filter;
1266 kevp->flags = kev11.flags;
1267 kevp->fflags = kev11.fflags;
1268 kevp->data = (uintptr_t)kev11.data;
1269 kevp->udata = kev11.udata;
1270 bzero(&kevp->ext, sizeof(kevp->ext));
1278 freebsd11_kevent(struct thread *td, struct freebsd11_kevent_args *uap)
1280 struct kevent_copyops k_ops = {
1282 .k_copyout = kevent11_copyout,
1283 .k_copyin = kevent11_copyin,
1284 .kevent_size = sizeof(struct freebsd11_kevent),
1286 struct g_kevent_args gk_args = {
1288 .changelist = uap->changelist,
1289 .nchanges = uap->nchanges,
1290 .eventlist = uap->eventlist,
1291 .nevents = uap->nevents,
1292 .timeout = uap->timeout,
1295 return (kern_kevent_generic(td, &gk_args, &k_ops, "freebsd11_kevent"));
1300 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1301 struct kevent_copyops *k_ops, const struct timespec *timeout)
1303 cap_rights_t rights;
1307 cap_rights_init_zero(&rights);
1309 cap_rights_set_one(&rights, CAP_KQUEUE_CHANGE);
1311 cap_rights_set_one(&rights, CAP_KQUEUE_EVENT);
1312 error = fget(td, fd, &rights, &fp);
1316 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1323 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1324 struct kevent_copyops *k_ops, const struct timespec *timeout)
1326 struct kevent keva[KQ_NEVENTS];
1327 struct kevent *kevp, *changes;
1328 int i, n, nerrors, error;
1334 while (nchanges > 0) {
1335 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1336 error = k_ops->k_copyin(k_ops->arg, keva, n);
1340 for (i = 0; i < n; i++) {
1344 kevp->flags &= ~EV_SYSFLAGS;
1345 error = kqueue_register(kq, kevp, td, M_WAITOK);
1346 if (error || (kevp->flags & EV_RECEIPT)) {
1349 kevp->flags = EV_ERROR;
1351 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1359 td->td_retval[0] = nerrors;
1363 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1367 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1368 struct kevent_copyops *k_ops, const struct timespec *timeout)
1373 error = kqueue_acquire(fp, &kq);
1376 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1377 kqueue_release(kq, 0);
1382 * Performs a kevent() call on a temporarily created kqueue. This can be
1383 * used to perform one-shot polling, similar to poll() and select().
1386 kern_kevent_anonymous(struct thread *td, int nevents,
1387 struct kevent_copyops *k_ops)
1389 struct kqueue kq = {};
1394 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1395 kqueue_drain(&kq, td);
1396 kqueue_destroy(&kq);
1401 kqueue_add_filteropts(int filt, const struct filterops *filtops)
1406 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1408 "trying to add a filterop that is out of range: %d is beyond %d\n",
1409 ~filt, EVFILT_SYSCOUNT);
1412 mtx_lock(&filterops_lock);
1413 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1414 sysfilt_ops[~filt].for_fop != NULL)
1417 sysfilt_ops[~filt].for_fop = filtops;
1418 sysfilt_ops[~filt].for_refcnt = 0;
1420 mtx_unlock(&filterops_lock);
1426 kqueue_del_filteropts(int filt)
1431 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1434 mtx_lock(&filterops_lock);
1435 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1436 sysfilt_ops[~filt].for_fop == NULL)
1438 else if (sysfilt_ops[~filt].for_refcnt != 0)
1441 sysfilt_ops[~filt].for_fop = &null_filtops;
1442 sysfilt_ops[~filt].for_refcnt = 0;
1444 mtx_unlock(&filterops_lock);
1449 static const struct filterops *
1450 kqueue_fo_find(int filt)
1453 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1456 if (sysfilt_ops[~filt].for_nolock)
1457 return sysfilt_ops[~filt].for_fop;
1459 mtx_lock(&filterops_lock);
1460 sysfilt_ops[~filt].for_refcnt++;
1461 if (sysfilt_ops[~filt].for_fop == NULL)
1462 sysfilt_ops[~filt].for_fop = &null_filtops;
1463 mtx_unlock(&filterops_lock);
1465 return sysfilt_ops[~filt].for_fop;
1469 kqueue_fo_release(int filt)
1472 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1475 if (sysfilt_ops[~filt].for_nolock)
1478 mtx_lock(&filterops_lock);
1479 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1480 ("filter object refcount not valid on release"));
1481 sysfilt_ops[~filt].for_refcnt--;
1482 mtx_unlock(&filterops_lock);
1486 * A ref to kq (obtained via kqueue_acquire) must be held.
1489 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td,
1492 const struct filterops *fops;
1494 struct knote *kn, *tkn;
1496 int error, filt, event;
1497 int haskqglobal, filedesc_unlock;
1499 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1507 filedesc_unlock = 0;
1510 fops = kqueue_fo_find(filt);
1514 if (kev->flags & EV_ADD) {
1515 /* Reject an invalid flag pair early */
1516 if (kev->flags & EV_KEEPUDATA) {
1523 * Prevent waiting with locks. Non-sleepable
1524 * allocation failures are handled in the loop, only
1525 * if the spare knote appears to be actually required.
1527 tkn = knote_alloc(mflag);
1534 KASSERT(td != NULL, ("td is NULL"));
1535 if (kev->ident > INT_MAX)
1538 error = fget(td, kev->ident, &cap_event_rights, &fp);
1542 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1543 kev->ident, M_NOWAIT) != 0) {
1547 error = kqueue_expand(kq, fops, kev->ident, mflag);
1553 if (fp->f_type == DTYPE_KQUEUE) {
1555 * If we add some intelligence about what we are doing,
1556 * we should be able to support events on ourselves.
1557 * We need to know when we are doing this to prevent
1558 * getting both the knlist lock and the kq lock since
1559 * they are the same thing.
1561 if (fp->f_data == kq) {
1567 * Pre-lock the filedesc before the global
1568 * lock mutex, see the comment in
1571 FILEDESC_XLOCK(td->td_proc->p_fd);
1572 filedesc_unlock = 1;
1573 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1577 if (kev->ident < kq->kq_knlistsize) {
1578 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1579 if (kev->filter == kn->kn_filter)
1583 if ((kev->flags & EV_ADD) == EV_ADD) {
1584 error = kqueue_expand(kq, fops, kev->ident, mflag);
1592 * If possible, find an existing knote to use for this kevent.
1594 if (kev->filter == EVFILT_PROC &&
1595 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1596 /* This is an internal creation of a process tracking
1597 * note. Don't attempt to coalesce this with an
1601 } else if (kq->kq_knhashmask != 0) {
1604 list = &kq->kq_knhash[
1605 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1606 SLIST_FOREACH(kn, list, kn_link)
1607 if (kev->ident == kn->kn_id &&
1608 kev->filter == kn->kn_filter)
1613 /* knote is in the process of changing, wait for it to stabilize. */
1614 if (kn != NULL && kn_in_flux(kn)) {
1615 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1616 if (filedesc_unlock) {
1617 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1618 filedesc_unlock = 0;
1620 kq->kq_state |= KQ_FLUXWAIT;
1621 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1630 * kn now contains the matching knote, or NULL if no match
1633 if (kev->flags & EV_ADD) {
1645 * apply reference counts to knote structure, and
1646 * do not release it at the end of this routine.
1651 kn->kn_sfflags = kev->fflags;
1652 kn->kn_sdata = kev->data;
1655 kn->kn_kevent = *kev;
1656 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1657 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1658 kn->kn_status = KN_DETACHED;
1659 if ((kev->flags & EV_DISABLE) != 0)
1660 kn->kn_status |= KN_DISABLED;
1663 error = knote_attach(kn, kq);
1670 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1671 knote_drop_detached(kn, td);
1674 knl = kn_list_lock(kn);
1677 /* No matching knote and the EV_ADD flag is not set. */
1684 if (kev->flags & EV_DELETE) {
1691 if (kev->flags & EV_FORCEONESHOT) {
1692 kn->kn_flags |= EV_ONESHOT;
1693 KNOTE_ACTIVATE(kn, 1);
1696 if ((kev->flags & EV_ENABLE) != 0)
1697 kn->kn_status &= ~KN_DISABLED;
1698 else if ((kev->flags & EV_DISABLE) != 0)
1699 kn->kn_status |= KN_DISABLED;
1702 * The user may change some filter values after the initial EV_ADD,
1703 * but doing so will not reset any filter which has already been
1706 kn->kn_status |= KN_SCAN;
1709 knl = kn_list_lock(kn);
1710 if ((kev->flags & EV_KEEPUDATA) == 0)
1711 kn->kn_kevent.udata = kev->udata;
1712 if (!fops->f_isfd && fops->f_touch != NULL) {
1713 fops->f_touch(kn, kev, EVENT_REGISTER);
1715 kn->kn_sfflags = kev->fflags;
1716 kn->kn_sdata = kev->data;
1721 * We can get here with kn->kn_knlist == NULL. This can happen when
1722 * the initial attach event decides that the event is "completed"
1723 * already, e.g., filt_procattach() is called on a zombie process. It
1724 * will call filt_proc() which will remove it from the list, and NULL
1727 * KN_DISABLED will be stable while the knote is in flux, so the
1728 * unlocked read will not race with an update.
1730 if ((kn->kn_status & KN_DISABLED) == 0)
1731 event = kn->kn_fop->f_event(kn, 0);
1737 kn->kn_status |= KN_ACTIVE;
1738 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1741 kn->kn_status &= ~KN_SCAN;
1743 kn_list_unlock(knl);
1747 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1748 if (filedesc_unlock)
1749 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1754 kqueue_fo_release(filt);
1759 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1767 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1771 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1782 kqueue_release(struct kqueue *kq, int locked)
1789 if (kq->kq_refcnt == 1)
1790 wakeup(&kq->kq_refcnt);
1796 ast_kqueue(struct thread *td, int tda __unused)
1798 taskqueue_quiesce(taskqueue_kqueue_ctx);
1802 kqueue_schedtask(struct kqueue *kq)
1805 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1806 ("scheduling kqueue task while draining"));
1808 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1809 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1810 kq->kq_state |= KQ_TASKSCHED;
1811 ast_sched(curthread, TDA_KQUEUE);
1816 * Expand the kq to make sure we have storage for fops/ident pair.
1818 * Return 0 on success (or no work necessary), return errno on failure.
1821 kqueue_expand(struct kqueue *kq, const struct filterops *fops, uintptr_t ident,
1824 struct klist *list, *tmp_knhash, *to_free;
1825 u_long tmp_knhashmask;
1826 int error, fd, size;
1834 if (kq->kq_knlistsize <= fd) {
1835 size = kq->kq_knlistsize;
1838 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1842 if ((kq->kq_state & KQ_CLOSING) != 0) {
1845 } else if (kq->kq_knlistsize > fd) {
1848 if (kq->kq_knlist != NULL) {
1849 bcopy(kq->kq_knlist, list,
1850 kq->kq_knlistsize * sizeof(*list));
1851 to_free = kq->kq_knlist;
1852 kq->kq_knlist = NULL;
1854 bzero((caddr_t)list +
1855 kq->kq_knlistsize * sizeof(*list),
1856 (size - kq->kq_knlistsize) * sizeof(*list));
1857 kq->kq_knlistsize = size;
1858 kq->kq_knlist = list;
1863 if (kq->kq_knhashmask == 0) {
1864 tmp_knhash = hashinit_flags(KN_HASHSIZE, M_KQUEUE,
1865 &tmp_knhashmask, (mflag & M_WAITOK) != 0 ?
1866 HASH_WAITOK : HASH_NOWAIT);
1867 if (tmp_knhash == NULL)
1870 if ((kq->kq_state & KQ_CLOSING) != 0) {
1871 to_free = tmp_knhash;
1873 } else if (kq->kq_knhashmask == 0) {
1874 kq->kq_knhash = tmp_knhash;
1875 kq->kq_knhashmask = tmp_knhashmask;
1877 to_free = tmp_knhash;
1882 free(to_free, M_KQUEUE);
1889 kqueue_task(void *arg, int pending)
1897 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1900 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1902 kq->kq_state &= ~KQ_TASKSCHED;
1903 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1904 wakeup(&kq->kq_state);
1907 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1911 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1912 * We treat KN_MARKER knotes as if they are in flux.
1915 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1916 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1918 struct kevent *kevp;
1919 struct knote *kn, *marker;
1921 sbintime_t asbt, rsbt;
1922 int count, error, haskqglobal, influx, nkev, touch;
1931 if (maxevents < 0) {
1938 if (!timespecvalid_interval(tsp)) {
1942 if (timespecisset(tsp)) {
1943 if (tsp->tv_sec <= INT32_MAX) {
1944 rsbt = tstosbt(*tsp);
1945 if (TIMESEL(&asbt, rsbt))
1946 asbt += tc_tick_sbt;
1947 if (asbt <= SBT_MAX - rsbt)
1951 rsbt >>= tc_precexp;
1958 marker = knote_alloc(M_WAITOK);
1959 marker->kn_status = KN_MARKER;
1964 if (kq->kq_count == 0) {
1966 error = EWOULDBLOCK;
1968 kq->kq_state |= KQ_SLEEP;
1969 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1970 "kqread", asbt, rsbt, C_ABSOLUTE);
1974 /* don't restart after signals... */
1975 if (error == ERESTART)
1977 else if (error == EWOULDBLOCK)
1982 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1986 kn = TAILQ_FIRST(&kq->kq_head);
1988 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1994 kq->kq_state |= KQ_FLUXWAIT;
1995 error = msleep(kq, &kq->kq_lock, PSOCK,
2000 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2001 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
2002 kn->kn_status &= ~KN_QUEUED;
2008 if (count == maxevents)
2012 KASSERT(!kn_in_flux(kn),
2013 ("knote %p is unexpectedly in flux", kn));
2015 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
2016 kn->kn_status &= ~KN_QUEUED;
2021 * We don't need to lock the list since we've
2022 * marked it as in flux.
2027 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
2028 kn->kn_status &= ~KN_QUEUED;
2033 * We don't need to lock the list since we've
2034 * marked the knote as being in flux.
2036 *kevp = kn->kn_kevent;
2041 kn->kn_status |= KN_SCAN;
2044 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
2045 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
2046 knl = kn_list_lock(kn);
2047 if (kn->kn_fop->f_event(kn, 0) == 0) {
2049 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2050 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
2054 kn_list_unlock(knl);
2058 touch = (!kn->kn_fop->f_isfd &&
2059 kn->kn_fop->f_touch != NULL);
2061 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
2063 *kevp = kn->kn_kevent;
2065 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
2066 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
2068 * Manually clear knotes who weren't
2071 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
2075 if (kn->kn_flags & EV_DISPATCH)
2076 kn->kn_status |= KN_DISABLED;
2077 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
2080 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2082 kn->kn_status &= ~KN_SCAN;
2084 kn_list_unlock(knl);
2088 /* we are returning a copy to the user */
2093 if (nkev == KQ_NEVENTS) {
2096 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2104 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
2112 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
2113 td->td_retval[0] = maxevents - count;
2119 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
2120 struct ucred *active_cred, struct thread *td)
2123 * Enabling sigio causes two major problems:
2124 * 1) infinite recursion:
2125 * Synopsys: kevent is being used to track signals and have FIOASYNC
2126 * set. On receipt of a signal this will cause a kqueue to recurse
2127 * into itself over and over. Sending the sigio causes the kqueue
2128 * to become ready, which in turn posts sigio again, forever.
2129 * Solution: this can be solved by setting a flag in the kqueue that
2130 * we have a SIGIO in progress.
2131 * 2) locking problems:
2132 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
2133 * us above the proc and pgrp locks.
2134 * Solution: Post a signal using an async mechanism, being sure to
2135 * record a generation count in the delivery so that we do not deliver
2136 * a signal to the wrong process.
2138 * Note, these two mechanisms are somewhat mutually exclusive!
2147 kq->kq_state |= KQ_ASYNC;
2149 kq->kq_state &= ~KQ_ASYNC;
2154 return (fsetown(*(int *)data, &kq->kq_sigio));
2157 *(int *)data = fgetown(&kq->kq_sigio);
2167 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
2174 if ((error = kqueue_acquire(fp, &kq)))
2178 if (events & (POLLIN | POLLRDNORM)) {
2180 revents |= events & (POLLIN | POLLRDNORM);
2182 selrecord(td, &kq->kq_sel);
2183 if (SEL_WAITING(&kq->kq_sel))
2184 kq->kq_state |= KQ_SEL;
2187 kqueue_release(kq, 1);
2194 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred)
2197 bzero((void *)st, sizeof *st);
2199 * We no longer return kq_count because the unlocked value is useless.
2200 * If you spent all this time getting the count, why not spend your
2201 * syscall better by calling kevent?
2203 * XXX - This is needed for libc_r.
2205 st->st_mode = S_IFIFO;
2210 kqueue_drain(struct kqueue *kq, struct thread *td)
2217 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
2218 ("kqueue already closing"));
2219 kq->kq_state |= KQ_CLOSING;
2220 if (kq->kq_refcnt > 1)
2221 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
2223 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
2225 KASSERT(knlist_empty(&kq->kq_sel.si_note),
2226 ("kqueue's knlist not empty"));
2228 for (i = 0; i < kq->kq_knlistsize; i++) {
2229 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
2230 if (kn_in_flux(kn)) {
2231 kq->kq_state |= KQ_FLUXWAIT;
2232 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
2241 if (kq->kq_knhashmask != 0) {
2242 for (i = 0; i <= kq->kq_knhashmask; i++) {
2243 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
2244 if (kn_in_flux(kn)) {
2245 kq->kq_state |= KQ_FLUXWAIT;
2246 msleep(kq, &kq->kq_lock, PSOCK,
2258 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
2259 kq->kq_state |= KQ_TASKDRAIN;
2260 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2263 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2264 selwakeuppri(&kq->kq_sel, PSOCK);
2265 if (!SEL_WAITING(&kq->kq_sel))
2266 kq->kq_state &= ~KQ_SEL;
2273 kqueue_destroy(struct kqueue *kq)
2276 KASSERT(kq->kq_fdp == NULL,
2277 ("kqueue still attached to a file descriptor"));
2278 seldrain(&kq->kq_sel);
2279 knlist_destroy(&kq->kq_sel.si_note);
2280 mtx_destroy(&kq->kq_lock);
2282 if (kq->kq_knhash != NULL)
2283 free(kq->kq_knhash, M_KQUEUE);
2284 if (kq->kq_knlist != NULL)
2285 free(kq->kq_knlist, M_KQUEUE);
2287 funsetown(&kq->kq_sigio);
2292 kqueue_close(struct file *fp, struct thread *td)
2294 struct kqueue *kq = fp->f_data;
2295 struct filedesc *fdp;
2297 int filedesc_unlock;
2299 if ((error = kqueue_acquire(fp, &kq)))
2301 kqueue_drain(kq, td);
2304 * We could be called due to the knote_drop() doing fdrop(),
2305 * called from kqueue_register(). In this case the global
2306 * lock is owned, and filedesc sx is locked before, to not
2307 * take the sleepable lock after non-sleepable.
2311 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2312 FILEDESC_XLOCK(fdp);
2313 filedesc_unlock = 1;
2315 filedesc_unlock = 0;
2316 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2317 if (filedesc_unlock)
2318 FILEDESC_XUNLOCK(fdp);
2321 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2322 crfree(kq->kq_cred);
2330 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2332 struct kqueue *kq = fp->f_data;
2334 kif->kf_type = KF_TYPE_KQUEUE;
2335 kif->kf_un.kf_kqueue.kf_kqueue_addr = (uintptr_t)kq;
2336 kif->kf_un.kf_kqueue.kf_kqueue_count = kq->kq_count;
2337 kif->kf_un.kf_kqueue.kf_kqueue_state = kq->kq_state;
2342 kqueue_wakeup(struct kqueue *kq)
2346 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2347 kq->kq_state &= ~KQ_SLEEP;
2350 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2351 selwakeuppri(&kq->kq_sel, PSOCK);
2352 if (!SEL_WAITING(&kq->kq_sel))
2353 kq->kq_state &= ~KQ_SEL;
2355 if (!knlist_empty(&kq->kq_sel.si_note))
2356 kqueue_schedtask(kq);
2357 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2358 pgsigio(&kq->kq_sigio, SIGIO, 0);
2363 * Walk down a list of knotes, activating them if their event has triggered.
2365 * There is a possibility to optimize in the case of one kq watching another.
2366 * Instead of scheduling a task to wake it up, you could pass enough state
2367 * down the chain to make up the parent kqueue. Make this code functional
2371 knote(struct knlist *list, long hint, int lockflags)
2374 struct knote *kn, *tkn;
2380 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2382 if ((lockflags & KNF_LISTLOCKED) == 0)
2383 list->kl_lock(list->kl_lockarg);
2386 * If we unlock the list lock (and enter influx), we can
2387 * eliminate the kqueue scheduling, but this will introduce
2388 * four lock/unlock's for each knote to test. Also, marker
2389 * would be needed to keep iteration position, since filters
2390 * or other threads could remove events.
2392 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2395 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2397 * Do not process the influx notes, except for
2398 * the influx coming from the kq unlock in the
2399 * kqueue_scan(). In the later case, we do
2400 * not interfere with the scan, since the code
2401 * fragment in kqueue_scan() locks the knlist,
2402 * and cannot proceed until we finished.
2405 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2408 error = kn->kn_fop->f_event(kn, hint);
2412 KNOTE_ACTIVATE(kn, 1);
2415 if (kn->kn_fop->f_event(kn, hint))
2416 KNOTE_ACTIVATE(kn, 1);
2420 if ((lockflags & KNF_LISTLOCKED) == 0)
2421 list->kl_unlock(list->kl_lockarg);
2425 * add a knote to a knlist
2428 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2431 KNL_ASSERT_LOCK(knl, islocked);
2432 KQ_NOTOWNED(kn->kn_kq);
2433 KASSERT(kn_in_flux(kn), ("knote %p not in flux", kn));
2434 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2435 ("knote %p was not detached", kn));
2437 knl->kl_lock(knl->kl_lockarg);
2438 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2440 knl->kl_unlock(knl->kl_lockarg);
2442 kn->kn_knlist = knl;
2443 kn->kn_status &= ~KN_DETACHED;
2444 KQ_UNLOCK(kn->kn_kq);
2448 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2452 KASSERT(!kqislocked || knlislocked, ("kq locked w/o knl locked"));
2453 KNL_ASSERT_LOCK(knl, knlislocked);
2454 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2455 KASSERT(kqislocked || kn_in_flux(kn), ("knote %p not in flux", kn));
2456 KASSERT((kn->kn_status & KN_DETACHED) == 0,
2457 ("knote %p was already detached", kn));
2459 knl->kl_lock(knl->kl_lockarg);
2460 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2461 kn->kn_knlist = NULL;
2463 kn_list_unlock(knl);
2466 kn->kn_status |= KN_DETACHED;
2468 KQ_UNLOCK(kn->kn_kq);
2472 * remove knote from the specified knlist
2475 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2478 knlist_remove_kq(knl, kn, islocked, 0);
2482 knlist_empty(struct knlist *knl)
2485 KNL_ASSERT_LOCKED(knl);
2486 return (SLIST_EMPTY(&knl->kl_list));
2489 static struct mtx knlist_lock;
2490 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2492 static void knlist_mtx_lock(void *arg);
2493 static void knlist_mtx_unlock(void *arg);
2496 knlist_mtx_lock(void *arg)
2499 mtx_lock((struct mtx *)arg);
2503 knlist_mtx_unlock(void *arg)
2506 mtx_unlock((struct mtx *)arg);
2510 knlist_mtx_assert_lock(void *arg, int what)
2513 if (what == LA_LOCKED)
2514 mtx_assert((struct mtx *)arg, MA_OWNED);
2516 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2520 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2521 void (*kl_unlock)(void *),
2522 void (*kl_assert_lock)(void *, int))
2526 knl->kl_lockarg = &knlist_lock;
2528 knl->kl_lockarg = lock;
2530 if (kl_lock == NULL)
2531 knl->kl_lock = knlist_mtx_lock;
2533 knl->kl_lock = kl_lock;
2534 if (kl_unlock == NULL)
2535 knl->kl_unlock = knlist_mtx_unlock;
2537 knl->kl_unlock = kl_unlock;
2538 if (kl_assert_lock == NULL)
2539 knl->kl_assert_lock = knlist_mtx_assert_lock;
2541 knl->kl_assert_lock = kl_assert_lock;
2543 knl->kl_autodestroy = 0;
2544 SLIST_INIT(&knl->kl_list);
2548 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2551 knlist_init(knl, lock, NULL, NULL, NULL);
2555 knlist_alloc(struct mtx *lock)
2559 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2560 knlist_init_mtx(knl, lock);
2565 knlist_destroy(struct knlist *knl)
2568 KASSERT(KNLIST_EMPTY(knl),
2569 ("destroying knlist %p with knotes on it", knl));
2573 knlist_detach(struct knlist *knl)
2576 KNL_ASSERT_LOCKED(knl);
2577 knl->kl_autodestroy = 1;
2578 if (knlist_empty(knl)) {
2579 knlist_destroy(knl);
2580 free(knl, M_KQUEUE);
2585 * Even if we are locked, we may need to drop the lock to allow any influx
2586 * knotes time to "settle".
2589 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2591 struct knote *kn, *kn2;
2594 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2596 KNL_ASSERT_LOCKED(knl);
2598 KNL_ASSERT_UNLOCKED(knl);
2599 again: /* need to reacquire lock since we have dropped it */
2600 knl->kl_lock(knl->kl_lockarg);
2603 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2606 if (kn_in_flux(kn)) {
2610 knlist_remove_kq(knl, kn, 1, 1);
2614 knote_drop_detached(kn, td);
2616 /* Make sure cleared knotes disappear soon */
2617 kn->kn_flags |= EV_EOF | EV_ONESHOT;
2623 if (!SLIST_EMPTY(&knl->kl_list)) {
2624 /* there are still in flux knotes remaining */
2625 kn = SLIST_FIRST(&knl->kl_list);
2628 KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2629 knl->kl_unlock(knl->kl_lockarg);
2630 kq->kq_state |= KQ_FLUXWAIT;
2631 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2637 KNL_ASSERT_LOCKED(knl);
2639 knl->kl_unlock(knl->kl_lockarg);
2640 KNL_ASSERT_UNLOCKED(knl);
2645 * Remove all knotes referencing a specified fd must be called with FILEDESC
2646 * lock. This prevents a race where a new fd comes along and occupies the
2647 * entry and we attach a knote to the fd.
2650 knote_fdclose(struct thread *td, int fd)
2652 struct filedesc *fdp = td->td_proc->p_fd;
2657 FILEDESC_XLOCK_ASSERT(fdp);
2660 * We shouldn't have to worry about new kevents appearing on fd
2661 * since filedesc is locked.
2663 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2668 while (kq->kq_knlistsize > fd &&
2669 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2670 if (kn_in_flux(kn)) {
2671 /* someone else might be waiting on our knote */
2674 kq->kq_state |= KQ_FLUXWAIT;
2675 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2689 knote_attach(struct knote *kn, struct kqueue *kq)
2693 KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2696 if ((kq->kq_state & KQ_CLOSING) != 0)
2698 if (kn->kn_fop->f_isfd) {
2699 if (kn->kn_id >= kq->kq_knlistsize)
2701 list = &kq->kq_knlist[kn->kn_id];
2703 if (kq->kq_knhash == NULL)
2705 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2707 SLIST_INSERT_HEAD(list, kn, kn_link);
2712 knote_drop(struct knote *kn, struct thread *td)
2715 if ((kn->kn_status & KN_DETACHED) == 0)
2716 kn->kn_fop->f_detach(kn);
2717 knote_drop_detached(kn, td);
2721 knote_drop_detached(struct knote *kn, struct thread *td)
2728 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2729 ("knote %p still attached", kn));
2733 KASSERT(kn->kn_influx == 1,
2734 ("knote_drop called on %p with influx %d", kn, kn->kn_influx));
2736 if (kn->kn_fop->f_isfd)
2737 list = &kq->kq_knlist[kn->kn_id];
2739 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2741 if (!SLIST_EMPTY(list))
2742 SLIST_REMOVE(list, kn, knote, kn_link);
2743 if (kn->kn_status & KN_QUEUED)
2747 if (kn->kn_fop->f_isfd) {
2748 fdrop(kn->kn_fp, td);
2751 kqueue_fo_release(kn->kn_kevent.filter);
2757 knote_enqueue(struct knote *kn)
2759 struct kqueue *kq = kn->kn_kq;
2761 KQ_OWNED(kn->kn_kq);
2762 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2764 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2765 kn->kn_status |= KN_QUEUED;
2771 knote_dequeue(struct knote *kn)
2773 struct kqueue *kq = kn->kn_kq;
2775 KQ_OWNED(kn->kn_kq);
2776 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2778 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2779 kn->kn_status &= ~KN_QUEUED;
2787 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2788 NULL, NULL, UMA_ALIGN_PTR, 0);
2789 ast_register(TDA_KQUEUE, ASTR_ASTF_REQUIRED, 0, ast_kqueue);
2791 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2793 static struct knote *
2794 knote_alloc(int mflag)
2797 return (uma_zalloc(knote_zone, mflag | M_ZERO));
2801 knote_free(struct knote *kn)
2804 uma_zfree(knote_zone, kn);
2808 * Register the kev w/ the kq specified by fd.
2811 kqfd_register(int fd, struct kevent *kev, struct thread *td, int mflag)
2815 cap_rights_t rights;
2818 error = fget(td, fd, cap_rights_init_one(&rights, CAP_KQUEUE_CHANGE),
2822 if ((error = kqueue_acquire(fp, &kq)) != 0)
2825 error = kqueue_register(kq, kev, td, mflag);
2826 kqueue_release(kq, 0);