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"
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/capsicum.h>
37 #include <sys/kernel.h>
39 #include <sys/mutex.h>
40 #include <sys/rwlock.h>
42 #include <sys/malloc.h>
43 #include <sys/unistd.h>
45 #include <sys/filedesc.h>
46 #include <sys/filio.h>
47 #include <sys/fcntl.h>
48 #include <sys/kthread.h>
49 #include <sys/selinfo.h>
50 #include <sys/queue.h>
51 #include <sys/event.h>
52 #include <sys/eventvar.h>
54 #include <sys/protosw.h>
55 #include <sys/sigio.h>
56 #include <sys/signalvar.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysproto.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/taskqueue.h>
66 #include <sys/ktrace.h>
68 #include <machine/atomic.h>
72 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
75 * This lock is used if multiple kq locks are required. This possibly
76 * should be made into a per proc lock.
78 static struct mtx kq_global;
79 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
80 #define KQ_GLOBAL_LOCK(lck, haslck) do { \
85 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
91 TASKQUEUE_DEFINE_THREAD(kqueue);
93 static int kevent_copyout(void *arg, struct kevent *kevp, int count);
94 static int kevent_copyin(void *arg, struct kevent *kevp, int count);
95 static int kqueue_register(struct kqueue *kq, struct kevent *kev,
96 struct thread *td, int waitok);
97 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
98 static void kqueue_release(struct kqueue *kq, int locked);
99 static int kqueue_expand(struct kqueue *kq, struct filterops *fops,
100 uintptr_t ident, int waitok);
101 static void kqueue_task(void *arg, int pending);
102 static int kqueue_scan(struct kqueue *kq, int maxevents,
103 struct kevent_copyops *k_ops,
104 const struct timespec *timeout,
105 struct kevent *keva, struct thread *td);
106 static void kqueue_wakeup(struct kqueue *kq);
107 static struct filterops *kqueue_fo_find(int filt);
108 static void kqueue_fo_release(int filt);
110 static fo_rdwr_t kqueue_read;
111 static fo_rdwr_t kqueue_write;
112 static fo_truncate_t kqueue_truncate;
113 static fo_ioctl_t kqueue_ioctl;
114 static fo_poll_t kqueue_poll;
115 static fo_kqfilter_t kqueue_kqfilter;
116 static fo_stat_t kqueue_stat;
117 static fo_close_t kqueue_close;
119 static struct fileops kqueueops = {
120 .fo_read = kqueue_read,
121 .fo_write = kqueue_write,
122 .fo_truncate = kqueue_truncate,
123 .fo_ioctl = kqueue_ioctl,
124 .fo_poll = kqueue_poll,
125 .fo_kqfilter = kqueue_kqfilter,
126 .fo_stat = kqueue_stat,
127 .fo_close = kqueue_close,
128 .fo_chmod = invfo_chmod,
129 .fo_chown = invfo_chown,
130 .fo_sendfile = invfo_sendfile,
133 static int knote_attach(struct knote *kn, struct kqueue *kq);
134 static void knote_drop(struct knote *kn, struct thread *td);
135 static void knote_enqueue(struct knote *kn);
136 static void knote_dequeue(struct knote *kn);
137 static void knote_init(void);
138 static struct knote *knote_alloc(int waitok);
139 static void knote_free(struct knote *kn);
141 static void filt_kqdetach(struct knote *kn);
142 static int filt_kqueue(struct knote *kn, long hint);
143 static int filt_procattach(struct knote *kn);
144 static void filt_procdetach(struct knote *kn);
145 static int filt_proc(struct knote *kn, long hint);
146 static int filt_fileattach(struct knote *kn);
147 static void filt_timerexpire(void *knx);
148 static int filt_timerattach(struct knote *kn);
149 static void filt_timerdetach(struct knote *kn);
150 static int filt_timer(struct knote *kn, long hint);
151 static int filt_userattach(struct knote *kn);
152 static void filt_userdetach(struct knote *kn);
153 static int filt_user(struct knote *kn, long hint);
154 static void filt_usertouch(struct knote *kn, struct kevent *kev,
157 static struct filterops file_filtops = {
159 .f_attach = filt_fileattach,
161 static struct filterops kqread_filtops = {
163 .f_detach = filt_kqdetach,
164 .f_event = filt_kqueue,
166 /* XXX - move to kern_proc.c? */
167 static struct filterops proc_filtops = {
169 .f_attach = filt_procattach,
170 .f_detach = filt_procdetach,
171 .f_event = filt_proc,
173 static struct filterops timer_filtops = {
175 .f_attach = filt_timerattach,
176 .f_detach = filt_timerdetach,
177 .f_event = filt_timer,
179 static struct filterops user_filtops = {
180 .f_attach = filt_userattach,
181 .f_detach = filt_userdetach,
182 .f_event = filt_user,
183 .f_touch = filt_usertouch,
186 static uma_zone_t knote_zone;
187 static unsigned int kq_ncallouts = 0;
188 static unsigned int kq_calloutmax = 4 * 1024;
189 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
190 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
192 /* XXX - ensure not KN_INFLUX?? */
193 #define KNOTE_ACTIVATE(kn, islock) do { \
195 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
197 KQ_LOCK((kn)->kn_kq); \
198 (kn)->kn_status |= KN_ACTIVE; \
199 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
200 knote_enqueue((kn)); \
202 KQ_UNLOCK((kn)->kn_kq); \
204 #define KQ_LOCK(kq) do { \
205 mtx_lock(&(kq)->kq_lock); \
207 #define KQ_FLUX_WAKEUP(kq) do { \
208 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
209 (kq)->kq_state &= ~KQ_FLUXWAIT; \
213 #define KQ_UNLOCK_FLUX(kq) do { \
214 KQ_FLUX_WAKEUP(kq); \
215 mtx_unlock(&(kq)->kq_lock); \
217 #define KQ_UNLOCK(kq) do { \
218 mtx_unlock(&(kq)->kq_lock); \
220 #define KQ_OWNED(kq) do { \
221 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
223 #define KQ_NOTOWNED(kq) do { \
224 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
226 #define KN_LIST_LOCK(kn) do { \
227 if (kn->kn_knlist != NULL) \
228 kn->kn_knlist->kl_lock(kn->kn_knlist->kl_lockarg); \
230 #define KN_LIST_UNLOCK(kn) do { \
231 if (kn->kn_knlist != NULL) \
232 kn->kn_knlist->kl_unlock(kn->kn_knlist->kl_lockarg); \
234 #define KNL_ASSERT_LOCK(knl, islocked) do { \
236 KNL_ASSERT_LOCKED(knl); \
238 KNL_ASSERT_UNLOCKED(knl); \
241 #define KNL_ASSERT_LOCKED(knl) do { \
242 knl->kl_assert_locked((knl)->kl_lockarg); \
244 #define KNL_ASSERT_UNLOCKED(knl) do { \
245 knl->kl_assert_unlocked((knl)->kl_lockarg); \
247 #else /* !INVARIANTS */
248 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
249 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
250 #endif /* INVARIANTS */
252 #define KN_HASHSIZE 64 /* XXX should be tunable */
253 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
256 filt_nullattach(struct knote *kn)
262 struct filterops null_filtops = {
264 .f_attach = filt_nullattach,
267 /* XXX - make SYSINIT to add these, and move into respective modules. */
268 extern struct filterops sig_filtops;
269 extern struct filterops fs_filtops;
272 * Table for for all system-defined filters.
274 static struct mtx filterops_lock;
275 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
278 struct filterops *for_fop;
280 } sysfilt_ops[EVFILT_SYSCOUNT] = {
281 { &file_filtops }, /* EVFILT_READ */
282 { &file_filtops }, /* EVFILT_WRITE */
283 { &null_filtops }, /* EVFILT_AIO */
284 { &file_filtops }, /* EVFILT_VNODE */
285 { &proc_filtops }, /* EVFILT_PROC */
286 { &sig_filtops }, /* EVFILT_SIGNAL */
287 { &timer_filtops }, /* EVFILT_TIMER */
288 { &null_filtops }, /* former EVFILT_NETDEV */
289 { &fs_filtops }, /* EVFILT_FS */
290 { &null_filtops }, /* EVFILT_LIO */
291 { &user_filtops }, /* EVFILT_USER */
295 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
299 filt_fileattach(struct knote *kn)
302 return (fo_kqfilter(kn->kn_fp, kn));
307 kqueue_kqfilter(struct file *fp, struct knote *kn)
309 struct kqueue *kq = kn->kn_fp->f_data;
311 if (kn->kn_filter != EVFILT_READ)
314 kn->kn_status |= KN_KQUEUE;
315 kn->kn_fop = &kqread_filtops;
316 knlist_add(&kq->kq_sel.si_note, kn, 0);
322 filt_kqdetach(struct knote *kn)
324 struct kqueue *kq = kn->kn_fp->f_data;
326 knlist_remove(&kq->kq_sel.si_note, kn, 0);
331 filt_kqueue(struct knote *kn, long hint)
333 struct kqueue *kq = kn->kn_fp->f_data;
335 kn->kn_data = kq->kq_count;
336 return (kn->kn_data > 0);
339 /* XXX - move to kern_proc.c? */
341 filt_procattach(struct knote *kn)
348 p = pfind(kn->kn_id);
349 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
350 p = zpfind(kn->kn_id);
352 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
358 if ((error = p_cansee(curthread, p))) {
363 kn->kn_ptr.p_proc = p;
364 kn->kn_flags |= EV_CLEAR; /* automatically set */
367 * Internal flag indicating registration done by kernel for the
368 * purposes of getting a NOTE_CHILD notification.
370 if (kn->kn_flags & EV_FLAG2) {
371 kn->kn_flags &= ~EV_FLAG2;
372 kn->kn_data = kn->kn_sdata; /* ppid */
373 kn->kn_fflags = NOTE_CHILD;
374 kn->kn_sfflags &= ~NOTE_EXIT;
375 immediate = 1; /* Force immediate activation of child note. */
378 * Internal flag indicating registration done by kernel (for other than
381 if (kn->kn_flags & EV_FLAG1) {
382 kn->kn_flags &= ~EV_FLAG1;
386 knlist_add(&p->p_klist, kn, 1);
389 * Immediately activate any child notes or, in the case of a zombie
390 * target process, exit notes. The latter is necessary to handle the
391 * case where the target process, e.g. a child, dies before the kevent
394 if (immediate && filt_proc(kn, NOTE_EXIT))
395 KNOTE_ACTIVATE(kn, 0);
403 * The knote may be attached to a different process, which may exit,
404 * leaving nothing for the knote to be attached to. So when the process
405 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
406 * it will be deleted when read out. However, as part of the knote deletion,
407 * this routine is called, so a check is needed to avoid actually performing
408 * a detach, because the original process does not exist any more.
410 /* XXX - move to kern_proc.c? */
412 filt_procdetach(struct knote *kn)
416 p = kn->kn_ptr.p_proc;
417 knlist_remove(&p->p_klist, kn, 0);
418 kn->kn_ptr.p_proc = NULL;
421 /* XXX - move to kern_proc.c? */
423 filt_proc(struct knote *kn, long hint)
425 struct proc *p = kn->kn_ptr.p_proc;
429 * mask off extra data
431 event = (u_int)hint & NOTE_PCTRLMASK;
434 * if the user is interested in this event, record it.
436 if (kn->kn_sfflags & event)
437 kn->kn_fflags |= event;
440 * process is gone, so flag the event as finished.
442 if (event == NOTE_EXIT) {
443 if (!(kn->kn_status & KN_DETACHED))
444 knlist_remove_inevent(&p->p_klist, kn);
445 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
446 kn->kn_ptr.p_proc = NULL;
447 if (kn->kn_fflags & NOTE_EXIT)
448 kn->kn_data = p->p_xstat;
449 if (kn->kn_fflags == 0)
450 kn->kn_flags |= EV_DROP;
454 return (kn->kn_fflags != 0);
458 * Called when the process forked. It mostly does the same as the
459 * knote(), activating all knotes registered to be activated when the
460 * process forked. Additionally, for each knote attached to the
461 * parent, check whether user wants to track the new process. If so
462 * attach a new knote to it, and immediately report an event with the
466 knote_fork(struct knlist *list, int pid)
475 list->kl_lock(list->kl_lockarg);
477 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
478 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX)
482 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
488 * The same as knote(), activate the event.
490 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
491 kn->kn_status |= KN_HASKQLOCK;
492 if (kn->kn_fop->f_event(kn, NOTE_FORK))
493 KNOTE_ACTIVATE(kn, 1);
494 kn->kn_status &= ~KN_HASKQLOCK;
500 * The NOTE_TRACK case. In addition to the activation
501 * of the event, we need to register new events to
502 * track the child. Drop the locks in preparation for
503 * the call to kqueue_register().
505 kn->kn_status |= KN_INFLUX;
507 list->kl_unlock(list->kl_lockarg);
510 * Activate existing knote and register tracking knotes with
513 * First register a knote to get just the child notice. This
514 * must be a separate note from a potential NOTE_EXIT
515 * notification since both NOTE_CHILD and NOTE_EXIT are defined
516 * to use the data field (in conflicting ways).
519 kev.filter = kn->kn_filter;
520 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT | EV_FLAG2;
521 kev.fflags = kn->kn_sfflags;
522 kev.data = kn->kn_id; /* parent */
523 kev.udata = kn->kn_kevent.udata;/* preserve udata */
524 error = kqueue_register(kq, &kev, NULL, 0);
526 kn->kn_fflags |= NOTE_TRACKERR;
529 * Then register another knote to track other potential events
530 * from the new process.
533 kev.filter = kn->kn_filter;
534 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
535 kev.fflags = kn->kn_sfflags;
536 kev.data = kn->kn_id; /* parent */
537 kev.udata = kn->kn_kevent.udata;/* preserve udata */
538 error = kqueue_register(kq, &kev, NULL, 0);
540 kn->kn_fflags |= NOTE_TRACKERR;
541 if (kn->kn_fop->f_event(kn, NOTE_FORK))
542 KNOTE_ACTIVATE(kn, 0);
544 kn->kn_status &= ~KN_INFLUX;
546 list->kl_lock(list->kl_lockarg);
548 list->kl_unlock(list->kl_lockarg);
552 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
553 * interval timer support code.
556 #define NOTE_TIMER_PRECMASK (NOTE_SECONDS|NOTE_MSECONDS|NOTE_USECONDS| \
560 timer2sbintime(intptr_t data, int flags)
564 * Macros for converting to the fractional second portion of an
565 * sbintime_t using 64bit multiplication to improve precision.
567 #define NS_TO_SBT(ns) (((ns) * (((uint64_t)1 << 63) / 500000000)) >> 32)
568 #define US_TO_SBT(us) (((us) * (((uint64_t)1 << 63) / 500000)) >> 32)
569 #define MS_TO_SBT(ms) (((ms) * (((uint64_t)1 << 63) / 500)) >> 32)
570 switch (flags & NOTE_TIMER_PRECMASK) {
573 if (data > (SBT_MAX / SBT_1S))
576 return ((sbintime_t)data << 32);
577 case NOTE_MSECONDS: /* FALLTHROUGH */
580 int64_t secs = data / 1000;
582 if (secs > (SBT_MAX / SBT_1S))
585 return (secs << 32 | MS_TO_SBT(data % 1000));
587 return MS_TO_SBT(data);
589 if (data >= 1000000) {
590 int64_t secs = data / 1000000;
592 if (secs > (SBT_MAX / SBT_1S))
595 return (secs << 32 | US_TO_SBT(data % 1000000));
597 return US_TO_SBT(data);
599 if (data >= 1000000000) {
600 int64_t secs = data / 1000000000;
602 if (secs > (SBT_MAX / SBT_1S))
605 return (secs << 32 | US_TO_SBT(data % 1000000000));
607 return NS_TO_SBT(data);
615 filt_timerexpire(void *knx)
617 struct callout *calloutp;
622 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
624 if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
625 calloutp = (struct callout *)kn->kn_hook;
626 *kn->kn_ptr.p_nexttime += timer2sbintime(kn->kn_sdata,
628 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
629 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
634 * data contains amount of time to sleep
637 filt_timerattach(struct knote *kn)
639 struct callout *calloutp;
641 unsigned int ncallouts;
643 if ((intptr_t)kn->kn_sdata < 0)
645 if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
647 /* Only precision unit are supported in flags so far */
648 if (kn->kn_sfflags & ~NOTE_TIMER_PRECMASK)
651 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
656 ncallouts = kq_ncallouts;
657 if (ncallouts >= kq_calloutmax)
659 } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
661 kn->kn_flags |= EV_CLEAR; /* automatically set */
662 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
663 kn->kn_ptr.p_nexttime = malloc(sizeof(sbintime_t), M_KQUEUE, M_WAITOK);
664 calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
665 callout_init(calloutp, CALLOUT_MPSAFE);
666 kn->kn_hook = calloutp;
667 *kn->kn_ptr.p_nexttime = to + sbinuptime();
668 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
669 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
675 filt_timerdetach(struct knote *kn)
677 struct callout *calloutp;
680 calloutp = (struct callout *)kn->kn_hook;
681 callout_drain(calloutp);
682 free(calloutp, M_KQUEUE);
683 free(kn->kn_ptr.p_nexttime, M_KQUEUE);
684 old = atomic_fetchadd_int(&kq_ncallouts, -1);
685 KASSERT(old > 0, ("Number of callouts cannot become negative"));
686 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
690 filt_timer(struct knote *kn, long hint)
693 return (kn->kn_data != 0);
697 filt_userattach(struct knote *kn)
701 * EVFILT_USER knotes are not attached to anything in the kernel.
704 if (kn->kn_fflags & NOTE_TRIGGER)
712 filt_userdetach(__unused struct knote *kn)
716 * EVFILT_USER knotes are not attached to anything in the kernel.
721 filt_user(struct knote *kn, __unused long hint)
724 return (kn->kn_hookid);
728 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
734 if (kev->fflags & NOTE_TRIGGER)
737 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
738 kev->fflags &= NOTE_FFLAGSMASK;
744 kn->kn_sfflags &= kev->fflags;
748 kn->kn_sfflags |= kev->fflags;
752 kn->kn_sfflags = kev->fflags;
756 /* XXX Return error? */
759 kn->kn_sdata = kev->data;
760 if (kev->flags & EV_CLEAR) {
768 *kev = kn->kn_kevent;
769 kev->fflags = kn->kn_sfflags;
770 kev->data = kn->kn_sdata;
771 if (kn->kn_flags & EV_CLEAR) {
779 panic("filt_usertouch() - invalid type (%ld)", type);
785 sys_kqueue(struct thread *td, struct kqueue_args *uap)
788 return (kern_kqueue(td, 0));
792 kern_kqueue(struct thread *td, int flags)
794 struct filedesc *fdp;
799 fdp = td->td_proc->p_fd;
800 error = falloc(td, &fp, &fd, flags);
804 /* An extra reference on `fp' has been held for us by falloc(). */
805 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
806 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
807 TAILQ_INIT(&kq->kq_head);
809 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
810 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
813 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
814 FILEDESC_XUNLOCK(fdp);
816 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
819 td->td_retval[0] = fd;
824 #ifndef _SYS_SYSPROTO_H_
827 const struct kevent *changelist;
829 struct kevent *eventlist;
831 const struct timespec *timeout;
835 sys_kevent(struct thread *td, struct kevent_args *uap)
837 struct timespec ts, *tsp;
838 struct kevent_copyops k_ops = { uap,
845 struct uio *ktruioin = NULL;
846 struct uio *ktruioout = NULL;
849 if (uap->timeout != NULL) {
850 error = copyin(uap->timeout, &ts, sizeof(ts));
858 if (KTRPOINT(td, KTR_GENIO)) {
859 ktriov.iov_base = uap->changelist;
860 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
861 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
862 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
864 ktruioin = cloneuio(&ktruio);
865 ktriov.iov_base = uap->eventlist;
866 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
867 ktruioout = cloneuio(&ktruio);
871 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
875 if (ktruioin != NULL) {
876 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
877 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
878 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
879 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
887 * Copy 'count' items into the destination list pointed to by uap->eventlist.
890 kevent_copyout(void *arg, struct kevent *kevp, int count)
892 struct kevent_args *uap;
895 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
896 uap = (struct kevent_args *)arg;
898 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
900 uap->eventlist += count;
905 * Copy 'count' items from the list pointed to by uap->changelist.
908 kevent_copyin(void *arg, struct kevent *kevp, int count)
910 struct kevent_args *uap;
913 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
914 uap = (struct kevent_args *)arg;
916 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
918 uap->changelist += count;
923 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
924 struct kevent_copyops *k_ops, const struct timespec *timeout)
930 cap_rights_init(&rights);
932 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
934 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
935 error = fget(td, fd, &rights, &fp);
939 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
946 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
947 struct kevent_copyops *k_ops, const struct timespec *timeout)
949 struct kevent keva[KQ_NEVENTS];
950 struct kevent *kevp, *changes;
952 int i, n, nerrors, error;
954 error = kqueue_acquire(fp, &kq);
960 while (nchanges > 0) {
961 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
962 error = k_ops->k_copyin(k_ops->arg, keva, n);
966 for (i = 0; i < n; i++) {
970 kevp->flags &= ~EV_SYSFLAGS;
971 error = kqueue_register(kq, kevp, td, 1);
972 if (error || (kevp->flags & EV_RECEIPT)) {
974 kevp->flags = EV_ERROR;
976 (void) k_ops->k_copyout(k_ops->arg,
988 td->td_retval[0] = nerrors;
993 error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
995 kqueue_release(kq, 0);
1000 kqueue_add_filteropts(int filt, struct filterops *filtops)
1005 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1007 "trying to add a filterop that is out of range: %d is beyond %d\n",
1008 ~filt, EVFILT_SYSCOUNT);
1011 mtx_lock(&filterops_lock);
1012 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1013 sysfilt_ops[~filt].for_fop != NULL)
1016 sysfilt_ops[~filt].for_fop = filtops;
1017 sysfilt_ops[~filt].for_refcnt = 0;
1019 mtx_unlock(&filterops_lock);
1025 kqueue_del_filteropts(int filt)
1030 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1033 mtx_lock(&filterops_lock);
1034 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1035 sysfilt_ops[~filt].for_fop == NULL)
1037 else if (sysfilt_ops[~filt].for_refcnt != 0)
1040 sysfilt_ops[~filt].for_fop = &null_filtops;
1041 sysfilt_ops[~filt].for_refcnt = 0;
1043 mtx_unlock(&filterops_lock);
1048 static struct filterops *
1049 kqueue_fo_find(int filt)
1052 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1055 mtx_lock(&filterops_lock);
1056 sysfilt_ops[~filt].for_refcnt++;
1057 if (sysfilt_ops[~filt].for_fop == NULL)
1058 sysfilt_ops[~filt].for_fop = &null_filtops;
1059 mtx_unlock(&filterops_lock);
1061 return sysfilt_ops[~filt].for_fop;
1065 kqueue_fo_release(int filt)
1068 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1071 mtx_lock(&filterops_lock);
1072 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1073 ("filter object refcount not valid on release"));
1074 sysfilt_ops[~filt].for_refcnt--;
1075 mtx_unlock(&filterops_lock);
1079 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1080 * influence if memory allocation should wait. Make sure it is 0 if you
1084 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1086 struct filterops *fops;
1088 struct knote *kn, *tkn;
1089 cap_rights_t rights;
1090 int error, filt, event;
1091 int haskqglobal, filedesc_unlock;
1097 filedesc_unlock = 0;
1100 fops = kqueue_fo_find(filt);
1104 tkn = knote_alloc(waitok); /* prevent waiting with locks */
1108 KASSERT(td != NULL, ("td is NULL"));
1109 if (kev->ident > INT_MAX)
1112 error = fget(td, kev->ident,
1113 cap_rights_init(&rights, CAP_EVENT), &fp);
1117 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1118 kev->ident, 0) != 0) {
1122 error = kqueue_expand(kq, fops, kev->ident, waitok);
1128 if (fp->f_type == DTYPE_KQUEUE) {
1130 * If we add some intelligence about what we are doing,
1131 * we should be able to support events on ourselves.
1132 * We need to know when we are doing this to prevent
1133 * getting both the knlist lock and the kq lock since
1134 * they are the same thing.
1136 if (fp->f_data == kq) {
1142 * Pre-lock the filedesc before the global
1143 * lock mutex, see the comment in
1146 FILEDESC_XLOCK(td->td_proc->p_fd);
1147 filedesc_unlock = 1;
1148 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1152 if (kev->ident < kq->kq_knlistsize) {
1153 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1154 if (kev->filter == kn->kn_filter)
1158 if ((kev->flags & EV_ADD) == EV_ADD)
1159 kqueue_expand(kq, fops, kev->ident, waitok);
1164 * If possible, find an existing knote to use for this kevent.
1166 if (kev->filter == EVFILT_PROC &&
1167 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1168 /* This is an internal creation of a process tracking
1169 * note. Don't attempt to coalesce this with an
1173 } else if (kq->kq_knhashmask != 0) {
1176 list = &kq->kq_knhash[
1177 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1178 SLIST_FOREACH(kn, list, kn_link)
1179 if (kev->ident == kn->kn_id &&
1180 kev->filter == kn->kn_filter)
1185 /* knote is in the process of changing, wait for it to stabilize. */
1186 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1187 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1188 if (filedesc_unlock) {
1189 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1190 filedesc_unlock = 0;
1192 kq->kq_state |= KQ_FLUXWAIT;
1193 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1202 * kn now contains the matching knote, or NULL if no match
1205 if (kev->flags & EV_ADD) {
1217 * apply reference counts to knote structure, and
1218 * do not release it at the end of this routine.
1223 kn->kn_sfflags = kev->fflags;
1224 kn->kn_sdata = kev->data;
1227 kn->kn_kevent = *kev;
1228 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1229 EV_ENABLE | EV_DISABLE);
1230 kn->kn_status = KN_INFLUX|KN_DETACHED;
1232 error = knote_attach(kn, kq);
1239 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1246 /* No matching knote and the EV_ADD flag is not set. */
1253 if (kev->flags & EV_DELETE) {
1254 kn->kn_status |= KN_INFLUX;
1256 if (!(kn->kn_status & KN_DETACHED))
1257 kn->kn_fop->f_detach(kn);
1263 * The user may change some filter values after the initial EV_ADD,
1264 * but doing so will not reset any filter which has already been
1267 kn->kn_status |= KN_INFLUX | KN_SCAN;
1270 kn->kn_kevent.udata = kev->udata;
1271 if (!fops->f_isfd && fops->f_touch != NULL) {
1272 fops->f_touch(kn, kev, EVENT_REGISTER);
1274 kn->kn_sfflags = kev->fflags;
1275 kn->kn_sdata = kev->data;
1279 * We can get here with kn->kn_knlist == NULL. This can happen when
1280 * the initial attach event decides that the event is "completed"
1281 * already. i.e. filt_procattach is called on a zombie process. It
1282 * will call filt_proc which will remove it from the list, and NULL
1286 event = kn->kn_fop->f_event(kn, 0);
1289 KNOTE_ACTIVATE(kn, 1);
1290 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1293 if ((kev->flags & EV_DISABLE) &&
1294 ((kn->kn_status & KN_DISABLED) == 0)) {
1295 kn->kn_status |= KN_DISABLED;
1298 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1299 kn->kn_status &= ~KN_DISABLED;
1300 if ((kn->kn_status & KN_ACTIVE) &&
1301 ((kn->kn_status & KN_QUEUED) == 0))
1307 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1308 if (filedesc_unlock)
1309 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1315 kqueue_fo_release(filt);
1320 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1328 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1332 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1343 kqueue_release(struct kqueue *kq, int locked)
1350 if (kq->kq_refcnt == 1)
1351 wakeup(&kq->kq_refcnt);
1357 kqueue_schedtask(struct kqueue *kq)
1361 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1362 ("scheduling kqueue task while draining"));
1364 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1365 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1366 kq->kq_state |= KQ_TASKSCHED;
1371 * Expand the kq to make sure we have storage for fops/ident pair.
1373 * Return 0 on success (or no work necessary), return errno on failure.
1375 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1376 * If kqueue_register is called from a non-fd context, there usually/should
1380 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1383 struct klist *list, *tmp_knhash, *to_free;
1384 u_long tmp_knhashmask;
1387 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1394 if (kq->kq_knlistsize <= fd) {
1395 size = kq->kq_knlistsize;
1398 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1402 if (kq->kq_knlistsize > fd) {
1406 if (kq->kq_knlist != NULL) {
1407 bcopy(kq->kq_knlist, list,
1408 kq->kq_knlistsize * sizeof(*list));
1409 to_free = kq->kq_knlist;
1410 kq->kq_knlist = NULL;
1412 bzero((caddr_t)list +
1413 kq->kq_knlistsize * sizeof(*list),
1414 (size - kq->kq_knlistsize) * sizeof(*list));
1415 kq->kq_knlistsize = size;
1416 kq->kq_knlist = list;
1421 if (kq->kq_knhashmask == 0) {
1422 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1424 if (tmp_knhash == NULL)
1427 if (kq->kq_knhashmask == 0) {
1428 kq->kq_knhash = tmp_knhash;
1429 kq->kq_knhashmask = tmp_knhashmask;
1431 to_free = tmp_knhash;
1436 free(to_free, M_KQUEUE);
1443 kqueue_task(void *arg, int pending)
1451 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1454 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1456 kq->kq_state &= ~KQ_TASKSCHED;
1457 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1458 wakeup(&kq->kq_state);
1461 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1465 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1466 * We treat KN_MARKER knotes as if they are INFLUX.
1469 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1470 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1472 struct kevent *kevp;
1473 struct knote *kn, *marker;
1474 sbintime_t asbt, rsbt;
1475 int count, error, haskqglobal, influx, nkev, touch;
1487 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1488 tsp->tv_nsec >= 1000000000) {
1492 if (timespecisset(tsp)) {
1493 if (tsp->tv_sec <= INT32_MAX) {
1494 rsbt = tstosbt(*tsp);
1495 if (TIMESEL(&asbt, rsbt))
1496 asbt += tc_tick_sbt;
1497 if (asbt <= SBT_MAX - rsbt)
1501 rsbt >>= tc_precexp;
1508 marker = knote_alloc(1);
1509 if (marker == NULL) {
1513 marker->kn_status = KN_MARKER;
1518 if (kq->kq_count == 0) {
1520 error = EWOULDBLOCK;
1522 kq->kq_state |= KQ_SLEEP;
1523 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1524 "kqread", asbt, rsbt, C_ABSOLUTE);
1528 /* don't restart after signals... */
1529 if (error == ERESTART)
1531 else if (error == EWOULDBLOCK)
1536 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1540 kn = TAILQ_FIRST(&kq->kq_head);
1542 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1543 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1548 kq->kq_state |= KQ_FLUXWAIT;
1549 error = msleep(kq, &kq->kq_lock, PSOCK,
1554 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1555 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1556 kn->kn_status &= ~KN_QUEUED;
1562 if (count == maxevents)
1566 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1567 ("KN_INFLUX set when not suppose to be"));
1569 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1570 kn->kn_status &= ~KN_QUEUED;
1571 kn->kn_status |= KN_INFLUX;
1575 * We don't need to lock the list since we've marked
1578 if (!(kn->kn_status & KN_DETACHED))
1579 kn->kn_fop->f_detach(kn);
1583 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1584 kn->kn_status &= ~KN_QUEUED;
1585 kn->kn_status |= KN_INFLUX;
1589 * We don't need to lock the list since we've marked
1592 *kevp = kn->kn_kevent;
1593 if (!(kn->kn_status & KN_DETACHED))
1594 kn->kn_fop->f_detach(kn);
1599 kn->kn_status |= KN_INFLUX | KN_SCAN;
1601 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1602 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1604 if (kn->kn_fop->f_event(kn, 0) == 0) {
1606 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1608 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1615 touch = (!kn->kn_fop->f_isfd &&
1616 kn->kn_fop->f_touch != NULL);
1618 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1620 *kevp = kn->kn_kevent;
1622 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1623 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1625 * Manually clear knotes who weren't
1628 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1632 if (kn->kn_flags & EV_DISPATCH)
1633 kn->kn_status |= KN_DISABLED;
1634 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1637 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1639 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1644 /* we are returning a copy to the user */
1649 if (nkev == KQ_NEVENTS) {
1652 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1660 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1668 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1669 td->td_retval[0] = maxevents - count;
1675 * This could be expanded to call kqueue_scan, if desired.
1679 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1680 int flags, struct thread *td)
1687 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1688 int flags, struct thread *td)
1695 kqueue_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1704 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1705 struct ucred *active_cred, struct thread *td)
1708 * Enabling sigio causes two major problems:
1709 * 1) infinite recursion:
1710 * Synopsys: kevent is being used to track signals and have FIOASYNC
1711 * set. On receipt of a signal this will cause a kqueue to recurse
1712 * into itself over and over. Sending the sigio causes the kqueue
1713 * to become ready, which in turn posts sigio again, forever.
1714 * Solution: this can be solved by setting a flag in the kqueue that
1715 * we have a SIGIO in progress.
1716 * 2) locking problems:
1717 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1718 * us above the proc and pgrp locks.
1719 * Solution: Post a signal using an async mechanism, being sure to
1720 * record a generation count in the delivery so that we do not deliver
1721 * a signal to the wrong process.
1723 * Note, these two mechanisms are somewhat mutually exclusive!
1732 kq->kq_state |= KQ_ASYNC;
1734 kq->kq_state &= ~KQ_ASYNC;
1739 return (fsetown(*(int *)data, &kq->kq_sigio));
1742 *(int *)data = fgetown(&kq->kq_sigio);
1752 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1759 if ((error = kqueue_acquire(fp, &kq)))
1763 if (events & (POLLIN | POLLRDNORM)) {
1765 revents |= events & (POLLIN | POLLRDNORM);
1767 selrecord(td, &kq->kq_sel);
1768 if (SEL_WAITING(&kq->kq_sel))
1769 kq->kq_state |= KQ_SEL;
1772 kqueue_release(kq, 1);
1779 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1783 bzero((void *)st, sizeof *st);
1785 * We no longer return kq_count because the unlocked value is useless.
1786 * If you spent all this time getting the count, why not spend your
1787 * syscall better by calling kevent?
1789 * XXX - This is needed for libc_r.
1791 st->st_mode = S_IFIFO;
1797 kqueue_close(struct file *fp, struct thread *td)
1799 struct kqueue *kq = fp->f_data;
1800 struct filedesc *fdp;
1804 int filedesc_unlock;
1806 if ((error = kqueue_acquire(fp, &kq)))
1809 filedesc_unlock = 0;
1812 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1813 ("kqueue already closing"));
1814 kq->kq_state |= KQ_CLOSING;
1815 if (kq->kq_refcnt > 1)
1816 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1818 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1821 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1822 ("kqueue's knlist not empty"));
1824 for (i = 0; i < kq->kq_knlistsize; i++) {
1825 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1826 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1827 kq->kq_state |= KQ_FLUXWAIT;
1828 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1831 kn->kn_status |= KN_INFLUX;
1833 if (!(kn->kn_status & KN_DETACHED))
1834 kn->kn_fop->f_detach(kn);
1839 if (kq->kq_knhashmask != 0) {
1840 for (i = 0; i <= kq->kq_knhashmask; i++) {
1841 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1842 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1843 kq->kq_state |= KQ_FLUXWAIT;
1844 msleep(kq, &kq->kq_lock, PSOCK,
1848 kn->kn_status |= KN_INFLUX;
1850 if (!(kn->kn_status & KN_DETACHED))
1851 kn->kn_fop->f_detach(kn);
1858 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1859 kq->kq_state |= KQ_TASKDRAIN;
1860 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1863 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1864 selwakeuppri(&kq->kq_sel, PSOCK);
1865 if (!SEL_WAITING(&kq->kq_sel))
1866 kq->kq_state &= ~KQ_SEL;
1872 * We could be called due to the knote_drop() doing fdrop(),
1873 * called from kqueue_register(). In this case the global
1874 * lock is owned, and filedesc sx is locked before, to not
1875 * take the sleepable lock after non-sleepable.
1877 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1878 FILEDESC_XLOCK(fdp);
1879 filedesc_unlock = 1;
1881 filedesc_unlock = 0;
1882 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1883 if (filedesc_unlock)
1884 FILEDESC_XUNLOCK(fdp);
1886 seldrain(&kq->kq_sel);
1887 knlist_destroy(&kq->kq_sel.si_note);
1888 mtx_destroy(&kq->kq_lock);
1891 if (kq->kq_knhash != NULL)
1892 free(kq->kq_knhash, M_KQUEUE);
1893 if (kq->kq_knlist != NULL)
1894 free(kq->kq_knlist, M_KQUEUE);
1896 funsetown(&kq->kq_sigio);
1904 kqueue_wakeup(struct kqueue *kq)
1908 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1909 kq->kq_state &= ~KQ_SLEEP;
1912 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1913 selwakeuppri(&kq->kq_sel, PSOCK);
1914 if (!SEL_WAITING(&kq->kq_sel))
1915 kq->kq_state &= ~KQ_SEL;
1917 if (!knlist_empty(&kq->kq_sel.si_note))
1918 kqueue_schedtask(kq);
1919 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1920 pgsigio(&kq->kq_sigio, SIGIO, 0);
1925 * Walk down a list of knotes, activating them if their event has triggered.
1927 * There is a possibility to optimize in the case of one kq watching another.
1928 * Instead of scheduling a task to wake it up, you could pass enough state
1929 * down the chain to make up the parent kqueue. Make this code functional
1933 knote(struct knlist *list, long hint, int lockflags)
1936 struct knote *kn, *tkn;
1943 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1945 if ((lockflags & KNF_LISTLOCKED) == 0)
1946 list->kl_lock(list->kl_lockarg);
1949 * If we unlock the list lock (and set KN_INFLUX), we can
1950 * eliminate the kqueue scheduling, but this will introduce
1951 * four lock/unlock's for each knote to test. Also, marker
1952 * would be needed to keep iteration position, since filters
1953 * or other threads could remove events.
1955 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
1958 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1960 * Do not process the influx notes, except for
1961 * the influx coming from the kq unlock in the
1962 * kqueue_scan(). In the later case, we do
1963 * not interfere with the scan, since the code
1964 * fragment in kqueue_scan() locks the knlist,
1965 * and cannot proceed until we finished.
1968 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1969 own_influx = (kn->kn_status & KN_INFLUX) == 0;
1971 kn->kn_status |= KN_INFLUX;
1973 error = kn->kn_fop->f_event(kn, hint);
1976 kn->kn_status &= ~KN_INFLUX;
1978 KNOTE_ACTIVATE(kn, 1);
1981 kn->kn_status |= KN_HASKQLOCK;
1982 if (kn->kn_fop->f_event(kn, hint))
1983 KNOTE_ACTIVATE(kn, 1);
1984 kn->kn_status &= ~KN_HASKQLOCK;
1988 if ((lockflags & KNF_LISTLOCKED) == 0)
1989 list->kl_unlock(list->kl_lockarg);
1993 * add a knote to a knlist
1996 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1998 KNL_ASSERT_LOCK(knl, islocked);
1999 KQ_NOTOWNED(kn->kn_kq);
2000 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
2001 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
2003 knl->kl_lock(knl->kl_lockarg);
2004 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2006 knl->kl_unlock(knl->kl_lockarg);
2008 kn->kn_knlist = knl;
2009 kn->kn_status &= ~KN_DETACHED;
2010 KQ_UNLOCK(kn->kn_kq);
2014 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
2016 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2017 KNL_ASSERT_LOCK(knl, knlislocked);
2018 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2020 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2021 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2023 knl->kl_lock(knl->kl_lockarg);
2024 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2025 kn->kn_knlist = NULL;
2027 knl->kl_unlock(knl->kl_lockarg);
2030 kn->kn_status |= KN_DETACHED;
2032 KQ_UNLOCK(kn->kn_kq);
2036 * remove knote from the specified knlist
2039 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2042 knlist_remove_kq(knl, kn, islocked, 0);
2046 * remove knote from the specified knlist while in f_event handler.
2049 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
2052 knlist_remove_kq(knl, kn, 1,
2053 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
2057 knlist_empty(struct knlist *knl)
2060 KNL_ASSERT_LOCKED(knl);
2061 return SLIST_EMPTY(&knl->kl_list);
2064 static struct mtx knlist_lock;
2065 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2067 static void knlist_mtx_lock(void *arg);
2068 static void knlist_mtx_unlock(void *arg);
2071 knlist_mtx_lock(void *arg)
2074 mtx_lock((struct mtx *)arg);
2078 knlist_mtx_unlock(void *arg)
2081 mtx_unlock((struct mtx *)arg);
2085 knlist_mtx_assert_locked(void *arg)
2088 mtx_assert((struct mtx *)arg, MA_OWNED);
2092 knlist_mtx_assert_unlocked(void *arg)
2095 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2099 knlist_rw_rlock(void *arg)
2102 rw_rlock((struct rwlock *)arg);
2106 knlist_rw_runlock(void *arg)
2109 rw_runlock((struct rwlock *)arg);
2113 knlist_rw_assert_locked(void *arg)
2116 rw_assert((struct rwlock *)arg, RA_LOCKED);
2120 knlist_rw_assert_unlocked(void *arg)
2123 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2127 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2128 void (*kl_unlock)(void *),
2129 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2133 knl->kl_lockarg = &knlist_lock;
2135 knl->kl_lockarg = lock;
2137 if (kl_lock == NULL)
2138 knl->kl_lock = knlist_mtx_lock;
2140 knl->kl_lock = kl_lock;
2141 if (kl_unlock == NULL)
2142 knl->kl_unlock = knlist_mtx_unlock;
2144 knl->kl_unlock = kl_unlock;
2145 if (kl_assert_locked == NULL)
2146 knl->kl_assert_locked = knlist_mtx_assert_locked;
2148 knl->kl_assert_locked = kl_assert_locked;
2149 if (kl_assert_unlocked == NULL)
2150 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2152 knl->kl_assert_unlocked = kl_assert_unlocked;
2154 SLIST_INIT(&knl->kl_list);
2158 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2161 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2165 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2168 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2169 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2173 knlist_destroy(struct knlist *knl)
2178 * if we run across this error, we need to find the offending
2179 * driver and have it call knlist_clear or knlist_delete.
2181 if (!SLIST_EMPTY(&knl->kl_list))
2182 printf("WARNING: destroying knlist w/ knotes on it!\n");
2185 knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2186 SLIST_INIT(&knl->kl_list);
2190 * Even if we are locked, we may need to drop the lock to allow any influx
2191 * knotes time to "settle".
2194 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2196 struct knote *kn, *kn2;
2200 KNL_ASSERT_LOCKED(knl);
2202 KNL_ASSERT_UNLOCKED(knl);
2203 again: /* need to reacquire lock since we have dropped it */
2204 knl->kl_lock(knl->kl_lockarg);
2207 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2210 if ((kn->kn_status & KN_INFLUX)) {
2214 knlist_remove_kq(knl, kn, 1, 1);
2216 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2220 /* Make sure cleared knotes disappear soon */
2221 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2227 if (!SLIST_EMPTY(&knl->kl_list)) {
2228 /* there are still KN_INFLUX remaining */
2229 kn = SLIST_FIRST(&knl->kl_list);
2232 KASSERT(kn->kn_status & KN_INFLUX,
2233 ("knote removed w/o list lock"));
2234 knl->kl_unlock(knl->kl_lockarg);
2235 kq->kq_state |= KQ_FLUXWAIT;
2236 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2242 KNL_ASSERT_LOCKED(knl);
2244 knl->kl_unlock(knl->kl_lockarg);
2245 KNL_ASSERT_UNLOCKED(knl);
2250 * Remove all knotes referencing a specified fd must be called with FILEDESC
2251 * lock. This prevents a race where a new fd comes along and occupies the
2252 * entry and we attach a knote to the fd.
2255 knote_fdclose(struct thread *td, int fd)
2257 struct filedesc *fdp = td->td_proc->p_fd;
2262 FILEDESC_XLOCK_ASSERT(fdp);
2265 * We shouldn't have to worry about new kevents appearing on fd
2266 * since filedesc is locked.
2268 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2273 while (kq->kq_knlistsize > fd &&
2274 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2275 if (kn->kn_status & KN_INFLUX) {
2276 /* someone else might be waiting on our knote */
2279 kq->kq_state |= KQ_FLUXWAIT;
2280 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2283 kn->kn_status |= KN_INFLUX;
2285 if (!(kn->kn_status & KN_DETACHED))
2286 kn->kn_fop->f_detach(kn);
2296 knote_attach(struct knote *kn, struct kqueue *kq)
2300 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2303 if (kn->kn_fop->f_isfd) {
2304 if (kn->kn_id >= kq->kq_knlistsize)
2306 list = &kq->kq_knlist[kn->kn_id];
2308 if (kq->kq_knhash == NULL)
2310 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2313 SLIST_INSERT_HEAD(list, kn, kn_link);
2319 * knote must already have been detached using the f_detach method.
2320 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2321 * to prevent other removal.
2324 knote_drop(struct knote *kn, struct thread *td)
2332 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2333 ("knote_drop called without KN_INFLUX set in kn_status"));
2336 if (kn->kn_fop->f_isfd)
2337 list = &kq->kq_knlist[kn->kn_id];
2339 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2341 if (!SLIST_EMPTY(list))
2342 SLIST_REMOVE(list, kn, knote, kn_link);
2343 if (kn->kn_status & KN_QUEUED)
2347 if (kn->kn_fop->f_isfd) {
2348 fdrop(kn->kn_fp, td);
2351 kqueue_fo_release(kn->kn_kevent.filter);
2357 knote_enqueue(struct knote *kn)
2359 struct kqueue *kq = kn->kn_kq;
2361 KQ_OWNED(kn->kn_kq);
2362 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2364 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2365 kn->kn_status |= KN_QUEUED;
2371 knote_dequeue(struct knote *kn)
2373 struct kqueue *kq = kn->kn_kq;
2375 KQ_OWNED(kn->kn_kq);
2376 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2378 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2379 kn->kn_status &= ~KN_QUEUED;
2387 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2388 NULL, NULL, UMA_ALIGN_PTR, 0);
2390 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2392 static struct knote *
2393 knote_alloc(int waitok)
2395 return ((struct knote *)uma_zalloc(knote_zone,
2396 (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2400 knote_free(struct knote *kn)
2403 uma_zfree(knote_zone, kn);
2407 * Register the kev w/ the kq specified by fd.
2410 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2414 cap_rights_t rights;
2417 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2420 if ((error = kqueue_acquire(fp, &kq)) != 0)
2423 error = kqueue_register(kq, kev, td, waitok);
2425 kqueue_release(kq, 0);