2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
5 * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
6 * Copyright (c) 2009 Apple, Inc.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include "opt_ktrace.h"
35 #include "opt_kqueue.h"
37 #ifdef COMPAT_FREEBSD11
38 #define _WANT_FREEBSD11_KEVENT
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/capsicum.h>
44 #include <sys/kernel.h>
46 #include <sys/mutex.h>
47 #include <sys/rwlock.h>
49 #include <sys/malloc.h>
50 #include <sys/unistd.h>
52 #include <sys/filedesc.h>
53 #include <sys/filio.h>
54 #include <sys/fcntl.h>
55 #include <sys/kthread.h>
56 #include <sys/selinfo.h>
57 #include <sys/queue.h>
58 #include <sys/event.h>
59 #include <sys/eventvar.h>
61 #include <sys/protosw.h>
62 #include <sys/resourcevar.h>
63 #include <sys/sigio.h>
64 #include <sys/signalvar.h>
65 #include <sys/socket.h>
66 #include <sys/socketvar.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysproto.h>
70 #include <sys/syscallsubr.h>
71 #include <sys/taskqueue.h>
75 #include <sys/ktrace.h>
77 #include <machine/atomic.h>
81 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
84 * This lock is used if multiple kq locks are required. This possibly
85 * should be made into a per proc lock.
87 static struct mtx kq_global;
88 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
89 #define KQ_GLOBAL_LOCK(lck, haslck) do { \
94 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
100 TASKQUEUE_DEFINE_THREAD(kqueue_ctx);
102 static int kevent_copyout(void *arg, struct kevent *kevp, int count);
103 static int kevent_copyin(void *arg, struct kevent *kevp, int count);
104 static int kqueue_register(struct kqueue *kq, struct kevent *kev,
105 struct thread *td, int waitok);
106 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
107 static void kqueue_release(struct kqueue *kq, int locked);
108 static void kqueue_destroy(struct kqueue *kq);
109 static void kqueue_drain(struct kqueue *kq, struct thread *td);
110 static int kqueue_expand(struct kqueue *kq, struct filterops *fops,
111 uintptr_t ident, int waitok);
112 static void kqueue_task(void *arg, int pending);
113 static int kqueue_scan(struct kqueue *kq, int maxevents,
114 struct kevent_copyops *k_ops,
115 const struct timespec *timeout,
116 struct kevent *keva, struct thread *td);
117 static void kqueue_wakeup(struct kqueue *kq);
118 static struct filterops *kqueue_fo_find(int filt);
119 static void kqueue_fo_release(int filt);
120 struct g_kevent_args;
121 static int kern_kevent_generic(struct thread *td,
122 struct g_kevent_args *uap,
123 struct kevent_copyops *k_ops, const char *struct_name);
125 static fo_ioctl_t kqueue_ioctl;
126 static fo_poll_t kqueue_poll;
127 static fo_kqfilter_t kqueue_kqfilter;
128 static fo_stat_t kqueue_stat;
129 static fo_close_t kqueue_close;
130 static fo_fill_kinfo_t kqueue_fill_kinfo;
132 static struct fileops kqueueops = {
133 .fo_read = invfo_rdwr,
134 .fo_write = invfo_rdwr,
135 .fo_truncate = invfo_truncate,
136 .fo_ioctl = kqueue_ioctl,
137 .fo_poll = kqueue_poll,
138 .fo_kqfilter = kqueue_kqfilter,
139 .fo_stat = kqueue_stat,
140 .fo_close = kqueue_close,
141 .fo_chmod = invfo_chmod,
142 .fo_chown = invfo_chown,
143 .fo_sendfile = invfo_sendfile,
144 .fo_fill_kinfo = kqueue_fill_kinfo,
147 static int knote_attach(struct knote *kn, struct kqueue *kq);
148 static void knote_drop(struct knote *kn, struct thread *td);
149 static void knote_drop_detached(struct knote *kn, struct thread *td);
150 static void knote_enqueue(struct knote *kn);
151 static void knote_dequeue(struct knote *kn);
152 static void knote_init(void);
153 static struct knote *knote_alloc(int waitok);
154 static void knote_free(struct knote *kn);
156 static void filt_kqdetach(struct knote *kn);
157 static int filt_kqueue(struct knote *kn, long hint);
158 static int filt_procattach(struct knote *kn);
159 static void filt_procdetach(struct knote *kn);
160 static int filt_proc(struct knote *kn, long hint);
161 static int filt_fileattach(struct knote *kn);
162 static void filt_timerexpire(void *knx);
163 static int filt_timerattach(struct knote *kn);
164 static void filt_timerdetach(struct knote *kn);
165 static void filt_timerstart(struct knote *kn, sbintime_t to);
166 static void filt_timertouch(struct knote *kn, struct kevent *kev,
168 static int filt_timervalidate(struct knote *kn, sbintime_t *to);
169 static int filt_timer(struct knote *kn, long hint);
170 static int filt_userattach(struct knote *kn);
171 static void filt_userdetach(struct knote *kn);
172 static int filt_user(struct knote *kn, long hint);
173 static void filt_usertouch(struct knote *kn, struct kevent *kev,
176 static struct filterops file_filtops = {
178 .f_attach = filt_fileattach,
180 static struct filterops kqread_filtops = {
182 .f_detach = filt_kqdetach,
183 .f_event = filt_kqueue,
185 /* XXX - move to kern_proc.c? */
186 static struct filterops proc_filtops = {
188 .f_attach = filt_procattach,
189 .f_detach = filt_procdetach,
190 .f_event = filt_proc,
192 static struct filterops timer_filtops = {
194 .f_attach = filt_timerattach,
195 .f_detach = filt_timerdetach,
196 .f_event = filt_timer,
197 .f_touch = filt_timertouch,
199 static struct filterops user_filtops = {
200 .f_attach = filt_userattach,
201 .f_detach = filt_userdetach,
202 .f_event = filt_user,
203 .f_touch = filt_usertouch,
206 static uma_zone_t knote_zone;
207 static unsigned int kq_ncallouts = 0;
208 static unsigned int kq_calloutmax = 4 * 1024;
209 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
210 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
212 /* XXX - ensure not influx ? */
213 #define KNOTE_ACTIVATE(kn, islock) do { \
215 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
217 KQ_LOCK((kn)->kn_kq); \
218 (kn)->kn_status |= KN_ACTIVE; \
219 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
220 knote_enqueue((kn)); \
222 KQ_UNLOCK((kn)->kn_kq); \
224 #define KQ_LOCK(kq) do { \
225 mtx_lock(&(kq)->kq_lock); \
227 #define KQ_FLUX_WAKEUP(kq) do { \
228 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
229 (kq)->kq_state &= ~KQ_FLUXWAIT; \
233 #define KQ_UNLOCK_FLUX(kq) do { \
234 KQ_FLUX_WAKEUP(kq); \
235 mtx_unlock(&(kq)->kq_lock); \
237 #define KQ_UNLOCK(kq) do { \
238 mtx_unlock(&(kq)->kq_lock); \
240 #define KQ_OWNED(kq) do { \
241 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
243 #define KQ_NOTOWNED(kq) do { \
244 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
247 static struct knlist *
248 kn_list_lock(struct knote *kn)
254 knl->kl_lock(knl->kl_lockarg);
259 kn_list_unlock(struct knlist *knl)
265 do_free = knl->kl_autodestroy && knlist_empty(knl);
266 knl->kl_unlock(knl->kl_lockarg);
274 kn_in_flux(struct knote *kn)
277 return (kn->kn_influx > 0);
281 kn_enter_flux(struct knote *kn)
285 MPASS(kn->kn_influx < INT_MAX);
290 kn_leave_flux(struct knote *kn)
294 MPASS(kn->kn_influx > 0);
296 return (kn->kn_influx == 0);
299 #define KNL_ASSERT_LOCK(knl, islocked) do { \
301 KNL_ASSERT_LOCKED(knl); \
303 KNL_ASSERT_UNLOCKED(knl); \
306 #define KNL_ASSERT_LOCKED(knl) do { \
307 knl->kl_assert_locked((knl)->kl_lockarg); \
309 #define KNL_ASSERT_UNLOCKED(knl) do { \
310 knl->kl_assert_unlocked((knl)->kl_lockarg); \
312 #else /* !INVARIANTS */
313 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
314 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
315 #endif /* INVARIANTS */
318 #define KN_HASHSIZE 64 /* XXX should be tunable */
321 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
324 filt_nullattach(struct knote *kn)
330 struct filterops null_filtops = {
332 .f_attach = filt_nullattach,
335 /* XXX - make SYSINIT to add these, and move into respective modules. */
336 extern struct filterops sig_filtops;
337 extern struct filterops fs_filtops;
340 * Table for for all system-defined filters.
342 static struct mtx filterops_lock;
343 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
346 struct filterops *for_fop;
349 } sysfilt_ops[EVFILT_SYSCOUNT] = {
350 { &file_filtops, 1 }, /* EVFILT_READ */
351 { &file_filtops, 1 }, /* EVFILT_WRITE */
352 { &null_filtops }, /* EVFILT_AIO */
353 { &file_filtops, 1 }, /* EVFILT_VNODE */
354 { &proc_filtops, 1 }, /* EVFILT_PROC */
355 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
356 { &timer_filtops, 1 }, /* EVFILT_TIMER */
357 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
358 { &fs_filtops, 1 }, /* EVFILT_FS */
359 { &null_filtops }, /* EVFILT_LIO */
360 { &user_filtops, 1 }, /* EVFILT_USER */
361 { &null_filtops }, /* EVFILT_SENDFILE */
362 { &file_filtops, 1 }, /* EVFILT_EMPTY */
366 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
370 filt_fileattach(struct knote *kn)
373 return (fo_kqfilter(kn->kn_fp, kn));
378 kqueue_kqfilter(struct file *fp, struct knote *kn)
380 struct kqueue *kq = kn->kn_fp->f_data;
382 if (kn->kn_filter != EVFILT_READ)
385 kn->kn_status |= KN_KQUEUE;
386 kn->kn_fop = &kqread_filtops;
387 knlist_add(&kq->kq_sel.si_note, kn, 0);
393 filt_kqdetach(struct knote *kn)
395 struct kqueue *kq = kn->kn_fp->f_data;
397 knlist_remove(&kq->kq_sel.si_note, kn, 0);
402 filt_kqueue(struct knote *kn, long hint)
404 struct kqueue *kq = kn->kn_fp->f_data;
406 kn->kn_data = kq->kq_count;
407 return (kn->kn_data > 0);
410 /* XXX - move to kern_proc.c? */
412 filt_procattach(struct knote *kn)
416 bool exiting, immediate;
418 exiting = immediate = false;
419 if (kn->kn_sfflags & NOTE_EXIT)
420 p = pfind_any(kn->kn_id);
422 p = pfind(kn->kn_id);
425 if (p->p_flag & P_WEXIT)
428 if ((error = p_cansee(curthread, p))) {
433 kn->kn_ptr.p_proc = p;
434 kn->kn_flags |= EV_CLEAR; /* automatically set */
437 * Internal flag indicating registration done by kernel for the
438 * purposes of getting a NOTE_CHILD notification.
440 if (kn->kn_flags & EV_FLAG2) {
441 kn->kn_flags &= ~EV_FLAG2;
442 kn->kn_data = kn->kn_sdata; /* ppid */
443 kn->kn_fflags = NOTE_CHILD;
444 kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
445 immediate = true; /* Force immediate activation of child note. */
448 * Internal flag indicating registration done by kernel (for other than
451 if (kn->kn_flags & EV_FLAG1) {
452 kn->kn_flags &= ~EV_FLAG1;
455 knlist_add(p->p_klist, kn, 1);
458 * Immediately activate any child notes or, in the case of a zombie
459 * target process, exit notes. The latter is necessary to handle the
460 * case where the target process, e.g. a child, dies before the kevent
463 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
464 KNOTE_ACTIVATE(kn, 0);
472 * The knote may be attached to a different process, which may exit,
473 * leaving nothing for the knote to be attached to. So when the process
474 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
475 * it will be deleted when read out. However, as part of the knote deletion,
476 * this routine is called, so a check is needed to avoid actually performing
477 * a detach, because the original process does not exist any more.
479 /* XXX - move to kern_proc.c? */
481 filt_procdetach(struct knote *kn)
484 knlist_remove(kn->kn_knlist, kn, 0);
485 kn->kn_ptr.p_proc = NULL;
488 /* XXX - move to kern_proc.c? */
490 filt_proc(struct knote *kn, long hint)
495 p = kn->kn_ptr.p_proc;
496 if (p == NULL) /* already activated, from attach filter */
499 /* Mask off extra data. */
500 event = (u_int)hint & NOTE_PCTRLMASK;
502 /* If the user is interested in this event, record it. */
503 if (kn->kn_sfflags & event)
504 kn->kn_fflags |= event;
506 /* Process is gone, so flag the event as finished. */
507 if (event == NOTE_EXIT) {
508 kn->kn_flags |= EV_EOF | EV_ONESHOT;
509 kn->kn_ptr.p_proc = NULL;
510 if (kn->kn_fflags & NOTE_EXIT)
511 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
512 if (kn->kn_fflags == 0)
513 kn->kn_flags |= EV_DROP;
517 return (kn->kn_fflags != 0);
521 * Called when the process forked. It mostly does the same as the
522 * knote(), activating all knotes registered to be activated when the
523 * process forked. Additionally, for each knote attached to the
524 * parent, check whether user wants to track the new process. If so
525 * attach a new knote to it, and immediately report an event with the
529 knote_fork(struct knlist *list, int pid)
538 list->kl_lock(list->kl_lockarg);
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, 0);
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, 0);
600 kn->kn_fflags |= NOTE_TRACKERR;
601 if (kn->kn_fop->f_event(kn, NOTE_FORK))
602 KNOTE_ACTIVATE(kn, 0);
606 list->kl_lock(list->kl_lockarg);
608 list->kl_unlock(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(intptr_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 | US_TO_SBT(data % 1000000000));
668 return (NS_TO_SBT(data));
675 struct kq_timer_cb_data {
677 sbintime_t next; /* next timer event fires at */
678 sbintime_t to; /* precalculated timer period, 0 for abs */
682 filt_timerexpire(void *knx)
685 struct kq_timer_cb_data *kc;
689 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
691 if ((kn->kn_flags & EV_ONESHOT) != 0)
697 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
698 PCPU_GET(cpuid), C_ABSOLUTE);
702 * data contains amount of time to sleep
705 filt_timervalidate(struct knote *kn, sbintime_t *to)
710 if (kn->kn_sdata < 0)
712 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
715 * The only fflags values supported are the timer unit
716 * (precision) and the absolute time indicator.
718 if ((kn->kn_sfflags & ~(NOTE_TIMER_PRECMASK | NOTE_ABSTIME)) != 0)
721 *to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
722 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
733 filt_timerattach(struct knote *kn)
735 struct kq_timer_cb_data *kc;
737 unsigned int ncallouts;
740 error = filt_timervalidate(kn, &to);
745 ncallouts = kq_ncallouts;
746 if (ncallouts >= kq_calloutmax)
748 } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
750 if ((kn->kn_sfflags & NOTE_ABSTIME) == 0)
751 kn->kn_flags |= EV_CLEAR; /* automatically set */
752 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
753 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
754 callout_init(&kc->c, 1);
755 filt_timerstart(kn, to);
761 filt_timerstart(struct knote *kn, sbintime_t to)
763 struct kq_timer_cb_data *kc;
766 if ((kn->kn_sfflags & NOTE_ABSTIME) != 0) {
770 kc->next = to + sbinuptime();
773 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
774 PCPU_GET(cpuid), C_ABSOLUTE);
778 filt_timerdetach(struct knote *kn)
780 struct kq_timer_cb_data *kc;
781 unsigned int old __unused;
784 callout_drain(&kc->c);
786 old = atomic_fetchadd_int(&kq_ncallouts, -1);
787 KASSERT(old > 0, ("Number of callouts cannot become negative"));
788 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
792 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
794 struct kq_timer_cb_data *kc;
801 /* Handle re-added timers that update data/fflags */
802 if (kev->flags & EV_ADD) {
805 /* Drain any existing callout. */
806 callout_drain(&kc->c);
808 /* Throw away any existing undelivered record
809 * of the timer expiration. This is done under
810 * the presumption that if a process is
811 * re-adding this timer with new parameters,
812 * it is no longer interested in what may have
813 * happened under the old parameters. If it is
814 * interested, it can wait for the expiration,
815 * delete the old timer definition, and then
818 * This has to be done while the kq is locked:
819 * - if enqueued, dequeue
820 * - make it no longer active
821 * - clear the count of expiration events
825 if (kn->kn_status & KN_QUEUED)
828 kn->kn_status &= ~KN_ACTIVE;
832 /* Reschedule timer based on new data/fflags */
833 kn->kn_sfflags = kev->fflags;
834 kn->kn_sdata = kev->data;
835 error = filt_timervalidate(kn, &to);
837 kn->kn_flags |= EV_ERROR;
840 filt_timerstart(kn, to);
845 *kev = kn->kn_kevent;
846 if (kn->kn_flags & EV_CLEAR) {
853 panic("filt_timertouch() - invalid type (%ld)", type);
859 filt_timer(struct knote *kn, long hint)
862 return (kn->kn_data != 0);
866 filt_userattach(struct knote *kn)
870 * EVFILT_USER knotes are not attached to anything in the kernel.
873 if (kn->kn_fflags & NOTE_TRIGGER)
881 filt_userdetach(__unused struct knote *kn)
885 * EVFILT_USER knotes are not attached to anything in the kernel.
890 filt_user(struct knote *kn, __unused long hint)
893 return (kn->kn_hookid);
897 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
903 if (kev->fflags & NOTE_TRIGGER)
906 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
907 kev->fflags &= NOTE_FFLAGSMASK;
913 kn->kn_sfflags &= kev->fflags;
917 kn->kn_sfflags |= kev->fflags;
921 kn->kn_sfflags = kev->fflags;
925 /* XXX Return error? */
928 kn->kn_sdata = kev->data;
929 if (kev->flags & EV_CLEAR) {
937 *kev = kn->kn_kevent;
938 kev->fflags = kn->kn_sfflags;
939 kev->data = kn->kn_sdata;
940 if (kn->kn_flags & EV_CLEAR) {
948 panic("filt_usertouch() - invalid type (%ld)", type);
954 sys_kqueue(struct thread *td, struct kqueue_args *uap)
957 return (kern_kqueue(td, 0, NULL));
961 kqueue_init(struct kqueue *kq)
964 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
965 TAILQ_INIT(&kq->kq_head);
966 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
967 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
971 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
973 struct filedesc *fdp;
979 fdp = td->td_proc->p_fd;
981 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
984 error = falloc_caps(td, &fp, &fd, flags, fcaps);
986 chgkqcnt(cred->cr_ruidinfo, -1, 0);
990 /* An extra reference on `fp' has been held for us by falloc(). */
991 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
994 kq->kq_cred = crhold(cred);
997 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
998 FILEDESC_XUNLOCK(fdp);
1000 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
1003 td->td_retval[0] = fd;
1007 struct g_kevent_args {
1013 const struct timespec *timeout;
1017 sys_kevent(struct thread *td, struct kevent_args *uap)
1019 struct kevent_copyops k_ops = {
1021 .k_copyout = kevent_copyout,
1022 .k_copyin = kevent_copyin,
1023 .kevent_size = sizeof(struct kevent),
1025 struct g_kevent_args gk_args = {
1027 .changelist = uap->changelist,
1028 .nchanges = uap->nchanges,
1029 .eventlist = uap->eventlist,
1030 .nevents = uap->nevents,
1031 .timeout = uap->timeout,
1034 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent"));
1038 kern_kevent_generic(struct thread *td, struct g_kevent_args *uap,
1039 struct kevent_copyops *k_ops, const char *struct_name)
1041 struct timespec ts, *tsp;
1043 struct kevent *eventlist = uap->eventlist;
1047 if (uap->timeout != NULL) {
1048 error = copyin(uap->timeout, &ts, sizeof(ts));
1056 if (KTRPOINT(td, KTR_STRUCT_ARRAY))
1057 ktrstructarray(struct_name, UIO_USERSPACE, uap->changelist,
1058 uap->nchanges, k_ops->kevent_size);
1061 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1065 if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1066 ktrstructarray(struct_name, UIO_USERSPACE, eventlist,
1067 td->td_retval[0], k_ops->kevent_size);
1074 * Copy 'count' items into the destination list pointed to by uap->eventlist.
1077 kevent_copyout(void *arg, struct kevent *kevp, int count)
1079 struct kevent_args *uap;
1082 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1083 uap = (struct kevent_args *)arg;
1085 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1087 uap->eventlist += count;
1092 * Copy 'count' items from the list pointed to by uap->changelist.
1095 kevent_copyin(void *arg, struct kevent *kevp, int count)
1097 struct kevent_args *uap;
1100 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1101 uap = (struct kevent_args *)arg;
1103 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1105 uap->changelist += count;
1109 #ifdef COMPAT_FREEBSD11
1111 kevent11_copyout(void *arg, struct kevent *kevp, int count)
1113 struct freebsd11_kevent_args *uap;
1114 struct kevent_freebsd11 kev11;
1117 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1118 uap = (struct freebsd11_kevent_args *)arg;
1120 for (i = 0; i < count; i++) {
1121 kev11.ident = kevp->ident;
1122 kev11.filter = kevp->filter;
1123 kev11.flags = kevp->flags;
1124 kev11.fflags = kevp->fflags;
1125 kev11.data = kevp->data;
1126 kev11.udata = kevp->udata;
1127 error = copyout(&kev11, uap->eventlist, sizeof(kev11));
1137 * Copy 'count' items from the list pointed to by uap->changelist.
1140 kevent11_copyin(void *arg, struct kevent *kevp, int count)
1142 struct freebsd11_kevent_args *uap;
1143 struct kevent_freebsd11 kev11;
1146 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1147 uap = (struct freebsd11_kevent_args *)arg;
1149 for (i = 0; i < count; i++) {
1150 error = copyin(uap->changelist, &kev11, sizeof(kev11));
1153 kevp->ident = kev11.ident;
1154 kevp->filter = kev11.filter;
1155 kevp->flags = kev11.flags;
1156 kevp->fflags = kev11.fflags;
1157 kevp->data = (uintptr_t)kev11.data;
1158 kevp->udata = kev11.udata;
1159 bzero(&kevp->ext, sizeof(kevp->ext));
1167 freebsd11_kevent(struct thread *td, struct freebsd11_kevent_args *uap)
1169 struct kevent_copyops k_ops = {
1171 .k_copyout = kevent11_copyout,
1172 .k_copyin = kevent11_copyin,
1173 .kevent_size = sizeof(struct kevent_freebsd11),
1175 struct g_kevent_args gk_args = {
1177 .changelist = uap->changelist,
1178 .nchanges = uap->nchanges,
1179 .eventlist = uap->eventlist,
1180 .nevents = uap->nevents,
1181 .timeout = uap->timeout,
1184 return (kern_kevent_generic(td, &gk_args, &k_ops, "kevent_freebsd11"));
1189 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1190 struct kevent_copyops *k_ops, const struct timespec *timeout)
1192 cap_rights_t rights;
1196 cap_rights_init(&rights);
1198 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
1200 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
1201 error = fget(td, fd, &rights, &fp);
1205 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1212 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1213 struct kevent_copyops *k_ops, const struct timespec *timeout)
1215 struct kevent keva[KQ_NEVENTS];
1216 struct kevent *kevp, *changes;
1217 int i, n, nerrors, error;
1220 while (nchanges > 0) {
1221 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1222 error = k_ops->k_copyin(k_ops->arg, keva, n);
1226 for (i = 0; i < n; i++) {
1230 kevp->flags &= ~EV_SYSFLAGS;
1231 error = kqueue_register(kq, kevp, td, 1);
1232 if (error || (kevp->flags & EV_RECEIPT)) {
1235 kevp->flags = EV_ERROR;
1237 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1245 td->td_retval[0] = nerrors;
1249 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1253 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1254 struct kevent_copyops *k_ops, const struct timespec *timeout)
1259 error = kqueue_acquire(fp, &kq);
1262 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1263 kqueue_release(kq, 0);
1268 * Performs a kevent() call on a temporarily created kqueue. This can be
1269 * used to perform one-shot polling, similar to poll() and select().
1272 kern_kevent_anonymous(struct thread *td, int nevents,
1273 struct kevent_copyops *k_ops)
1275 struct kqueue kq = {};
1280 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1281 kqueue_drain(&kq, td);
1282 kqueue_destroy(&kq);
1287 kqueue_add_filteropts(int filt, struct filterops *filtops)
1292 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1294 "trying to add a filterop that is out of range: %d is beyond %d\n",
1295 ~filt, EVFILT_SYSCOUNT);
1298 mtx_lock(&filterops_lock);
1299 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1300 sysfilt_ops[~filt].for_fop != NULL)
1303 sysfilt_ops[~filt].for_fop = filtops;
1304 sysfilt_ops[~filt].for_refcnt = 0;
1306 mtx_unlock(&filterops_lock);
1312 kqueue_del_filteropts(int filt)
1317 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1320 mtx_lock(&filterops_lock);
1321 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1322 sysfilt_ops[~filt].for_fop == NULL)
1324 else if (sysfilt_ops[~filt].for_refcnt != 0)
1327 sysfilt_ops[~filt].for_fop = &null_filtops;
1328 sysfilt_ops[~filt].for_refcnt = 0;
1330 mtx_unlock(&filterops_lock);
1335 static struct filterops *
1336 kqueue_fo_find(int filt)
1339 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1342 if (sysfilt_ops[~filt].for_nolock)
1343 return sysfilt_ops[~filt].for_fop;
1345 mtx_lock(&filterops_lock);
1346 sysfilt_ops[~filt].for_refcnt++;
1347 if (sysfilt_ops[~filt].for_fop == NULL)
1348 sysfilt_ops[~filt].for_fop = &null_filtops;
1349 mtx_unlock(&filterops_lock);
1351 return sysfilt_ops[~filt].for_fop;
1355 kqueue_fo_release(int filt)
1358 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1361 if (sysfilt_ops[~filt].for_nolock)
1364 mtx_lock(&filterops_lock);
1365 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1366 ("filter object refcount not valid on release"));
1367 sysfilt_ops[~filt].for_refcnt--;
1368 mtx_unlock(&filterops_lock);
1372 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1373 * influence if memory allocation should wait. Make sure it is 0 if you
1377 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1379 struct filterops *fops;
1381 struct knote *kn, *tkn;
1383 int error, filt, event;
1384 int haskqglobal, filedesc_unlock;
1386 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1394 filedesc_unlock = 0;
1397 fops = kqueue_fo_find(filt);
1401 if (kev->flags & EV_ADD) {
1403 * Prevent waiting with locks. Non-sleepable
1404 * allocation failures are handled in the loop, only
1405 * if the spare knote appears to be actually required.
1407 tkn = knote_alloc(waitok);
1414 KASSERT(td != NULL, ("td is NULL"));
1415 if (kev->ident > INT_MAX)
1418 error = fget(td, kev->ident, &cap_event_rights, &fp);
1422 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1423 kev->ident, 0) != 0) {
1427 error = kqueue_expand(kq, fops, kev->ident, waitok);
1433 if (fp->f_type == DTYPE_KQUEUE) {
1435 * If we add some intelligence about what we are doing,
1436 * we should be able to support events on ourselves.
1437 * We need to know when we are doing this to prevent
1438 * getting both the knlist lock and the kq lock since
1439 * they are the same thing.
1441 if (fp->f_data == kq) {
1447 * Pre-lock the filedesc before the global
1448 * lock mutex, see the comment in
1451 FILEDESC_XLOCK(td->td_proc->p_fd);
1452 filedesc_unlock = 1;
1453 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1457 if (kev->ident < kq->kq_knlistsize) {
1458 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1459 if (kev->filter == kn->kn_filter)
1463 if ((kev->flags & EV_ADD) == EV_ADD)
1464 kqueue_expand(kq, fops, kev->ident, waitok);
1469 * If possible, find an existing knote to use for this kevent.
1471 if (kev->filter == EVFILT_PROC &&
1472 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1473 /* This is an internal creation of a process tracking
1474 * note. Don't attempt to coalesce this with an
1478 } else if (kq->kq_knhashmask != 0) {
1481 list = &kq->kq_knhash[
1482 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1483 SLIST_FOREACH(kn, list, kn_link)
1484 if (kev->ident == kn->kn_id &&
1485 kev->filter == kn->kn_filter)
1490 /* knote is in the process of changing, wait for it to stabilize. */
1491 if (kn != NULL && kn_in_flux(kn)) {
1492 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1493 if (filedesc_unlock) {
1494 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1495 filedesc_unlock = 0;
1497 kq->kq_state |= KQ_FLUXWAIT;
1498 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1507 * kn now contains the matching knote, or NULL if no match
1510 if (kev->flags & EV_ADD) {
1522 * apply reference counts to knote structure, and
1523 * do not release it at the end of this routine.
1528 kn->kn_sfflags = kev->fflags;
1529 kn->kn_sdata = kev->data;
1532 kn->kn_kevent = *kev;
1533 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1534 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1535 kn->kn_status = KN_DETACHED;
1536 if ((kev->flags & EV_DISABLE) != 0)
1537 kn->kn_status |= KN_DISABLED;
1540 error = knote_attach(kn, kq);
1547 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1548 knote_drop_detached(kn, td);
1551 knl = kn_list_lock(kn);
1554 /* No matching knote and the EV_ADD flag is not set. */
1561 if (kev->flags & EV_DELETE) {
1568 if (kev->flags & EV_FORCEONESHOT) {
1569 kn->kn_flags |= EV_ONESHOT;
1570 KNOTE_ACTIVATE(kn, 1);
1573 if ((kev->flags & EV_ENABLE) != 0)
1574 kn->kn_status &= ~KN_DISABLED;
1575 else if ((kev->flags & EV_DISABLE) != 0)
1576 kn->kn_status |= KN_DISABLED;
1579 * The user may change some filter values after the initial EV_ADD,
1580 * but doing so will not reset any filter which has already been
1583 kn->kn_status |= KN_SCAN;
1586 knl = kn_list_lock(kn);
1587 kn->kn_kevent.udata = kev->udata;
1588 if (!fops->f_isfd && fops->f_touch != NULL) {
1589 fops->f_touch(kn, kev, EVENT_REGISTER);
1591 kn->kn_sfflags = kev->fflags;
1592 kn->kn_sdata = kev->data;
1597 * We can get here with kn->kn_knlist == NULL. This can happen when
1598 * the initial attach event decides that the event is "completed"
1599 * already, e.g., filt_procattach() is called on a zombie process. It
1600 * will call filt_proc() which will remove it from the list, and NULL
1603 * KN_DISABLED will be stable while the knote is in flux, so the
1604 * unlocked read will not race with an update.
1606 if ((kn->kn_status & KN_DISABLED) == 0)
1607 event = kn->kn_fop->f_event(kn, 0);
1613 kn->kn_status |= KN_ACTIVE;
1614 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1617 kn->kn_status &= ~KN_SCAN;
1619 kn_list_unlock(knl);
1623 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1624 if (filedesc_unlock)
1625 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1630 kqueue_fo_release(filt);
1635 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1643 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1647 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1658 kqueue_release(struct kqueue *kq, int locked)
1665 if (kq->kq_refcnt == 1)
1666 wakeup(&kq->kq_refcnt);
1672 kqueue_schedtask(struct kqueue *kq)
1676 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1677 ("scheduling kqueue task while draining"));
1679 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1680 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1681 kq->kq_state |= KQ_TASKSCHED;
1686 * Expand the kq to make sure we have storage for fops/ident pair.
1688 * Return 0 on success (or no work necessary), return errno on failure.
1690 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1691 * If kqueue_register is called from a non-fd context, there usually/should
1695 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1698 struct klist *list, *tmp_knhash, *to_free;
1699 u_long tmp_knhashmask;
1702 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1709 if (kq->kq_knlistsize <= fd) {
1710 size = kq->kq_knlistsize;
1713 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1717 if (kq->kq_knlistsize > fd) {
1721 if (kq->kq_knlist != NULL) {
1722 bcopy(kq->kq_knlist, list,
1723 kq->kq_knlistsize * sizeof(*list));
1724 to_free = kq->kq_knlist;
1725 kq->kq_knlist = NULL;
1727 bzero((caddr_t)list +
1728 kq->kq_knlistsize * sizeof(*list),
1729 (size - kq->kq_knlistsize) * sizeof(*list));
1730 kq->kq_knlistsize = size;
1731 kq->kq_knlist = list;
1736 if (kq->kq_knhashmask == 0) {
1737 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1739 if (tmp_knhash == NULL)
1742 if (kq->kq_knhashmask == 0) {
1743 kq->kq_knhash = tmp_knhash;
1744 kq->kq_knhashmask = tmp_knhashmask;
1746 to_free = tmp_knhash;
1751 free(to_free, M_KQUEUE);
1758 kqueue_task(void *arg, int pending)
1766 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1769 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1771 kq->kq_state &= ~KQ_TASKSCHED;
1772 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1773 wakeup(&kq->kq_state);
1776 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1780 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1781 * We treat KN_MARKER knotes as if they are in flux.
1784 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1785 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1787 struct kevent *kevp;
1788 struct knote *kn, *marker;
1790 sbintime_t asbt, rsbt;
1791 int count, error, haskqglobal, influx, nkev, touch;
1803 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1804 tsp->tv_nsec >= 1000000000) {
1808 if (timespecisset(tsp)) {
1809 if (tsp->tv_sec <= INT32_MAX) {
1810 rsbt = tstosbt(*tsp);
1811 if (TIMESEL(&asbt, rsbt))
1812 asbt += tc_tick_sbt;
1813 if (asbt <= SBT_MAX - rsbt)
1817 rsbt >>= tc_precexp;
1824 marker = knote_alloc(1);
1825 marker->kn_status = KN_MARKER;
1830 if (kq->kq_count == 0) {
1832 error = EWOULDBLOCK;
1834 kq->kq_state |= KQ_SLEEP;
1835 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1836 "kqread", asbt, rsbt, C_ABSOLUTE);
1840 /* don't restart after signals... */
1841 if (error == ERESTART)
1843 else if (error == EWOULDBLOCK)
1848 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1852 kn = TAILQ_FIRST(&kq->kq_head);
1854 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1860 kq->kq_state |= KQ_FLUXWAIT;
1861 error = msleep(kq, &kq->kq_lock, PSOCK,
1866 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1867 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1868 kn->kn_status &= ~KN_QUEUED;
1874 if (count == maxevents)
1878 KASSERT(!kn_in_flux(kn),
1879 ("knote %p is unexpectedly in flux", kn));
1881 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1882 kn->kn_status &= ~KN_QUEUED;
1887 * We don't need to lock the list since we've
1888 * marked it as in flux.
1893 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1894 kn->kn_status &= ~KN_QUEUED;
1899 * We don't need to lock the list since we've
1900 * marked the knote as being in flux.
1902 *kevp = kn->kn_kevent;
1907 kn->kn_status |= KN_SCAN;
1910 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1911 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1912 knl = kn_list_lock(kn);
1913 if (kn->kn_fop->f_event(kn, 0) == 0) {
1915 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1916 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
1920 kn_list_unlock(knl);
1924 touch = (!kn->kn_fop->f_isfd &&
1925 kn->kn_fop->f_touch != NULL);
1927 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1929 *kevp = kn->kn_kevent;
1931 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1932 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1934 * Manually clear knotes who weren't
1937 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1941 if (kn->kn_flags & EV_DISPATCH)
1942 kn->kn_status |= KN_DISABLED;
1943 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1946 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1948 kn->kn_status &= ~KN_SCAN;
1950 kn_list_unlock(knl);
1954 /* we are returning a copy to the user */
1959 if (nkev == KQ_NEVENTS) {
1962 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1970 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1978 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1979 td->td_retval[0] = maxevents - count;
1985 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1986 struct ucred *active_cred, struct thread *td)
1989 * Enabling sigio causes two major problems:
1990 * 1) infinite recursion:
1991 * Synopsys: kevent is being used to track signals and have FIOASYNC
1992 * set. On receipt of a signal this will cause a kqueue to recurse
1993 * into itself over and over. Sending the sigio causes the kqueue
1994 * to become ready, which in turn posts sigio again, forever.
1995 * Solution: this can be solved by setting a flag in the kqueue that
1996 * we have a SIGIO in progress.
1997 * 2) locking problems:
1998 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1999 * us above the proc and pgrp locks.
2000 * Solution: Post a signal using an async mechanism, being sure to
2001 * record a generation count in the delivery so that we do not deliver
2002 * a signal to the wrong process.
2004 * Note, these two mechanisms are somewhat mutually exclusive!
2013 kq->kq_state |= KQ_ASYNC;
2015 kq->kq_state &= ~KQ_ASYNC;
2020 return (fsetown(*(int *)data, &kq->kq_sigio));
2023 *(int *)data = fgetown(&kq->kq_sigio);
2033 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
2040 if ((error = kqueue_acquire(fp, &kq)))
2044 if (events & (POLLIN | POLLRDNORM)) {
2046 revents |= events & (POLLIN | POLLRDNORM);
2048 selrecord(td, &kq->kq_sel);
2049 if (SEL_WAITING(&kq->kq_sel))
2050 kq->kq_state |= KQ_SEL;
2053 kqueue_release(kq, 1);
2060 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
2064 bzero((void *)st, sizeof *st);
2066 * We no longer return kq_count because the unlocked value is useless.
2067 * If you spent all this time getting the count, why not spend your
2068 * syscall better by calling kevent?
2070 * XXX - This is needed for libc_r.
2072 st->st_mode = S_IFIFO;
2077 kqueue_drain(struct kqueue *kq, struct thread *td)
2084 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
2085 ("kqueue already closing"));
2086 kq->kq_state |= KQ_CLOSING;
2087 if (kq->kq_refcnt > 1)
2088 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
2090 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
2092 KASSERT(knlist_empty(&kq->kq_sel.si_note),
2093 ("kqueue's knlist not empty"));
2095 for (i = 0; i < kq->kq_knlistsize; i++) {
2096 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
2097 if (kn_in_flux(kn)) {
2098 kq->kq_state |= KQ_FLUXWAIT;
2099 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
2108 if (kq->kq_knhashmask != 0) {
2109 for (i = 0; i <= kq->kq_knhashmask; i++) {
2110 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
2111 if (kn_in_flux(kn)) {
2112 kq->kq_state |= KQ_FLUXWAIT;
2113 msleep(kq, &kq->kq_lock, PSOCK,
2125 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
2126 kq->kq_state |= KQ_TASKDRAIN;
2127 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2130 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2131 selwakeuppri(&kq->kq_sel, PSOCK);
2132 if (!SEL_WAITING(&kq->kq_sel))
2133 kq->kq_state &= ~KQ_SEL;
2140 kqueue_destroy(struct kqueue *kq)
2143 KASSERT(kq->kq_fdp == NULL,
2144 ("kqueue still attached to a file descriptor"));
2145 seldrain(&kq->kq_sel);
2146 knlist_destroy(&kq->kq_sel.si_note);
2147 mtx_destroy(&kq->kq_lock);
2149 if (kq->kq_knhash != NULL)
2150 free(kq->kq_knhash, M_KQUEUE);
2151 if (kq->kq_knlist != NULL)
2152 free(kq->kq_knlist, M_KQUEUE);
2154 funsetown(&kq->kq_sigio);
2159 kqueue_close(struct file *fp, struct thread *td)
2161 struct kqueue *kq = fp->f_data;
2162 struct filedesc *fdp;
2164 int filedesc_unlock;
2166 if ((error = kqueue_acquire(fp, &kq)))
2168 kqueue_drain(kq, td);
2171 * We could be called due to the knote_drop() doing fdrop(),
2172 * called from kqueue_register(). In this case the global
2173 * lock is owned, and filedesc sx is locked before, to not
2174 * take the sleepable lock after non-sleepable.
2178 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2179 FILEDESC_XLOCK(fdp);
2180 filedesc_unlock = 1;
2182 filedesc_unlock = 0;
2183 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2184 if (filedesc_unlock)
2185 FILEDESC_XUNLOCK(fdp);
2188 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2189 crfree(kq->kq_cred);
2197 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2200 kif->kf_type = KF_TYPE_KQUEUE;
2205 kqueue_wakeup(struct kqueue *kq)
2209 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2210 kq->kq_state &= ~KQ_SLEEP;
2213 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2214 selwakeuppri(&kq->kq_sel, PSOCK);
2215 if (!SEL_WAITING(&kq->kq_sel))
2216 kq->kq_state &= ~KQ_SEL;
2218 if (!knlist_empty(&kq->kq_sel.si_note))
2219 kqueue_schedtask(kq);
2220 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2221 pgsigio(&kq->kq_sigio, SIGIO, 0);
2226 * Walk down a list of knotes, activating them if their event has triggered.
2228 * There is a possibility to optimize in the case of one kq watching another.
2229 * Instead of scheduling a task to wake it up, you could pass enough state
2230 * down the chain to make up the parent kqueue. Make this code functional
2234 knote(struct knlist *list, long hint, int lockflags)
2237 struct knote *kn, *tkn;
2243 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2245 if ((lockflags & KNF_LISTLOCKED) == 0)
2246 list->kl_lock(list->kl_lockarg);
2249 * If we unlock the list lock (and enter influx), we can
2250 * eliminate the kqueue scheduling, but this will introduce
2251 * four lock/unlock's for each knote to test. Also, marker
2252 * would be needed to keep iteration position, since filters
2253 * or other threads could remove events.
2255 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2258 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2260 * Do not process the influx notes, except for
2261 * the influx coming from the kq unlock in the
2262 * kqueue_scan(). In the later case, we do
2263 * not interfere with the scan, since the code
2264 * fragment in kqueue_scan() locks the knlist,
2265 * and cannot proceed until we finished.
2268 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2271 error = kn->kn_fop->f_event(kn, hint);
2275 KNOTE_ACTIVATE(kn, 1);
2278 if (kn->kn_fop->f_event(kn, hint))
2279 KNOTE_ACTIVATE(kn, 1);
2283 if ((lockflags & KNF_LISTLOCKED) == 0)
2284 list->kl_unlock(list->kl_lockarg);
2288 * add a knote to a knlist
2291 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2294 KNL_ASSERT_LOCK(knl, islocked);
2295 KQ_NOTOWNED(kn->kn_kq);
2296 KASSERT(kn_in_flux(kn), ("knote %p not in flux", kn));
2297 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2298 ("knote %p was not detached", kn));
2300 knl->kl_lock(knl->kl_lockarg);
2301 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2303 knl->kl_unlock(knl->kl_lockarg);
2305 kn->kn_knlist = knl;
2306 kn->kn_status &= ~KN_DETACHED;
2307 KQ_UNLOCK(kn->kn_kq);
2311 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2315 KASSERT(!kqislocked || knlislocked, ("kq locked w/o knl locked"));
2316 KNL_ASSERT_LOCK(knl, knlislocked);
2317 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2318 KASSERT(kqislocked || kn_in_flux(kn), ("knote %p not in flux", kn));
2319 KASSERT((kn->kn_status & KN_DETACHED) == 0,
2320 ("knote %p was already detached", kn));
2322 knl->kl_lock(knl->kl_lockarg);
2323 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2324 kn->kn_knlist = NULL;
2326 kn_list_unlock(knl);
2329 kn->kn_status |= KN_DETACHED;
2331 KQ_UNLOCK(kn->kn_kq);
2335 * remove knote from the specified knlist
2338 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2341 knlist_remove_kq(knl, kn, islocked, 0);
2345 knlist_empty(struct knlist *knl)
2348 KNL_ASSERT_LOCKED(knl);
2349 return (SLIST_EMPTY(&knl->kl_list));
2352 static struct mtx knlist_lock;
2353 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2355 static void knlist_mtx_lock(void *arg);
2356 static void knlist_mtx_unlock(void *arg);
2359 knlist_mtx_lock(void *arg)
2362 mtx_lock((struct mtx *)arg);
2366 knlist_mtx_unlock(void *arg)
2369 mtx_unlock((struct mtx *)arg);
2373 knlist_mtx_assert_locked(void *arg)
2376 mtx_assert((struct mtx *)arg, MA_OWNED);
2380 knlist_mtx_assert_unlocked(void *arg)
2383 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2387 knlist_rw_rlock(void *arg)
2390 rw_rlock((struct rwlock *)arg);
2394 knlist_rw_runlock(void *arg)
2397 rw_runlock((struct rwlock *)arg);
2401 knlist_rw_assert_locked(void *arg)
2404 rw_assert((struct rwlock *)arg, RA_LOCKED);
2408 knlist_rw_assert_unlocked(void *arg)
2411 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2415 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2416 void (*kl_unlock)(void *),
2417 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2421 knl->kl_lockarg = &knlist_lock;
2423 knl->kl_lockarg = lock;
2425 if (kl_lock == NULL)
2426 knl->kl_lock = knlist_mtx_lock;
2428 knl->kl_lock = kl_lock;
2429 if (kl_unlock == NULL)
2430 knl->kl_unlock = knlist_mtx_unlock;
2432 knl->kl_unlock = kl_unlock;
2433 if (kl_assert_locked == NULL)
2434 knl->kl_assert_locked = knlist_mtx_assert_locked;
2436 knl->kl_assert_locked = kl_assert_locked;
2437 if (kl_assert_unlocked == NULL)
2438 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2440 knl->kl_assert_unlocked = kl_assert_unlocked;
2442 knl->kl_autodestroy = 0;
2443 SLIST_INIT(&knl->kl_list);
2447 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2450 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2454 knlist_alloc(struct mtx *lock)
2458 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2459 knlist_init_mtx(knl, lock);
2464 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2467 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2468 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2472 knlist_destroy(struct knlist *knl)
2475 KASSERT(KNLIST_EMPTY(knl),
2476 ("destroying knlist %p with knotes on it", knl));
2480 knlist_detach(struct knlist *knl)
2483 KNL_ASSERT_LOCKED(knl);
2484 knl->kl_autodestroy = 1;
2485 if (knlist_empty(knl)) {
2486 knlist_destroy(knl);
2487 free(knl, M_KQUEUE);
2492 * Even if we are locked, we may need to drop the lock to allow any influx
2493 * knotes time to "settle".
2496 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2498 struct knote *kn, *kn2;
2501 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2503 KNL_ASSERT_LOCKED(knl);
2505 KNL_ASSERT_UNLOCKED(knl);
2506 again: /* need to reacquire lock since we have dropped it */
2507 knl->kl_lock(knl->kl_lockarg);
2510 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2513 if (kn_in_flux(kn)) {
2517 knlist_remove_kq(knl, kn, 1, 1);
2521 knote_drop_detached(kn, td);
2523 /* Make sure cleared knotes disappear soon */
2524 kn->kn_flags |= EV_EOF | EV_ONESHOT;
2530 if (!SLIST_EMPTY(&knl->kl_list)) {
2531 /* there are still in flux knotes remaining */
2532 kn = SLIST_FIRST(&knl->kl_list);
2535 KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2536 knl->kl_unlock(knl->kl_lockarg);
2537 kq->kq_state |= KQ_FLUXWAIT;
2538 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2544 KNL_ASSERT_LOCKED(knl);
2546 knl->kl_unlock(knl->kl_lockarg);
2547 KNL_ASSERT_UNLOCKED(knl);
2552 * Remove all knotes referencing a specified fd must be called with FILEDESC
2553 * lock. This prevents a race where a new fd comes along and occupies the
2554 * entry and we attach a knote to the fd.
2557 knote_fdclose(struct thread *td, int fd)
2559 struct filedesc *fdp = td->td_proc->p_fd;
2564 FILEDESC_XLOCK_ASSERT(fdp);
2567 * We shouldn't have to worry about new kevents appearing on fd
2568 * since filedesc is locked.
2570 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2575 while (kq->kq_knlistsize > fd &&
2576 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2577 if (kn_in_flux(kn)) {
2578 /* someone else might be waiting on our knote */
2581 kq->kq_state |= KQ_FLUXWAIT;
2582 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2596 knote_attach(struct knote *kn, struct kqueue *kq)
2600 KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2603 if (kn->kn_fop->f_isfd) {
2604 if (kn->kn_id >= kq->kq_knlistsize)
2606 list = &kq->kq_knlist[kn->kn_id];
2608 if (kq->kq_knhash == NULL)
2610 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2612 SLIST_INSERT_HEAD(list, kn, kn_link);
2617 knote_drop(struct knote *kn, struct thread *td)
2620 if ((kn->kn_status & KN_DETACHED) == 0)
2621 kn->kn_fop->f_detach(kn);
2622 knote_drop_detached(kn, td);
2626 knote_drop_detached(struct knote *kn, struct thread *td)
2633 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2634 ("knote %p still attached", kn));
2638 KASSERT(kn->kn_influx == 1,
2639 ("knote_drop called on %p with influx %d", kn, kn->kn_influx));
2641 if (kn->kn_fop->f_isfd)
2642 list = &kq->kq_knlist[kn->kn_id];
2644 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2646 if (!SLIST_EMPTY(list))
2647 SLIST_REMOVE(list, kn, knote, kn_link);
2648 if (kn->kn_status & KN_QUEUED)
2652 if (kn->kn_fop->f_isfd) {
2653 fdrop(kn->kn_fp, td);
2656 kqueue_fo_release(kn->kn_kevent.filter);
2662 knote_enqueue(struct knote *kn)
2664 struct kqueue *kq = kn->kn_kq;
2666 KQ_OWNED(kn->kn_kq);
2667 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2669 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2670 kn->kn_status |= KN_QUEUED;
2676 knote_dequeue(struct knote *kn)
2678 struct kqueue *kq = kn->kn_kq;
2680 KQ_OWNED(kn->kn_kq);
2681 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2683 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2684 kn->kn_status &= ~KN_QUEUED;
2692 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2693 NULL, NULL, UMA_ALIGN_PTR, 0);
2695 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2697 static struct knote *
2698 knote_alloc(int waitok)
2701 return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2706 knote_free(struct knote *kn)
2709 uma_zfree(knote_zone, kn);
2713 * Register the kev w/ the kq specified by fd.
2716 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2720 cap_rights_t rights;
2723 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2726 if ((error = kqueue_acquire(fp, &kq)) != 0)
2729 error = kqueue_register(kq, kev, td, waitok);
2730 kqueue_release(kq, 0);