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_drop_detached(struct knote *kn, struct thread *td);
140 static void knote_enqueue(struct knote *kn);
141 static void knote_dequeue(struct knote *kn);
142 static void knote_init(void);
143 static struct knote *knote_alloc(int waitok);
144 static void knote_free(struct knote *kn);
146 static void filt_kqdetach(struct knote *kn);
147 static int filt_kqueue(struct knote *kn, long hint);
148 static int filt_procattach(struct knote *kn);
149 static void filt_procdetach(struct knote *kn);
150 static int filt_proc(struct knote *kn, long hint);
151 static int filt_fileattach(struct knote *kn);
152 static void filt_timerexpire(void *knx);
153 static int filt_timerattach(struct knote *kn);
154 static void filt_timerdetach(struct knote *kn);
155 static int filt_timer(struct knote *kn, long hint);
156 static int filt_userattach(struct knote *kn);
157 static void filt_userdetach(struct knote *kn);
158 static int filt_user(struct knote *kn, long hint);
159 static void filt_usertouch(struct knote *kn, struct kevent *kev,
162 static struct filterops file_filtops = {
164 .f_attach = filt_fileattach,
166 static struct filterops kqread_filtops = {
168 .f_detach = filt_kqdetach,
169 .f_event = filt_kqueue,
171 /* XXX - move to kern_proc.c? */
172 static struct filterops proc_filtops = {
174 .f_attach = filt_procattach,
175 .f_detach = filt_procdetach,
176 .f_event = filt_proc,
178 static struct filterops timer_filtops = {
180 .f_attach = filt_timerattach,
181 .f_detach = filt_timerdetach,
182 .f_event = filt_timer,
184 static struct filterops user_filtops = {
185 .f_attach = filt_userattach,
186 .f_detach = filt_userdetach,
187 .f_event = filt_user,
188 .f_touch = filt_usertouch,
191 static uma_zone_t knote_zone;
192 static unsigned int kq_ncallouts = 0;
193 static unsigned int kq_calloutmax = 4 * 1024;
194 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
195 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
197 /* XXX - ensure not influx ? */
198 #define KNOTE_ACTIVATE(kn, islock) do { \
200 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
202 KQ_LOCK((kn)->kn_kq); \
203 (kn)->kn_status |= KN_ACTIVE; \
204 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
205 knote_enqueue((kn)); \
207 KQ_UNLOCK((kn)->kn_kq); \
209 #define KQ_LOCK(kq) do { \
210 mtx_lock(&(kq)->kq_lock); \
212 #define KQ_FLUX_WAKEUP(kq) do { \
213 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
214 (kq)->kq_state &= ~KQ_FLUXWAIT; \
218 #define KQ_UNLOCK_FLUX(kq) do { \
219 KQ_FLUX_WAKEUP(kq); \
220 mtx_unlock(&(kq)->kq_lock); \
222 #define KQ_UNLOCK(kq) do { \
223 mtx_unlock(&(kq)->kq_lock); \
225 #define KQ_OWNED(kq) do { \
226 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
228 #define KQ_NOTOWNED(kq) do { \
229 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
232 static struct knlist *
233 kn_list_lock(struct knote *kn)
239 knl->kl_lock(knl->kl_lockarg);
244 kn_list_unlock(struct knlist *knl)
250 do_free = knl->kl_autodestroy && knlist_empty(knl);
251 knl->kl_unlock(knl->kl_lockarg);
259 kn_in_flux(struct knote *kn)
262 return (kn->kn_influx > 0);
266 kn_enter_flux(struct knote *kn)
270 MPASS(kn->kn_influx < INT_MAX);
275 kn_leave_flux(struct knote *kn)
279 MPASS(kn->kn_influx > 0);
281 return (kn->kn_influx == 0);
284 #define KNL_ASSERT_LOCK(knl, islocked) do { \
286 KNL_ASSERT_LOCKED(knl); \
288 KNL_ASSERT_UNLOCKED(knl); \
291 #define KNL_ASSERT_LOCKED(knl) do { \
292 knl->kl_assert_locked((knl)->kl_lockarg); \
294 #define KNL_ASSERT_UNLOCKED(knl) do { \
295 knl->kl_assert_unlocked((knl)->kl_lockarg); \
297 #else /* !INVARIANTS */
298 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
299 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
300 #endif /* INVARIANTS */
303 #define KN_HASHSIZE 64 /* XXX should be tunable */
306 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
309 filt_nullattach(struct knote *kn)
315 struct filterops null_filtops = {
317 .f_attach = filt_nullattach,
320 /* XXX - make SYSINIT to add these, and move into respective modules. */
321 extern struct filterops sig_filtops;
322 extern struct filterops fs_filtops;
325 * Table for for all system-defined filters.
327 static struct mtx filterops_lock;
328 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
331 struct filterops *for_fop;
334 } sysfilt_ops[EVFILT_SYSCOUNT] = {
335 { &file_filtops, 1 }, /* EVFILT_READ */
336 { &file_filtops, 1 }, /* EVFILT_WRITE */
337 { &null_filtops }, /* EVFILT_AIO */
338 { &file_filtops, 1 }, /* EVFILT_VNODE */
339 { &proc_filtops, 1 }, /* EVFILT_PROC */
340 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
341 { &timer_filtops, 1 }, /* EVFILT_TIMER */
342 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
343 { &fs_filtops, 1 }, /* EVFILT_FS */
344 { &null_filtops }, /* EVFILT_LIO */
345 { &user_filtops, 1 }, /* EVFILT_USER */
346 { &null_filtops }, /* EVFILT_SENDFILE */
347 { &file_filtops, 1 }, /* EVFILT_EMPTY */
351 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
355 filt_fileattach(struct knote *kn)
358 return (fo_kqfilter(kn->kn_fp, kn));
363 kqueue_kqfilter(struct file *fp, struct knote *kn)
365 struct kqueue *kq = kn->kn_fp->f_data;
367 if (kn->kn_filter != EVFILT_READ)
370 kn->kn_status |= KN_KQUEUE;
371 kn->kn_fop = &kqread_filtops;
372 knlist_add(&kq->kq_sel.si_note, kn, 0);
378 filt_kqdetach(struct knote *kn)
380 struct kqueue *kq = kn->kn_fp->f_data;
382 knlist_remove(&kq->kq_sel.si_note, kn, 0);
387 filt_kqueue(struct knote *kn, long hint)
389 struct kqueue *kq = kn->kn_fp->f_data;
391 kn->kn_data = kq->kq_count;
392 return (kn->kn_data > 0);
395 /* XXX - move to kern_proc.c? */
397 filt_procattach(struct knote *kn)
401 bool exiting, immediate;
403 exiting = immediate = false;
404 p = pfind(kn->kn_id);
405 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
406 p = zpfind(kn->kn_id);
408 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
414 if ((error = p_cansee(curthread, p))) {
419 kn->kn_ptr.p_proc = p;
420 kn->kn_flags |= EV_CLEAR; /* automatically set */
423 * Internal flag indicating registration done by kernel for the
424 * purposes of getting a NOTE_CHILD notification.
426 if (kn->kn_flags & EV_FLAG2) {
427 kn->kn_flags &= ~EV_FLAG2;
428 kn->kn_data = kn->kn_sdata; /* ppid */
429 kn->kn_fflags = NOTE_CHILD;
430 kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
431 immediate = true; /* Force immediate activation of child note. */
434 * Internal flag indicating registration done by kernel (for other than
437 if (kn->kn_flags & EV_FLAG1) {
438 kn->kn_flags &= ~EV_FLAG1;
441 knlist_add(p->p_klist, kn, 1);
444 * Immediately activate any child notes or, in the case of a zombie
445 * target process, exit notes. The latter is necessary to handle the
446 * case where the target process, e.g. a child, dies before the kevent
449 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
450 KNOTE_ACTIVATE(kn, 0);
458 * The knote may be attached to a different process, which may exit,
459 * leaving nothing for the knote to be attached to. So when the process
460 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
461 * it will be deleted when read out. However, as part of the knote deletion,
462 * this routine is called, so a check is needed to avoid actually performing
463 * a detach, because the original process does not exist any more.
465 /* XXX - move to kern_proc.c? */
467 filt_procdetach(struct knote *kn)
470 knlist_remove(kn->kn_knlist, kn, 0);
471 kn->kn_ptr.p_proc = NULL;
474 /* XXX - move to kern_proc.c? */
476 filt_proc(struct knote *kn, long hint)
481 p = kn->kn_ptr.p_proc;
482 if (p == NULL) /* already activated, from attach filter */
485 /* Mask off extra data. */
486 event = (u_int)hint & NOTE_PCTRLMASK;
488 /* If the user is interested in this event, record it. */
489 if (kn->kn_sfflags & event)
490 kn->kn_fflags |= event;
492 /* Process is gone, so flag the event as finished. */
493 if (event == NOTE_EXIT) {
494 kn->kn_flags |= EV_EOF | EV_ONESHOT;
495 kn->kn_ptr.p_proc = NULL;
496 if (kn->kn_fflags & NOTE_EXIT)
497 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
498 if (kn->kn_fflags == 0)
499 kn->kn_flags |= EV_DROP;
503 return (kn->kn_fflags != 0);
507 * Called when the process forked. It mostly does the same as the
508 * knote(), activating all knotes registered to be activated when the
509 * process forked. Additionally, for each knote attached to the
510 * parent, check whether user wants to track the new process. If so
511 * attach a new knote to it, and immediately report an event with the
515 knote_fork(struct knlist *list, int pid)
524 list->kl_lock(list->kl_lockarg);
526 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
529 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
535 * The same as knote(), activate the event.
537 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
538 kn->kn_status |= KN_HASKQLOCK;
539 if (kn->kn_fop->f_event(kn, NOTE_FORK))
540 KNOTE_ACTIVATE(kn, 1);
541 kn->kn_status &= ~KN_HASKQLOCK;
547 * The NOTE_TRACK case. In addition to the activation
548 * of the event, we need to register new events to
549 * track the child. Drop the locks in preparation for
550 * the call to kqueue_register().
554 list->kl_unlock(list->kl_lockarg);
557 * Activate existing knote and register tracking knotes with
560 * First register a knote to get just the child notice. This
561 * must be a separate note from a potential NOTE_EXIT
562 * notification since both NOTE_CHILD and NOTE_EXIT are defined
563 * to use the data field (in conflicting ways).
566 kev.filter = kn->kn_filter;
567 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
569 kev.fflags = kn->kn_sfflags;
570 kev.data = kn->kn_id; /* parent */
571 kev.udata = kn->kn_kevent.udata;/* preserve udata */
572 error = kqueue_register(kq, &kev, NULL, 0);
574 kn->kn_fflags |= NOTE_TRACKERR;
577 * Then register another knote to track other potential events
578 * from the new process.
581 kev.filter = kn->kn_filter;
582 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
583 kev.fflags = kn->kn_sfflags;
584 kev.data = kn->kn_id; /* parent */
585 kev.udata = kn->kn_kevent.udata;/* preserve udata */
586 error = kqueue_register(kq, &kev, NULL, 0);
588 kn->kn_fflags |= NOTE_TRACKERR;
589 if (kn->kn_fop->f_event(kn, NOTE_FORK))
590 KNOTE_ACTIVATE(kn, 0);
594 list->kl_lock(list->kl_lockarg);
596 list->kl_unlock(list->kl_lockarg);
600 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
601 * interval timer support code.
604 #define NOTE_TIMER_PRECMASK (NOTE_SECONDS|NOTE_MSECONDS|NOTE_USECONDS| \
608 timer2sbintime(intptr_t data, int flags)
612 * Macros for converting to the fractional second portion of an
613 * sbintime_t using 64bit multiplication to improve precision.
615 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
616 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
617 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
618 switch (flags & NOTE_TIMER_PRECMASK) {
621 if (data > (SBT_MAX / SBT_1S))
624 return ((sbintime_t)data << 32);
625 case NOTE_MSECONDS: /* FALLTHROUGH */
628 int64_t secs = data / 1000;
630 if (secs > (SBT_MAX / SBT_1S))
633 return (secs << 32 | MS_TO_SBT(data % 1000));
635 return MS_TO_SBT(data);
637 if (data >= 1000000) {
638 int64_t secs = data / 1000000;
640 if (secs > (SBT_MAX / SBT_1S))
643 return (secs << 32 | US_TO_SBT(data % 1000000));
645 return US_TO_SBT(data);
647 if (data >= 1000000000) {
648 int64_t secs = data / 1000000000;
650 if (secs > (SBT_MAX / SBT_1S))
653 return (secs << 32 | US_TO_SBT(data % 1000000000));
655 return (NS_TO_SBT(data));
662 struct kq_timer_cb_data {
664 sbintime_t next; /* next timer event fires at */
665 sbintime_t to; /* precalculated timer period */
669 filt_timerexpire(void *knx)
672 struct kq_timer_cb_data *kc;
676 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
678 if ((kn->kn_flags & EV_ONESHOT) != 0)
683 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
684 PCPU_GET(cpuid), C_ABSOLUTE);
688 * data contains amount of time to sleep
691 filt_timerattach(struct knote *kn)
693 struct kq_timer_cb_data *kc;
695 unsigned int ncallouts;
697 if (kn->kn_sdata < 0)
699 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
701 /* Only precision unit are supported in flags so far */
702 if ((kn->kn_sfflags & ~NOTE_TIMER_PRECMASK) != 0)
705 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
710 ncallouts = kq_ncallouts;
711 if (ncallouts >= kq_calloutmax)
713 } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
715 kn->kn_flags |= EV_CLEAR; /* automatically set */
716 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
717 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
718 callout_init(&kc->c, 1);
719 kc->next = to + sbinuptime();
721 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
722 PCPU_GET(cpuid), C_ABSOLUTE);
728 filt_timerdetach(struct knote *kn)
730 struct kq_timer_cb_data *kc;
734 callout_drain(&kc->c);
736 old = atomic_fetchadd_int(&kq_ncallouts, -1);
737 KASSERT(old > 0, ("Number of callouts cannot become negative"));
738 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
742 filt_timer(struct knote *kn, long hint)
745 return (kn->kn_data != 0);
749 filt_userattach(struct knote *kn)
753 * EVFILT_USER knotes are not attached to anything in the kernel.
756 if (kn->kn_fflags & NOTE_TRIGGER)
764 filt_userdetach(__unused struct knote *kn)
768 * EVFILT_USER knotes are not attached to anything in the kernel.
773 filt_user(struct knote *kn, __unused long hint)
776 return (kn->kn_hookid);
780 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
786 if (kev->fflags & NOTE_TRIGGER)
789 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
790 kev->fflags &= NOTE_FFLAGSMASK;
796 kn->kn_sfflags &= kev->fflags;
800 kn->kn_sfflags |= kev->fflags;
804 kn->kn_sfflags = kev->fflags;
808 /* XXX Return error? */
811 kn->kn_sdata = kev->data;
812 if (kev->flags & EV_CLEAR) {
820 *kev = kn->kn_kevent;
821 kev->fflags = kn->kn_sfflags;
822 kev->data = kn->kn_sdata;
823 if (kn->kn_flags & EV_CLEAR) {
831 panic("filt_usertouch() - invalid type (%ld)", type);
837 sys_kqueue(struct thread *td, struct kqueue_args *uap)
840 return (kern_kqueue(td, 0, NULL));
844 kqueue_init(struct kqueue *kq)
847 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
848 TAILQ_INIT(&kq->kq_head);
849 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
850 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
854 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
856 struct filedesc *fdp;
862 fdp = td->td_proc->p_fd;
864 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
867 error = falloc_caps(td, &fp, &fd, flags, fcaps);
869 chgkqcnt(cred->cr_ruidinfo, -1, 0);
873 /* An extra reference on `fp' has been held for us by falloc(). */
874 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
877 kq->kq_cred = crhold(cred);
880 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
881 FILEDESC_XUNLOCK(fdp);
883 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
886 td->td_retval[0] = fd;
892 kev_iovlen(int n, u_int kgio)
895 if (n < 0 || n >= kgio / sizeof(struct kevent))
897 return (n * sizeof(struct kevent));
901 #ifndef _SYS_SYSPROTO_H_
904 const struct kevent *changelist;
906 struct kevent *eventlist;
908 const struct timespec *timeout;
912 sys_kevent(struct thread *td, struct kevent_args *uap)
914 struct timespec ts, *tsp;
915 struct kevent_copyops k_ops = {
917 .k_copyout = kevent_copyout,
918 .k_copyin = kevent_copyin,
924 struct uio *ktruioin = NULL;
925 struct uio *ktruioout = NULL;
929 if (uap->timeout != NULL) {
930 error = copyin(uap->timeout, &ts, sizeof(ts));
938 if (KTRPOINT(td, KTR_GENIO)) {
939 kgio = ktr_geniosize;
940 ktriov.iov_base = uap->changelist;
941 ktriov.iov_len = kev_iovlen(uap->nchanges, kgio);
942 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
943 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
945 ktruioin = cloneuio(&ktruio);
946 ktriov.iov_base = uap->eventlist;
947 ktriov.iov_len = kev_iovlen(uap->nevents, kgio);
948 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
949 ktruioout = cloneuio(&ktruio);
953 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
957 if (ktruioin != NULL) {
958 ktruioin->uio_resid = kev_iovlen(uap->nchanges, kgio);
959 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
960 ktruioout->uio_resid = kev_iovlen(td->td_retval[0], kgio);
961 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
969 * Copy 'count' items into the destination list pointed to by uap->eventlist.
972 kevent_copyout(void *arg, struct kevent *kevp, int count)
974 struct kevent_args *uap;
977 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
978 uap = (struct kevent_args *)arg;
980 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
982 uap->eventlist += count;
987 * Copy 'count' items from the list pointed to by uap->changelist.
990 kevent_copyin(void *arg, struct kevent *kevp, int count)
992 struct kevent_args *uap;
995 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
996 uap = (struct kevent_args *)arg;
998 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
1000 uap->changelist += count;
1005 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
1006 struct kevent_copyops *k_ops, const struct timespec *timeout)
1008 cap_rights_t rights;
1012 cap_rights_init(&rights);
1014 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
1016 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
1017 error = fget(td, fd, &rights, &fp);
1021 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1028 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1029 struct kevent_copyops *k_ops, const struct timespec *timeout)
1031 struct kevent keva[KQ_NEVENTS];
1032 struct kevent *kevp, *changes;
1033 int i, n, nerrors, error;
1036 while (nchanges > 0) {
1037 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1038 error = k_ops->k_copyin(k_ops->arg, keva, n);
1042 for (i = 0; i < n; i++) {
1046 kevp->flags &= ~EV_SYSFLAGS;
1047 error = kqueue_register(kq, kevp, td, 1);
1048 if (error || (kevp->flags & EV_RECEIPT)) {
1051 kevp->flags = EV_ERROR;
1053 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1061 td->td_retval[0] = nerrors;
1065 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1069 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1070 struct kevent_copyops *k_ops, const struct timespec *timeout)
1075 error = kqueue_acquire(fp, &kq);
1078 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1079 kqueue_release(kq, 0);
1084 * Performs a kevent() call on a temporarily created kqueue. This can be
1085 * used to perform one-shot polling, similar to poll() and select().
1088 kern_kevent_anonymous(struct thread *td, int nevents,
1089 struct kevent_copyops *k_ops)
1091 struct kqueue kq = {};
1096 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1097 kqueue_drain(&kq, td);
1098 kqueue_destroy(&kq);
1103 kqueue_add_filteropts(int filt, struct filterops *filtops)
1108 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1110 "trying to add a filterop that is out of range: %d is beyond %d\n",
1111 ~filt, EVFILT_SYSCOUNT);
1114 mtx_lock(&filterops_lock);
1115 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1116 sysfilt_ops[~filt].for_fop != NULL)
1119 sysfilt_ops[~filt].for_fop = filtops;
1120 sysfilt_ops[~filt].for_refcnt = 0;
1122 mtx_unlock(&filterops_lock);
1128 kqueue_del_filteropts(int filt)
1133 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1136 mtx_lock(&filterops_lock);
1137 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1138 sysfilt_ops[~filt].for_fop == NULL)
1140 else if (sysfilt_ops[~filt].for_refcnt != 0)
1143 sysfilt_ops[~filt].for_fop = &null_filtops;
1144 sysfilt_ops[~filt].for_refcnt = 0;
1146 mtx_unlock(&filterops_lock);
1151 static struct filterops *
1152 kqueue_fo_find(int filt)
1155 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1158 if (sysfilt_ops[~filt].for_nolock)
1159 return sysfilt_ops[~filt].for_fop;
1161 mtx_lock(&filterops_lock);
1162 sysfilt_ops[~filt].for_refcnt++;
1163 if (sysfilt_ops[~filt].for_fop == NULL)
1164 sysfilt_ops[~filt].for_fop = &null_filtops;
1165 mtx_unlock(&filterops_lock);
1167 return sysfilt_ops[~filt].for_fop;
1171 kqueue_fo_release(int filt)
1174 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1177 if (sysfilt_ops[~filt].for_nolock)
1180 mtx_lock(&filterops_lock);
1181 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1182 ("filter object refcount not valid on release"));
1183 sysfilt_ops[~filt].for_refcnt--;
1184 mtx_unlock(&filterops_lock);
1188 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1189 * influence if memory allocation should wait. Make sure it is 0 if you
1193 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1195 struct filterops *fops;
1197 struct knote *kn, *tkn;
1199 cap_rights_t rights;
1200 int error, filt, event;
1201 int haskqglobal, filedesc_unlock;
1203 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1211 filedesc_unlock = 0;
1214 fops = kqueue_fo_find(filt);
1218 if (kev->flags & EV_ADD) {
1220 * Prevent waiting with locks. Non-sleepable
1221 * allocation failures are handled in the loop, only
1222 * if the spare knote appears to be actually required.
1224 tkn = knote_alloc(waitok);
1231 KASSERT(td != NULL, ("td is NULL"));
1232 if (kev->ident > INT_MAX)
1235 error = fget(td, kev->ident,
1236 cap_rights_init(&rights, CAP_EVENT), &fp);
1240 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1241 kev->ident, 0) != 0) {
1245 error = kqueue_expand(kq, fops, kev->ident, waitok);
1251 if (fp->f_type == DTYPE_KQUEUE) {
1253 * If we add some intelligence about what we are doing,
1254 * we should be able to support events on ourselves.
1255 * We need to know when we are doing this to prevent
1256 * getting both the knlist lock and the kq lock since
1257 * they are the same thing.
1259 if (fp->f_data == kq) {
1265 * Pre-lock the filedesc before the global
1266 * lock mutex, see the comment in
1269 FILEDESC_XLOCK(td->td_proc->p_fd);
1270 filedesc_unlock = 1;
1271 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1275 if (kev->ident < kq->kq_knlistsize) {
1276 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1277 if (kev->filter == kn->kn_filter)
1281 if ((kev->flags & EV_ADD) == EV_ADD)
1282 kqueue_expand(kq, fops, kev->ident, waitok);
1287 * If possible, find an existing knote to use for this kevent.
1289 if (kev->filter == EVFILT_PROC &&
1290 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1291 /* This is an internal creation of a process tracking
1292 * note. Don't attempt to coalesce this with an
1296 } else if (kq->kq_knhashmask != 0) {
1299 list = &kq->kq_knhash[
1300 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1301 SLIST_FOREACH(kn, list, kn_link)
1302 if (kev->ident == kn->kn_id &&
1303 kev->filter == kn->kn_filter)
1308 /* knote is in the process of changing, wait for it to stabilize. */
1309 if (kn != NULL && kn_in_flux(kn)) {
1310 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1311 if (filedesc_unlock) {
1312 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1313 filedesc_unlock = 0;
1315 kq->kq_state |= KQ_FLUXWAIT;
1316 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1325 * kn now contains the matching knote, or NULL if no match
1328 if (kev->flags & EV_ADD) {
1340 * apply reference counts to knote structure, and
1341 * do not release it at the end of this routine.
1346 kn->kn_sfflags = kev->fflags;
1347 kn->kn_sdata = kev->data;
1350 kn->kn_kevent = *kev;
1351 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1352 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1353 kn->kn_status = KN_DETACHED;
1356 error = knote_attach(kn, kq);
1363 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1364 knote_drop_detached(kn, td);
1367 knl = kn_list_lock(kn);
1370 /* No matching knote and the EV_ADD flag is not set. */
1377 if (kev->flags & EV_DELETE) {
1384 if (kev->flags & EV_FORCEONESHOT) {
1385 kn->kn_flags |= EV_ONESHOT;
1386 KNOTE_ACTIVATE(kn, 1);
1390 * The user may change some filter values after the initial EV_ADD,
1391 * but doing so will not reset any filter which has already been
1394 kn->kn_status |= KN_SCAN;
1397 knl = kn_list_lock(kn);
1398 kn->kn_kevent.udata = kev->udata;
1399 if (!fops->f_isfd && fops->f_touch != NULL) {
1400 fops->f_touch(kn, kev, EVENT_REGISTER);
1402 kn->kn_sfflags = kev->fflags;
1403 kn->kn_sdata = kev->data;
1407 * We can get here with kn->kn_knlist == NULL. This can happen when
1408 * the initial attach event decides that the event is "completed"
1409 * already. i.e. filt_procattach is called on a zombie process. It
1410 * will call filt_proc which will remove it from the list, and NULL
1414 if ((kev->flags & EV_ENABLE) != 0)
1415 kn->kn_status &= ~KN_DISABLED;
1416 else if ((kev->flags & EV_DISABLE) != 0)
1417 kn->kn_status |= KN_DISABLED;
1419 if ((kn->kn_status & KN_DISABLED) == 0)
1420 event = kn->kn_fop->f_event(kn, 0);
1426 kn->kn_status |= KN_ACTIVE;
1427 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1430 kn->kn_status &= ~KN_SCAN;
1432 kn_list_unlock(knl);
1436 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1437 if (filedesc_unlock)
1438 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1443 kqueue_fo_release(filt);
1448 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1456 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1460 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1471 kqueue_release(struct kqueue *kq, int locked)
1478 if (kq->kq_refcnt == 1)
1479 wakeup(&kq->kq_refcnt);
1485 kqueue_schedtask(struct kqueue *kq)
1489 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1490 ("scheduling kqueue task while draining"));
1492 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1493 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1494 kq->kq_state |= KQ_TASKSCHED;
1499 * Expand the kq to make sure we have storage for fops/ident pair.
1501 * Return 0 on success (or no work necessary), return errno on failure.
1503 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1504 * If kqueue_register is called from a non-fd context, there usually/should
1508 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1511 struct klist *list, *tmp_knhash, *to_free;
1512 u_long tmp_knhashmask;
1515 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1522 if (kq->kq_knlistsize <= fd) {
1523 size = kq->kq_knlistsize;
1526 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1530 if (kq->kq_knlistsize > fd) {
1534 if (kq->kq_knlist != NULL) {
1535 bcopy(kq->kq_knlist, list,
1536 kq->kq_knlistsize * sizeof(*list));
1537 to_free = kq->kq_knlist;
1538 kq->kq_knlist = NULL;
1540 bzero((caddr_t)list +
1541 kq->kq_knlistsize * sizeof(*list),
1542 (size - kq->kq_knlistsize) * sizeof(*list));
1543 kq->kq_knlistsize = size;
1544 kq->kq_knlist = list;
1549 if (kq->kq_knhashmask == 0) {
1550 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1552 if (tmp_knhash == NULL)
1555 if (kq->kq_knhashmask == 0) {
1556 kq->kq_knhash = tmp_knhash;
1557 kq->kq_knhashmask = tmp_knhashmask;
1559 to_free = tmp_knhash;
1564 free(to_free, M_KQUEUE);
1571 kqueue_task(void *arg, int pending)
1579 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1582 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1584 kq->kq_state &= ~KQ_TASKSCHED;
1585 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1586 wakeup(&kq->kq_state);
1589 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1593 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1594 * We treat KN_MARKER knotes as if they are in flux.
1597 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1598 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1600 struct kevent *kevp;
1601 struct knote *kn, *marker;
1603 sbintime_t asbt, rsbt;
1604 int count, error, haskqglobal, influx, nkev, touch;
1616 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1617 tsp->tv_nsec >= 1000000000) {
1621 if (timespecisset(tsp)) {
1622 if (tsp->tv_sec <= INT32_MAX) {
1623 rsbt = tstosbt(*tsp);
1624 if (TIMESEL(&asbt, rsbt))
1625 asbt += tc_tick_sbt;
1626 if (asbt <= SBT_MAX - rsbt)
1630 rsbt >>= tc_precexp;
1637 marker = knote_alloc(1);
1638 marker->kn_status = KN_MARKER;
1643 if (kq->kq_count == 0) {
1645 error = EWOULDBLOCK;
1647 kq->kq_state |= KQ_SLEEP;
1648 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1649 "kqread", asbt, rsbt, C_ABSOLUTE);
1653 /* don't restart after signals... */
1654 if (error == ERESTART)
1656 else if (error == EWOULDBLOCK)
1661 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1665 kn = TAILQ_FIRST(&kq->kq_head);
1667 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1673 kq->kq_state |= KQ_FLUXWAIT;
1674 error = msleep(kq, &kq->kq_lock, PSOCK,
1679 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1680 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1681 kn->kn_status &= ~KN_QUEUED;
1687 if (count == maxevents)
1691 KASSERT(!kn_in_flux(kn),
1692 ("knote %p is unexpectedly in flux", kn));
1694 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1695 kn->kn_status &= ~KN_QUEUED;
1700 * We don't need to lock the list since we've
1701 * marked it as in flux.
1706 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1707 kn->kn_status &= ~KN_QUEUED;
1712 * We don't need to lock the list since we've
1713 * marked the knote as being in flux.
1715 *kevp = kn->kn_kevent;
1720 kn->kn_status |= KN_SCAN;
1723 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1724 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1725 knl = kn_list_lock(kn);
1726 if (kn->kn_fop->f_event(kn, 0) == 0) {
1728 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1729 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
1733 kn_list_unlock(knl);
1737 touch = (!kn->kn_fop->f_isfd &&
1738 kn->kn_fop->f_touch != NULL);
1740 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1742 *kevp = kn->kn_kevent;
1744 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1745 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1747 * Manually clear knotes who weren't
1750 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1754 if (kn->kn_flags & EV_DISPATCH)
1755 kn->kn_status |= KN_DISABLED;
1756 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1759 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1761 kn->kn_status &= ~KN_SCAN;
1763 kn_list_unlock(knl);
1767 /* we are returning a copy to the user */
1772 if (nkev == KQ_NEVENTS) {
1775 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1783 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1791 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1792 td->td_retval[0] = maxevents - count;
1798 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1799 struct ucred *active_cred, struct thread *td)
1802 * Enabling sigio causes two major problems:
1803 * 1) infinite recursion:
1804 * Synopsys: kevent is being used to track signals and have FIOASYNC
1805 * set. On receipt of a signal this will cause a kqueue to recurse
1806 * into itself over and over. Sending the sigio causes the kqueue
1807 * to become ready, which in turn posts sigio again, forever.
1808 * Solution: this can be solved by setting a flag in the kqueue that
1809 * we have a SIGIO in progress.
1810 * 2) locking problems:
1811 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1812 * us above the proc and pgrp locks.
1813 * Solution: Post a signal using an async mechanism, being sure to
1814 * record a generation count in the delivery so that we do not deliver
1815 * a signal to the wrong process.
1817 * Note, these two mechanisms are somewhat mutually exclusive!
1826 kq->kq_state |= KQ_ASYNC;
1828 kq->kq_state &= ~KQ_ASYNC;
1833 return (fsetown(*(int *)data, &kq->kq_sigio));
1836 *(int *)data = fgetown(&kq->kq_sigio);
1846 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1853 if ((error = kqueue_acquire(fp, &kq)))
1857 if (events & (POLLIN | POLLRDNORM)) {
1859 revents |= events & (POLLIN | POLLRDNORM);
1861 selrecord(td, &kq->kq_sel);
1862 if (SEL_WAITING(&kq->kq_sel))
1863 kq->kq_state |= KQ_SEL;
1866 kqueue_release(kq, 1);
1873 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1877 bzero((void *)st, sizeof *st);
1879 * We no longer return kq_count because the unlocked value is useless.
1880 * If you spent all this time getting the count, why not spend your
1881 * syscall better by calling kevent?
1883 * XXX - This is needed for libc_r.
1885 st->st_mode = S_IFIFO;
1890 kqueue_drain(struct kqueue *kq, struct thread *td)
1897 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1898 ("kqueue already closing"));
1899 kq->kq_state |= KQ_CLOSING;
1900 if (kq->kq_refcnt > 1)
1901 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1903 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1905 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1906 ("kqueue's knlist not empty"));
1908 for (i = 0; i < kq->kq_knlistsize; i++) {
1909 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1910 if (kn_in_flux(kn)) {
1911 kq->kq_state |= KQ_FLUXWAIT;
1912 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1921 if (kq->kq_knhashmask != 0) {
1922 for (i = 0; i <= kq->kq_knhashmask; i++) {
1923 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1924 if (kn_in_flux(kn)) {
1925 kq->kq_state |= KQ_FLUXWAIT;
1926 msleep(kq, &kq->kq_lock, PSOCK,
1938 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1939 kq->kq_state |= KQ_TASKDRAIN;
1940 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1943 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1944 selwakeuppri(&kq->kq_sel, PSOCK);
1945 if (!SEL_WAITING(&kq->kq_sel))
1946 kq->kq_state &= ~KQ_SEL;
1953 kqueue_destroy(struct kqueue *kq)
1956 KASSERT(kq->kq_fdp == NULL,
1957 ("kqueue still attached to a file descriptor"));
1958 seldrain(&kq->kq_sel);
1959 knlist_destroy(&kq->kq_sel.si_note);
1960 mtx_destroy(&kq->kq_lock);
1962 if (kq->kq_knhash != NULL)
1963 free(kq->kq_knhash, M_KQUEUE);
1964 if (kq->kq_knlist != NULL)
1965 free(kq->kq_knlist, M_KQUEUE);
1967 funsetown(&kq->kq_sigio);
1972 kqueue_close(struct file *fp, struct thread *td)
1974 struct kqueue *kq = fp->f_data;
1975 struct filedesc *fdp;
1977 int filedesc_unlock;
1979 if ((error = kqueue_acquire(fp, &kq)))
1981 kqueue_drain(kq, td);
1984 * We could be called due to the knote_drop() doing fdrop(),
1985 * called from kqueue_register(). In this case the global
1986 * lock is owned, and filedesc sx is locked before, to not
1987 * take the sleepable lock after non-sleepable.
1991 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1992 FILEDESC_XLOCK(fdp);
1993 filedesc_unlock = 1;
1995 filedesc_unlock = 0;
1996 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1997 if (filedesc_unlock)
1998 FILEDESC_XUNLOCK(fdp);
2001 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
2002 crfree(kq->kq_cred);
2010 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2013 kif->kf_type = KF_TYPE_KQUEUE;
2018 kqueue_wakeup(struct kqueue *kq)
2022 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2023 kq->kq_state &= ~KQ_SLEEP;
2026 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2027 selwakeuppri(&kq->kq_sel, PSOCK);
2028 if (!SEL_WAITING(&kq->kq_sel))
2029 kq->kq_state &= ~KQ_SEL;
2031 if (!knlist_empty(&kq->kq_sel.si_note))
2032 kqueue_schedtask(kq);
2033 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2034 pgsigio(&kq->kq_sigio, SIGIO, 0);
2039 * Walk down a list of knotes, activating them if their event has triggered.
2041 * There is a possibility to optimize in the case of one kq watching another.
2042 * Instead of scheduling a task to wake it up, you could pass enough state
2043 * down the chain to make up the parent kqueue. Make this code functional
2047 knote(struct knlist *list, long hint, int lockflags)
2050 struct knote *kn, *tkn;
2056 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2058 if ((lockflags & KNF_LISTLOCKED) == 0)
2059 list->kl_lock(list->kl_lockarg);
2062 * If we unlock the list lock (and enter influx), we can
2063 * eliminate the kqueue scheduling, but this will introduce
2064 * four lock/unlock's for each knote to test. Also, marker
2065 * would be needed to keep iteration position, since filters
2066 * or other threads could remove events.
2068 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2071 if (kn_in_flux(kn) && (kn->kn_status & KN_SCAN) == 0) {
2073 * Do not process the influx notes, except for
2074 * the influx coming from the kq unlock in the
2075 * kqueue_scan(). In the later case, we do
2076 * not interfere with the scan, since the code
2077 * fragment in kqueue_scan() locks the knlist,
2078 * and cannot proceed until we finished.
2081 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2084 error = kn->kn_fop->f_event(kn, hint);
2088 KNOTE_ACTIVATE(kn, 1);
2091 kn->kn_status |= KN_HASKQLOCK;
2092 if (kn->kn_fop->f_event(kn, hint))
2093 KNOTE_ACTIVATE(kn, 1);
2094 kn->kn_status &= ~KN_HASKQLOCK;
2098 if ((lockflags & KNF_LISTLOCKED) == 0)
2099 list->kl_unlock(list->kl_lockarg);
2103 * add a knote to a knlist
2106 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2109 KNL_ASSERT_LOCK(knl, islocked);
2110 KQ_NOTOWNED(kn->kn_kq);
2111 KASSERT(kn_in_flux(kn), ("knote %p not in flux", kn));
2112 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2113 ("knote %p was not detached", kn));
2115 knl->kl_lock(knl->kl_lockarg);
2116 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2118 knl->kl_unlock(knl->kl_lockarg);
2120 kn->kn_knlist = knl;
2121 kn->kn_status &= ~KN_DETACHED;
2122 KQ_UNLOCK(kn->kn_kq);
2126 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2130 KASSERT(!kqislocked || knlislocked, ("kq locked w/o knl locked"));
2131 KNL_ASSERT_LOCK(knl, knlislocked);
2132 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2133 KASSERT(kqislocked || kn_in_flux(kn), ("knote %p not in flux", kn));
2134 KASSERT((kn->kn_status & KN_DETACHED) == 0,
2135 ("knote %p was already detached", kn));
2137 knl->kl_lock(knl->kl_lockarg);
2138 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2139 kn->kn_knlist = NULL;
2141 kn_list_unlock(knl);
2144 kn->kn_status |= KN_DETACHED;
2146 KQ_UNLOCK(kn->kn_kq);
2150 * remove knote from the specified knlist
2153 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2156 knlist_remove_kq(knl, kn, islocked, 0);
2160 knlist_empty(struct knlist *knl)
2163 KNL_ASSERT_LOCKED(knl);
2164 return (SLIST_EMPTY(&knl->kl_list));
2167 static struct mtx knlist_lock;
2168 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2170 static void knlist_mtx_lock(void *arg);
2171 static void knlist_mtx_unlock(void *arg);
2174 knlist_mtx_lock(void *arg)
2177 mtx_lock((struct mtx *)arg);
2181 knlist_mtx_unlock(void *arg)
2184 mtx_unlock((struct mtx *)arg);
2188 knlist_mtx_assert_locked(void *arg)
2191 mtx_assert((struct mtx *)arg, MA_OWNED);
2195 knlist_mtx_assert_unlocked(void *arg)
2198 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2202 knlist_rw_rlock(void *arg)
2205 rw_rlock((struct rwlock *)arg);
2209 knlist_rw_runlock(void *arg)
2212 rw_runlock((struct rwlock *)arg);
2216 knlist_rw_assert_locked(void *arg)
2219 rw_assert((struct rwlock *)arg, RA_LOCKED);
2223 knlist_rw_assert_unlocked(void *arg)
2226 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2230 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2231 void (*kl_unlock)(void *),
2232 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2236 knl->kl_lockarg = &knlist_lock;
2238 knl->kl_lockarg = lock;
2240 if (kl_lock == NULL)
2241 knl->kl_lock = knlist_mtx_lock;
2243 knl->kl_lock = kl_lock;
2244 if (kl_unlock == NULL)
2245 knl->kl_unlock = knlist_mtx_unlock;
2247 knl->kl_unlock = kl_unlock;
2248 if (kl_assert_locked == NULL)
2249 knl->kl_assert_locked = knlist_mtx_assert_locked;
2251 knl->kl_assert_locked = kl_assert_locked;
2252 if (kl_assert_unlocked == NULL)
2253 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2255 knl->kl_assert_unlocked = kl_assert_unlocked;
2257 knl->kl_autodestroy = 0;
2258 SLIST_INIT(&knl->kl_list);
2262 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2265 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2269 knlist_alloc(struct mtx *lock)
2273 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2274 knlist_init_mtx(knl, lock);
2279 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2282 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2283 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2287 knlist_destroy(struct knlist *knl)
2290 KASSERT(KNLIST_EMPTY(knl),
2291 ("destroying knlist %p with knotes on it", knl));
2295 knlist_detach(struct knlist *knl)
2298 KNL_ASSERT_LOCKED(knl);
2299 knl->kl_autodestroy = 1;
2300 if (knlist_empty(knl)) {
2301 knlist_destroy(knl);
2302 free(knl, M_KQUEUE);
2307 * Even if we are locked, we may need to drop the lock to allow any influx
2308 * knotes time to "settle".
2311 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2313 struct knote *kn, *kn2;
2316 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2318 KNL_ASSERT_LOCKED(knl);
2320 KNL_ASSERT_UNLOCKED(knl);
2321 again: /* need to reacquire lock since we have dropped it */
2322 knl->kl_lock(knl->kl_lockarg);
2325 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2328 if (kn_in_flux(kn)) {
2332 knlist_remove_kq(knl, kn, 1, 1);
2336 knote_drop_detached(kn, td);
2338 /* Make sure cleared knotes disappear soon */
2339 kn->kn_flags |= EV_EOF | EV_ONESHOT;
2345 if (!SLIST_EMPTY(&knl->kl_list)) {
2346 /* there are still in flux knotes remaining */
2347 kn = SLIST_FIRST(&knl->kl_list);
2350 KASSERT(kn_in_flux(kn), ("knote removed w/o list lock"));
2351 knl->kl_unlock(knl->kl_lockarg);
2352 kq->kq_state |= KQ_FLUXWAIT;
2353 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2359 KNL_ASSERT_LOCKED(knl);
2361 knl->kl_unlock(knl->kl_lockarg);
2362 KNL_ASSERT_UNLOCKED(knl);
2367 * Remove all knotes referencing a specified fd must be called with FILEDESC
2368 * lock. This prevents a race where a new fd comes along and occupies the
2369 * entry and we attach a knote to the fd.
2372 knote_fdclose(struct thread *td, int fd)
2374 struct filedesc *fdp = td->td_proc->p_fd;
2379 FILEDESC_XLOCK_ASSERT(fdp);
2382 * We shouldn't have to worry about new kevents appearing on fd
2383 * since filedesc is locked.
2385 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2390 while (kq->kq_knlistsize > fd &&
2391 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2392 if (kn_in_flux(kn)) {
2393 /* someone else might be waiting on our knote */
2396 kq->kq_state |= KQ_FLUXWAIT;
2397 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2411 knote_attach(struct knote *kn, struct kqueue *kq)
2415 KASSERT(kn_in_flux(kn), ("knote %p not marked influx", kn));
2418 if (kn->kn_fop->f_isfd) {
2419 if (kn->kn_id >= kq->kq_knlistsize)
2421 list = &kq->kq_knlist[kn->kn_id];
2423 if (kq->kq_knhash == NULL)
2425 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2427 SLIST_INSERT_HEAD(list, kn, kn_link);
2432 knote_drop(struct knote *kn, struct thread *td)
2435 if ((kn->kn_status & KN_DETACHED) == 0)
2436 kn->kn_fop->f_detach(kn);
2437 knote_drop_detached(kn, td);
2441 knote_drop_detached(struct knote *kn, struct thread *td)
2448 KASSERT((kn->kn_status & KN_DETACHED) != 0,
2449 ("knote %p still attached", kn));
2453 KASSERT(kn->kn_influx == 1,
2454 ("knote_drop called on %p with influx %d", kn, kn->kn_influx));
2456 if (kn->kn_fop->f_isfd)
2457 list = &kq->kq_knlist[kn->kn_id];
2459 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2461 if (!SLIST_EMPTY(list))
2462 SLIST_REMOVE(list, kn, knote, kn_link);
2463 if (kn->kn_status & KN_QUEUED)
2467 if (kn->kn_fop->f_isfd) {
2468 fdrop(kn->kn_fp, td);
2471 kqueue_fo_release(kn->kn_kevent.filter);
2477 knote_enqueue(struct knote *kn)
2479 struct kqueue *kq = kn->kn_kq;
2481 KQ_OWNED(kn->kn_kq);
2482 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2484 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2485 kn->kn_status |= KN_QUEUED;
2491 knote_dequeue(struct knote *kn)
2493 struct kqueue *kq = kn->kn_kq;
2495 KQ_OWNED(kn->kn_kq);
2496 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2498 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2499 kn->kn_status &= ~KN_QUEUED;
2507 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2508 NULL, NULL, UMA_ALIGN_PTR, 0);
2510 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2512 static struct knote *
2513 knote_alloc(int waitok)
2516 return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2521 knote_free(struct knote *kn)
2524 uma_zfree(knote_zone, kn);
2528 * Register the kev w/ the kq specified by fd.
2531 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2535 cap_rights_t rights;
2538 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2541 if ((error = kqueue_acquire(fp, &kq)) != 0)
2544 error = kqueue_register(kq, kev, td, waitok);
2545 kqueue_release(kq, 0);