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/queue.h>
52 #include <sys/event.h>
53 #include <sys/eventvar.h>
55 #include <sys/protosw.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sigio.h>
58 #include <sys/signalvar.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
62 #include <sys/sysctl.h>
63 #include <sys/sysproto.h>
64 #include <sys/syscallsubr.h>
65 #include <sys/taskqueue.h>
69 #include <sys/ktrace.h>
71 #include <machine/atomic.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 void filt_timerstart(struct knote *kn, sbintime_t to);
155 static void filt_timertouch(struct knote *kn, struct kevent *kev,
157 static int filt_timervalidate(struct knote *kn, sbintime_t *to);
158 static int filt_timer(struct knote *kn, long hint);
159 static int filt_userattach(struct knote *kn);
160 static void filt_userdetach(struct knote *kn);
161 static int filt_user(struct knote *kn, long hint);
162 static void filt_usertouch(struct knote *kn, struct kevent *kev,
165 static struct filterops file_filtops = {
167 .f_attach = filt_fileattach,
169 static struct filterops kqread_filtops = {
171 .f_detach = filt_kqdetach,
172 .f_event = filt_kqueue,
174 /* XXX - move to kern_proc.c? */
175 static struct filterops proc_filtops = {
177 .f_attach = filt_procattach,
178 .f_detach = filt_procdetach,
179 .f_event = filt_proc,
181 static struct filterops timer_filtops = {
183 .f_attach = filt_timerattach,
184 .f_detach = filt_timerdetach,
185 .f_event = filt_timer,
186 .f_touch = filt_timertouch,
188 static struct filterops user_filtops = {
189 .f_attach = filt_userattach,
190 .f_detach = filt_userdetach,
191 .f_event = filt_user,
192 .f_touch = filt_usertouch,
195 static uma_zone_t knote_zone;
196 static unsigned int kq_ncallouts = 0;
197 static unsigned int kq_calloutmax = 4 * 1024;
198 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
199 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
201 /* XXX - ensure not KN_INFLUX?? */
202 #define KNOTE_ACTIVATE(kn, islock) do { \
204 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
206 KQ_LOCK((kn)->kn_kq); \
207 (kn)->kn_status |= KN_ACTIVE; \
208 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
209 knote_enqueue((kn)); \
211 KQ_UNLOCK((kn)->kn_kq); \
213 #define KQ_LOCK(kq) do { \
214 mtx_lock(&(kq)->kq_lock); \
216 #define KQ_FLUX_WAKEUP(kq) do { \
217 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
218 (kq)->kq_state &= ~KQ_FLUXWAIT; \
222 #define KQ_UNLOCK_FLUX(kq) do { \
223 KQ_FLUX_WAKEUP(kq); \
224 mtx_unlock(&(kq)->kq_lock); \
226 #define KQ_UNLOCK(kq) do { \
227 mtx_unlock(&(kq)->kq_lock); \
229 #define KQ_OWNED(kq) do { \
230 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
232 #define KQ_NOTOWNED(kq) do { \
233 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
236 static struct knlist *
237 kn_list_lock(struct knote *kn)
243 knl->kl_lock(knl->kl_lockarg);
248 kn_list_unlock(struct knlist *knl)
254 do_free = knl->kl_autodestroy && knlist_empty(knl);
255 knl->kl_unlock(knl->kl_lockarg);
262 #define KNL_ASSERT_LOCK(knl, islocked) do { \
264 KNL_ASSERT_LOCKED(knl); \
266 KNL_ASSERT_UNLOCKED(knl); \
269 #define KNL_ASSERT_LOCKED(knl) do { \
270 knl->kl_assert_locked((knl)->kl_lockarg); \
272 #define KNL_ASSERT_UNLOCKED(knl) do { \
273 knl->kl_assert_unlocked((knl)->kl_lockarg); \
275 #else /* !INVARIANTS */
276 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
277 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
278 #endif /* INVARIANTS */
281 #define KN_HASHSIZE 64 /* XXX should be tunable */
284 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
287 filt_nullattach(struct knote *kn)
293 struct filterops null_filtops = {
295 .f_attach = filt_nullattach,
298 /* XXX - make SYSINIT to add these, and move into respective modules. */
299 extern struct filterops sig_filtops;
300 extern struct filterops fs_filtops;
303 * Table for for all system-defined filters.
305 static struct mtx filterops_lock;
306 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
309 struct filterops *for_fop;
312 } sysfilt_ops[EVFILT_SYSCOUNT] = {
313 { &file_filtops, 1 }, /* EVFILT_READ */
314 { &file_filtops, 1 }, /* EVFILT_WRITE */
315 { &null_filtops }, /* EVFILT_AIO */
316 { &file_filtops, 1 }, /* EVFILT_VNODE */
317 { &proc_filtops, 1 }, /* EVFILT_PROC */
318 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
319 { &timer_filtops, 1 }, /* EVFILT_TIMER */
320 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
321 { &fs_filtops, 1 }, /* EVFILT_FS */
322 { &null_filtops }, /* EVFILT_LIO */
323 { &user_filtops, 1 }, /* EVFILT_USER */
324 { &null_filtops }, /* EVFILT_SENDFILE */
328 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
332 filt_fileattach(struct knote *kn)
335 return (fo_kqfilter(kn->kn_fp, kn));
340 kqueue_kqfilter(struct file *fp, struct knote *kn)
342 struct kqueue *kq = kn->kn_fp->f_data;
344 if (kn->kn_filter != EVFILT_READ)
347 kn->kn_status |= KN_KQUEUE;
348 kn->kn_fop = &kqread_filtops;
349 knlist_add(&kq->kq_sel.si_note, kn, 0);
355 filt_kqdetach(struct knote *kn)
357 struct kqueue *kq = kn->kn_fp->f_data;
359 knlist_remove(&kq->kq_sel.si_note, kn, 0);
364 filt_kqueue(struct knote *kn, long hint)
366 struct kqueue *kq = kn->kn_fp->f_data;
368 kn->kn_data = kq->kq_count;
369 return (kn->kn_data > 0);
372 /* XXX - move to kern_proc.c? */
374 filt_procattach(struct knote *kn)
378 bool exiting, immediate;
380 exiting = immediate = false;
381 p = pfind(kn->kn_id);
382 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
383 p = zpfind(kn->kn_id);
385 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
391 if ((error = p_cansee(curthread, p))) {
396 kn->kn_ptr.p_proc = p;
397 kn->kn_flags |= EV_CLEAR; /* automatically set */
400 * Internal flag indicating registration done by kernel for the
401 * purposes of getting a NOTE_CHILD notification.
403 if (kn->kn_flags & EV_FLAG2) {
404 kn->kn_flags &= ~EV_FLAG2;
405 kn->kn_data = kn->kn_sdata; /* ppid */
406 kn->kn_fflags = NOTE_CHILD;
407 kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
408 immediate = true; /* Force immediate activation of child note. */
411 * Internal flag indicating registration done by kernel (for other than
414 if (kn->kn_flags & EV_FLAG1) {
415 kn->kn_flags &= ~EV_FLAG1;
418 knlist_add(p->p_klist, kn, 1);
421 * Immediately activate any child notes or, in the case of a zombie
422 * target process, exit notes. The latter is necessary to handle the
423 * case where the target process, e.g. a child, dies before the kevent
426 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
427 KNOTE_ACTIVATE(kn, 0);
435 * The knote may be attached to a different process, which may exit,
436 * leaving nothing for the knote to be attached to. So when the process
437 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
438 * it will be deleted when read out. However, as part of the knote deletion,
439 * this routine is called, so a check is needed to avoid actually performing
440 * a detach, because the original process does not exist any more.
442 /* XXX - move to kern_proc.c? */
444 filt_procdetach(struct knote *kn)
447 knlist_remove(kn->kn_knlist, kn, 0);
448 kn->kn_ptr.p_proc = NULL;
451 /* XXX - move to kern_proc.c? */
453 filt_proc(struct knote *kn, long hint)
458 p = kn->kn_ptr.p_proc;
459 if (p == NULL) /* already activated, from attach filter */
462 /* Mask off extra data. */
463 event = (u_int)hint & NOTE_PCTRLMASK;
465 /* If the user is interested in this event, record it. */
466 if (kn->kn_sfflags & event)
467 kn->kn_fflags |= event;
469 /* Process is gone, so flag the event as finished. */
470 if (event == NOTE_EXIT) {
471 kn->kn_flags |= EV_EOF | EV_ONESHOT;
472 kn->kn_ptr.p_proc = NULL;
473 if (kn->kn_fflags & NOTE_EXIT)
474 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
475 if (kn->kn_fflags == 0)
476 kn->kn_flags |= EV_DROP;
480 return (kn->kn_fflags != 0);
484 * Called when the process forked. It mostly does the same as the
485 * knote(), activating all knotes registered to be activated when the
486 * process forked. Additionally, for each knote attached to the
487 * parent, check whether user wants to track the new process. If so
488 * attach a new knote to it, and immediately report an event with the
492 knote_fork(struct knlist *list, int pid)
501 list->kl_lock(list->kl_lockarg);
503 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
506 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
512 * The same as knote(), activate the event.
514 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
515 kn->kn_status |= KN_HASKQLOCK;
516 if (kn->kn_fop->f_event(kn, NOTE_FORK))
517 KNOTE_ACTIVATE(kn, 1);
518 kn->kn_status &= ~KN_HASKQLOCK;
524 * The NOTE_TRACK case. In addition to the activation
525 * of the event, we need to register new events to
526 * track the child. Drop the locks in preparation for
527 * the call to kqueue_register().
529 kn->kn_status |= KN_INFLUX;
531 list->kl_unlock(list->kl_lockarg);
534 * Activate existing knote and register tracking knotes with
537 * First register a knote to get just the child notice. This
538 * must be a separate note from a potential NOTE_EXIT
539 * notification since both NOTE_CHILD and NOTE_EXIT are defined
540 * to use the data field (in conflicting ways).
543 kev.filter = kn->kn_filter;
544 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
546 kev.fflags = kn->kn_sfflags;
547 kev.data = kn->kn_id; /* parent */
548 kev.udata = kn->kn_kevent.udata;/* preserve udata */
549 error = kqueue_register(kq, &kev, NULL, 0);
551 kn->kn_fflags |= NOTE_TRACKERR;
554 * Then register another knote to track other potential events
555 * from the new process.
558 kev.filter = kn->kn_filter;
559 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
560 kev.fflags = kn->kn_sfflags;
561 kev.data = kn->kn_id; /* parent */
562 kev.udata = kn->kn_kevent.udata;/* preserve udata */
563 error = kqueue_register(kq, &kev, NULL, 0);
565 kn->kn_fflags |= NOTE_TRACKERR;
566 if (kn->kn_fop->f_event(kn, NOTE_FORK))
567 KNOTE_ACTIVATE(kn, 0);
569 kn->kn_status &= ~KN_INFLUX;
571 list->kl_lock(list->kl_lockarg);
573 list->kl_unlock(list->kl_lockarg);
577 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
578 * interval timer support code.
581 #define NOTE_TIMER_PRECMASK \
582 (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
585 timer2sbintime(intptr_t data, int flags)
590 * Macros for converting to the fractional second portion of an
591 * sbintime_t using 64bit multiplication to improve precision.
593 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
594 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
595 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
596 switch (flags & NOTE_TIMER_PRECMASK) {
599 if (data > (SBT_MAX / SBT_1S))
602 return ((sbintime_t)data << 32);
603 case NOTE_MSECONDS: /* FALLTHROUGH */
608 if (secs > (SBT_MAX / SBT_1S))
611 return (secs << 32 | MS_TO_SBT(data % 1000));
613 return (MS_TO_SBT(data));
615 if (data >= 1000000) {
616 secs = data / 1000000;
618 if (secs > (SBT_MAX / SBT_1S))
621 return (secs << 32 | US_TO_SBT(data % 1000000));
623 return (US_TO_SBT(data));
625 if (data >= 1000000000) {
626 secs = data / 1000000000;
628 if (secs > (SBT_MAX / SBT_1S))
631 return (secs << 32 | US_TO_SBT(data % 1000000000));
633 return (NS_TO_SBT(data));
640 struct kq_timer_cb_data {
642 sbintime_t next; /* next timer event fires at */
643 sbintime_t to; /* precalculated timer period */
647 filt_timerexpire(void *knx)
650 struct kq_timer_cb_data *kc;
654 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
656 if ((kn->kn_flags & EV_ONESHOT) != 0)
661 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
662 PCPU_GET(cpuid), C_ABSOLUTE);
666 * data contains amount of time to sleep
669 filt_timervalidate(struct knote *kn, sbintime_t *to)
672 if (kn->kn_sdata < 0)
674 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
677 * The only fflags values supported are the timer unit
678 * (precision) and the absolute time indicator.
680 if ((kn->kn_sfflags & ~NOTE_TIMER_PRECMASK) != 0)
683 *to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
690 filt_timerattach(struct knote *kn)
692 struct kq_timer_cb_data *kc;
694 unsigned int ncallouts;
697 error = filt_timervalidate(kn, &to);
702 ncallouts = kq_ncallouts;
703 if (ncallouts >= kq_calloutmax)
705 } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
707 kn->kn_flags |= EV_CLEAR; /* automatically set */
708 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
709 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
710 callout_init(&kc->c, 1);
711 filt_timerstart(kn, to);
717 filt_timerstart(struct knote *kn, sbintime_t to)
719 struct kq_timer_cb_data *kc;
722 kc->next = to + sbinuptime();
724 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
725 PCPU_GET(cpuid), C_ABSOLUTE);
729 filt_timerdetach(struct knote *kn)
731 struct kq_timer_cb_data *kc;
735 callout_drain(&kc->c);
737 old = atomic_fetchadd_int(&kq_ncallouts, -1);
738 KASSERT(old > 0, ("Number of callouts cannot become negative"));
739 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
743 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
745 struct kq_timer_cb_data *kc;
752 /* Handle re-added timers that update data/fflags */
753 if (kev->flags & EV_ADD) {
756 /* Drain any existing callout. */
757 callout_drain(&kc->c);
759 /* Throw away any existing undelivered record
760 * of the timer expiration. This is done under
761 * the presumption that if a process is
762 * re-adding this timer with new parameters,
763 * it is no longer interested in what may have
764 * happened under the old parameters. If it is
765 * interested, it can wait for the expiration,
766 * delete the old timer definition, and then
769 * This has to be done while the kq is locked:
770 * - if enqueued, dequeue
771 * - make it no longer active
772 * - clear the count of expiration events
776 if (kn->kn_status & KN_QUEUED)
779 kn->kn_status &= ~KN_ACTIVE;
783 /* Reschedule timer based on new data/fflags */
784 kn->kn_sfflags = kev->fflags;
785 kn->kn_sdata = kev->data;
786 error = filt_timervalidate(kn, &to);
788 kn->kn_flags |= EV_ERROR;
791 filt_timerstart(kn, to);
796 *kev = kn->kn_kevent;
797 if (kn->kn_flags & EV_CLEAR) {
804 panic("filt_timertouch() - invalid type (%ld)", type);
810 filt_timer(struct knote *kn, long hint)
813 return (kn->kn_data != 0);
817 filt_userattach(struct knote *kn)
821 * EVFILT_USER knotes are not attached to anything in the kernel.
824 if (kn->kn_fflags & NOTE_TRIGGER)
832 filt_userdetach(__unused struct knote *kn)
836 * EVFILT_USER knotes are not attached to anything in the kernel.
841 filt_user(struct knote *kn, __unused long hint)
844 return (kn->kn_hookid);
848 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
854 if (kev->fflags & NOTE_TRIGGER)
857 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
858 kev->fflags &= NOTE_FFLAGSMASK;
864 kn->kn_sfflags &= kev->fflags;
868 kn->kn_sfflags |= kev->fflags;
872 kn->kn_sfflags = kev->fflags;
876 /* XXX Return error? */
879 kn->kn_sdata = kev->data;
880 if (kev->flags & EV_CLEAR) {
888 *kev = kn->kn_kevent;
889 kev->fflags = kn->kn_sfflags;
890 kev->data = kn->kn_sdata;
891 if (kn->kn_flags & EV_CLEAR) {
899 panic("filt_usertouch() - invalid type (%ld)", type);
905 sys_kqueue(struct thread *td, struct kqueue_args *uap)
908 return (kern_kqueue(td, 0, NULL));
912 kqueue_init(struct kqueue *kq)
915 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
916 TAILQ_INIT(&kq->kq_head);
917 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
918 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
922 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
924 struct filedesc *fdp;
930 fdp = td->td_proc->p_fd;
932 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
935 error = falloc_caps(td, &fp, &fd, flags, fcaps);
937 chgkqcnt(cred->cr_ruidinfo, -1, 0);
941 /* An extra reference on `fp' has been held for us by falloc(). */
942 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
945 kq->kq_cred = crhold(cred);
948 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
949 FILEDESC_XUNLOCK(fdp);
951 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
954 td->td_retval[0] = fd;
958 #ifndef _SYS_SYSPROTO_H_
961 const struct kevent *changelist;
963 struct kevent *eventlist;
965 const struct timespec *timeout;
969 sys_kevent(struct thread *td, struct kevent_args *uap)
971 struct timespec ts, *tsp;
972 struct kevent_copyops k_ops = {
974 .k_copyout = kevent_copyout,
975 .k_copyin = kevent_copyin,
978 struct kevent *eventlist = uap->eventlist;
982 if (uap->timeout != NULL) {
983 error = copyin(uap->timeout, &ts, sizeof(ts));
991 if (KTRPOINT(td, KTR_STRUCT_ARRAY))
992 ktrstructarray("kevent", UIO_USERSPACE, uap->changelist,
993 uap->nchanges, sizeof(struct kevent));
996 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1000 if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1001 ktrstructarray("kevent", UIO_USERSPACE, eventlist,
1002 td->td_retval[0], sizeof(struct kevent));
1009 * Copy 'count' items into the destination list pointed to by uap->eventlist.
1012 kevent_copyout(void *arg, struct kevent *kevp, int count)
1014 struct kevent_args *uap;
1017 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1018 uap = (struct kevent_args *)arg;
1020 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1022 uap->eventlist += count;
1027 * Copy 'count' items from the list pointed to by uap->changelist.
1030 kevent_copyin(void *arg, struct kevent *kevp, int count)
1032 struct kevent_args *uap;
1035 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1036 uap = (struct kevent_args *)arg;
1038 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1040 uap->changelist += count;
1045 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1046 struct kevent_copyops *k_ops, const struct timespec *timeout)
1048 cap_rights_t rights;
1052 cap_rights_init(&rights);
1054 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
1056 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
1057 error = fget(td, fd, &rights, &fp);
1061 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1068 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1069 struct kevent_copyops *k_ops, const struct timespec *timeout)
1071 struct kevent keva[KQ_NEVENTS];
1072 struct kevent *kevp, *changes;
1073 int i, n, nerrors, error;
1076 while (nchanges > 0) {
1077 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1078 error = k_ops->k_copyin(k_ops->arg, keva, n);
1082 for (i = 0; i < n; i++) {
1086 kevp->flags &= ~EV_SYSFLAGS;
1087 error = kqueue_register(kq, kevp, td, 1);
1088 if (error || (kevp->flags & EV_RECEIPT)) {
1091 kevp->flags = EV_ERROR;
1093 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1101 td->td_retval[0] = nerrors;
1105 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1109 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1110 struct kevent_copyops *k_ops, const struct timespec *timeout)
1115 error = kqueue_acquire(fp, &kq);
1118 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1119 kqueue_release(kq, 0);
1124 * Performs a kevent() call on a temporarily created kqueue. This can be
1125 * used to perform one-shot polling, similar to poll() and select().
1128 kern_kevent_anonymous(struct thread *td, int nevents,
1129 struct kevent_copyops *k_ops)
1131 struct kqueue kq = {};
1136 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1137 kqueue_drain(&kq, td);
1138 kqueue_destroy(&kq);
1143 kqueue_add_filteropts(int filt, struct filterops *filtops)
1148 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1150 "trying to add a filterop that is out of range: %d is beyond %d\n",
1151 ~filt, EVFILT_SYSCOUNT);
1154 mtx_lock(&filterops_lock);
1155 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1156 sysfilt_ops[~filt].for_fop != NULL)
1159 sysfilt_ops[~filt].for_fop = filtops;
1160 sysfilt_ops[~filt].for_refcnt = 0;
1162 mtx_unlock(&filterops_lock);
1168 kqueue_del_filteropts(int filt)
1173 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1176 mtx_lock(&filterops_lock);
1177 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1178 sysfilt_ops[~filt].for_fop == NULL)
1180 else if (sysfilt_ops[~filt].for_refcnt != 0)
1183 sysfilt_ops[~filt].for_fop = &null_filtops;
1184 sysfilt_ops[~filt].for_refcnt = 0;
1186 mtx_unlock(&filterops_lock);
1191 static struct filterops *
1192 kqueue_fo_find(int filt)
1195 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1198 if (sysfilt_ops[~filt].for_nolock)
1199 return sysfilt_ops[~filt].for_fop;
1201 mtx_lock(&filterops_lock);
1202 sysfilt_ops[~filt].for_refcnt++;
1203 if (sysfilt_ops[~filt].for_fop == NULL)
1204 sysfilt_ops[~filt].for_fop = &null_filtops;
1205 mtx_unlock(&filterops_lock);
1207 return sysfilt_ops[~filt].for_fop;
1211 kqueue_fo_release(int filt)
1214 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1217 if (sysfilt_ops[~filt].for_nolock)
1220 mtx_lock(&filterops_lock);
1221 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1222 ("filter object refcount not valid on release"));
1223 sysfilt_ops[~filt].for_refcnt--;
1224 mtx_unlock(&filterops_lock);
1228 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1229 * influence if memory allocation should wait. Make sure it is 0 if you
1233 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1235 struct filterops *fops;
1237 struct knote *kn, *tkn;
1239 cap_rights_t rights;
1240 int error, filt, event;
1241 int haskqglobal, filedesc_unlock;
1243 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1251 filedesc_unlock = 0;
1254 fops = kqueue_fo_find(filt);
1258 if (kev->flags & EV_ADD) {
1260 * Prevent waiting with locks. Non-sleepable
1261 * allocation failures are handled in the loop, only
1262 * if the spare knote appears to be actually required.
1264 tkn = knote_alloc(waitok);
1271 KASSERT(td != NULL, ("td is NULL"));
1272 if (kev->ident > INT_MAX)
1275 error = fget(td, kev->ident,
1276 cap_rights_init(&rights, CAP_EVENT), &fp);
1280 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1281 kev->ident, 0) != 0) {
1285 error = kqueue_expand(kq, fops, kev->ident, waitok);
1291 if (fp->f_type == DTYPE_KQUEUE) {
1293 * If we add some intelligence about what we are doing,
1294 * we should be able to support events on ourselves.
1295 * We need to know when we are doing this to prevent
1296 * getting both the knlist lock and the kq lock since
1297 * they are the same thing.
1299 if (fp->f_data == kq) {
1305 * Pre-lock the filedesc before the global
1306 * lock mutex, see the comment in
1309 FILEDESC_XLOCK(td->td_proc->p_fd);
1310 filedesc_unlock = 1;
1311 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1315 if (kev->ident < kq->kq_knlistsize) {
1316 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1317 if (kev->filter == kn->kn_filter)
1321 if ((kev->flags & EV_ADD) == EV_ADD)
1322 kqueue_expand(kq, fops, kev->ident, waitok);
1327 * If possible, find an existing knote to use for this kevent.
1329 if (kev->filter == EVFILT_PROC &&
1330 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1331 /* This is an internal creation of a process tracking
1332 * note. Don't attempt to coalesce this with an
1336 } else if (kq->kq_knhashmask != 0) {
1339 list = &kq->kq_knhash[
1340 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1341 SLIST_FOREACH(kn, list, kn_link)
1342 if (kev->ident == kn->kn_id &&
1343 kev->filter == kn->kn_filter)
1348 /* knote is in the process of changing, wait for it to stabilize. */
1349 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1350 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1351 if (filedesc_unlock) {
1352 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1353 filedesc_unlock = 0;
1355 kq->kq_state |= KQ_FLUXWAIT;
1356 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1365 * kn now contains the matching knote, or NULL if no match
1368 if (kev->flags & EV_ADD) {
1380 * apply reference counts to knote structure, and
1381 * do not release it at the end of this routine.
1386 kn->kn_sfflags = kev->fflags;
1387 kn->kn_sdata = kev->data;
1390 kn->kn_kevent = *kev;
1391 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1392 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1393 kn->kn_status = KN_INFLUX|KN_DETACHED;
1395 error = knote_attach(kn, kq);
1402 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1406 knl = kn_list_lock(kn);
1409 /* No matching knote and the EV_ADD flag is not set. */
1416 if (kev->flags & EV_DELETE) {
1417 kn->kn_status |= KN_INFLUX;
1419 if (!(kn->kn_status & KN_DETACHED))
1420 kn->kn_fop->f_detach(kn);
1425 if (kev->flags & EV_FORCEONESHOT) {
1426 kn->kn_flags |= EV_ONESHOT;
1427 KNOTE_ACTIVATE(kn, 1);
1431 * The user may change some filter values after the initial EV_ADD,
1432 * but doing so will not reset any filter which has already been
1435 kn->kn_status |= KN_INFLUX | KN_SCAN;
1437 knl = kn_list_lock(kn);
1438 kn->kn_kevent.udata = kev->udata;
1439 if (!fops->f_isfd && fops->f_touch != NULL) {
1440 fops->f_touch(kn, kev, EVENT_REGISTER);
1442 kn->kn_sfflags = kev->fflags;
1443 kn->kn_sdata = kev->data;
1447 * We can get here with kn->kn_knlist == NULL. This can happen when
1448 * the initial attach event decides that the event is "completed"
1449 * already. i.e. filt_procattach is called on a zombie process. It
1450 * will call filt_proc which will remove it from the list, and NULL
1454 if ((kev->flags & EV_ENABLE) != 0)
1455 kn->kn_status &= ~KN_DISABLED;
1456 else if ((kev->flags & EV_DISABLE) != 0)
1457 kn->kn_status |= KN_DISABLED;
1459 if ((kn->kn_status & KN_DISABLED) == 0)
1460 event = kn->kn_fop->f_event(kn, 0);
1466 kn->kn_status |= KN_ACTIVE;
1467 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1470 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1471 kn_list_unlock(knl);
1475 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1476 if (filedesc_unlock)
1477 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1482 kqueue_fo_release(filt);
1487 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1495 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1499 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1510 kqueue_release(struct kqueue *kq, int locked)
1517 if (kq->kq_refcnt == 1)
1518 wakeup(&kq->kq_refcnt);
1524 kqueue_schedtask(struct kqueue *kq)
1528 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1529 ("scheduling kqueue task while draining"));
1531 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1532 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1533 kq->kq_state |= KQ_TASKSCHED;
1538 * Expand the kq to make sure we have storage for fops/ident pair.
1540 * Return 0 on success (or no work necessary), return errno on failure.
1542 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1543 * If kqueue_register is called from a non-fd context, there usually/should
1547 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1550 struct klist *list, *tmp_knhash, *to_free;
1551 u_long tmp_knhashmask;
1554 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1561 if (kq->kq_knlistsize <= fd) {
1562 size = kq->kq_knlistsize;
1565 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1569 if (kq->kq_knlistsize > fd) {
1573 if (kq->kq_knlist != NULL) {
1574 bcopy(kq->kq_knlist, list,
1575 kq->kq_knlistsize * sizeof(*list));
1576 to_free = kq->kq_knlist;
1577 kq->kq_knlist = NULL;
1579 bzero((caddr_t)list +
1580 kq->kq_knlistsize * sizeof(*list),
1581 (size - kq->kq_knlistsize) * sizeof(*list));
1582 kq->kq_knlistsize = size;
1583 kq->kq_knlist = list;
1588 if (kq->kq_knhashmask == 0) {
1589 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1591 if (tmp_knhash == NULL)
1594 if (kq->kq_knhashmask == 0) {
1595 kq->kq_knhash = tmp_knhash;
1596 kq->kq_knhashmask = tmp_knhashmask;
1598 to_free = tmp_knhash;
1603 free(to_free, M_KQUEUE);
1610 kqueue_task(void *arg, int pending)
1618 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1621 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1623 kq->kq_state &= ~KQ_TASKSCHED;
1624 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1625 wakeup(&kq->kq_state);
1628 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1632 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1633 * We treat KN_MARKER knotes as if they are INFLUX.
1636 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1637 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1639 struct kevent *kevp;
1640 struct knote *kn, *marker;
1642 sbintime_t asbt, rsbt;
1643 int count, error, haskqglobal, influx, nkev, touch;
1655 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1656 tsp->tv_nsec >= 1000000000) {
1660 if (timespecisset(tsp)) {
1661 if (tsp->tv_sec <= INT32_MAX) {
1662 rsbt = tstosbt(*tsp);
1663 if (TIMESEL(&asbt, rsbt))
1664 asbt += tc_tick_sbt;
1665 if (asbt <= SBT_MAX - rsbt)
1669 rsbt >>= tc_precexp;
1676 marker = knote_alloc(1);
1677 marker->kn_status = KN_MARKER;
1682 if (kq->kq_count == 0) {
1684 error = EWOULDBLOCK;
1686 kq->kq_state |= KQ_SLEEP;
1687 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1688 "kqread", asbt, rsbt, C_ABSOLUTE);
1692 /* don't restart after signals... */
1693 if (error == ERESTART)
1695 else if (error == EWOULDBLOCK)
1700 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1704 kn = TAILQ_FIRST(&kq->kq_head);
1706 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1707 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1712 kq->kq_state |= KQ_FLUXWAIT;
1713 error = msleep(kq, &kq->kq_lock, PSOCK,
1718 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1719 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1720 kn->kn_status &= ~KN_QUEUED;
1726 if (count == maxevents)
1730 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1731 ("KN_INFLUX set when not suppose to be"));
1733 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1734 kn->kn_status &= ~KN_QUEUED;
1735 kn->kn_status |= KN_INFLUX;
1739 * We don't need to lock the list since we've marked
1742 if (!(kn->kn_status & KN_DETACHED))
1743 kn->kn_fop->f_detach(kn);
1747 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1748 kn->kn_status &= ~KN_QUEUED;
1749 kn->kn_status |= KN_INFLUX;
1753 * We don't need to lock the list since we've marked
1756 *kevp = kn->kn_kevent;
1757 if (!(kn->kn_status & KN_DETACHED))
1758 kn->kn_fop->f_detach(kn);
1763 kn->kn_status |= KN_INFLUX | KN_SCAN;
1765 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1766 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1767 knl = kn_list_lock(kn);
1768 if (kn->kn_fop->f_event(kn, 0) == 0) {
1770 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1772 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1775 kn_list_unlock(knl);
1779 touch = (!kn->kn_fop->f_isfd &&
1780 kn->kn_fop->f_touch != NULL);
1782 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1784 *kevp = kn->kn_kevent;
1786 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1787 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1789 * Manually clear knotes who weren't
1792 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1796 if (kn->kn_flags & EV_DISPATCH)
1797 kn->kn_status |= KN_DISABLED;
1798 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1801 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1803 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1804 kn_list_unlock(knl);
1808 /* we are returning a copy to the user */
1813 if (nkev == KQ_NEVENTS) {
1816 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1824 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1832 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1833 td->td_retval[0] = maxevents - count;
1839 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1840 struct ucred *active_cred, struct thread *td)
1843 * Enabling sigio causes two major problems:
1844 * 1) infinite recursion:
1845 * Synopsys: kevent is being used to track signals and have FIOASYNC
1846 * set. On receipt of a signal this will cause a kqueue to recurse
1847 * into itself over and over. Sending the sigio causes the kqueue
1848 * to become ready, which in turn posts sigio again, forever.
1849 * Solution: this can be solved by setting a flag in the kqueue that
1850 * we have a SIGIO in progress.
1851 * 2) locking problems:
1852 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1853 * us above the proc and pgrp locks.
1854 * Solution: Post a signal using an async mechanism, being sure to
1855 * record a generation count in the delivery so that we do not deliver
1856 * a signal to the wrong process.
1858 * Note, these two mechanisms are somewhat mutually exclusive!
1867 kq->kq_state |= KQ_ASYNC;
1869 kq->kq_state &= ~KQ_ASYNC;
1874 return (fsetown(*(int *)data, &kq->kq_sigio));
1877 *(int *)data = fgetown(&kq->kq_sigio);
1887 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1894 if ((error = kqueue_acquire(fp, &kq)))
1898 if (events & (POLLIN | POLLRDNORM)) {
1900 revents |= events & (POLLIN | POLLRDNORM);
1902 selrecord(td, &kq->kq_sel);
1903 if (SEL_WAITING(&kq->kq_sel))
1904 kq->kq_state |= KQ_SEL;
1907 kqueue_release(kq, 1);
1914 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1918 bzero((void *)st, sizeof *st);
1920 * We no longer return kq_count because the unlocked value is useless.
1921 * If you spent all this time getting the count, why not spend your
1922 * syscall better by calling kevent?
1924 * XXX - This is needed for libc_r.
1926 st->st_mode = S_IFIFO;
1931 kqueue_drain(struct kqueue *kq, struct thread *td)
1938 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1939 ("kqueue already closing"));
1940 kq->kq_state |= KQ_CLOSING;
1941 if (kq->kq_refcnt > 1)
1942 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1944 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1946 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1947 ("kqueue's knlist not empty"));
1949 for (i = 0; i < kq->kq_knlistsize; i++) {
1950 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1951 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1952 kq->kq_state |= KQ_FLUXWAIT;
1953 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1956 kn->kn_status |= KN_INFLUX;
1958 if (!(kn->kn_status & KN_DETACHED))
1959 kn->kn_fop->f_detach(kn);
1964 if (kq->kq_knhashmask != 0) {
1965 for (i = 0; i <= kq->kq_knhashmask; i++) {
1966 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1967 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1968 kq->kq_state |= KQ_FLUXWAIT;
1969 msleep(kq, &kq->kq_lock, PSOCK,
1973 kn->kn_status |= KN_INFLUX;
1975 if (!(kn->kn_status & KN_DETACHED))
1976 kn->kn_fop->f_detach(kn);
1983 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1984 kq->kq_state |= KQ_TASKDRAIN;
1985 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1988 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1989 selwakeuppri(&kq->kq_sel, PSOCK);
1990 if (!SEL_WAITING(&kq->kq_sel))
1991 kq->kq_state &= ~KQ_SEL;
1998 kqueue_destroy(struct kqueue *kq)
2001 KASSERT(kq->kq_fdp == NULL,
2002 ("kqueue still attached to a file descriptor"));
2003 seldrain(&kq->kq_sel);
2004 knlist_destroy(&kq->kq_sel.si_note);
2005 mtx_destroy(&kq->kq_lock);
2007 if (kq->kq_knhash != NULL)
2008 free(kq->kq_knhash, M_KQUEUE);
2009 if (kq->kq_knlist != NULL)
2010 free(kq->kq_knlist, M_KQUEUE);
2012 funsetown(&kq->kq_sigio);
2017 kqueue_close(struct file *fp, struct thread *td)
2019 struct kqueue *kq = fp->f_data;
2020 struct filedesc *fdp;
2022 int filedesc_unlock;
2024 if ((error = kqueue_acquire(fp, &kq)))
2026 kqueue_drain(kq, td);
2029 * We could be called due to the knote_drop() doing fdrop(),
2030 * called from kqueue_register(). In this case the global
2031 * lock is owned, and filedesc sx is locked before, to not
2032 * take the sleepable lock after non-sleepable.
2036 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2037 FILEDESC_XLOCK(fdp);
2038 filedesc_unlock = 1;
2040 filedesc_unlock = 0;
2041 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2042 if (filedesc_unlock)
2043 FILEDESC_XUNLOCK(fdp);
2046 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2047 crfree(kq->kq_cred);
2055 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2058 kif->kf_type = KF_TYPE_KQUEUE;
2063 kqueue_wakeup(struct kqueue *kq)
2067 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2068 kq->kq_state &= ~KQ_SLEEP;
2071 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2072 selwakeuppri(&kq->kq_sel, PSOCK);
2073 if (!SEL_WAITING(&kq->kq_sel))
2074 kq->kq_state &= ~KQ_SEL;
2076 if (!knlist_empty(&kq->kq_sel.si_note))
2077 kqueue_schedtask(kq);
2078 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2079 pgsigio(&kq->kq_sigio, SIGIO, 0);
2084 * Walk down a list of knotes, activating them if their event has triggered.
2086 * There is a possibility to optimize in the case of one kq watching another.
2087 * Instead of scheduling a task to wake it up, you could pass enough state
2088 * down the chain to make up the parent kqueue. Make this code functional
2092 knote(struct knlist *list, long hint, int lockflags)
2095 struct knote *kn, *tkn;
2102 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2104 if ((lockflags & KNF_LISTLOCKED) == 0)
2105 list->kl_lock(list->kl_lockarg);
2108 * If we unlock the list lock (and set KN_INFLUX), we can
2109 * eliminate the kqueue scheduling, but this will introduce
2110 * four lock/unlock's for each knote to test. Also, marker
2111 * would be needed to keep iteration position, since filters
2112 * or other threads could remove events.
2114 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2117 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
2119 * Do not process the influx notes, except for
2120 * the influx coming from the kq unlock in the
2121 * kqueue_scan(). In the later case, we do
2122 * not interfere with the scan, since the code
2123 * fragment in kqueue_scan() locks the knlist,
2124 * and cannot proceed until we finished.
2127 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2128 own_influx = (kn->kn_status & KN_INFLUX) == 0;
2130 kn->kn_status |= KN_INFLUX;
2132 error = kn->kn_fop->f_event(kn, hint);
2135 kn->kn_status &= ~KN_INFLUX;
2137 KNOTE_ACTIVATE(kn, 1);
2140 kn->kn_status |= KN_HASKQLOCK;
2141 if (kn->kn_fop->f_event(kn, hint))
2142 KNOTE_ACTIVATE(kn, 1);
2143 kn->kn_status &= ~KN_HASKQLOCK;
2147 if ((lockflags & KNF_LISTLOCKED) == 0)
2148 list->kl_unlock(list->kl_lockarg);
2152 * add a knote to a knlist
2155 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2157 KNL_ASSERT_LOCK(knl, islocked);
2158 KQ_NOTOWNED(kn->kn_kq);
2159 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
2160 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
2162 knl->kl_lock(knl->kl_lockarg);
2163 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2165 knl->kl_unlock(knl->kl_lockarg);
2167 kn->kn_knlist = knl;
2168 kn->kn_status &= ~KN_DETACHED;
2169 KQ_UNLOCK(kn->kn_kq);
2173 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2176 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2177 KNL_ASSERT_LOCK(knl, knlislocked);
2178 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2180 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2181 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2183 knl->kl_lock(knl->kl_lockarg);
2184 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2185 kn->kn_knlist = NULL;
2187 kn_list_unlock(knl);
2190 kn->kn_status |= KN_DETACHED;
2192 KQ_UNLOCK(kn->kn_kq);
2196 * remove knote from the specified knlist
2199 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2202 knlist_remove_kq(knl, kn, islocked, 0);
2206 knlist_empty(struct knlist *knl)
2209 KNL_ASSERT_LOCKED(knl);
2210 return (SLIST_EMPTY(&knl->kl_list));
2213 static struct mtx knlist_lock;
2214 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2216 static void knlist_mtx_lock(void *arg);
2217 static void knlist_mtx_unlock(void *arg);
2220 knlist_mtx_lock(void *arg)
2223 mtx_lock((struct mtx *)arg);
2227 knlist_mtx_unlock(void *arg)
2230 mtx_unlock((struct mtx *)arg);
2234 knlist_mtx_assert_locked(void *arg)
2237 mtx_assert((struct mtx *)arg, MA_OWNED);
2241 knlist_mtx_assert_unlocked(void *arg)
2244 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2248 knlist_rw_rlock(void *arg)
2251 rw_rlock((struct rwlock *)arg);
2255 knlist_rw_runlock(void *arg)
2258 rw_runlock((struct rwlock *)arg);
2262 knlist_rw_assert_locked(void *arg)
2265 rw_assert((struct rwlock *)arg, RA_LOCKED);
2269 knlist_rw_assert_unlocked(void *arg)
2272 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2276 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2277 void (*kl_unlock)(void *),
2278 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2282 knl->kl_lockarg = &knlist_lock;
2284 knl->kl_lockarg = lock;
2286 if (kl_lock == NULL)
2287 knl->kl_lock = knlist_mtx_lock;
2289 knl->kl_lock = kl_lock;
2290 if (kl_unlock == NULL)
2291 knl->kl_unlock = knlist_mtx_unlock;
2293 knl->kl_unlock = kl_unlock;
2294 if (kl_assert_locked == NULL)
2295 knl->kl_assert_locked = knlist_mtx_assert_locked;
2297 knl->kl_assert_locked = kl_assert_locked;
2298 if (kl_assert_unlocked == NULL)
2299 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2301 knl->kl_assert_unlocked = kl_assert_unlocked;
2303 knl->kl_autodestroy = 0;
2304 SLIST_INIT(&knl->kl_list);
2308 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2311 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2315 knlist_alloc(struct mtx *lock)
2319 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2320 knlist_init_mtx(knl, lock);
2325 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2328 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2329 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2333 knlist_destroy(struct knlist *knl)
2336 KASSERT(KNLIST_EMPTY(knl),
2337 ("destroying knlist %p with knotes on it", knl));
2341 knlist_detach(struct knlist *knl)
2344 KNL_ASSERT_LOCKED(knl);
2345 knl->kl_autodestroy = 1;
2346 if (knlist_empty(knl)) {
2347 knlist_destroy(knl);
2348 free(knl, M_KQUEUE);
2353 * Even if we are locked, we may need to drop the lock to allow any influx
2354 * knotes time to "settle".
2357 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2359 struct knote *kn, *kn2;
2362 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2364 KNL_ASSERT_LOCKED(knl);
2366 KNL_ASSERT_UNLOCKED(knl);
2367 again: /* need to reacquire lock since we have dropped it */
2368 knl->kl_lock(knl->kl_lockarg);
2371 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2374 if ((kn->kn_status & KN_INFLUX)) {
2378 knlist_remove_kq(knl, kn, 1, 1);
2380 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2384 /* Make sure cleared knotes disappear soon */
2385 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2391 if (!SLIST_EMPTY(&knl->kl_list)) {
2392 /* there are still KN_INFLUX remaining */
2393 kn = SLIST_FIRST(&knl->kl_list);
2396 KASSERT(kn->kn_status & KN_INFLUX,
2397 ("knote removed w/o list lock"));
2398 knl->kl_unlock(knl->kl_lockarg);
2399 kq->kq_state |= KQ_FLUXWAIT;
2400 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2406 KNL_ASSERT_LOCKED(knl);
2408 knl->kl_unlock(knl->kl_lockarg);
2409 KNL_ASSERT_UNLOCKED(knl);
2414 * Remove all knotes referencing a specified fd must be called with FILEDESC
2415 * lock. This prevents a race where a new fd comes along and occupies the
2416 * entry and we attach a knote to the fd.
2419 knote_fdclose(struct thread *td, int fd)
2421 struct filedesc *fdp = td->td_proc->p_fd;
2426 FILEDESC_XLOCK_ASSERT(fdp);
2429 * We shouldn't have to worry about new kevents appearing on fd
2430 * since filedesc is locked.
2432 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2437 while (kq->kq_knlistsize > fd &&
2438 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2439 if (kn->kn_status & KN_INFLUX) {
2440 /* someone else might be waiting on our knote */
2443 kq->kq_state |= KQ_FLUXWAIT;
2444 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2447 kn->kn_status |= KN_INFLUX;
2449 if (!(kn->kn_status & KN_DETACHED))
2450 kn->kn_fop->f_detach(kn);
2460 knote_attach(struct knote *kn, struct kqueue *kq)
2464 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2467 if (kn->kn_fop->f_isfd) {
2468 if (kn->kn_id >= kq->kq_knlistsize)
2470 list = &kq->kq_knlist[kn->kn_id];
2472 if (kq->kq_knhash == NULL)
2474 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2476 SLIST_INSERT_HEAD(list, kn, kn_link);
2481 * knote must already have been detached using the f_detach method.
2482 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2483 * to prevent other removal.
2486 knote_drop(struct knote *kn, struct thread *td)
2494 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2495 ("knote_drop called without KN_INFLUX set in kn_status"));
2498 if (kn->kn_fop->f_isfd)
2499 list = &kq->kq_knlist[kn->kn_id];
2501 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2503 if (!SLIST_EMPTY(list))
2504 SLIST_REMOVE(list, kn, knote, kn_link);
2505 if (kn->kn_status & KN_QUEUED)
2509 if (kn->kn_fop->f_isfd) {
2510 fdrop(kn->kn_fp, td);
2513 kqueue_fo_release(kn->kn_kevent.filter);
2519 knote_enqueue(struct knote *kn)
2521 struct kqueue *kq = kn->kn_kq;
2523 KQ_OWNED(kn->kn_kq);
2524 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2526 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2527 kn->kn_status |= KN_QUEUED;
2533 knote_dequeue(struct knote *kn)
2535 struct kqueue *kq = kn->kn_kq;
2537 KQ_OWNED(kn->kn_kq);
2538 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2540 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2541 kn->kn_status &= ~KN_QUEUED;
2549 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2550 NULL, NULL, UMA_ALIGN_PTR, 0);
2552 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2554 static struct knote *
2555 knote_alloc(int waitok)
2558 return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2563 knote_free(struct knote *kn)
2566 uma_zfree(knote_zone, kn);
2570 * Register the kev w/ the kq specified by fd.
2573 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2577 cap_rights_t rights;
2580 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2583 if ((error = kqueue_acquire(fp, &kq)) != 0)
2586 error = kqueue_register(kq, kev, td, waitok);
2587 kqueue_release(kq, 0);