2 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
3 * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
4 * Copyright (c) 2009 Apple, Inc.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include "opt_ktrace.h"
33 #include "opt_kqueue.h"
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/capsicum.h>
38 #include <sys/kernel.h>
40 #include <sys/mutex.h>
41 #include <sys/rwlock.h>
43 #include <sys/malloc.h>
44 #include <sys/unistd.h>
46 #include <sys/filedesc.h>
47 #include <sys/filio.h>
48 #include <sys/fcntl.h>
49 #include <sys/kthread.h>
50 #include <sys/selinfo.h>
51 #include <sys/stdatomic.h>
52 #include <sys/queue.h>
53 #include <sys/event.h>
54 #include <sys/eventvar.h>
56 #include <sys/protosw.h>
57 #include <sys/resourcevar.h>
58 #include <sys/sigio.h>
59 #include <sys/signalvar.h>
60 #include <sys/socket.h>
61 #include <sys/socketvar.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysproto.h>
65 #include <sys/syscallsubr.h>
66 #include <sys/taskqueue.h>
70 #include <sys/ktrace.h>
75 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
78 * This lock is used if multiple kq locks are required. This possibly
79 * should be made into a per proc lock.
81 static struct mtx kq_global;
82 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
83 #define KQ_GLOBAL_LOCK(lck, haslck) do { \
88 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
94 TASKQUEUE_DEFINE_THREAD(kqueue_ctx);
96 static int kevent_copyout(void *arg, struct kevent *kevp, int count);
97 static int kevent_copyin(void *arg, struct kevent *kevp, int count);
98 static int kqueue_register(struct kqueue *kq, struct kevent *kev,
99 struct thread *td, int waitok);
100 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
101 static void kqueue_release(struct kqueue *kq, int locked);
102 static void kqueue_destroy(struct kqueue *kq);
103 static void kqueue_drain(struct kqueue *kq, struct thread *td);
104 static int kqueue_expand(struct kqueue *kq, struct filterops *fops,
105 uintptr_t ident, int waitok);
106 static void kqueue_task(void *arg, int pending);
107 static int kqueue_scan(struct kqueue *kq, int maxevents,
108 struct kevent_copyops *k_ops,
109 const struct timespec *timeout,
110 struct kevent *keva, struct thread *td);
111 static void kqueue_wakeup(struct kqueue *kq);
112 static struct filterops *kqueue_fo_find(int filt);
113 static void kqueue_fo_release(int filt);
115 static fo_ioctl_t kqueue_ioctl;
116 static fo_poll_t kqueue_poll;
117 static fo_kqfilter_t kqueue_kqfilter;
118 static fo_stat_t kqueue_stat;
119 static fo_close_t kqueue_close;
120 static fo_fill_kinfo_t kqueue_fill_kinfo;
122 static struct fileops kqueueops = {
123 .fo_read = invfo_rdwr,
124 .fo_write = invfo_rdwr,
125 .fo_truncate = invfo_truncate,
126 .fo_ioctl = kqueue_ioctl,
127 .fo_poll = kqueue_poll,
128 .fo_kqfilter = kqueue_kqfilter,
129 .fo_stat = kqueue_stat,
130 .fo_close = kqueue_close,
131 .fo_chmod = invfo_chmod,
132 .fo_chown = invfo_chown,
133 .fo_sendfile = invfo_sendfile,
134 .fo_fill_kinfo = kqueue_fill_kinfo,
137 static int knote_attach(struct knote *kn, struct kqueue *kq);
138 static void knote_drop(struct knote *kn, struct thread *td);
139 static void knote_enqueue(struct knote *kn);
140 static void knote_dequeue(struct knote *kn);
141 static void knote_init(void);
142 static struct knote *knote_alloc(int waitok);
143 static void knote_free(struct knote *kn);
145 static void filt_kqdetach(struct knote *kn);
146 static int filt_kqueue(struct knote *kn, long hint);
147 static int filt_procattach(struct knote *kn);
148 static void filt_procdetach(struct knote *kn);
149 static int filt_proc(struct knote *kn, long hint);
150 static int filt_fileattach(struct knote *kn);
151 static void filt_timerexpire(void *knx);
152 static int filt_timerattach(struct knote *kn);
153 static void filt_timerdetach(struct knote *kn);
154 static int filt_timer(struct knote *kn, long hint);
155 static int filt_userattach(struct knote *kn);
156 static void filt_userdetach(struct knote *kn);
157 static int filt_user(struct knote *kn, long hint);
158 static void filt_usertouch(struct knote *kn, struct kevent *kev,
161 static struct filterops file_filtops = {
163 .f_attach = filt_fileattach,
165 static struct filterops kqread_filtops = {
167 .f_detach = filt_kqdetach,
168 .f_event = filt_kqueue,
170 /* XXX - move to kern_proc.c? */
171 static struct filterops proc_filtops = {
173 .f_attach = filt_procattach,
174 .f_detach = filt_procdetach,
175 .f_event = filt_proc,
177 static struct filterops timer_filtops = {
179 .f_attach = filt_timerattach,
180 .f_detach = filt_timerdetach,
181 .f_event = filt_timer,
183 static struct filterops user_filtops = {
184 .f_attach = filt_userattach,
185 .f_detach = filt_userdetach,
186 .f_event = filt_user,
187 .f_touch = filt_usertouch,
190 static uma_zone_t knote_zone;
191 static atomic_uint kq_ncallouts = ATOMIC_VAR_INIT(0);
192 static unsigned int kq_calloutmax = 4 * 1024;
193 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
194 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
196 /* XXX - ensure not KN_INFLUX?? */
197 #define KNOTE_ACTIVATE(kn, islock) do { \
199 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
201 KQ_LOCK((kn)->kn_kq); \
202 (kn)->kn_status |= KN_ACTIVE; \
203 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
204 knote_enqueue((kn)); \
206 KQ_UNLOCK((kn)->kn_kq); \
208 #define KQ_LOCK(kq) do { \
209 mtx_lock(&(kq)->kq_lock); \
211 #define KQ_FLUX_WAKEUP(kq) do { \
212 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
213 (kq)->kq_state &= ~KQ_FLUXWAIT; \
217 #define KQ_UNLOCK_FLUX(kq) do { \
218 KQ_FLUX_WAKEUP(kq); \
219 mtx_unlock(&(kq)->kq_lock); \
221 #define KQ_UNLOCK(kq) do { \
222 mtx_unlock(&(kq)->kq_lock); \
224 #define KQ_OWNED(kq) do { \
225 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
227 #define KQ_NOTOWNED(kq) do { \
228 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
230 #define KN_LIST_LOCK(kn) do { \
231 if (kn->kn_knlist != NULL) \
232 kn->kn_knlist->kl_lock(kn->kn_knlist->kl_lockarg); \
234 #define KN_LIST_UNLOCK(kn) do { \
235 if (kn->kn_knlist != NULL) \
236 kn->kn_knlist->kl_unlock(kn->kn_knlist->kl_lockarg); \
238 #define KNL_ASSERT_LOCK(knl, islocked) do { \
240 KNL_ASSERT_LOCKED(knl); \
242 KNL_ASSERT_UNLOCKED(knl); \
245 #define KNL_ASSERT_LOCKED(knl) do { \
246 knl->kl_assert_locked((knl)->kl_lockarg); \
248 #define KNL_ASSERT_UNLOCKED(knl) do { \
249 knl->kl_assert_unlocked((knl)->kl_lockarg); \
251 #else /* !INVARIANTS */
252 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
253 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
254 #endif /* INVARIANTS */
257 #define KN_HASHSIZE 64 /* XXX should be tunable */
260 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
263 filt_nullattach(struct knote *kn)
269 struct filterops null_filtops = {
271 .f_attach = filt_nullattach,
274 /* XXX - make SYSINIT to add these, and move into respective modules. */
275 extern struct filterops sig_filtops;
276 extern struct filterops fs_filtops;
279 * Table for for all system-defined filters.
281 static struct mtx filterops_lock;
282 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
285 struct filterops *for_fop;
288 } sysfilt_ops[EVFILT_SYSCOUNT] = {
289 { &file_filtops, 1 }, /* EVFILT_READ */
290 { &file_filtops, 1 }, /* EVFILT_WRITE */
291 { &null_filtops }, /* EVFILT_AIO */
292 { &file_filtops, 1 }, /* EVFILT_VNODE */
293 { &proc_filtops, 1 }, /* EVFILT_PROC */
294 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
295 { &timer_filtops, 1 }, /* EVFILT_TIMER */
296 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
297 { &fs_filtops, 1 }, /* EVFILT_FS */
298 { &null_filtops }, /* EVFILT_LIO */
299 { &user_filtops, 1 }, /* EVFILT_USER */
300 { &null_filtops }, /* EVFILT_SENDFILE */
304 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
308 filt_fileattach(struct knote *kn)
311 return (fo_kqfilter(kn->kn_fp, kn));
316 kqueue_kqfilter(struct file *fp, struct knote *kn)
318 struct kqueue *kq = kn->kn_fp->f_data;
320 if (kn->kn_filter != EVFILT_READ)
323 kn->kn_status |= KN_KQUEUE;
324 kn->kn_fop = &kqread_filtops;
325 knlist_add(&kq->kq_sel.si_note, kn, 0);
331 filt_kqdetach(struct knote *kn)
333 struct kqueue *kq = kn->kn_fp->f_data;
335 knlist_remove(&kq->kq_sel.si_note, kn, 0);
340 filt_kqueue(struct knote *kn, long hint)
342 struct kqueue *kq = kn->kn_fp->f_data;
344 kn->kn_data = kq->kq_count;
345 return (kn->kn_data > 0);
348 /* XXX - move to kern_proc.c? */
350 filt_procattach(struct knote *kn)
357 p = pfind(kn->kn_id);
358 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
359 p = zpfind(kn->kn_id);
361 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
367 if ((error = p_cansee(curthread, p))) {
372 kn->kn_ptr.p_proc = p;
373 kn->kn_flags |= EV_CLEAR; /* automatically set */
376 * Internal flag indicating registration done by kernel for the
377 * purposes of getting a NOTE_CHILD notification.
379 if (kn->kn_flags & EV_FLAG2) {
380 kn->kn_flags &= ~EV_FLAG2;
381 kn->kn_data = kn->kn_sdata; /* ppid */
382 kn->kn_fflags = NOTE_CHILD;
383 kn->kn_sfflags &= ~NOTE_EXIT;
384 immediate = 1; /* Force immediate activation of child note. */
387 * Internal flag indicating registration done by kernel (for other than
390 if (kn->kn_flags & EV_FLAG1) {
391 kn->kn_flags &= ~EV_FLAG1;
395 knlist_add(&p->p_klist, kn, 1);
398 * Immediately activate any child notes or, in the case of a zombie
399 * target process, exit notes. The latter is necessary to handle the
400 * case where the target process, e.g. a child, dies before the kevent
403 if (immediate && filt_proc(kn, NOTE_EXIT))
404 KNOTE_ACTIVATE(kn, 0);
412 * The knote may be attached to a different process, which may exit,
413 * leaving nothing for the knote to be attached to. So when the process
414 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
415 * it will be deleted when read out. However, as part of the knote deletion,
416 * this routine is called, so a check is needed to avoid actually performing
417 * a detach, because the original process does not exist any more.
419 /* XXX - move to kern_proc.c? */
421 filt_procdetach(struct knote *kn)
425 p = kn->kn_ptr.p_proc;
426 knlist_remove(&p->p_klist, kn, 0);
427 kn->kn_ptr.p_proc = NULL;
430 /* XXX - move to kern_proc.c? */
432 filt_proc(struct knote *kn, long hint)
437 p = kn->kn_ptr.p_proc;
438 /* Mask off extra data. */
439 event = (u_int)hint & NOTE_PCTRLMASK;
441 /* If the user is interested in this event, record it. */
442 if (kn->kn_sfflags & event)
443 kn->kn_fflags |= event;
445 /* Process is gone, so flag the event as finished. */
446 if (event == NOTE_EXIT) {
447 if (!(kn->kn_status & KN_DETACHED))
448 knlist_remove_inevent(&p->p_klist, kn);
449 kn->kn_flags |= EV_EOF | EV_ONESHOT;
450 kn->kn_ptr.p_proc = NULL;
451 if (kn->kn_fflags & NOTE_EXIT)
452 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
453 if (kn->kn_fflags == 0)
454 kn->kn_flags |= EV_DROP;
458 return (kn->kn_fflags != 0);
462 * Called when the process forked. It mostly does the same as the
463 * knote(), activating all knotes registered to be activated when the
464 * process forked. Additionally, for each knote attached to the
465 * parent, check whether user wants to track the new process. If so
466 * attach a new knote to it, and immediately report an event with the
470 knote_fork(struct knlist *list, int pid)
479 list->kl_lock(list->kl_lockarg);
481 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
483 * XXX - Why do we skip the kn if it is _INFLUX? Does this
484 * mean we will not properly wake up some notes?
486 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX)
490 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
496 * The same as knote(), activate the event.
498 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
499 kn->kn_status |= KN_HASKQLOCK;
500 if (kn->kn_fop->f_event(kn, NOTE_FORK))
501 KNOTE_ACTIVATE(kn, 1);
502 kn->kn_status &= ~KN_HASKQLOCK;
508 * The NOTE_TRACK case. In addition to the activation
509 * of the event, we need to register new events to
510 * track the child. Drop the locks in preparation for
511 * the call to kqueue_register().
513 kn->kn_status |= KN_INFLUX;
515 list->kl_unlock(list->kl_lockarg);
518 * Activate existing knote and register tracking knotes with
521 * First register a knote to get just the child notice. This
522 * must be a separate note from a potential NOTE_EXIT
523 * notification since both NOTE_CHILD and NOTE_EXIT are defined
524 * to use the data field (in conflicting ways).
527 kev.filter = kn->kn_filter;
528 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT | EV_FLAG2;
529 kev.fflags = kn->kn_sfflags;
530 kev.data = kn->kn_id; /* parent */
531 kev.udata = kn->kn_kevent.udata;/* preserve udata */
532 error = kqueue_register(kq, &kev, NULL, 0);
534 kn->kn_fflags |= NOTE_TRACKERR;
537 * Then register another knote to track other potential events
538 * from the new process.
541 kev.filter = kn->kn_filter;
542 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
543 kev.fflags = kn->kn_sfflags;
544 kev.data = kn->kn_id; /* parent */
545 kev.udata = kn->kn_kevent.udata;/* preserve udata */
546 error = kqueue_register(kq, &kev, NULL, 0);
548 kn->kn_fflags |= NOTE_TRACKERR;
549 if (kn->kn_fop->f_event(kn, NOTE_FORK))
550 KNOTE_ACTIVATE(kn, 0);
552 kn->kn_status &= ~KN_INFLUX;
554 list->kl_lock(list->kl_lockarg);
556 list->kl_unlock(list->kl_lockarg);
560 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
561 * interval timer support code.
564 #define NOTE_TIMER_PRECMASK (NOTE_SECONDS|NOTE_MSECONDS|NOTE_USECONDS| \
568 timer2sbintime(intptr_t data, int flags)
572 * Macros for converting to the fractional second portion of an
573 * sbintime_t using 64bit multiplication to improve precision.
575 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
576 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
577 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
578 switch (flags & NOTE_TIMER_PRECMASK) {
581 if (data > (SBT_MAX / SBT_1S))
584 return ((sbintime_t)data << 32);
585 case NOTE_MSECONDS: /* FALLTHROUGH */
588 int64_t secs = data / 1000;
590 if (secs > (SBT_MAX / SBT_1S))
593 return (secs << 32 | MS_TO_SBT(data % 1000));
595 return MS_TO_SBT(data);
597 if (data >= 1000000) {
598 int64_t secs = data / 1000000;
600 if (secs > (SBT_MAX / SBT_1S))
603 return (secs << 32 | US_TO_SBT(data % 1000000));
605 return US_TO_SBT(data);
607 if (data >= 1000000000) {
608 int64_t secs = data / 1000000000;
610 if (secs > (SBT_MAX / SBT_1S))
613 return (secs << 32 | US_TO_SBT(data % 1000000000));
615 return NS_TO_SBT(data);
623 filt_timerexpire(void *knx)
625 struct callout *calloutp;
630 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
632 if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
633 calloutp = (struct callout *)kn->kn_hook;
634 *kn->kn_ptr.p_nexttime += timer2sbintime(kn->kn_sdata,
636 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
637 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
642 * data contains amount of time to sleep
645 filt_timerattach(struct knote *kn)
647 struct callout *calloutp;
649 unsigned int ncallouts;
651 if ((intptr_t)kn->kn_sdata < 0)
653 if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
655 /* Only precision unit are supported in flags so far */
656 if (kn->kn_sfflags & ~NOTE_TIMER_PRECMASK)
659 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
663 ncallouts = atomic_load_explicit(&kq_ncallouts, memory_order_relaxed);
665 if (ncallouts >= kq_calloutmax)
667 } while (!atomic_compare_exchange_weak_explicit(&kq_ncallouts,
668 &ncallouts, ncallouts + 1, memory_order_relaxed,
669 memory_order_relaxed));
671 kn->kn_flags |= EV_CLEAR; /* automatically set */
672 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
673 kn->kn_ptr.p_nexttime = malloc(sizeof(sbintime_t), M_KQUEUE, M_WAITOK);
674 calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
675 callout_init(calloutp, 1);
676 kn->kn_hook = calloutp;
677 *kn->kn_ptr.p_nexttime = to + sbinuptime();
678 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
679 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
685 filt_timerdetach(struct knote *kn)
687 struct callout *calloutp;
690 calloutp = (struct callout *)kn->kn_hook;
691 callout_drain(calloutp);
692 free(calloutp, M_KQUEUE);
693 free(kn->kn_ptr.p_nexttime, M_KQUEUE);
694 old = atomic_fetch_sub_explicit(&kq_ncallouts, 1, memory_order_relaxed);
695 KASSERT(old > 0, ("Number of callouts cannot become negative"));
696 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
700 filt_timer(struct knote *kn, long hint)
703 return (kn->kn_data != 0);
707 filt_userattach(struct knote *kn)
711 * EVFILT_USER knotes are not attached to anything in the kernel.
714 if (kn->kn_fflags & NOTE_TRIGGER)
722 filt_userdetach(__unused struct knote *kn)
726 * EVFILT_USER knotes are not attached to anything in the kernel.
731 filt_user(struct knote *kn, __unused long hint)
734 return (kn->kn_hookid);
738 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
744 if (kev->fflags & NOTE_TRIGGER)
747 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
748 kev->fflags &= NOTE_FFLAGSMASK;
754 kn->kn_sfflags &= kev->fflags;
758 kn->kn_sfflags |= kev->fflags;
762 kn->kn_sfflags = kev->fflags;
766 /* XXX Return error? */
769 kn->kn_sdata = kev->data;
770 if (kev->flags & EV_CLEAR) {
778 *kev = kn->kn_kevent;
779 kev->fflags = kn->kn_sfflags;
780 kev->data = kn->kn_sdata;
781 if (kn->kn_flags & EV_CLEAR) {
789 panic("filt_usertouch() - invalid type (%ld)", type);
795 sys_kqueue(struct thread *td, struct kqueue_args *uap)
798 return (kern_kqueue(td, 0, NULL));
802 kqueue_init(struct kqueue *kq)
805 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
806 TAILQ_INIT(&kq->kq_head);
807 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
808 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
812 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
814 struct filedesc *fdp;
820 fdp = td->td_proc->p_fd;
822 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
825 error = falloc_caps(td, &fp, &fd, flags, fcaps);
827 chgkqcnt(cred->cr_ruidinfo, -1, 0);
831 /* An extra reference on `fp' has been held for us by falloc(). */
832 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
835 kq->kq_cred = crhold(cred);
838 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
839 FILEDESC_XUNLOCK(fdp);
841 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
844 td->td_retval[0] = fd;
848 #ifndef _SYS_SYSPROTO_H_
851 const struct kevent *changelist;
853 struct kevent *eventlist;
855 const struct timespec *timeout;
859 sys_kevent(struct thread *td, struct kevent_args *uap)
861 struct timespec ts, *tsp;
862 struct kevent_copyops k_ops = { uap,
869 struct uio *ktruioin = NULL;
870 struct uio *ktruioout = NULL;
873 if (uap->timeout != NULL) {
874 error = copyin(uap->timeout, &ts, sizeof(ts));
882 if (KTRPOINT(td, KTR_GENIO)) {
883 ktriov.iov_base = uap->changelist;
884 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
885 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
886 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
888 ktruioin = cloneuio(&ktruio);
889 ktriov.iov_base = uap->eventlist;
890 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
891 ktruioout = cloneuio(&ktruio);
895 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
899 if (ktruioin != NULL) {
900 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
901 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
902 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
903 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
911 * Copy 'count' items into the destination list pointed to by uap->eventlist.
914 kevent_copyout(void *arg, struct kevent *kevp, int count)
916 struct kevent_args *uap;
919 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
920 uap = (struct kevent_args *)arg;
922 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
924 uap->eventlist += count;
929 * Copy 'count' items from the list pointed to by uap->changelist.
932 kevent_copyin(void *arg, struct kevent *kevp, int count)
934 struct kevent_args *uap;
937 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
938 uap = (struct kevent_args *)arg;
940 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
942 uap->changelist += count;
947 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
948 struct kevent_copyops *k_ops, const struct timespec *timeout)
954 cap_rights_init(&rights);
956 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
958 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
959 error = fget(td, fd, &rights, &fp);
963 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
970 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
971 struct kevent_copyops *k_ops, const struct timespec *timeout)
973 struct kevent keva[KQ_NEVENTS];
974 struct kevent *kevp, *changes;
975 int i, n, nerrors, error;
978 while (nchanges > 0) {
979 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
980 error = k_ops->k_copyin(k_ops->arg, keva, n);
984 for (i = 0; i < n; i++) {
988 kevp->flags &= ~EV_SYSFLAGS;
989 error = kqueue_register(kq, kevp, td, 1);
990 if (error || (kevp->flags & EV_RECEIPT)) {
993 kevp->flags = EV_ERROR;
995 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1003 td->td_retval[0] = nerrors;
1007 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1011 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1012 struct kevent_copyops *k_ops, const struct timespec *timeout)
1017 error = kqueue_acquire(fp, &kq);
1020 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1021 kqueue_release(kq, 0);
1026 * Performs a kevent() call on a temporarily created kqueue. This can be
1027 * used to perform one-shot polling, similar to poll() and select().
1030 kern_kevent_anonymous(struct thread *td, int nevents,
1031 struct kevent_copyops *k_ops)
1033 struct kqueue kq = {};
1038 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1039 kqueue_drain(&kq, td);
1040 kqueue_destroy(&kq);
1045 kqueue_add_filteropts(int filt, struct filterops *filtops)
1050 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1052 "trying to add a filterop that is out of range: %d is beyond %d\n",
1053 ~filt, EVFILT_SYSCOUNT);
1056 mtx_lock(&filterops_lock);
1057 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1058 sysfilt_ops[~filt].for_fop != NULL)
1061 sysfilt_ops[~filt].for_fop = filtops;
1062 sysfilt_ops[~filt].for_refcnt = 0;
1064 mtx_unlock(&filterops_lock);
1070 kqueue_del_filteropts(int filt)
1075 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1078 mtx_lock(&filterops_lock);
1079 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1080 sysfilt_ops[~filt].for_fop == NULL)
1082 else if (sysfilt_ops[~filt].for_refcnt != 0)
1085 sysfilt_ops[~filt].for_fop = &null_filtops;
1086 sysfilt_ops[~filt].for_refcnt = 0;
1088 mtx_unlock(&filterops_lock);
1093 static struct filterops *
1094 kqueue_fo_find(int filt)
1097 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1100 if (sysfilt_ops[~filt].for_nolock)
1101 return sysfilt_ops[~filt].for_fop;
1103 mtx_lock(&filterops_lock);
1104 sysfilt_ops[~filt].for_refcnt++;
1105 if (sysfilt_ops[~filt].for_fop == NULL)
1106 sysfilt_ops[~filt].for_fop = &null_filtops;
1107 mtx_unlock(&filterops_lock);
1109 return sysfilt_ops[~filt].for_fop;
1113 kqueue_fo_release(int filt)
1116 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1119 if (sysfilt_ops[~filt].for_nolock)
1122 mtx_lock(&filterops_lock);
1123 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1124 ("filter object refcount not valid on release"));
1125 sysfilt_ops[~filt].for_refcnt--;
1126 mtx_unlock(&filterops_lock);
1130 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1131 * influence if memory allocation should wait. Make sure it is 0 if you
1135 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1137 struct filterops *fops;
1139 struct knote *kn, *tkn;
1140 cap_rights_t rights;
1141 int error, filt, event;
1142 int haskqglobal, filedesc_unlock;
1144 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1151 filedesc_unlock = 0;
1154 fops = kqueue_fo_find(filt);
1158 if (kev->flags & EV_ADD) {
1160 * Prevent waiting with locks. Non-sleepable
1161 * allocation failures are handled in the loop, only
1162 * if the spare knote appears to be actually required.
1164 tkn = knote_alloc(waitok);
1171 KASSERT(td != NULL, ("td is NULL"));
1172 error = fget(td, kev->ident,
1173 cap_rights_init(&rights, CAP_EVENT), &fp);
1177 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1178 kev->ident, 0) != 0) {
1182 error = kqueue_expand(kq, fops, kev->ident, waitok);
1188 if (fp->f_type == DTYPE_KQUEUE) {
1190 * If we add some intelligence about what we are doing,
1191 * we should be able to support events on ourselves.
1192 * We need to know when we are doing this to prevent
1193 * getting both the knlist lock and the kq lock since
1194 * they are the same thing.
1196 if (fp->f_data == kq) {
1202 * Pre-lock the filedesc before the global
1203 * lock mutex, see the comment in
1206 FILEDESC_XLOCK(td->td_proc->p_fd);
1207 filedesc_unlock = 1;
1208 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1212 if (kev->ident < kq->kq_knlistsize) {
1213 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1214 if (kev->filter == kn->kn_filter)
1218 if ((kev->flags & EV_ADD) == EV_ADD)
1219 kqueue_expand(kq, fops, kev->ident, waitok);
1224 * If possible, find an existing knote to use for this kevent.
1226 if (kev->filter == EVFILT_PROC &&
1227 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1228 /* This is an internal creation of a process tracking
1229 * note. Don't attempt to coalesce this with an
1233 } else if (kq->kq_knhashmask != 0) {
1236 list = &kq->kq_knhash[
1237 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1238 SLIST_FOREACH(kn, list, kn_link)
1239 if (kev->ident == kn->kn_id &&
1240 kev->filter == kn->kn_filter)
1245 /* knote is in the process of changing, wait for it to stabilize. */
1246 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1247 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1248 if (filedesc_unlock) {
1249 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1250 filedesc_unlock = 0;
1252 kq->kq_state |= KQ_FLUXWAIT;
1253 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1262 * kn now contains the matching knote, or NULL if no match
1265 if (kev->flags & EV_ADD) {
1277 * apply reference counts to knote structure, and
1278 * do not release it at the end of this routine.
1283 kn->kn_sfflags = kev->fflags;
1284 kn->kn_sdata = kev->data;
1287 kn->kn_kevent = *kev;
1288 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1289 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1290 kn->kn_status = KN_INFLUX|KN_DETACHED;
1292 error = knote_attach(kn, kq);
1299 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1306 /* No matching knote and the EV_ADD flag is not set. */
1313 if (kev->flags & EV_DELETE) {
1314 kn->kn_status |= KN_INFLUX;
1316 if (!(kn->kn_status & KN_DETACHED))
1317 kn->kn_fop->f_detach(kn);
1322 if (kev->flags & EV_FORCEONESHOT) {
1323 kn->kn_flags |= EV_ONESHOT;
1324 KNOTE_ACTIVATE(kn, 1);
1328 * The user may change some filter values after the initial EV_ADD,
1329 * but doing so will not reset any filter which has already been
1332 kn->kn_status |= KN_INFLUX | KN_SCAN;
1335 kn->kn_kevent.udata = kev->udata;
1336 if (!fops->f_isfd && fops->f_touch != NULL) {
1337 fops->f_touch(kn, kev, EVENT_REGISTER);
1339 kn->kn_sfflags = kev->fflags;
1340 kn->kn_sdata = kev->data;
1344 * We can get here with kn->kn_knlist == NULL. This can happen when
1345 * the initial attach event decides that the event is "completed"
1346 * already. i.e. filt_procattach is called on a zombie process. It
1347 * will call filt_proc which will remove it from the list, and NULL
1351 if ((kev->flags & EV_ENABLE) != 0)
1352 kn->kn_status &= ~KN_DISABLED;
1353 else if ((kev->flags & EV_DISABLE) != 0)
1354 kn->kn_status |= KN_DISABLED;
1356 if ((kn->kn_status & KN_DISABLED) == 0)
1357 event = kn->kn_fop->f_event(kn, 0);
1363 kn->kn_status |= KN_ACTIVE;
1364 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1367 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1372 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1373 if (filedesc_unlock)
1374 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1379 kqueue_fo_release(filt);
1384 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1392 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1396 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1407 kqueue_release(struct kqueue *kq, int locked)
1414 if (kq->kq_refcnt == 1)
1415 wakeup(&kq->kq_refcnt);
1421 kqueue_schedtask(struct kqueue *kq)
1425 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1426 ("scheduling kqueue task while draining"));
1428 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1429 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1430 kq->kq_state |= KQ_TASKSCHED;
1435 * Expand the kq to make sure we have storage for fops/ident pair.
1437 * Return 0 on success (or no work necessary), return errno on failure.
1439 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1440 * If kqueue_register is called from a non-fd context, there usually/should
1444 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1447 struct klist *list, *tmp_knhash, *to_free;
1448 u_long tmp_knhashmask;
1451 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1458 if (kq->kq_knlistsize <= fd) {
1459 size = kq->kq_knlistsize;
1462 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1466 if (kq->kq_knlistsize > fd) {
1470 if (kq->kq_knlist != NULL) {
1471 bcopy(kq->kq_knlist, list,
1472 kq->kq_knlistsize * sizeof(*list));
1473 to_free = kq->kq_knlist;
1474 kq->kq_knlist = NULL;
1476 bzero((caddr_t)list +
1477 kq->kq_knlistsize * sizeof(*list),
1478 (size - kq->kq_knlistsize) * sizeof(*list));
1479 kq->kq_knlistsize = size;
1480 kq->kq_knlist = list;
1485 if (kq->kq_knhashmask == 0) {
1486 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1488 if (tmp_knhash == NULL)
1491 if (kq->kq_knhashmask == 0) {
1492 kq->kq_knhash = tmp_knhash;
1493 kq->kq_knhashmask = tmp_knhashmask;
1495 to_free = tmp_knhash;
1500 free(to_free, M_KQUEUE);
1507 kqueue_task(void *arg, int pending)
1515 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1518 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1520 kq->kq_state &= ~KQ_TASKSCHED;
1521 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1522 wakeup(&kq->kq_state);
1525 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1529 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1530 * We treat KN_MARKER knotes as if they are INFLUX.
1533 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1534 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1536 struct kevent *kevp;
1537 struct knote *kn, *marker;
1538 sbintime_t asbt, rsbt;
1539 int count, error, haskqglobal, influx, nkev, touch;
1551 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1552 tsp->tv_nsec >= 1000000000) {
1556 if (timespecisset(tsp)) {
1557 if (tsp->tv_sec <= INT32_MAX) {
1558 rsbt = tstosbt(*tsp);
1559 if (TIMESEL(&asbt, rsbt))
1560 asbt += tc_tick_sbt;
1561 if (asbt <= SBT_MAX - rsbt)
1565 rsbt >>= tc_precexp;
1572 marker = knote_alloc(1);
1573 marker->kn_status = KN_MARKER;
1578 if (kq->kq_count == 0) {
1580 error = EWOULDBLOCK;
1582 kq->kq_state |= KQ_SLEEP;
1583 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1584 "kqread", asbt, rsbt, C_ABSOLUTE);
1588 /* don't restart after signals... */
1589 if (error == ERESTART)
1591 else if (error == EWOULDBLOCK)
1596 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1600 kn = TAILQ_FIRST(&kq->kq_head);
1602 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1603 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1608 kq->kq_state |= KQ_FLUXWAIT;
1609 error = msleep(kq, &kq->kq_lock, PSOCK,
1614 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1615 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1616 kn->kn_status &= ~KN_QUEUED;
1622 if (count == maxevents)
1626 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1627 ("KN_INFLUX set when not suppose to be"));
1629 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1630 kn->kn_status &= ~KN_QUEUED;
1631 kn->kn_status |= KN_INFLUX;
1635 * We don't need to lock the list since we've marked
1638 if (!(kn->kn_status & KN_DETACHED))
1639 kn->kn_fop->f_detach(kn);
1643 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1644 kn->kn_status &= ~KN_QUEUED;
1645 kn->kn_status |= KN_INFLUX;
1649 * We don't need to lock the list since we've marked
1652 *kevp = kn->kn_kevent;
1653 if (!(kn->kn_status & KN_DETACHED))
1654 kn->kn_fop->f_detach(kn);
1659 kn->kn_status |= KN_INFLUX | KN_SCAN;
1661 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1662 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1664 if (kn->kn_fop->f_event(kn, 0) == 0) {
1666 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1668 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1675 touch = (!kn->kn_fop->f_isfd &&
1676 kn->kn_fop->f_touch != NULL);
1678 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1680 *kevp = kn->kn_kevent;
1682 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1683 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1685 * Manually clear knotes who weren't
1688 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1692 if (kn->kn_flags & EV_DISPATCH)
1693 kn->kn_status |= KN_DISABLED;
1694 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1697 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1699 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1704 /* we are returning a copy to the user */
1709 if (nkev == KQ_NEVENTS) {
1712 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1720 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1728 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1729 td->td_retval[0] = maxevents - count;
1735 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1736 struct ucred *active_cred, struct thread *td)
1739 * Enabling sigio causes two major problems:
1740 * 1) infinite recursion:
1741 * Synopsys: kevent is being used to track signals and have FIOASYNC
1742 * set. On receipt of a signal this will cause a kqueue to recurse
1743 * into itself over and over. Sending the sigio causes the kqueue
1744 * to become ready, which in turn posts sigio again, forever.
1745 * Solution: this can be solved by setting a flag in the kqueue that
1746 * we have a SIGIO in progress.
1747 * 2) locking problems:
1748 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1749 * us above the proc and pgrp locks.
1750 * Solution: Post a signal using an async mechanism, being sure to
1751 * record a generation count in the delivery so that we do not deliver
1752 * a signal to the wrong process.
1754 * Note, these two mechanisms are somewhat mutually exclusive!
1763 kq->kq_state |= KQ_ASYNC;
1765 kq->kq_state &= ~KQ_ASYNC;
1770 return (fsetown(*(int *)data, &kq->kq_sigio));
1773 *(int *)data = fgetown(&kq->kq_sigio);
1783 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1790 if ((error = kqueue_acquire(fp, &kq)))
1794 if (events & (POLLIN | POLLRDNORM)) {
1796 revents |= events & (POLLIN | POLLRDNORM);
1798 selrecord(td, &kq->kq_sel);
1799 if (SEL_WAITING(&kq->kq_sel))
1800 kq->kq_state |= KQ_SEL;
1803 kqueue_release(kq, 1);
1810 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1814 bzero((void *)st, sizeof *st);
1816 * We no longer return kq_count because the unlocked value is useless.
1817 * If you spent all this time getting the count, why not spend your
1818 * syscall better by calling kevent?
1820 * XXX - This is needed for libc_r.
1822 st->st_mode = S_IFIFO;
1827 kqueue_drain(struct kqueue *kq, struct thread *td)
1834 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1835 ("kqueue already closing"));
1836 kq->kq_state |= KQ_CLOSING;
1837 if (kq->kq_refcnt > 1)
1838 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1840 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1842 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1843 ("kqueue's knlist not empty"));
1845 for (i = 0; i < kq->kq_knlistsize; i++) {
1846 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1847 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1848 kq->kq_state |= KQ_FLUXWAIT;
1849 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1852 kn->kn_status |= KN_INFLUX;
1854 if (!(kn->kn_status & KN_DETACHED))
1855 kn->kn_fop->f_detach(kn);
1860 if (kq->kq_knhashmask != 0) {
1861 for (i = 0; i <= kq->kq_knhashmask; i++) {
1862 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1863 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1864 kq->kq_state |= KQ_FLUXWAIT;
1865 msleep(kq, &kq->kq_lock, PSOCK,
1869 kn->kn_status |= KN_INFLUX;
1871 if (!(kn->kn_status & KN_DETACHED))
1872 kn->kn_fop->f_detach(kn);
1879 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1880 kq->kq_state |= KQ_TASKDRAIN;
1881 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1884 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1885 selwakeuppri(&kq->kq_sel, PSOCK);
1886 if (!SEL_WAITING(&kq->kq_sel))
1887 kq->kq_state &= ~KQ_SEL;
1894 kqueue_destroy(struct kqueue *kq)
1897 KASSERT(kq->kq_fdp == NULL,
1898 ("kqueue still attached to a file descriptor"));
1899 seldrain(&kq->kq_sel);
1900 knlist_destroy(&kq->kq_sel.si_note);
1901 mtx_destroy(&kq->kq_lock);
1903 if (kq->kq_knhash != NULL)
1904 free(kq->kq_knhash, M_KQUEUE);
1905 if (kq->kq_knlist != NULL)
1906 free(kq->kq_knlist, M_KQUEUE);
1908 funsetown(&kq->kq_sigio);
1913 kqueue_close(struct file *fp, struct thread *td)
1915 struct kqueue *kq = fp->f_data;
1916 struct filedesc *fdp;
1918 int filedesc_unlock;
1920 if ((error = kqueue_acquire(fp, &kq)))
1922 kqueue_drain(kq, td);
1925 * We could be called due to the knote_drop() doing fdrop(),
1926 * called from kqueue_register(). In this case the global
1927 * lock is owned, and filedesc sx is locked before, to not
1928 * take the sleepable lock after non-sleepable.
1932 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1933 FILEDESC_XLOCK(fdp);
1934 filedesc_unlock = 1;
1936 filedesc_unlock = 0;
1937 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1938 if (filedesc_unlock)
1939 FILEDESC_XUNLOCK(fdp);
1942 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1943 crfree(kq->kq_cred);
1951 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1954 kif->kf_type = KF_TYPE_KQUEUE;
1959 kqueue_wakeup(struct kqueue *kq)
1963 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1964 kq->kq_state &= ~KQ_SLEEP;
1967 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1968 selwakeuppri(&kq->kq_sel, PSOCK);
1969 if (!SEL_WAITING(&kq->kq_sel))
1970 kq->kq_state &= ~KQ_SEL;
1972 if (!knlist_empty(&kq->kq_sel.si_note))
1973 kqueue_schedtask(kq);
1974 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1975 pgsigio(&kq->kq_sigio, SIGIO, 0);
1980 * Walk down a list of knotes, activating them if their event has triggered.
1982 * There is a possibility to optimize in the case of one kq watching another.
1983 * Instead of scheduling a task to wake it up, you could pass enough state
1984 * down the chain to make up the parent kqueue. Make this code functional
1988 knote(struct knlist *list, long hint, int lockflags)
1991 struct knote *kn, *tkn;
1997 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1999 if ((lockflags & KNF_LISTLOCKED) == 0)
2000 list->kl_lock(list->kl_lockarg);
2003 * If we unlock the list lock (and set KN_INFLUX), we can
2004 * eliminate the kqueue scheduling, but this will introduce
2005 * four lock/unlock's for each knote to test. Also, marker
2006 * would be needed to keep iteration position, since filters
2007 * or other threads could remove events.
2009 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2012 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
2014 * Do not process the influx notes, except for
2015 * the influx coming from the kq unlock in the
2016 * kqueue_scan(). In the later case, we do
2017 * not interfere with the scan, since the code
2018 * fragment in kqueue_scan() locks the knlist,
2019 * and cannot proceed until we finished.
2022 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2023 kn->kn_status |= KN_INFLUX;
2025 error = kn->kn_fop->f_event(kn, hint);
2027 kn->kn_status &= ~KN_INFLUX;
2029 KNOTE_ACTIVATE(kn, 1);
2032 kn->kn_status |= KN_HASKQLOCK;
2033 if (kn->kn_fop->f_event(kn, hint))
2034 KNOTE_ACTIVATE(kn, 1);
2035 kn->kn_status &= ~KN_HASKQLOCK;
2039 if ((lockflags & KNF_LISTLOCKED) == 0)
2040 list->kl_unlock(list->kl_lockarg);
2044 * add a knote to a knlist
2047 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2049 KNL_ASSERT_LOCK(knl, islocked);
2050 KQ_NOTOWNED(kn->kn_kq);
2051 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
2052 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
2054 knl->kl_lock(knl->kl_lockarg);
2055 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2057 knl->kl_unlock(knl->kl_lockarg);
2059 kn->kn_knlist = knl;
2060 kn->kn_status &= ~KN_DETACHED;
2061 KQ_UNLOCK(kn->kn_kq);
2065 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
2067 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2068 KNL_ASSERT_LOCK(knl, knlislocked);
2069 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2071 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2072 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2074 knl->kl_lock(knl->kl_lockarg);
2075 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2076 kn->kn_knlist = NULL;
2078 knl->kl_unlock(knl->kl_lockarg);
2081 kn->kn_status |= KN_DETACHED;
2083 KQ_UNLOCK(kn->kn_kq);
2087 * remove knote from the specified knlist
2090 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2093 knlist_remove_kq(knl, kn, islocked, 0);
2097 * remove knote from the specified knlist while in f_event handler.
2100 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
2103 knlist_remove_kq(knl, kn, 1,
2104 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
2108 knlist_empty(struct knlist *knl)
2111 KNL_ASSERT_LOCKED(knl);
2112 return SLIST_EMPTY(&knl->kl_list);
2115 static struct mtx knlist_lock;
2116 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2118 static void knlist_mtx_lock(void *arg);
2119 static void knlist_mtx_unlock(void *arg);
2122 knlist_mtx_lock(void *arg)
2125 mtx_lock((struct mtx *)arg);
2129 knlist_mtx_unlock(void *arg)
2132 mtx_unlock((struct mtx *)arg);
2136 knlist_mtx_assert_locked(void *arg)
2139 mtx_assert((struct mtx *)arg, MA_OWNED);
2143 knlist_mtx_assert_unlocked(void *arg)
2146 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2150 knlist_rw_rlock(void *arg)
2153 rw_rlock((struct rwlock *)arg);
2157 knlist_rw_runlock(void *arg)
2160 rw_runlock((struct rwlock *)arg);
2164 knlist_rw_assert_locked(void *arg)
2167 rw_assert((struct rwlock *)arg, RA_LOCKED);
2171 knlist_rw_assert_unlocked(void *arg)
2174 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2178 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2179 void (*kl_unlock)(void *),
2180 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2184 knl->kl_lockarg = &knlist_lock;
2186 knl->kl_lockarg = lock;
2188 if (kl_lock == NULL)
2189 knl->kl_lock = knlist_mtx_lock;
2191 knl->kl_lock = kl_lock;
2192 if (kl_unlock == NULL)
2193 knl->kl_unlock = knlist_mtx_unlock;
2195 knl->kl_unlock = kl_unlock;
2196 if (kl_assert_locked == NULL)
2197 knl->kl_assert_locked = knlist_mtx_assert_locked;
2199 knl->kl_assert_locked = kl_assert_locked;
2200 if (kl_assert_unlocked == NULL)
2201 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2203 knl->kl_assert_unlocked = kl_assert_unlocked;
2205 SLIST_INIT(&knl->kl_list);
2209 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2212 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2216 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2219 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2220 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2224 knlist_destroy(struct knlist *knl)
2229 * if we run across this error, we need to find the offending
2230 * driver and have it call knlist_clear or knlist_delete.
2232 if (!SLIST_EMPTY(&knl->kl_list))
2233 printf("WARNING: destroying knlist w/ knotes on it!\n");
2236 knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2237 SLIST_INIT(&knl->kl_list);
2241 * Even if we are locked, we may need to drop the lock to allow any influx
2242 * knotes time to "settle".
2245 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2247 struct knote *kn, *kn2;
2251 KNL_ASSERT_LOCKED(knl);
2253 KNL_ASSERT_UNLOCKED(knl);
2254 again: /* need to reacquire lock since we have dropped it */
2255 knl->kl_lock(knl->kl_lockarg);
2258 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2261 if ((kn->kn_status & KN_INFLUX)) {
2265 knlist_remove_kq(knl, kn, 1, 1);
2267 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2271 /* Make sure cleared knotes disappear soon */
2272 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2278 if (!SLIST_EMPTY(&knl->kl_list)) {
2279 /* there are still KN_INFLUX remaining */
2280 kn = SLIST_FIRST(&knl->kl_list);
2283 KASSERT(kn->kn_status & KN_INFLUX,
2284 ("knote removed w/o list lock"));
2285 knl->kl_unlock(knl->kl_lockarg);
2286 kq->kq_state |= KQ_FLUXWAIT;
2287 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2293 KNL_ASSERT_LOCKED(knl);
2295 knl->kl_unlock(knl->kl_lockarg);
2296 KNL_ASSERT_UNLOCKED(knl);
2301 * Remove all knotes referencing a specified fd must be called with FILEDESC
2302 * lock. This prevents a race where a new fd comes along and occupies the
2303 * entry and we attach a knote to the fd.
2306 knote_fdclose(struct thread *td, int fd)
2308 struct filedesc *fdp = td->td_proc->p_fd;
2313 FILEDESC_XLOCK_ASSERT(fdp);
2316 * We shouldn't have to worry about new kevents appearing on fd
2317 * since filedesc is locked.
2319 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2324 while (kq->kq_knlistsize > fd &&
2325 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2326 if (kn->kn_status & KN_INFLUX) {
2327 /* someone else might be waiting on our knote */
2330 kq->kq_state |= KQ_FLUXWAIT;
2331 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2334 kn->kn_status |= KN_INFLUX;
2336 if (!(kn->kn_status & KN_DETACHED))
2337 kn->kn_fop->f_detach(kn);
2347 knote_attach(struct knote *kn, struct kqueue *kq)
2351 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2354 if (kn->kn_fop->f_isfd) {
2355 if (kn->kn_id >= kq->kq_knlistsize)
2357 list = &kq->kq_knlist[kn->kn_id];
2359 if (kq->kq_knhash == NULL)
2361 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2364 SLIST_INSERT_HEAD(list, kn, kn_link);
2370 * knote must already have been detached using the f_detach method.
2371 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2372 * to prevent other removal.
2375 knote_drop(struct knote *kn, struct thread *td)
2383 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2384 ("knote_drop called without KN_INFLUX set in kn_status"));
2387 if (kn->kn_fop->f_isfd)
2388 list = &kq->kq_knlist[kn->kn_id];
2390 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2392 if (!SLIST_EMPTY(list))
2393 SLIST_REMOVE(list, kn, knote, kn_link);
2394 if (kn->kn_status & KN_QUEUED)
2398 if (kn->kn_fop->f_isfd) {
2399 fdrop(kn->kn_fp, td);
2402 kqueue_fo_release(kn->kn_kevent.filter);
2408 knote_enqueue(struct knote *kn)
2410 struct kqueue *kq = kn->kn_kq;
2412 KQ_OWNED(kn->kn_kq);
2413 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2415 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2416 kn->kn_status |= KN_QUEUED;
2422 knote_dequeue(struct knote *kn)
2424 struct kqueue *kq = kn->kn_kq;
2426 KQ_OWNED(kn->kn_kq);
2427 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2429 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2430 kn->kn_status &= ~KN_QUEUED;
2438 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2439 NULL, NULL, UMA_ALIGN_PTR, 0);
2441 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2443 static struct knote *
2444 knote_alloc(int waitok)
2447 return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2452 knote_free(struct knote *kn)
2455 uma_zfree(knote_zone, kn);
2459 * Register the kev w/ the kq specified by fd.
2462 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2466 cap_rights_t rights;
2469 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2472 if ((error = kqueue_acquire(fp, &kq)) != 0)
2475 error = kqueue_register(kq, kev, td, waitok);
2477 kqueue_release(kq, 0);