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)
502 memset(&kev, 0, sizeof(kev));
503 list->kl_lock(list->kl_lockarg);
504 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
507 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
513 * The same as knote(), activate the event.
515 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
516 kn->kn_status |= KN_HASKQLOCK;
517 if (kn->kn_fop->f_event(kn, NOTE_FORK))
518 KNOTE_ACTIVATE(kn, 1);
519 kn->kn_status &= ~KN_HASKQLOCK;
525 * The NOTE_TRACK case. In addition to the activation
526 * of the event, we need to register new events to
527 * track the child. Drop the locks in preparation for
528 * the call to kqueue_register().
530 kn->kn_status |= KN_INFLUX;
532 list->kl_unlock(list->kl_lockarg);
535 * Activate existing knote and register tracking knotes with
538 * First register a knote to get just the child notice. This
539 * must be a separate note from a potential NOTE_EXIT
540 * notification since both NOTE_CHILD and NOTE_EXIT are defined
541 * to use the data field (in conflicting ways).
544 kev.filter = kn->kn_filter;
545 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
547 kev.fflags = kn->kn_sfflags;
548 kev.data = kn->kn_id; /* parent */
549 kev.udata = kn->kn_kevent.udata;/* preserve udata */
550 error = kqueue_register(kq, &kev, NULL, 0);
552 kn->kn_fflags |= NOTE_TRACKERR;
555 * Then register another knote to track other potential events
556 * from the new process.
559 kev.filter = kn->kn_filter;
560 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
561 kev.fflags = kn->kn_sfflags;
562 kev.data = kn->kn_id; /* parent */
563 kev.udata = kn->kn_kevent.udata;/* preserve udata */
564 error = kqueue_register(kq, &kev, NULL, 0);
566 kn->kn_fflags |= NOTE_TRACKERR;
567 if (kn->kn_fop->f_event(kn, NOTE_FORK))
568 KNOTE_ACTIVATE(kn, 0);
569 list->kl_lock(list->kl_lockarg);
571 kn->kn_status &= ~KN_INFLUX;
574 list->kl_unlock(list->kl_lockarg);
578 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
579 * interval timer support code.
582 #define NOTE_TIMER_PRECMASK \
583 (NOTE_SECONDS | NOTE_MSECONDS | NOTE_USECONDS | NOTE_NSECONDS)
586 timer2sbintime(intptr_t data, int flags)
591 * Macros for converting to the fractional second portion of an
592 * sbintime_t using 64bit multiplication to improve precision.
594 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
595 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
596 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
597 switch (flags & NOTE_TIMER_PRECMASK) {
600 if (data > (SBT_MAX / SBT_1S))
603 return ((sbintime_t)data << 32);
604 case NOTE_MSECONDS: /* FALLTHROUGH */
609 if (secs > (SBT_MAX / SBT_1S))
612 return (secs << 32 | MS_TO_SBT(data % 1000));
614 return (MS_TO_SBT(data));
616 if (data >= 1000000) {
617 secs = data / 1000000;
619 if (secs > (SBT_MAX / SBT_1S))
622 return (secs << 32 | US_TO_SBT(data % 1000000));
624 return (US_TO_SBT(data));
626 if (data >= 1000000000) {
627 secs = data / 1000000000;
629 if (secs > (SBT_MAX / SBT_1S))
632 return (secs << 32 | US_TO_SBT(data % 1000000000));
634 return (NS_TO_SBT(data));
641 struct kq_timer_cb_data {
643 sbintime_t next; /* next timer event fires at */
644 sbintime_t to; /* precalculated timer period */
648 filt_timerexpire(void *knx)
651 struct kq_timer_cb_data *kc;
655 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
657 if ((kn->kn_flags & EV_ONESHOT) != 0)
662 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
663 PCPU_GET(cpuid), C_ABSOLUTE);
667 * data contains amount of time to sleep
670 filt_timervalidate(struct knote *kn, sbintime_t *to)
673 if (kn->kn_sdata < 0)
675 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
678 * The only fflags values supported are the timer unit
679 * (precision) and the absolute time indicator.
681 if ((kn->kn_sfflags & ~NOTE_TIMER_PRECMASK) != 0)
684 *to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
691 filt_timerattach(struct knote *kn)
693 struct kq_timer_cb_data *kc;
695 unsigned int ncallouts;
698 error = filt_timervalidate(kn, &to);
703 ncallouts = kq_ncallouts;
704 if (ncallouts >= kq_calloutmax)
706 } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
708 kn->kn_flags |= EV_CLEAR; /* automatically set */
709 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
710 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
711 callout_init(&kc->c, 1);
712 filt_timerstart(kn, to);
718 filt_timerstart(struct knote *kn, sbintime_t to)
720 struct kq_timer_cb_data *kc;
723 kc->next = to + sbinuptime();
725 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
726 PCPU_GET(cpuid), C_ABSOLUTE);
730 filt_timerdetach(struct knote *kn)
732 struct kq_timer_cb_data *kc;
736 callout_drain(&kc->c);
738 old = atomic_fetchadd_int(&kq_ncallouts, -1);
739 KASSERT(old > 0, ("Number of callouts cannot become negative"));
740 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
744 filt_timertouch(struct knote *kn, struct kevent *kev, u_long type)
746 struct kq_timer_cb_data *kc;
753 /* Handle re-added timers that update data/fflags */
754 if (kev->flags & EV_ADD) {
757 /* Drain any existing callout. */
758 callout_drain(&kc->c);
760 /* Throw away any existing undelivered record
761 * of the timer expiration. This is done under
762 * the presumption that if a process is
763 * re-adding this timer with new parameters,
764 * it is no longer interested in what may have
765 * happened under the old parameters. If it is
766 * interested, it can wait for the expiration,
767 * delete the old timer definition, and then
770 * This has to be done while the kq is locked:
771 * - if enqueued, dequeue
772 * - make it no longer active
773 * - clear the count of expiration events
777 if (kn->kn_status & KN_QUEUED)
780 kn->kn_status &= ~KN_ACTIVE;
784 /* Reschedule timer based on new data/fflags */
785 kn->kn_sfflags = kev->fflags;
786 kn->kn_sdata = kev->data;
787 error = filt_timervalidate(kn, &to);
789 kn->kn_flags |= EV_ERROR;
792 filt_timerstart(kn, to);
797 *kev = kn->kn_kevent;
798 if (kn->kn_flags & EV_CLEAR) {
805 panic("filt_timertouch() - invalid type (%ld)", type);
811 filt_timer(struct knote *kn, long hint)
814 return (kn->kn_data != 0);
818 filt_userattach(struct knote *kn)
822 * EVFILT_USER knotes are not attached to anything in the kernel.
825 if (kn->kn_fflags & NOTE_TRIGGER)
833 filt_userdetach(__unused struct knote *kn)
837 * EVFILT_USER knotes are not attached to anything in the kernel.
842 filt_user(struct knote *kn, __unused long hint)
845 return (kn->kn_hookid);
849 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
855 if (kev->fflags & NOTE_TRIGGER)
858 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
859 kev->fflags &= NOTE_FFLAGSMASK;
865 kn->kn_sfflags &= kev->fflags;
869 kn->kn_sfflags |= kev->fflags;
873 kn->kn_sfflags = kev->fflags;
877 /* XXX Return error? */
880 kn->kn_sdata = kev->data;
881 if (kev->flags & EV_CLEAR) {
889 *kev = kn->kn_kevent;
890 kev->fflags = kn->kn_sfflags;
891 kev->data = kn->kn_sdata;
892 if (kn->kn_flags & EV_CLEAR) {
900 panic("filt_usertouch() - invalid type (%ld)", type);
906 sys_kqueue(struct thread *td, struct kqueue_args *uap)
909 return (kern_kqueue(td, 0, NULL));
913 kqueue_init(struct kqueue *kq)
916 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
917 TAILQ_INIT(&kq->kq_head);
918 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
919 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
923 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
925 struct filedesc *fdp;
931 fdp = td->td_proc->p_fd;
933 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
936 error = falloc_caps(td, &fp, &fd, flags, fcaps);
938 chgkqcnt(cred->cr_ruidinfo, -1, 0);
942 /* An extra reference on `fp' has been held for us by falloc(). */
943 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
946 kq->kq_cred = crhold(cred);
949 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
950 FILEDESC_XUNLOCK(fdp);
952 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
955 td->td_retval[0] = fd;
959 #ifndef _SYS_SYSPROTO_H_
962 const struct kevent *changelist;
964 struct kevent *eventlist;
966 const struct timespec *timeout;
970 sys_kevent(struct thread *td, struct kevent_args *uap)
972 struct timespec ts, *tsp;
973 struct kevent_copyops k_ops = {
975 .k_copyout = kevent_copyout,
976 .k_copyin = kevent_copyin,
979 struct kevent *eventlist = uap->eventlist;
983 if (uap->timeout != NULL) {
984 error = copyin(uap->timeout, &ts, sizeof(ts));
992 if (KTRPOINT(td, KTR_STRUCT_ARRAY))
993 ktrstructarray("kevent", UIO_USERSPACE, uap->changelist,
994 uap->nchanges, sizeof(struct kevent));
997 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
1001 if (error == 0 && KTRPOINT(td, KTR_STRUCT_ARRAY))
1002 ktrstructarray("kevent", UIO_USERSPACE, eventlist,
1003 td->td_retval[0], sizeof(struct kevent));
1010 * Copy 'count' items into the destination list pointed to by uap->eventlist.
1013 kevent_copyout(void *arg, struct kevent *kevp, int count)
1015 struct kevent_args *uap;
1018 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1019 uap = (struct kevent_args *)arg;
1021 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
1023 uap->eventlist += count;
1028 * Copy 'count' items from the list pointed to by uap->changelist.
1031 kevent_copyin(void *arg, struct kevent *kevp, int count)
1033 struct kevent_args *uap;
1036 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
1037 uap = (struct kevent_args *)arg;
1039 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1041 uap->changelist += count;
1046 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1047 struct kevent_copyops *k_ops, const struct timespec *timeout)
1049 cap_rights_t rights;
1053 cap_rights_init(&rights);
1055 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
1057 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
1058 error = fget(td, fd, &rights, &fp);
1062 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1069 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1070 struct kevent_copyops *k_ops, const struct timespec *timeout)
1072 struct kevent keva[KQ_NEVENTS];
1073 struct kevent *kevp, *changes;
1074 int i, n, nerrors, error;
1077 while (nchanges > 0) {
1078 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1079 error = k_ops->k_copyin(k_ops->arg, keva, n);
1083 for (i = 0; i < n; i++) {
1087 kevp->flags &= ~EV_SYSFLAGS;
1088 error = kqueue_register(kq, kevp, td, 1);
1089 if (error || (kevp->flags & EV_RECEIPT)) {
1092 kevp->flags = EV_ERROR;
1094 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1102 td->td_retval[0] = nerrors;
1106 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1110 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1111 struct kevent_copyops *k_ops, const struct timespec *timeout)
1116 error = kqueue_acquire(fp, &kq);
1119 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1120 kqueue_release(kq, 0);
1125 * Performs a kevent() call on a temporarily created kqueue. This can be
1126 * used to perform one-shot polling, similar to poll() and select().
1129 kern_kevent_anonymous(struct thread *td, int nevents,
1130 struct kevent_copyops *k_ops)
1132 struct kqueue kq = {};
1137 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1138 kqueue_drain(&kq, td);
1139 kqueue_destroy(&kq);
1144 kqueue_add_filteropts(int filt, struct filterops *filtops)
1149 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1151 "trying to add a filterop that is out of range: %d is beyond %d\n",
1152 ~filt, EVFILT_SYSCOUNT);
1155 mtx_lock(&filterops_lock);
1156 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1157 sysfilt_ops[~filt].for_fop != NULL)
1160 sysfilt_ops[~filt].for_fop = filtops;
1161 sysfilt_ops[~filt].for_refcnt = 0;
1163 mtx_unlock(&filterops_lock);
1169 kqueue_del_filteropts(int filt)
1174 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1177 mtx_lock(&filterops_lock);
1178 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1179 sysfilt_ops[~filt].for_fop == NULL)
1181 else if (sysfilt_ops[~filt].for_refcnt != 0)
1184 sysfilt_ops[~filt].for_fop = &null_filtops;
1185 sysfilt_ops[~filt].for_refcnt = 0;
1187 mtx_unlock(&filterops_lock);
1192 static struct filterops *
1193 kqueue_fo_find(int filt)
1196 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1199 if (sysfilt_ops[~filt].for_nolock)
1200 return sysfilt_ops[~filt].for_fop;
1202 mtx_lock(&filterops_lock);
1203 sysfilt_ops[~filt].for_refcnt++;
1204 if (sysfilt_ops[~filt].for_fop == NULL)
1205 sysfilt_ops[~filt].for_fop = &null_filtops;
1206 mtx_unlock(&filterops_lock);
1208 return sysfilt_ops[~filt].for_fop;
1212 kqueue_fo_release(int filt)
1215 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1218 if (sysfilt_ops[~filt].for_nolock)
1221 mtx_lock(&filterops_lock);
1222 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1223 ("filter object refcount not valid on release"));
1224 sysfilt_ops[~filt].for_refcnt--;
1225 mtx_unlock(&filterops_lock);
1229 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1230 * influence if memory allocation should wait. Make sure it is 0 if you
1234 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1236 struct filterops *fops;
1238 struct knote *kn, *tkn;
1240 cap_rights_t rights;
1241 int error, filt, event;
1242 int haskqglobal, filedesc_unlock;
1244 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1252 filedesc_unlock = 0;
1255 fops = kqueue_fo_find(filt);
1259 if (kev->flags & EV_ADD) {
1261 * Prevent waiting with locks. Non-sleepable
1262 * allocation failures are handled in the loop, only
1263 * if the spare knote appears to be actually required.
1265 tkn = knote_alloc(waitok);
1272 KASSERT(td != NULL, ("td is NULL"));
1273 if (kev->ident > INT_MAX)
1276 error = fget(td, kev->ident,
1277 cap_rights_init(&rights, CAP_EVENT), &fp);
1281 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1282 kev->ident, 0) != 0) {
1286 error = kqueue_expand(kq, fops, kev->ident, waitok);
1292 if (fp->f_type == DTYPE_KQUEUE) {
1294 * If we add some intelligence about what we are doing,
1295 * we should be able to support events on ourselves.
1296 * We need to know when we are doing this to prevent
1297 * getting both the knlist lock and the kq lock since
1298 * they are the same thing.
1300 if (fp->f_data == kq) {
1306 * Pre-lock the filedesc before the global
1307 * lock mutex, see the comment in
1310 FILEDESC_XLOCK(td->td_proc->p_fd);
1311 filedesc_unlock = 1;
1312 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1316 if (kev->ident < kq->kq_knlistsize) {
1317 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1318 if (kev->filter == kn->kn_filter)
1322 if ((kev->flags & EV_ADD) == EV_ADD) {
1323 error = kqueue_expand(kq, fops, kev->ident, waitok);
1331 * If possible, find an existing knote to use for this kevent.
1333 if (kev->filter == EVFILT_PROC &&
1334 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1335 /* This is an internal creation of a process tracking
1336 * note. Don't attempt to coalesce this with an
1340 } else if (kq->kq_knhashmask != 0) {
1343 list = &kq->kq_knhash[
1344 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1345 SLIST_FOREACH(kn, list, kn_link)
1346 if (kev->ident == kn->kn_id &&
1347 kev->filter == kn->kn_filter)
1352 /* knote is in the process of changing, wait for it to stabilize. */
1353 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1354 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1355 if (filedesc_unlock) {
1356 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1357 filedesc_unlock = 0;
1359 kq->kq_state |= KQ_FLUXWAIT;
1360 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1369 * kn now contains the matching knote, or NULL if no match
1372 if (kev->flags & EV_ADD) {
1384 * apply reference counts to knote structure, and
1385 * do not release it at the end of this routine.
1390 kn->kn_sfflags = kev->fflags;
1391 kn->kn_sdata = kev->data;
1394 kn->kn_kevent = *kev;
1395 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1396 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1397 kn->kn_status = KN_INFLUX|KN_DETACHED;
1398 if ((kev->flags & EV_DISABLE) != 0)
1399 kn->kn_status |= KN_DISABLED;
1401 error = knote_attach(kn, kq);
1408 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1412 knl = kn_list_lock(kn);
1415 /* No matching knote and the EV_ADD flag is not set. */
1422 if (kev->flags & EV_DELETE) {
1423 kn->kn_status |= KN_INFLUX;
1425 if (!(kn->kn_status & KN_DETACHED))
1426 kn->kn_fop->f_detach(kn);
1431 if (kev->flags & EV_FORCEONESHOT) {
1432 kn->kn_flags |= EV_ONESHOT;
1433 KNOTE_ACTIVATE(kn, 1);
1436 if ((kev->flags & EV_ENABLE) != 0)
1437 kn->kn_status &= ~KN_DISABLED;
1438 else if ((kev->flags & EV_DISABLE) != 0)
1439 kn->kn_status |= KN_DISABLED;
1442 * The user may change some filter values after the initial EV_ADD,
1443 * but doing so will not reset any filter which has already been
1446 kn->kn_status |= KN_INFLUX | KN_SCAN;
1448 knl = kn_list_lock(kn);
1449 kn->kn_kevent.udata = kev->udata;
1450 if (!fops->f_isfd && fops->f_touch != NULL) {
1451 fops->f_touch(kn, kev, EVENT_REGISTER);
1453 kn->kn_sfflags = kev->fflags;
1454 kn->kn_sdata = kev->data;
1459 * We can get here with kn->kn_knlist == NULL. This can happen when
1460 * the initial attach event decides that the event is "completed"
1461 * already, e.g., filt_procattach() is called on a zombie process. It
1462 * will call filt_proc() which will remove it from the list, and NULL
1465 * KN_DISABLED will be stable while the knote is in flux, so the
1466 * unlocked read will not race with an update.
1468 if ((kn->kn_status & KN_DISABLED) == 0)
1469 event = kn->kn_fop->f_event(kn, 0);
1475 kn->kn_status |= KN_ACTIVE;
1476 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1479 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1480 kn_list_unlock(knl);
1484 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1485 if (filedesc_unlock)
1486 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1491 kqueue_fo_release(filt);
1496 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1504 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1508 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1519 kqueue_release(struct kqueue *kq, int locked)
1526 if (kq->kq_refcnt == 1)
1527 wakeup(&kq->kq_refcnt);
1533 kqueue_schedtask(struct kqueue *kq)
1537 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1538 ("scheduling kqueue task while draining"));
1540 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1541 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1542 kq->kq_state |= KQ_TASKSCHED;
1547 * Expand the kq to make sure we have storage for fops/ident pair.
1549 * Return 0 on success (or no work necessary), return errno on failure.
1551 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1552 * If kqueue_register is called from a non-fd context, there usually/should
1556 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1559 struct klist *list, *tmp_knhash, *to_free;
1560 u_long tmp_knhashmask;
1561 int error, fd, size;
1562 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1570 if (kq->kq_knlistsize <= fd) {
1571 size = kq->kq_knlistsize;
1574 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1578 if ((kq->kq_state & KQ_CLOSING) != 0) {
1581 } else if (kq->kq_knlistsize > fd) {
1584 if (kq->kq_knlist != NULL) {
1585 bcopy(kq->kq_knlist, list,
1586 kq->kq_knlistsize * sizeof(*list));
1587 to_free = kq->kq_knlist;
1588 kq->kq_knlist = NULL;
1590 bzero((caddr_t)list +
1591 kq->kq_knlistsize * sizeof(*list),
1592 (size - kq->kq_knlistsize) * sizeof(*list));
1593 kq->kq_knlistsize = size;
1594 kq->kq_knlist = list;
1599 if (kq->kq_knhashmask == 0) {
1600 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1602 if (tmp_knhash == NULL)
1605 if ((kq->kq_state & KQ_CLOSING) != 0) {
1606 to_free = tmp_knhash;
1608 } else if (kq->kq_knhashmask == 0) {
1609 kq->kq_knhash = tmp_knhash;
1610 kq->kq_knhashmask = tmp_knhashmask;
1612 to_free = tmp_knhash;
1617 free(to_free, M_KQUEUE);
1624 kqueue_task(void *arg, int pending)
1632 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1635 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1637 kq->kq_state &= ~KQ_TASKSCHED;
1638 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1639 wakeup(&kq->kq_state);
1642 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1646 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1647 * We treat KN_MARKER knotes as if they are INFLUX.
1650 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1651 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1653 struct kevent *kevp;
1654 struct knote *kn, *marker;
1656 sbintime_t asbt, rsbt;
1657 int count, error, haskqglobal, influx, nkev, touch;
1669 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1670 tsp->tv_nsec >= 1000000000) {
1674 if (timespecisset(tsp)) {
1675 if (tsp->tv_sec <= INT32_MAX) {
1676 rsbt = tstosbt(*tsp);
1677 if (TIMESEL(&asbt, rsbt))
1678 asbt += tc_tick_sbt;
1679 if (asbt <= SBT_MAX - rsbt)
1683 rsbt >>= tc_precexp;
1690 marker = knote_alloc(1);
1691 marker->kn_status = KN_MARKER;
1696 if (kq->kq_count == 0) {
1698 error = EWOULDBLOCK;
1700 kq->kq_state |= KQ_SLEEP;
1701 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1702 "kqread", asbt, rsbt, C_ABSOLUTE);
1706 /* don't restart after signals... */
1707 if (error == ERESTART)
1709 else if (error == EWOULDBLOCK)
1714 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1718 kn = TAILQ_FIRST(&kq->kq_head);
1720 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1721 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1726 kq->kq_state |= KQ_FLUXWAIT;
1727 error = msleep(kq, &kq->kq_lock, PSOCK,
1732 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1733 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1734 kn->kn_status &= ~KN_QUEUED;
1740 if (count == maxevents)
1744 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1745 ("KN_INFLUX set when not suppose to be"));
1747 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
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 if (!(kn->kn_status & KN_DETACHED))
1757 kn->kn_fop->f_detach(kn);
1761 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1762 kn->kn_status &= ~KN_QUEUED;
1763 kn->kn_status |= KN_INFLUX;
1767 * We don't need to lock the list since we've marked
1770 *kevp = kn->kn_kevent;
1771 if (!(kn->kn_status & KN_DETACHED))
1772 kn->kn_fop->f_detach(kn);
1777 kn->kn_status |= KN_INFLUX | KN_SCAN;
1779 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1780 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1781 knl = kn_list_lock(kn);
1782 if (kn->kn_fop->f_event(kn, 0) == 0) {
1784 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1786 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1789 kn_list_unlock(knl);
1793 touch = (!kn->kn_fop->f_isfd &&
1794 kn->kn_fop->f_touch != NULL);
1796 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1798 *kevp = kn->kn_kevent;
1800 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1801 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1803 * Manually clear knotes who weren't
1806 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1810 if (kn->kn_flags & EV_DISPATCH)
1811 kn->kn_status |= KN_DISABLED;
1812 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1815 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1817 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1818 kn_list_unlock(knl);
1822 /* we are returning a copy to the user */
1827 if (nkev == KQ_NEVENTS) {
1830 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1838 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1846 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1847 td->td_retval[0] = maxevents - count;
1853 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1854 struct ucred *active_cred, struct thread *td)
1857 * Enabling sigio causes two major problems:
1858 * 1) infinite recursion:
1859 * Synopsys: kevent is being used to track signals and have FIOASYNC
1860 * set. On receipt of a signal this will cause a kqueue to recurse
1861 * into itself over and over. Sending the sigio causes the kqueue
1862 * to become ready, which in turn posts sigio again, forever.
1863 * Solution: this can be solved by setting a flag in the kqueue that
1864 * we have a SIGIO in progress.
1865 * 2) locking problems:
1866 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1867 * us above the proc and pgrp locks.
1868 * Solution: Post a signal using an async mechanism, being sure to
1869 * record a generation count in the delivery so that we do not deliver
1870 * a signal to the wrong process.
1872 * Note, these two mechanisms are somewhat mutually exclusive!
1881 kq->kq_state |= KQ_ASYNC;
1883 kq->kq_state &= ~KQ_ASYNC;
1888 return (fsetown(*(int *)data, &kq->kq_sigio));
1891 *(int *)data = fgetown(&kq->kq_sigio);
1901 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1908 if ((error = kqueue_acquire(fp, &kq)))
1912 if (events & (POLLIN | POLLRDNORM)) {
1914 revents |= events & (POLLIN | POLLRDNORM);
1916 selrecord(td, &kq->kq_sel);
1917 if (SEL_WAITING(&kq->kq_sel))
1918 kq->kq_state |= KQ_SEL;
1921 kqueue_release(kq, 1);
1928 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1932 bzero((void *)st, sizeof *st);
1934 * We no longer return kq_count because the unlocked value is useless.
1935 * If you spent all this time getting the count, why not spend your
1936 * syscall better by calling kevent?
1938 * XXX - This is needed for libc_r.
1940 st->st_mode = S_IFIFO;
1945 kqueue_drain(struct kqueue *kq, struct thread *td)
1952 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1953 ("kqueue already closing"));
1954 kq->kq_state |= KQ_CLOSING;
1955 if (kq->kq_refcnt > 1)
1956 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1958 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1960 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1961 ("kqueue's knlist not empty"));
1963 for (i = 0; i < kq->kq_knlistsize; i++) {
1964 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1965 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1966 kq->kq_state |= KQ_FLUXWAIT;
1967 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1970 kn->kn_status |= KN_INFLUX;
1972 if (!(kn->kn_status & KN_DETACHED))
1973 kn->kn_fop->f_detach(kn);
1978 if (kq->kq_knhashmask != 0) {
1979 for (i = 0; i <= kq->kq_knhashmask; i++) {
1980 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1981 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1982 kq->kq_state |= KQ_FLUXWAIT;
1983 msleep(kq, &kq->kq_lock, PSOCK,
1987 kn->kn_status |= KN_INFLUX;
1989 if (!(kn->kn_status & KN_DETACHED))
1990 kn->kn_fop->f_detach(kn);
1997 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1998 kq->kq_state |= KQ_TASKDRAIN;
1999 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
2002 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2003 selwakeuppri(&kq->kq_sel, PSOCK);
2004 if (!SEL_WAITING(&kq->kq_sel))
2005 kq->kq_state &= ~KQ_SEL;
2012 kqueue_destroy(struct kqueue *kq)
2015 KASSERT(kq->kq_fdp == NULL,
2016 ("kqueue still attached to a file descriptor"));
2017 seldrain(&kq->kq_sel);
2018 knlist_destroy(&kq->kq_sel.si_note);
2019 mtx_destroy(&kq->kq_lock);
2021 if (kq->kq_knhash != NULL)
2022 free(kq->kq_knhash, M_KQUEUE);
2023 if (kq->kq_knlist != NULL)
2024 free(kq->kq_knlist, M_KQUEUE);
2026 funsetown(&kq->kq_sigio);
2031 kqueue_close(struct file *fp, struct thread *td)
2033 struct kqueue *kq = fp->f_data;
2034 struct filedesc *fdp;
2036 int filedesc_unlock;
2038 if ((error = kqueue_acquire(fp, &kq)))
2040 kqueue_drain(kq, td);
2043 * We could be called due to the knote_drop() doing fdrop(),
2044 * called from kqueue_register(). In this case the global
2045 * lock is owned, and filedesc sx is locked before, to not
2046 * take the sleepable lock after non-sleepable.
2050 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
2051 FILEDESC_XLOCK(fdp);
2052 filedesc_unlock = 1;
2054 filedesc_unlock = 0;
2055 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
2056 if (filedesc_unlock)
2057 FILEDESC_XUNLOCK(fdp);
2060 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2061 crfree(kq->kq_cred);
2069 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2072 kif->kf_type = KF_TYPE_KQUEUE;
2077 kqueue_wakeup(struct kqueue *kq)
2081 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2082 kq->kq_state &= ~KQ_SLEEP;
2085 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2086 selwakeuppri(&kq->kq_sel, PSOCK);
2087 if (!SEL_WAITING(&kq->kq_sel))
2088 kq->kq_state &= ~KQ_SEL;
2090 if (!knlist_empty(&kq->kq_sel.si_note))
2091 kqueue_schedtask(kq);
2092 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2093 pgsigio(&kq->kq_sigio, SIGIO, 0);
2098 * Walk down a list of knotes, activating them if their event has triggered.
2100 * There is a possibility to optimize in the case of one kq watching another.
2101 * Instead of scheduling a task to wake it up, you could pass enough state
2102 * down the chain to make up the parent kqueue. Make this code functional
2106 knote(struct knlist *list, long hint, int lockflags)
2109 struct knote *kn, *tkn;
2116 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2118 if ((lockflags & KNF_LISTLOCKED) == 0)
2119 list->kl_lock(list->kl_lockarg);
2122 * If we unlock the list lock (and set KN_INFLUX), we can
2123 * eliminate the kqueue scheduling, but this will introduce
2124 * four lock/unlock's for each knote to test. Also, marker
2125 * would be needed to keep iteration position, since filters
2126 * or other threads could remove events.
2128 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2131 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
2133 * Do not process the influx notes, except for
2134 * the influx coming from the kq unlock in the
2135 * kqueue_scan(). In the later case, we do
2136 * not interfere with the scan, since the code
2137 * fragment in kqueue_scan() locks the knlist,
2138 * and cannot proceed until we finished.
2141 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2142 own_influx = (kn->kn_status & KN_INFLUX) == 0;
2144 kn->kn_status |= KN_INFLUX;
2146 error = kn->kn_fop->f_event(kn, hint);
2149 kn->kn_status &= ~KN_INFLUX;
2151 KNOTE_ACTIVATE(kn, 1);
2154 kn->kn_status |= KN_HASKQLOCK;
2155 if (kn->kn_fop->f_event(kn, hint))
2156 KNOTE_ACTIVATE(kn, 1);
2157 kn->kn_status &= ~KN_HASKQLOCK;
2161 if ((lockflags & KNF_LISTLOCKED) == 0)
2162 list->kl_unlock(list->kl_lockarg);
2166 * add a knote to a knlist
2169 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2171 KNL_ASSERT_LOCK(knl, islocked);
2172 KQ_NOTOWNED(kn->kn_kq);
2173 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
2174 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
2176 knl->kl_lock(knl->kl_lockarg);
2177 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2179 knl->kl_unlock(knl->kl_lockarg);
2181 kn->kn_knlist = knl;
2182 kn->kn_status &= ~KN_DETACHED;
2183 KQ_UNLOCK(kn->kn_kq);
2187 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2190 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2191 KNL_ASSERT_LOCK(knl, knlislocked);
2192 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2194 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2195 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2197 knl->kl_lock(knl->kl_lockarg);
2198 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2199 kn->kn_knlist = NULL;
2201 kn_list_unlock(knl);
2204 kn->kn_status |= KN_DETACHED;
2206 KQ_UNLOCK(kn->kn_kq);
2210 * remove knote from the specified knlist
2213 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2216 knlist_remove_kq(knl, kn, islocked, 0);
2220 knlist_empty(struct knlist *knl)
2223 KNL_ASSERT_LOCKED(knl);
2224 return (SLIST_EMPTY(&knl->kl_list));
2227 static struct mtx knlist_lock;
2228 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2230 static void knlist_mtx_lock(void *arg);
2231 static void knlist_mtx_unlock(void *arg);
2234 knlist_mtx_lock(void *arg)
2237 mtx_lock((struct mtx *)arg);
2241 knlist_mtx_unlock(void *arg)
2244 mtx_unlock((struct mtx *)arg);
2248 knlist_mtx_assert_locked(void *arg)
2251 mtx_assert((struct mtx *)arg, MA_OWNED);
2255 knlist_mtx_assert_unlocked(void *arg)
2258 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2262 knlist_rw_rlock(void *arg)
2265 rw_rlock((struct rwlock *)arg);
2269 knlist_rw_runlock(void *arg)
2272 rw_runlock((struct rwlock *)arg);
2276 knlist_rw_assert_locked(void *arg)
2279 rw_assert((struct rwlock *)arg, RA_LOCKED);
2283 knlist_rw_assert_unlocked(void *arg)
2286 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2290 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2291 void (*kl_unlock)(void *),
2292 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2296 knl->kl_lockarg = &knlist_lock;
2298 knl->kl_lockarg = lock;
2300 if (kl_lock == NULL)
2301 knl->kl_lock = knlist_mtx_lock;
2303 knl->kl_lock = kl_lock;
2304 if (kl_unlock == NULL)
2305 knl->kl_unlock = knlist_mtx_unlock;
2307 knl->kl_unlock = kl_unlock;
2308 if (kl_assert_locked == NULL)
2309 knl->kl_assert_locked = knlist_mtx_assert_locked;
2311 knl->kl_assert_locked = kl_assert_locked;
2312 if (kl_assert_unlocked == NULL)
2313 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2315 knl->kl_assert_unlocked = kl_assert_unlocked;
2317 knl->kl_autodestroy = 0;
2318 SLIST_INIT(&knl->kl_list);
2322 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2325 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2329 knlist_alloc(struct mtx *lock)
2333 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2334 knlist_init_mtx(knl, lock);
2339 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2342 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2343 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2347 knlist_destroy(struct knlist *knl)
2350 KASSERT(KNLIST_EMPTY(knl),
2351 ("destroying knlist %p with knotes on it", knl));
2355 knlist_detach(struct knlist *knl)
2358 KNL_ASSERT_LOCKED(knl);
2359 knl->kl_autodestroy = 1;
2360 if (knlist_empty(knl)) {
2361 knlist_destroy(knl);
2362 free(knl, M_KQUEUE);
2367 * Even if we are locked, we may need to drop the lock to allow any influx
2368 * knotes time to "settle".
2371 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2373 struct knote *kn, *kn2;
2376 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2378 KNL_ASSERT_LOCKED(knl);
2380 KNL_ASSERT_UNLOCKED(knl);
2381 again: /* need to reacquire lock since we have dropped it */
2382 knl->kl_lock(knl->kl_lockarg);
2385 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2388 if ((kn->kn_status & KN_INFLUX)) {
2392 knlist_remove_kq(knl, kn, 1, 1);
2394 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2398 /* Make sure cleared knotes disappear soon */
2399 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2405 if (!SLIST_EMPTY(&knl->kl_list)) {
2406 /* there are still KN_INFLUX remaining */
2407 kn = SLIST_FIRST(&knl->kl_list);
2410 KASSERT(kn->kn_status & KN_INFLUX,
2411 ("knote removed w/o list lock"));
2412 knl->kl_unlock(knl->kl_lockarg);
2413 kq->kq_state |= KQ_FLUXWAIT;
2414 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2420 KNL_ASSERT_LOCKED(knl);
2422 knl->kl_unlock(knl->kl_lockarg);
2423 KNL_ASSERT_UNLOCKED(knl);
2428 * Remove all knotes referencing a specified fd must be called with FILEDESC
2429 * lock. This prevents a race where a new fd comes along and occupies the
2430 * entry and we attach a knote to the fd.
2433 knote_fdclose(struct thread *td, int fd)
2435 struct filedesc *fdp = td->td_proc->p_fd;
2440 FILEDESC_XLOCK_ASSERT(fdp);
2443 * We shouldn't have to worry about new kevents appearing on fd
2444 * since filedesc is locked.
2446 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2451 while (kq->kq_knlistsize > fd &&
2452 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2453 if (kn->kn_status & KN_INFLUX) {
2454 /* someone else might be waiting on our knote */
2457 kq->kq_state |= KQ_FLUXWAIT;
2458 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2461 kn->kn_status |= KN_INFLUX;
2463 if (!(kn->kn_status & KN_DETACHED))
2464 kn->kn_fop->f_detach(kn);
2474 knote_attach(struct knote *kn, struct kqueue *kq)
2478 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2481 if ((kq->kq_state & KQ_CLOSING) != 0)
2483 if (kn->kn_fop->f_isfd) {
2484 if (kn->kn_id >= kq->kq_knlistsize)
2486 list = &kq->kq_knlist[kn->kn_id];
2488 if (kq->kq_knhash == NULL)
2490 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2492 SLIST_INSERT_HEAD(list, kn, kn_link);
2497 * knote must already have been detached using the f_detach method.
2498 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2499 * to prevent other removal.
2502 knote_drop(struct knote *kn, struct thread *td)
2510 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2511 ("knote_drop called without KN_INFLUX set in kn_status"));
2514 if (kn->kn_fop->f_isfd)
2515 list = &kq->kq_knlist[kn->kn_id];
2517 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2519 if (!SLIST_EMPTY(list))
2520 SLIST_REMOVE(list, kn, knote, kn_link);
2521 if (kn->kn_status & KN_QUEUED)
2525 if (kn->kn_fop->f_isfd) {
2526 fdrop(kn->kn_fp, td);
2529 kqueue_fo_release(kn->kn_kevent.filter);
2535 knote_enqueue(struct knote *kn)
2537 struct kqueue *kq = kn->kn_kq;
2539 KQ_OWNED(kn->kn_kq);
2540 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2542 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2543 kn->kn_status |= KN_QUEUED;
2549 knote_dequeue(struct knote *kn)
2551 struct kqueue *kq = kn->kn_kq;
2553 KQ_OWNED(kn->kn_kq);
2554 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2556 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2557 kn->kn_status &= ~KN_QUEUED;
2565 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2566 NULL, NULL, UMA_ALIGN_PTR, 0);
2568 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2570 static struct knote *
2571 knote_alloc(int waitok)
2574 return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2579 knote_free(struct knote *kn)
2582 uma_zfree(knote_zone, kn);
2586 * Register the kev w/ the kq specified by fd.
2589 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2593 cap_rights_t rights;
2596 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2599 if ((error = kqueue_acquire(fp, &kq)) != 0)
2602 error = kqueue_register(kq, kev, td, waitok);
2603 kqueue_release(kq, 0);