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 int filt_timer(struct knote *kn, long hint);
155 static int filt_userattach(struct knote *kn);
156 static void filt_userdetach(struct knote *kn);
157 static int filt_user(struct knote *kn, long hint);
158 static void filt_usertouch(struct knote *kn, struct kevent *kev,
161 static struct filterops file_filtops = {
163 .f_attach = filt_fileattach,
165 static struct filterops kqread_filtops = {
167 .f_detach = filt_kqdetach,
168 .f_event = filt_kqueue,
170 /* XXX - move to kern_proc.c? */
171 static struct filterops proc_filtops = {
173 .f_attach = filt_procattach,
174 .f_detach = filt_procdetach,
175 .f_event = filt_proc,
177 static struct filterops timer_filtops = {
179 .f_attach = filt_timerattach,
180 .f_detach = filt_timerdetach,
181 .f_event = filt_timer,
183 static struct filterops user_filtops = {
184 .f_attach = filt_userattach,
185 .f_detach = filt_userdetach,
186 .f_event = filt_user,
187 .f_touch = filt_usertouch,
190 static uma_zone_t knote_zone;
191 static unsigned int kq_ncallouts = 0;
192 static unsigned int kq_calloutmax = 4 * 1024;
193 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
194 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
196 /* XXX - ensure not KN_INFLUX?? */
197 #define KNOTE_ACTIVATE(kn, islock) do { \
199 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
201 KQ_LOCK((kn)->kn_kq); \
202 (kn)->kn_status |= KN_ACTIVE; \
203 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
204 knote_enqueue((kn)); \
206 KQ_UNLOCK((kn)->kn_kq); \
208 #define KQ_LOCK(kq) do { \
209 mtx_lock(&(kq)->kq_lock); \
211 #define KQ_FLUX_WAKEUP(kq) do { \
212 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
213 (kq)->kq_state &= ~KQ_FLUXWAIT; \
217 #define KQ_UNLOCK_FLUX(kq) do { \
218 KQ_FLUX_WAKEUP(kq); \
219 mtx_unlock(&(kq)->kq_lock); \
221 #define KQ_UNLOCK(kq) do { \
222 mtx_unlock(&(kq)->kq_lock); \
224 #define KQ_OWNED(kq) do { \
225 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
227 #define KQ_NOTOWNED(kq) do { \
228 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
231 static struct knlist *
232 kn_list_lock(struct knote *kn)
238 knl->kl_lock(knl->kl_lockarg);
243 kn_list_unlock(struct knlist *knl)
249 do_free = knl->kl_autodestroy && knlist_empty(knl);
250 knl->kl_unlock(knl->kl_lockarg);
257 #define KNL_ASSERT_LOCK(knl, islocked) do { \
259 KNL_ASSERT_LOCKED(knl); \
261 KNL_ASSERT_UNLOCKED(knl); \
264 #define KNL_ASSERT_LOCKED(knl) do { \
265 knl->kl_assert_locked((knl)->kl_lockarg); \
267 #define KNL_ASSERT_UNLOCKED(knl) do { \
268 knl->kl_assert_unlocked((knl)->kl_lockarg); \
270 #else /* !INVARIANTS */
271 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
272 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
273 #endif /* INVARIANTS */
276 #define KN_HASHSIZE 64 /* XXX should be tunable */
279 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
282 filt_nullattach(struct knote *kn)
288 struct filterops null_filtops = {
290 .f_attach = filt_nullattach,
293 /* XXX - make SYSINIT to add these, and move into respective modules. */
294 extern struct filterops sig_filtops;
295 extern struct filterops fs_filtops;
298 * Table for for all system-defined filters.
300 static struct mtx filterops_lock;
301 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
304 struct filterops *for_fop;
307 } sysfilt_ops[EVFILT_SYSCOUNT] = {
308 { &file_filtops, 1 }, /* EVFILT_READ */
309 { &file_filtops, 1 }, /* EVFILT_WRITE */
310 { &null_filtops }, /* EVFILT_AIO */
311 { &file_filtops, 1 }, /* EVFILT_VNODE */
312 { &proc_filtops, 1 }, /* EVFILT_PROC */
313 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
314 { &timer_filtops, 1 }, /* EVFILT_TIMER */
315 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
316 { &fs_filtops, 1 }, /* EVFILT_FS */
317 { &null_filtops }, /* EVFILT_LIO */
318 { &user_filtops, 1 }, /* EVFILT_USER */
319 { &null_filtops }, /* EVFILT_SENDFILE */
323 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
327 filt_fileattach(struct knote *kn)
330 return (fo_kqfilter(kn->kn_fp, kn));
335 kqueue_kqfilter(struct file *fp, struct knote *kn)
337 struct kqueue *kq = kn->kn_fp->f_data;
339 if (kn->kn_filter != EVFILT_READ)
342 kn->kn_status |= KN_KQUEUE;
343 kn->kn_fop = &kqread_filtops;
344 knlist_add(&kq->kq_sel.si_note, kn, 0);
350 filt_kqdetach(struct knote *kn)
352 struct kqueue *kq = kn->kn_fp->f_data;
354 knlist_remove(&kq->kq_sel.si_note, kn, 0);
359 filt_kqueue(struct knote *kn, long hint)
361 struct kqueue *kq = kn->kn_fp->f_data;
363 kn->kn_data = kq->kq_count;
364 return (kn->kn_data > 0);
367 /* XXX - move to kern_proc.c? */
369 filt_procattach(struct knote *kn)
373 bool exiting, immediate;
375 exiting = immediate = false;
376 p = pfind(kn->kn_id);
377 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
378 p = zpfind(kn->kn_id);
380 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
386 if ((error = p_cansee(curthread, p))) {
391 kn->kn_ptr.p_proc = p;
392 kn->kn_flags |= EV_CLEAR; /* automatically set */
395 * Internal flag indicating registration done by kernel for the
396 * purposes of getting a NOTE_CHILD notification.
398 if (kn->kn_flags & EV_FLAG2) {
399 kn->kn_flags &= ~EV_FLAG2;
400 kn->kn_data = kn->kn_sdata; /* ppid */
401 kn->kn_fflags = NOTE_CHILD;
402 kn->kn_sfflags &= ~(NOTE_EXIT | NOTE_EXEC | NOTE_FORK);
403 immediate = true; /* Force immediate activation of child note. */
406 * Internal flag indicating registration done by kernel (for other than
409 if (kn->kn_flags & EV_FLAG1) {
410 kn->kn_flags &= ~EV_FLAG1;
413 knlist_add(p->p_klist, kn, 1);
416 * Immediately activate any child notes or, in the case of a zombie
417 * target process, exit notes. The latter is necessary to handle the
418 * case where the target process, e.g. a child, dies before the kevent
421 if (immediate || (exiting && filt_proc(kn, NOTE_EXIT)))
422 KNOTE_ACTIVATE(kn, 0);
430 * The knote may be attached to a different process, which may exit,
431 * leaving nothing for the knote to be attached to. So when the process
432 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
433 * it will be deleted when read out. However, as part of the knote deletion,
434 * this routine is called, so a check is needed to avoid actually performing
435 * a detach, because the original process does not exist any more.
437 /* XXX - move to kern_proc.c? */
439 filt_procdetach(struct knote *kn)
442 knlist_remove(kn->kn_knlist, kn, 0);
443 kn->kn_ptr.p_proc = NULL;
446 /* XXX - move to kern_proc.c? */
448 filt_proc(struct knote *kn, long hint)
453 p = kn->kn_ptr.p_proc;
454 if (p == NULL) /* already activated, from attach filter */
457 /* Mask off extra data. */
458 event = (u_int)hint & NOTE_PCTRLMASK;
460 /* If the user is interested in this event, record it. */
461 if (kn->kn_sfflags & event)
462 kn->kn_fflags |= event;
464 /* Process is gone, so flag the event as finished. */
465 if (event == NOTE_EXIT) {
466 kn->kn_flags |= EV_EOF | EV_ONESHOT;
467 kn->kn_ptr.p_proc = NULL;
468 if (kn->kn_fflags & NOTE_EXIT)
469 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
470 if (kn->kn_fflags == 0)
471 kn->kn_flags |= EV_DROP;
475 return (kn->kn_fflags != 0);
479 * Called when the process forked. It mostly does the same as the
480 * knote(), activating all knotes registered to be activated when the
481 * process forked. Additionally, for each knote attached to the
482 * parent, check whether user wants to track the new process. If so
483 * attach a new knote to it, and immediately report an event with the
487 knote_fork(struct knlist *list, int pid)
496 list->kl_lock(list->kl_lockarg);
498 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
501 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
507 * The same as knote(), activate the event.
509 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
510 kn->kn_status |= KN_HASKQLOCK;
511 if (kn->kn_fop->f_event(kn, NOTE_FORK))
512 KNOTE_ACTIVATE(kn, 1);
513 kn->kn_status &= ~KN_HASKQLOCK;
519 * The NOTE_TRACK case. In addition to the activation
520 * of the event, we need to register new events to
521 * track the child. Drop the locks in preparation for
522 * the call to kqueue_register().
524 kn->kn_status |= KN_INFLUX;
526 list->kl_unlock(list->kl_lockarg);
529 * Activate existing knote and register tracking knotes with
532 * First register a knote to get just the child notice. This
533 * must be a separate note from a potential NOTE_EXIT
534 * notification since both NOTE_CHILD and NOTE_EXIT are defined
535 * to use the data field (in conflicting ways).
538 kev.filter = kn->kn_filter;
539 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT |
541 kev.fflags = kn->kn_sfflags;
542 kev.data = kn->kn_id; /* parent */
543 kev.udata = kn->kn_kevent.udata;/* preserve udata */
544 error = kqueue_register(kq, &kev, NULL, 0);
546 kn->kn_fflags |= NOTE_TRACKERR;
549 * Then register another knote to track other potential events
550 * from the new process.
553 kev.filter = kn->kn_filter;
554 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
555 kev.fflags = kn->kn_sfflags;
556 kev.data = kn->kn_id; /* parent */
557 kev.udata = kn->kn_kevent.udata;/* preserve udata */
558 error = kqueue_register(kq, &kev, NULL, 0);
560 kn->kn_fflags |= NOTE_TRACKERR;
561 if (kn->kn_fop->f_event(kn, NOTE_FORK))
562 KNOTE_ACTIVATE(kn, 0);
564 kn->kn_status &= ~KN_INFLUX;
566 list->kl_lock(list->kl_lockarg);
568 list->kl_unlock(list->kl_lockarg);
572 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
573 * interval timer support code.
576 #define NOTE_TIMER_PRECMASK (NOTE_SECONDS|NOTE_MSECONDS|NOTE_USECONDS| \
580 timer2sbintime(intptr_t data, int flags)
584 * Macros for converting to the fractional second portion of an
585 * sbintime_t using 64bit multiplication to improve precision.
587 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
588 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
589 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
590 switch (flags & NOTE_TIMER_PRECMASK) {
593 if (data > (SBT_MAX / SBT_1S))
596 return ((sbintime_t)data << 32);
597 case NOTE_MSECONDS: /* FALLTHROUGH */
600 int64_t secs = data / 1000;
602 if (secs > (SBT_MAX / SBT_1S))
605 return (secs << 32 | MS_TO_SBT(data % 1000));
607 return MS_TO_SBT(data);
609 if (data >= 1000000) {
610 int64_t secs = data / 1000000;
612 if (secs > (SBT_MAX / SBT_1S))
615 return (secs << 32 | US_TO_SBT(data % 1000000));
617 return US_TO_SBT(data);
619 if (data >= 1000000000) {
620 int64_t secs = data / 1000000000;
622 if (secs > (SBT_MAX / SBT_1S))
625 return (secs << 32 | US_TO_SBT(data % 1000000000));
627 return (NS_TO_SBT(data));
634 struct kq_timer_cb_data {
636 sbintime_t next; /* next timer event fires at */
637 sbintime_t to; /* precalculated timer period */
641 filt_timerexpire(void *knx)
644 struct kq_timer_cb_data *kc;
648 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
650 if ((kn->kn_flags & EV_ONESHOT) != 0)
655 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
656 PCPU_GET(cpuid), C_ABSOLUTE);
660 * data contains amount of time to sleep
663 filt_timerattach(struct knote *kn)
665 struct kq_timer_cb_data *kc;
667 unsigned int ncallouts;
669 if (kn->kn_sdata < 0)
671 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
673 /* Only precision unit are supported in flags so far */
674 if ((kn->kn_sfflags & ~NOTE_TIMER_PRECMASK) != 0)
677 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
682 ncallouts = kq_ncallouts;
683 if (ncallouts >= kq_calloutmax)
685 } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
687 kn->kn_flags |= EV_CLEAR; /* automatically set */
688 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
689 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
690 callout_init(&kc->c, 1);
691 kc->next = to + sbinuptime();
693 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
694 PCPU_GET(cpuid), C_ABSOLUTE);
700 filt_timerdetach(struct knote *kn)
702 struct kq_timer_cb_data *kc;
706 callout_drain(&kc->c);
708 old = atomic_fetchadd_int(&kq_ncallouts, -1);
709 KASSERT(old > 0, ("Number of callouts cannot become negative"));
710 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
714 filt_timer(struct knote *kn, long hint)
717 return (kn->kn_data != 0);
721 filt_userattach(struct knote *kn)
725 * EVFILT_USER knotes are not attached to anything in the kernel.
728 if (kn->kn_fflags & NOTE_TRIGGER)
736 filt_userdetach(__unused struct knote *kn)
740 * EVFILT_USER knotes are not attached to anything in the kernel.
745 filt_user(struct knote *kn, __unused long hint)
748 return (kn->kn_hookid);
752 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
758 if (kev->fflags & NOTE_TRIGGER)
761 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
762 kev->fflags &= NOTE_FFLAGSMASK;
768 kn->kn_sfflags &= kev->fflags;
772 kn->kn_sfflags |= kev->fflags;
776 kn->kn_sfflags = kev->fflags;
780 /* XXX Return error? */
783 kn->kn_sdata = kev->data;
784 if (kev->flags & EV_CLEAR) {
792 *kev = kn->kn_kevent;
793 kev->fflags = kn->kn_sfflags;
794 kev->data = kn->kn_sdata;
795 if (kn->kn_flags & EV_CLEAR) {
803 panic("filt_usertouch() - invalid type (%ld)", type);
809 sys_kqueue(struct thread *td, struct kqueue_args *uap)
812 return (kern_kqueue(td, 0, NULL));
816 kqueue_init(struct kqueue *kq)
819 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
820 TAILQ_INIT(&kq->kq_head);
821 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
822 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
826 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
828 struct filedesc *fdp;
834 fdp = td->td_proc->p_fd;
836 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
839 error = falloc_caps(td, &fp, &fd, flags, fcaps);
841 chgkqcnt(cred->cr_ruidinfo, -1, 0);
845 /* An extra reference on `fp' has been held for us by falloc(). */
846 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
849 kq->kq_cred = crhold(cred);
852 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
853 FILEDESC_XUNLOCK(fdp);
855 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
858 td->td_retval[0] = fd;
864 kev_iovlen(int n, u_int kgio)
867 if (n < 0 || n >= kgio / sizeof(struct kevent))
869 return (n * sizeof(struct kevent));
873 #ifndef _SYS_SYSPROTO_H_
876 const struct kevent *changelist;
878 struct kevent *eventlist;
880 const struct timespec *timeout;
884 sys_kevent(struct thread *td, struct kevent_args *uap)
886 struct timespec ts, *tsp;
887 struct kevent_copyops k_ops = {
889 .k_copyout = kevent_copyout,
890 .k_copyin = kevent_copyin,
896 struct uio *ktruioin = NULL;
897 struct uio *ktruioout = NULL;
901 if (uap->timeout != NULL) {
902 error = copyin(uap->timeout, &ts, sizeof(ts));
910 if (KTRPOINT(td, KTR_GENIO)) {
911 kgio = ktr_geniosize;
912 ktriov.iov_base = uap->changelist;
913 ktriov.iov_len = kev_iovlen(uap->nchanges, kgio);
914 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
915 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
917 ktruioin = cloneuio(&ktruio);
918 ktriov.iov_base = uap->eventlist;
919 ktriov.iov_len = kev_iovlen(uap->nevents, kgio);
920 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
921 ktruioout = cloneuio(&ktruio);
925 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
929 if (ktruioin != NULL) {
930 ktruioin->uio_resid = kev_iovlen(uap->nchanges, kgio);
931 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
932 ktruioout->uio_resid = kev_iovlen(td->td_retval[0], kgio);
933 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
941 * Copy 'count' items into the destination list pointed to by uap->eventlist.
944 kevent_copyout(void *arg, struct kevent *kevp, int count)
946 struct kevent_args *uap;
949 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
950 uap = (struct kevent_args *)arg;
952 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
954 uap->eventlist += count;
959 * Copy 'count' items from the list pointed to by uap->changelist.
962 kevent_copyin(void *arg, struct kevent *kevp, int count)
964 struct kevent_args *uap;
967 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
968 uap = (struct kevent_args *)arg;
970 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
972 uap->changelist += count;
977 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
978 struct kevent_copyops *k_ops, const struct timespec *timeout)
984 cap_rights_init(&rights);
986 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
988 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
989 error = fget(td, fd, &rights, &fp);
993 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
1000 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
1001 struct kevent_copyops *k_ops, const struct timespec *timeout)
1003 struct kevent keva[KQ_NEVENTS];
1004 struct kevent *kevp, *changes;
1005 int i, n, nerrors, error;
1008 while (nchanges > 0) {
1009 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
1010 error = k_ops->k_copyin(k_ops->arg, keva, n);
1014 for (i = 0; i < n; i++) {
1018 kevp->flags &= ~EV_SYSFLAGS;
1019 error = kqueue_register(kq, kevp, td, 1);
1020 if (error || (kevp->flags & EV_RECEIPT)) {
1023 kevp->flags = EV_ERROR;
1025 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
1033 td->td_retval[0] = nerrors;
1037 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
1041 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
1042 struct kevent_copyops *k_ops, const struct timespec *timeout)
1047 error = kqueue_acquire(fp, &kq);
1050 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
1051 kqueue_release(kq, 0);
1056 * Performs a kevent() call on a temporarily created kqueue. This can be
1057 * used to perform one-shot polling, similar to poll() and select().
1060 kern_kevent_anonymous(struct thread *td, int nevents,
1061 struct kevent_copyops *k_ops)
1063 struct kqueue kq = {};
1068 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1069 kqueue_drain(&kq, td);
1070 kqueue_destroy(&kq);
1075 kqueue_add_filteropts(int filt, struct filterops *filtops)
1080 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1082 "trying to add a filterop that is out of range: %d is beyond %d\n",
1083 ~filt, EVFILT_SYSCOUNT);
1086 mtx_lock(&filterops_lock);
1087 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1088 sysfilt_ops[~filt].for_fop != NULL)
1091 sysfilt_ops[~filt].for_fop = filtops;
1092 sysfilt_ops[~filt].for_refcnt = 0;
1094 mtx_unlock(&filterops_lock);
1100 kqueue_del_filteropts(int filt)
1105 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1108 mtx_lock(&filterops_lock);
1109 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1110 sysfilt_ops[~filt].for_fop == NULL)
1112 else if (sysfilt_ops[~filt].for_refcnt != 0)
1115 sysfilt_ops[~filt].for_fop = &null_filtops;
1116 sysfilt_ops[~filt].for_refcnt = 0;
1118 mtx_unlock(&filterops_lock);
1123 static struct filterops *
1124 kqueue_fo_find(int filt)
1127 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1130 if (sysfilt_ops[~filt].for_nolock)
1131 return sysfilt_ops[~filt].for_fop;
1133 mtx_lock(&filterops_lock);
1134 sysfilt_ops[~filt].for_refcnt++;
1135 if (sysfilt_ops[~filt].for_fop == NULL)
1136 sysfilt_ops[~filt].for_fop = &null_filtops;
1137 mtx_unlock(&filterops_lock);
1139 return sysfilt_ops[~filt].for_fop;
1143 kqueue_fo_release(int filt)
1146 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1149 if (sysfilt_ops[~filt].for_nolock)
1152 mtx_lock(&filterops_lock);
1153 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1154 ("filter object refcount not valid on release"));
1155 sysfilt_ops[~filt].for_refcnt--;
1156 mtx_unlock(&filterops_lock);
1160 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1161 * influence if memory allocation should wait. Make sure it is 0 if you
1165 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1167 struct filterops *fops;
1169 struct knote *kn, *tkn;
1171 cap_rights_t rights;
1172 int error, filt, event;
1173 int haskqglobal, filedesc_unlock;
1175 if ((kev->flags & (EV_ENABLE | EV_DISABLE)) == (EV_ENABLE | EV_DISABLE))
1183 filedesc_unlock = 0;
1186 fops = kqueue_fo_find(filt);
1190 if (kev->flags & EV_ADD) {
1192 * Prevent waiting with locks. Non-sleepable
1193 * allocation failures are handled in the loop, only
1194 * if the spare knote appears to be actually required.
1196 tkn = knote_alloc(waitok);
1203 KASSERT(td != NULL, ("td is NULL"));
1204 if (kev->ident > INT_MAX)
1207 error = fget(td, kev->ident,
1208 cap_rights_init(&rights, CAP_EVENT), &fp);
1212 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1213 kev->ident, 0) != 0) {
1217 error = kqueue_expand(kq, fops, kev->ident, waitok);
1223 if (fp->f_type == DTYPE_KQUEUE) {
1225 * If we add some intelligence about what we are doing,
1226 * we should be able to support events on ourselves.
1227 * We need to know when we are doing this to prevent
1228 * getting both the knlist lock and the kq lock since
1229 * they are the same thing.
1231 if (fp->f_data == kq) {
1237 * Pre-lock the filedesc before the global
1238 * lock mutex, see the comment in
1241 FILEDESC_XLOCK(td->td_proc->p_fd);
1242 filedesc_unlock = 1;
1243 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1247 if (kev->ident < kq->kq_knlistsize) {
1248 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1249 if (kev->filter == kn->kn_filter)
1253 if ((kev->flags & EV_ADD) == EV_ADD)
1254 kqueue_expand(kq, fops, kev->ident, waitok);
1259 * If possible, find an existing knote to use for this kevent.
1261 if (kev->filter == EVFILT_PROC &&
1262 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1263 /* This is an internal creation of a process tracking
1264 * note. Don't attempt to coalesce this with an
1268 } else if (kq->kq_knhashmask != 0) {
1271 list = &kq->kq_knhash[
1272 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1273 SLIST_FOREACH(kn, list, kn_link)
1274 if (kev->ident == kn->kn_id &&
1275 kev->filter == kn->kn_filter)
1280 /* knote is in the process of changing, wait for it to stabilize. */
1281 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1282 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1283 if (filedesc_unlock) {
1284 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1285 filedesc_unlock = 0;
1287 kq->kq_state |= KQ_FLUXWAIT;
1288 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1297 * kn now contains the matching knote, or NULL if no match
1300 if (kev->flags & EV_ADD) {
1312 * apply reference counts to knote structure, and
1313 * do not release it at the end of this routine.
1318 kn->kn_sfflags = kev->fflags;
1319 kn->kn_sdata = kev->data;
1322 kn->kn_kevent = *kev;
1323 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1324 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1325 kn->kn_status = KN_INFLUX|KN_DETACHED;
1327 error = knote_attach(kn, kq);
1334 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1338 knl = kn_list_lock(kn);
1341 /* No matching knote and the EV_ADD flag is not set. */
1348 if (kev->flags & EV_DELETE) {
1349 kn->kn_status |= KN_INFLUX;
1351 if (!(kn->kn_status & KN_DETACHED))
1352 kn->kn_fop->f_detach(kn);
1357 if (kev->flags & EV_FORCEONESHOT) {
1358 kn->kn_flags |= EV_ONESHOT;
1359 KNOTE_ACTIVATE(kn, 1);
1363 * The user may change some filter values after the initial EV_ADD,
1364 * but doing so will not reset any filter which has already been
1367 kn->kn_status |= KN_INFLUX | KN_SCAN;
1369 knl = kn_list_lock(kn);
1370 kn->kn_kevent.udata = kev->udata;
1371 if (!fops->f_isfd && fops->f_touch != NULL) {
1372 fops->f_touch(kn, kev, EVENT_REGISTER);
1374 kn->kn_sfflags = kev->fflags;
1375 kn->kn_sdata = kev->data;
1379 * We can get here with kn->kn_knlist == NULL. This can happen when
1380 * the initial attach event decides that the event is "completed"
1381 * already. i.e. filt_procattach is called on a zombie process. It
1382 * will call filt_proc which will remove it from the list, and NULL
1386 if ((kev->flags & EV_ENABLE) != 0)
1387 kn->kn_status &= ~KN_DISABLED;
1388 else if ((kev->flags & EV_DISABLE) != 0)
1389 kn->kn_status |= KN_DISABLED;
1391 if ((kn->kn_status & KN_DISABLED) == 0)
1392 event = kn->kn_fop->f_event(kn, 0);
1398 kn->kn_status |= KN_ACTIVE;
1399 if ((kn->kn_status & (KN_ACTIVE | KN_DISABLED | KN_QUEUED)) ==
1402 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1403 kn_list_unlock(knl);
1407 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1408 if (filedesc_unlock)
1409 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1414 kqueue_fo_release(filt);
1419 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1427 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1431 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1442 kqueue_release(struct kqueue *kq, int locked)
1449 if (kq->kq_refcnt == 1)
1450 wakeup(&kq->kq_refcnt);
1456 kqueue_schedtask(struct kqueue *kq)
1460 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1461 ("scheduling kqueue task while draining"));
1463 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1464 taskqueue_enqueue(taskqueue_kqueue_ctx, &kq->kq_task);
1465 kq->kq_state |= KQ_TASKSCHED;
1470 * Expand the kq to make sure we have storage for fops/ident pair.
1472 * Return 0 on success (or no work necessary), return errno on failure.
1474 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1475 * If kqueue_register is called from a non-fd context, there usually/should
1479 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1482 struct klist *list, *tmp_knhash, *to_free;
1483 u_long tmp_knhashmask;
1486 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1493 if (kq->kq_knlistsize <= fd) {
1494 size = kq->kq_knlistsize;
1497 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1501 if (kq->kq_knlistsize > fd) {
1505 if (kq->kq_knlist != NULL) {
1506 bcopy(kq->kq_knlist, list,
1507 kq->kq_knlistsize * sizeof(*list));
1508 to_free = kq->kq_knlist;
1509 kq->kq_knlist = NULL;
1511 bzero((caddr_t)list +
1512 kq->kq_knlistsize * sizeof(*list),
1513 (size - kq->kq_knlistsize) * sizeof(*list));
1514 kq->kq_knlistsize = size;
1515 kq->kq_knlist = list;
1520 if (kq->kq_knhashmask == 0) {
1521 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1523 if (tmp_knhash == NULL)
1526 if (kq->kq_knhashmask == 0) {
1527 kq->kq_knhash = tmp_knhash;
1528 kq->kq_knhashmask = tmp_knhashmask;
1530 to_free = tmp_knhash;
1535 free(to_free, M_KQUEUE);
1542 kqueue_task(void *arg, int pending)
1550 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1553 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1555 kq->kq_state &= ~KQ_TASKSCHED;
1556 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1557 wakeup(&kq->kq_state);
1560 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1564 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1565 * We treat KN_MARKER knotes as if they are INFLUX.
1568 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1569 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1571 struct kevent *kevp;
1572 struct knote *kn, *marker;
1574 sbintime_t asbt, rsbt;
1575 int count, error, haskqglobal, influx, nkev, touch;
1587 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1588 tsp->tv_nsec >= 1000000000) {
1592 if (timespecisset(tsp)) {
1593 if (tsp->tv_sec <= INT32_MAX) {
1594 rsbt = tstosbt(*tsp);
1595 if (TIMESEL(&asbt, rsbt))
1596 asbt += tc_tick_sbt;
1597 if (asbt <= SBT_MAX - rsbt)
1601 rsbt >>= tc_precexp;
1608 marker = knote_alloc(1);
1609 marker->kn_status = KN_MARKER;
1614 if (kq->kq_count == 0) {
1616 error = EWOULDBLOCK;
1618 kq->kq_state |= KQ_SLEEP;
1619 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1620 "kqread", asbt, rsbt, C_ABSOLUTE);
1624 /* don't restart after signals... */
1625 if (error == ERESTART)
1627 else if (error == EWOULDBLOCK)
1632 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1636 kn = TAILQ_FIRST(&kq->kq_head);
1638 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1639 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1644 kq->kq_state |= KQ_FLUXWAIT;
1645 error = msleep(kq, &kq->kq_lock, PSOCK,
1650 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1651 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1652 kn->kn_status &= ~KN_QUEUED;
1658 if (count == maxevents)
1662 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1663 ("KN_INFLUX set when not suppose to be"));
1665 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1666 kn->kn_status &= ~KN_QUEUED;
1667 kn->kn_status |= KN_INFLUX;
1671 * We don't need to lock the list since we've marked
1674 if (!(kn->kn_status & KN_DETACHED))
1675 kn->kn_fop->f_detach(kn);
1679 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1680 kn->kn_status &= ~KN_QUEUED;
1681 kn->kn_status |= KN_INFLUX;
1685 * We don't need to lock the list since we've marked
1688 *kevp = kn->kn_kevent;
1689 if (!(kn->kn_status & KN_DETACHED))
1690 kn->kn_fop->f_detach(kn);
1695 kn->kn_status |= KN_INFLUX | KN_SCAN;
1697 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1698 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1699 knl = kn_list_lock(kn);
1700 if (kn->kn_fop->f_event(kn, 0) == 0) {
1702 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1704 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1707 kn_list_unlock(knl);
1711 touch = (!kn->kn_fop->f_isfd &&
1712 kn->kn_fop->f_touch != NULL);
1714 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1716 *kevp = kn->kn_kevent;
1718 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1719 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1721 * Manually clear knotes who weren't
1724 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1728 if (kn->kn_flags & EV_DISPATCH)
1729 kn->kn_status |= KN_DISABLED;
1730 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1733 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1735 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1736 kn_list_unlock(knl);
1740 /* we are returning a copy to the user */
1745 if (nkev == KQ_NEVENTS) {
1748 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1756 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1764 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1765 td->td_retval[0] = maxevents - count;
1771 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1772 struct ucred *active_cred, struct thread *td)
1775 * Enabling sigio causes two major problems:
1776 * 1) infinite recursion:
1777 * Synopsys: kevent is being used to track signals and have FIOASYNC
1778 * set. On receipt of a signal this will cause a kqueue to recurse
1779 * into itself over and over. Sending the sigio causes the kqueue
1780 * to become ready, which in turn posts sigio again, forever.
1781 * Solution: this can be solved by setting a flag in the kqueue that
1782 * we have a SIGIO in progress.
1783 * 2) locking problems:
1784 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1785 * us above the proc and pgrp locks.
1786 * Solution: Post a signal using an async mechanism, being sure to
1787 * record a generation count in the delivery so that we do not deliver
1788 * a signal to the wrong process.
1790 * Note, these two mechanisms are somewhat mutually exclusive!
1799 kq->kq_state |= KQ_ASYNC;
1801 kq->kq_state &= ~KQ_ASYNC;
1806 return (fsetown(*(int *)data, &kq->kq_sigio));
1809 *(int *)data = fgetown(&kq->kq_sigio);
1819 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1826 if ((error = kqueue_acquire(fp, &kq)))
1830 if (events & (POLLIN | POLLRDNORM)) {
1832 revents |= events & (POLLIN | POLLRDNORM);
1834 selrecord(td, &kq->kq_sel);
1835 if (SEL_WAITING(&kq->kq_sel))
1836 kq->kq_state |= KQ_SEL;
1839 kqueue_release(kq, 1);
1846 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1850 bzero((void *)st, sizeof *st);
1852 * We no longer return kq_count because the unlocked value is useless.
1853 * If you spent all this time getting the count, why not spend your
1854 * syscall better by calling kevent?
1856 * XXX - This is needed for libc_r.
1858 st->st_mode = S_IFIFO;
1863 kqueue_drain(struct kqueue *kq, struct thread *td)
1870 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1871 ("kqueue already closing"));
1872 kq->kq_state |= KQ_CLOSING;
1873 if (kq->kq_refcnt > 1)
1874 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1876 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1878 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1879 ("kqueue's knlist not empty"));
1881 for (i = 0; i < kq->kq_knlistsize; i++) {
1882 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1883 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1884 kq->kq_state |= KQ_FLUXWAIT;
1885 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1888 kn->kn_status |= KN_INFLUX;
1890 if (!(kn->kn_status & KN_DETACHED))
1891 kn->kn_fop->f_detach(kn);
1896 if (kq->kq_knhashmask != 0) {
1897 for (i = 0; i <= kq->kq_knhashmask; i++) {
1898 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1899 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1900 kq->kq_state |= KQ_FLUXWAIT;
1901 msleep(kq, &kq->kq_lock, PSOCK,
1905 kn->kn_status |= KN_INFLUX;
1907 if (!(kn->kn_status & KN_DETACHED))
1908 kn->kn_fop->f_detach(kn);
1915 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1916 kq->kq_state |= KQ_TASKDRAIN;
1917 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1920 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1921 selwakeuppri(&kq->kq_sel, PSOCK);
1922 if (!SEL_WAITING(&kq->kq_sel))
1923 kq->kq_state &= ~KQ_SEL;
1930 kqueue_destroy(struct kqueue *kq)
1933 KASSERT(kq->kq_fdp == NULL,
1934 ("kqueue still attached to a file descriptor"));
1935 seldrain(&kq->kq_sel);
1936 knlist_destroy(&kq->kq_sel.si_note);
1937 mtx_destroy(&kq->kq_lock);
1939 if (kq->kq_knhash != NULL)
1940 free(kq->kq_knhash, M_KQUEUE);
1941 if (kq->kq_knlist != NULL)
1942 free(kq->kq_knlist, M_KQUEUE);
1944 funsetown(&kq->kq_sigio);
1949 kqueue_close(struct file *fp, struct thread *td)
1951 struct kqueue *kq = fp->f_data;
1952 struct filedesc *fdp;
1954 int filedesc_unlock;
1956 if ((error = kqueue_acquire(fp, &kq)))
1958 kqueue_drain(kq, td);
1961 * We could be called due to the knote_drop() doing fdrop(),
1962 * called from kqueue_register(). In this case the global
1963 * lock is owned, and filedesc sx is locked before, to not
1964 * take the sleepable lock after non-sleepable.
1968 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1969 FILEDESC_XLOCK(fdp);
1970 filedesc_unlock = 1;
1972 filedesc_unlock = 0;
1973 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1974 if (filedesc_unlock)
1975 FILEDESC_XUNLOCK(fdp);
1978 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1979 crfree(kq->kq_cred);
1987 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1990 kif->kf_type = KF_TYPE_KQUEUE;
1995 kqueue_wakeup(struct kqueue *kq)
1999 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
2000 kq->kq_state &= ~KQ_SLEEP;
2003 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
2004 selwakeuppri(&kq->kq_sel, PSOCK);
2005 if (!SEL_WAITING(&kq->kq_sel))
2006 kq->kq_state &= ~KQ_SEL;
2008 if (!knlist_empty(&kq->kq_sel.si_note))
2009 kqueue_schedtask(kq);
2010 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
2011 pgsigio(&kq->kq_sigio, SIGIO, 0);
2016 * Walk down a list of knotes, activating them if their event has triggered.
2018 * There is a possibility to optimize in the case of one kq watching another.
2019 * Instead of scheduling a task to wake it up, you could pass enough state
2020 * down the chain to make up the parent kqueue. Make this code functional
2024 knote(struct knlist *list, long hint, int lockflags)
2027 struct knote *kn, *tkn;
2034 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
2036 if ((lockflags & KNF_LISTLOCKED) == 0)
2037 list->kl_lock(list->kl_lockarg);
2040 * If we unlock the list lock (and set KN_INFLUX), we can
2041 * eliminate the kqueue scheduling, but this will introduce
2042 * four lock/unlock's for each knote to test. Also, marker
2043 * would be needed to keep iteration position, since filters
2044 * or other threads could remove events.
2046 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
2049 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
2051 * Do not process the influx notes, except for
2052 * the influx coming from the kq unlock in the
2053 * kqueue_scan(). In the later case, we do
2054 * not interfere with the scan, since the code
2055 * fragment in kqueue_scan() locks the knlist,
2056 * and cannot proceed until we finished.
2059 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
2060 own_influx = (kn->kn_status & KN_INFLUX) == 0;
2062 kn->kn_status |= KN_INFLUX;
2064 error = kn->kn_fop->f_event(kn, hint);
2067 kn->kn_status &= ~KN_INFLUX;
2069 KNOTE_ACTIVATE(kn, 1);
2072 kn->kn_status |= KN_HASKQLOCK;
2073 if (kn->kn_fop->f_event(kn, hint))
2074 KNOTE_ACTIVATE(kn, 1);
2075 kn->kn_status &= ~KN_HASKQLOCK;
2079 if ((lockflags & KNF_LISTLOCKED) == 0)
2080 list->kl_unlock(list->kl_lockarg);
2084 * add a knote to a knlist
2087 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2089 KNL_ASSERT_LOCK(knl, islocked);
2090 KQ_NOTOWNED(kn->kn_kq);
2091 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
2092 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
2094 knl->kl_lock(knl->kl_lockarg);
2095 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2097 knl->kl_unlock(knl->kl_lockarg);
2099 kn->kn_knlist = knl;
2100 kn->kn_status &= ~KN_DETACHED;
2101 KQ_UNLOCK(kn->kn_kq);
2105 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked,
2108 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2109 KNL_ASSERT_LOCK(knl, knlislocked);
2110 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2112 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2113 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2115 knl->kl_lock(knl->kl_lockarg);
2116 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2117 kn->kn_knlist = NULL;
2119 kn_list_unlock(knl);
2122 kn->kn_status |= KN_DETACHED;
2124 KQ_UNLOCK(kn->kn_kq);
2128 * remove knote from the specified knlist
2131 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2134 knlist_remove_kq(knl, kn, islocked, 0);
2138 knlist_empty(struct knlist *knl)
2141 KNL_ASSERT_LOCKED(knl);
2142 return (SLIST_EMPTY(&knl->kl_list));
2145 static struct mtx knlist_lock;
2146 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2148 static void knlist_mtx_lock(void *arg);
2149 static void knlist_mtx_unlock(void *arg);
2152 knlist_mtx_lock(void *arg)
2155 mtx_lock((struct mtx *)arg);
2159 knlist_mtx_unlock(void *arg)
2162 mtx_unlock((struct mtx *)arg);
2166 knlist_mtx_assert_locked(void *arg)
2169 mtx_assert((struct mtx *)arg, MA_OWNED);
2173 knlist_mtx_assert_unlocked(void *arg)
2176 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2180 knlist_rw_rlock(void *arg)
2183 rw_rlock((struct rwlock *)arg);
2187 knlist_rw_runlock(void *arg)
2190 rw_runlock((struct rwlock *)arg);
2194 knlist_rw_assert_locked(void *arg)
2197 rw_assert((struct rwlock *)arg, RA_LOCKED);
2201 knlist_rw_assert_unlocked(void *arg)
2204 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2208 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2209 void (*kl_unlock)(void *),
2210 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2214 knl->kl_lockarg = &knlist_lock;
2216 knl->kl_lockarg = lock;
2218 if (kl_lock == NULL)
2219 knl->kl_lock = knlist_mtx_lock;
2221 knl->kl_lock = kl_lock;
2222 if (kl_unlock == NULL)
2223 knl->kl_unlock = knlist_mtx_unlock;
2225 knl->kl_unlock = kl_unlock;
2226 if (kl_assert_locked == NULL)
2227 knl->kl_assert_locked = knlist_mtx_assert_locked;
2229 knl->kl_assert_locked = kl_assert_locked;
2230 if (kl_assert_unlocked == NULL)
2231 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2233 knl->kl_assert_unlocked = kl_assert_unlocked;
2235 knl->kl_autodestroy = 0;
2236 SLIST_INIT(&knl->kl_list);
2240 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2243 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2247 knlist_alloc(struct mtx *lock)
2251 knl = malloc(sizeof(struct knlist), M_KQUEUE, M_WAITOK);
2252 knlist_init_mtx(knl, lock);
2257 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2260 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2261 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2265 knlist_destroy(struct knlist *knl)
2268 KASSERT(KNLIST_EMPTY(knl),
2269 ("destroying knlist %p with knotes on it", knl));
2273 knlist_detach(struct knlist *knl)
2276 KNL_ASSERT_LOCKED(knl);
2277 knl->kl_autodestroy = 1;
2278 if (knlist_empty(knl)) {
2279 knlist_destroy(knl);
2280 free(knl, M_KQUEUE);
2285 * Even if we are locked, we may need to drop the lock to allow any influx
2286 * knotes time to "settle".
2289 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2291 struct knote *kn, *kn2;
2294 KASSERT(!knl->kl_autodestroy, ("cleardel for autodestroy %p", knl));
2296 KNL_ASSERT_LOCKED(knl);
2298 KNL_ASSERT_UNLOCKED(knl);
2299 again: /* need to reacquire lock since we have dropped it */
2300 knl->kl_lock(knl->kl_lockarg);
2303 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2306 if ((kn->kn_status & KN_INFLUX)) {
2310 knlist_remove_kq(knl, kn, 1, 1);
2312 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2316 /* Make sure cleared knotes disappear soon */
2317 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2323 if (!SLIST_EMPTY(&knl->kl_list)) {
2324 /* there are still KN_INFLUX remaining */
2325 kn = SLIST_FIRST(&knl->kl_list);
2328 KASSERT(kn->kn_status & KN_INFLUX,
2329 ("knote removed w/o list lock"));
2330 knl->kl_unlock(knl->kl_lockarg);
2331 kq->kq_state |= KQ_FLUXWAIT;
2332 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2338 KNL_ASSERT_LOCKED(knl);
2340 knl->kl_unlock(knl->kl_lockarg);
2341 KNL_ASSERT_UNLOCKED(knl);
2346 * Remove all knotes referencing a specified fd must be called with FILEDESC
2347 * lock. This prevents a race where a new fd comes along and occupies the
2348 * entry and we attach a knote to the fd.
2351 knote_fdclose(struct thread *td, int fd)
2353 struct filedesc *fdp = td->td_proc->p_fd;
2358 FILEDESC_XLOCK_ASSERT(fdp);
2361 * We shouldn't have to worry about new kevents appearing on fd
2362 * since filedesc is locked.
2364 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2369 while (kq->kq_knlistsize > fd &&
2370 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2371 if (kn->kn_status & KN_INFLUX) {
2372 /* someone else might be waiting on our knote */
2375 kq->kq_state |= KQ_FLUXWAIT;
2376 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2379 kn->kn_status |= KN_INFLUX;
2381 if (!(kn->kn_status & KN_DETACHED))
2382 kn->kn_fop->f_detach(kn);
2392 knote_attach(struct knote *kn, struct kqueue *kq)
2396 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2399 if (kn->kn_fop->f_isfd) {
2400 if (kn->kn_id >= kq->kq_knlistsize)
2402 list = &kq->kq_knlist[kn->kn_id];
2404 if (kq->kq_knhash == NULL)
2406 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2408 SLIST_INSERT_HEAD(list, kn, kn_link);
2413 * knote must already have been detached using the f_detach method.
2414 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2415 * to prevent other removal.
2418 knote_drop(struct knote *kn, struct thread *td)
2426 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2427 ("knote_drop called without KN_INFLUX set in kn_status"));
2430 if (kn->kn_fop->f_isfd)
2431 list = &kq->kq_knlist[kn->kn_id];
2433 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2435 if (!SLIST_EMPTY(list))
2436 SLIST_REMOVE(list, kn, knote, kn_link);
2437 if (kn->kn_status & KN_QUEUED)
2441 if (kn->kn_fop->f_isfd) {
2442 fdrop(kn->kn_fp, td);
2445 kqueue_fo_release(kn->kn_kevent.filter);
2451 knote_enqueue(struct knote *kn)
2453 struct kqueue *kq = kn->kn_kq;
2455 KQ_OWNED(kn->kn_kq);
2456 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2458 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2459 kn->kn_status |= KN_QUEUED;
2465 knote_dequeue(struct knote *kn)
2467 struct kqueue *kq = kn->kn_kq;
2469 KQ_OWNED(kn->kn_kq);
2470 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2472 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2473 kn->kn_status &= ~KN_QUEUED;
2481 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2482 NULL, NULL, UMA_ALIGN_PTR, 0);
2484 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2486 static struct knote *
2487 knote_alloc(int waitok)
2490 return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2495 knote_free(struct knote *kn)
2498 uma_zfree(knote_zone, kn);
2502 * Register the kev w/ the kq specified by fd.
2505 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2509 cap_rights_t rights;
2512 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2515 if ((error = kqueue_acquire(fp, &kq)) != 0)
2518 error = kqueue_register(kq, kev, td, waitok);
2519 kqueue_release(kq, 0);