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));
614 struct kq_timer_cb_data {
616 sbintime_t next; /* next timer event fires at */
617 sbintime_t to; /* precalculated timer period */
621 filt_timerexpire(void *knx)
624 struct kq_timer_cb_data *kc;
628 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
630 if ((kn->kn_flags & EV_ONESHOT) != 0)
635 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
636 PCPU_GET(cpuid), C_ABSOLUTE);
640 * data contains amount of time to sleep
643 filt_timerattach(struct knote *kn)
645 struct kq_timer_cb_data *kc;
647 unsigned int ncallouts;
649 if (kn->kn_sdata < 0)
651 if (kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
653 /* Only precision unit are supported in flags so far */
654 if ((kn->kn_sfflags & ~NOTE_TIMER_PRECMASK) != 0)
657 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
662 ncallouts = kq_ncallouts;
663 if (ncallouts >= kq_calloutmax)
665 } while (!atomic_cmpset_int(&kq_ncallouts, ncallouts, ncallouts + 1));
667 kn->kn_flags |= EV_CLEAR; /* automatically set */
668 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
669 kn->kn_ptr.p_v = kc = malloc(sizeof(*kc), M_KQUEUE, M_WAITOK);
670 callout_init(&kc->c, 1);
671 kc->next = to + sbinuptime();
673 callout_reset_sbt_on(&kc->c, kc->next, 0, filt_timerexpire, kn,
674 PCPU_GET(cpuid), C_ABSOLUTE);
680 filt_timerdetach(struct knote *kn)
682 struct kq_timer_cb_data *kc;
686 callout_drain(&kc->c);
688 old = atomic_fetchadd_int(&kq_ncallouts, -1);
689 KASSERT(old > 0, ("Number of callouts cannot become negative"));
690 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
694 filt_timer(struct knote *kn, long hint)
697 return (kn->kn_data != 0);
701 filt_userattach(struct knote *kn)
705 * EVFILT_USER knotes are not attached to anything in the kernel.
708 if (kn->kn_fflags & NOTE_TRIGGER)
716 filt_userdetach(__unused struct knote *kn)
720 * EVFILT_USER knotes are not attached to anything in the kernel.
725 filt_user(struct knote *kn, __unused long hint)
728 return (kn->kn_hookid);
732 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
738 if (kev->fflags & NOTE_TRIGGER)
741 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
742 kev->fflags &= NOTE_FFLAGSMASK;
748 kn->kn_sfflags &= kev->fflags;
752 kn->kn_sfflags |= kev->fflags;
756 kn->kn_sfflags = kev->fflags;
760 /* XXX Return error? */
763 kn->kn_sdata = kev->data;
764 if (kev->flags & EV_CLEAR) {
772 *kev = kn->kn_kevent;
773 kev->fflags = kn->kn_sfflags;
774 kev->data = kn->kn_sdata;
775 if (kn->kn_flags & EV_CLEAR) {
783 panic("filt_usertouch() - invalid type (%ld)", type);
789 sys_kqueue(struct thread *td, struct kqueue_args *uap)
792 return (kern_kqueue(td, 0));
796 kern_kqueue(struct thread *td, int flags)
798 struct filedesc *fdp;
803 fdp = td->td_proc->p_fd;
804 error = falloc(td, &fp, &fd, flags);
808 /* An extra reference on `fp' has been held for us by falloc(). */
809 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
810 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
811 TAILQ_INIT(&kq->kq_head);
813 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
814 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
817 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
818 FILEDESC_XUNLOCK(fdp);
820 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
823 td->td_retval[0] = fd;
828 #ifndef _SYS_SYSPROTO_H_
831 const struct kevent *changelist;
833 struct kevent *eventlist;
835 const struct timespec *timeout;
839 sys_kevent(struct thread *td, struct kevent_args *uap)
841 struct timespec ts, *tsp;
842 struct kevent_copyops k_ops = { uap,
849 struct uio *ktruioin = NULL;
850 struct uio *ktruioout = NULL;
853 if (uap->timeout != NULL) {
854 error = copyin(uap->timeout, &ts, sizeof(ts));
862 if (KTRPOINT(td, KTR_GENIO)) {
863 ktriov.iov_base = uap->changelist;
864 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
865 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
866 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
868 ktruioin = cloneuio(&ktruio);
869 ktriov.iov_base = uap->eventlist;
870 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
871 ktruioout = cloneuio(&ktruio);
875 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
879 if (ktruioin != NULL) {
880 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
881 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
882 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
883 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
891 * Copy 'count' items into the destination list pointed to by uap->eventlist.
894 kevent_copyout(void *arg, struct kevent *kevp, int count)
896 struct kevent_args *uap;
899 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
900 uap = (struct kevent_args *)arg;
902 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
904 uap->eventlist += count;
909 * Copy 'count' items from the list pointed to by uap->changelist.
912 kevent_copyin(void *arg, struct kevent *kevp, int count)
914 struct kevent_args *uap;
917 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
918 uap = (struct kevent_args *)arg;
920 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
922 uap->changelist += count;
927 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
928 struct kevent_copyops *k_ops, const struct timespec *timeout)
934 cap_rights_init(&rights);
936 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
938 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
939 error = fget(td, fd, &rights, &fp);
943 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
950 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
951 struct kevent_copyops *k_ops, const struct timespec *timeout)
953 struct kevent keva[KQ_NEVENTS];
954 struct kevent *kevp, *changes;
956 int i, n, nerrors, error;
958 error = kqueue_acquire(fp, &kq);
964 while (nchanges > 0) {
965 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
966 error = k_ops->k_copyin(k_ops->arg, keva, n);
970 for (i = 0; i < n; i++) {
974 kevp->flags &= ~EV_SYSFLAGS;
975 error = kqueue_register(kq, kevp, td, 1);
976 if (error || (kevp->flags & EV_RECEIPT)) {
978 kevp->flags = EV_ERROR;
980 (void) k_ops->k_copyout(k_ops->arg,
992 td->td_retval[0] = nerrors;
997 error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
999 kqueue_release(kq, 0);
1004 kqueue_add_filteropts(int filt, struct filterops *filtops)
1009 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1011 "trying to add a filterop that is out of range: %d is beyond %d\n",
1012 ~filt, EVFILT_SYSCOUNT);
1015 mtx_lock(&filterops_lock);
1016 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1017 sysfilt_ops[~filt].for_fop != NULL)
1020 sysfilt_ops[~filt].for_fop = filtops;
1021 sysfilt_ops[~filt].for_refcnt = 0;
1023 mtx_unlock(&filterops_lock);
1029 kqueue_del_filteropts(int filt)
1034 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1037 mtx_lock(&filterops_lock);
1038 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1039 sysfilt_ops[~filt].for_fop == NULL)
1041 else if (sysfilt_ops[~filt].for_refcnt != 0)
1044 sysfilt_ops[~filt].for_fop = &null_filtops;
1045 sysfilt_ops[~filt].for_refcnt = 0;
1047 mtx_unlock(&filterops_lock);
1052 static struct filterops *
1053 kqueue_fo_find(int filt)
1056 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1059 mtx_lock(&filterops_lock);
1060 sysfilt_ops[~filt].for_refcnt++;
1061 if (sysfilt_ops[~filt].for_fop == NULL)
1062 sysfilt_ops[~filt].for_fop = &null_filtops;
1063 mtx_unlock(&filterops_lock);
1065 return sysfilt_ops[~filt].for_fop;
1069 kqueue_fo_release(int filt)
1072 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1075 mtx_lock(&filterops_lock);
1076 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1077 ("filter object refcount not valid on release"));
1078 sysfilt_ops[~filt].for_refcnt--;
1079 mtx_unlock(&filterops_lock);
1083 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1084 * influence if memory allocation should wait. Make sure it is 0 if you
1088 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1090 struct filterops *fops;
1092 struct knote *kn, *tkn;
1093 cap_rights_t rights;
1094 int error, filt, event;
1095 int haskqglobal, filedesc_unlock;
1101 filedesc_unlock = 0;
1104 fops = kqueue_fo_find(filt);
1108 tkn = knote_alloc(waitok); /* prevent waiting with locks */
1112 KASSERT(td != NULL, ("td is NULL"));
1113 if (kev->ident > INT_MAX)
1116 error = fget(td, kev->ident,
1117 cap_rights_init(&rights, CAP_EVENT), &fp);
1121 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1122 kev->ident, 0) != 0) {
1126 error = kqueue_expand(kq, fops, kev->ident, waitok);
1132 if (fp->f_type == DTYPE_KQUEUE) {
1134 * If we add some intelligence about what we are doing,
1135 * we should be able to support events on ourselves.
1136 * We need to know when we are doing this to prevent
1137 * getting both the knlist lock and the kq lock since
1138 * they are the same thing.
1140 if (fp->f_data == kq) {
1146 * Pre-lock the filedesc before the global
1147 * lock mutex, see the comment in
1150 FILEDESC_XLOCK(td->td_proc->p_fd);
1151 filedesc_unlock = 1;
1152 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1156 if (kev->ident < kq->kq_knlistsize) {
1157 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1158 if (kev->filter == kn->kn_filter)
1162 if ((kev->flags & EV_ADD) == EV_ADD)
1163 kqueue_expand(kq, fops, kev->ident, waitok);
1168 * If possible, find an existing knote to use for this kevent.
1170 if (kev->filter == EVFILT_PROC &&
1171 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1172 /* This is an internal creation of a process tracking
1173 * note. Don't attempt to coalesce this with an
1177 } else if (kq->kq_knhashmask != 0) {
1180 list = &kq->kq_knhash[
1181 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1182 SLIST_FOREACH(kn, list, kn_link)
1183 if (kev->ident == kn->kn_id &&
1184 kev->filter == kn->kn_filter)
1189 /* knote is in the process of changing, wait for it to stabilize. */
1190 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1191 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1192 if (filedesc_unlock) {
1193 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1194 filedesc_unlock = 0;
1196 kq->kq_state |= KQ_FLUXWAIT;
1197 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1206 * kn now contains the matching knote, or NULL if no match
1209 if (kev->flags & EV_ADD) {
1221 * apply reference counts to knote structure, and
1222 * do not release it at the end of this routine.
1227 kn->kn_sfflags = kev->fflags;
1228 kn->kn_sdata = kev->data;
1231 kn->kn_kevent = *kev;
1232 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1233 EV_ENABLE | EV_DISABLE);
1234 kn->kn_status = KN_INFLUX|KN_DETACHED;
1236 error = knote_attach(kn, kq);
1243 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1250 /* No matching knote and the EV_ADD flag is not set. */
1257 if (kev->flags & EV_DELETE) {
1258 kn->kn_status |= KN_INFLUX;
1260 if (!(kn->kn_status & KN_DETACHED))
1261 kn->kn_fop->f_detach(kn);
1267 * The user may change some filter values after the initial EV_ADD,
1268 * but doing so will not reset any filter which has already been
1271 kn->kn_status |= KN_INFLUX | KN_SCAN;
1274 kn->kn_kevent.udata = kev->udata;
1275 if (!fops->f_isfd && fops->f_touch != NULL) {
1276 fops->f_touch(kn, kev, EVENT_REGISTER);
1278 kn->kn_sfflags = kev->fflags;
1279 kn->kn_sdata = kev->data;
1283 * We can get here with kn->kn_knlist == NULL. This can happen when
1284 * the initial attach event decides that the event is "completed"
1285 * already. i.e. filt_procattach is called on a zombie process. It
1286 * will call filt_proc which will remove it from the list, and NULL
1290 event = kn->kn_fop->f_event(kn, 0);
1293 KNOTE_ACTIVATE(kn, 1);
1294 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1297 if ((kev->flags & EV_DISABLE) &&
1298 ((kn->kn_status & KN_DISABLED) == 0)) {
1299 kn->kn_status |= KN_DISABLED;
1302 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1303 kn->kn_status &= ~KN_DISABLED;
1304 if ((kn->kn_status & KN_ACTIVE) &&
1305 ((kn->kn_status & KN_QUEUED) == 0))
1311 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1312 if (filedesc_unlock)
1313 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1319 kqueue_fo_release(filt);
1324 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1332 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1336 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1347 kqueue_release(struct kqueue *kq, int locked)
1354 if (kq->kq_refcnt == 1)
1355 wakeup(&kq->kq_refcnt);
1361 kqueue_schedtask(struct kqueue *kq)
1365 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1366 ("scheduling kqueue task while draining"));
1368 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1369 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1370 kq->kq_state |= KQ_TASKSCHED;
1375 * Expand the kq to make sure we have storage for fops/ident pair.
1377 * Return 0 on success (or no work necessary), return errno on failure.
1379 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1380 * If kqueue_register is called from a non-fd context, there usually/should
1384 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1387 struct klist *list, *tmp_knhash, *to_free;
1388 u_long tmp_knhashmask;
1391 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1398 if (kq->kq_knlistsize <= fd) {
1399 size = kq->kq_knlistsize;
1402 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1406 if (kq->kq_knlistsize > fd) {
1410 if (kq->kq_knlist != NULL) {
1411 bcopy(kq->kq_knlist, list,
1412 kq->kq_knlistsize * sizeof(*list));
1413 to_free = kq->kq_knlist;
1414 kq->kq_knlist = NULL;
1416 bzero((caddr_t)list +
1417 kq->kq_knlistsize * sizeof(*list),
1418 (size - kq->kq_knlistsize) * sizeof(*list));
1419 kq->kq_knlistsize = size;
1420 kq->kq_knlist = list;
1425 if (kq->kq_knhashmask == 0) {
1426 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1428 if (tmp_knhash == NULL)
1431 if (kq->kq_knhashmask == 0) {
1432 kq->kq_knhash = tmp_knhash;
1433 kq->kq_knhashmask = tmp_knhashmask;
1435 to_free = tmp_knhash;
1440 free(to_free, M_KQUEUE);
1447 kqueue_task(void *arg, int pending)
1455 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1458 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1460 kq->kq_state &= ~KQ_TASKSCHED;
1461 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1462 wakeup(&kq->kq_state);
1465 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1469 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1470 * We treat KN_MARKER knotes as if they are INFLUX.
1473 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1474 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1476 struct kevent *kevp;
1477 struct knote *kn, *marker;
1478 sbintime_t asbt, rsbt;
1479 int count, error, haskqglobal, influx, nkev, touch;
1491 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1492 tsp->tv_nsec >= 1000000000) {
1496 if (timespecisset(tsp)) {
1497 if (tsp->tv_sec <= INT32_MAX) {
1498 rsbt = tstosbt(*tsp);
1499 if (TIMESEL(&asbt, rsbt))
1500 asbt += tc_tick_sbt;
1501 if (asbt <= SBT_MAX - rsbt)
1505 rsbt >>= tc_precexp;
1512 marker = knote_alloc(1);
1513 if (marker == NULL) {
1517 marker->kn_status = KN_MARKER;
1522 if (kq->kq_count == 0) {
1524 error = EWOULDBLOCK;
1526 kq->kq_state |= KQ_SLEEP;
1527 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1528 "kqread", asbt, rsbt, C_ABSOLUTE);
1532 /* don't restart after signals... */
1533 if (error == ERESTART)
1535 else if (error == EWOULDBLOCK)
1540 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1544 kn = TAILQ_FIRST(&kq->kq_head);
1546 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1547 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1552 kq->kq_state |= KQ_FLUXWAIT;
1553 error = msleep(kq, &kq->kq_lock, PSOCK,
1558 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1559 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1560 kn->kn_status &= ~KN_QUEUED;
1566 if (count == maxevents)
1570 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1571 ("KN_INFLUX set when not suppose to be"));
1573 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1574 kn->kn_status &= ~KN_QUEUED;
1575 kn->kn_status |= KN_INFLUX;
1579 * We don't need to lock the list since we've marked
1582 if (!(kn->kn_status & KN_DETACHED))
1583 kn->kn_fop->f_detach(kn);
1587 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1588 kn->kn_status &= ~KN_QUEUED;
1589 kn->kn_status |= KN_INFLUX;
1593 * We don't need to lock the list since we've marked
1596 *kevp = kn->kn_kevent;
1597 if (!(kn->kn_status & KN_DETACHED))
1598 kn->kn_fop->f_detach(kn);
1603 kn->kn_status |= KN_INFLUX | KN_SCAN;
1605 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1606 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1608 if (kn->kn_fop->f_event(kn, 0) == 0) {
1610 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1612 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1619 touch = (!kn->kn_fop->f_isfd &&
1620 kn->kn_fop->f_touch != NULL);
1622 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1624 *kevp = kn->kn_kevent;
1626 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1627 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1629 * Manually clear knotes who weren't
1632 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1636 if (kn->kn_flags & EV_DISPATCH)
1637 kn->kn_status |= KN_DISABLED;
1638 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1641 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1643 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1648 /* we are returning a copy to the user */
1653 if (nkev == KQ_NEVENTS) {
1656 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1664 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1672 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1673 td->td_retval[0] = maxevents - count;
1679 * This could be expanded to call kqueue_scan, if desired.
1683 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1684 int flags, struct thread *td)
1691 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1692 int flags, struct thread *td)
1699 kqueue_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1708 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1709 struct ucred *active_cred, struct thread *td)
1712 * Enabling sigio causes two major problems:
1713 * 1) infinite recursion:
1714 * Synopsys: kevent is being used to track signals and have FIOASYNC
1715 * set. On receipt of a signal this will cause a kqueue to recurse
1716 * into itself over and over. Sending the sigio causes the kqueue
1717 * to become ready, which in turn posts sigio again, forever.
1718 * Solution: this can be solved by setting a flag in the kqueue that
1719 * we have a SIGIO in progress.
1720 * 2) locking problems:
1721 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1722 * us above the proc and pgrp locks.
1723 * Solution: Post a signal using an async mechanism, being sure to
1724 * record a generation count in the delivery so that we do not deliver
1725 * a signal to the wrong process.
1727 * Note, these two mechanisms are somewhat mutually exclusive!
1736 kq->kq_state |= KQ_ASYNC;
1738 kq->kq_state &= ~KQ_ASYNC;
1743 return (fsetown(*(int *)data, &kq->kq_sigio));
1746 *(int *)data = fgetown(&kq->kq_sigio);
1756 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1763 if ((error = kqueue_acquire(fp, &kq)))
1767 if (events & (POLLIN | POLLRDNORM)) {
1769 revents |= events & (POLLIN | POLLRDNORM);
1771 selrecord(td, &kq->kq_sel);
1772 if (SEL_WAITING(&kq->kq_sel))
1773 kq->kq_state |= KQ_SEL;
1776 kqueue_release(kq, 1);
1783 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1787 bzero((void *)st, sizeof *st);
1789 * We no longer return kq_count because the unlocked value is useless.
1790 * If you spent all this time getting the count, why not spend your
1791 * syscall better by calling kevent?
1793 * XXX - This is needed for libc_r.
1795 st->st_mode = S_IFIFO;
1801 kqueue_close(struct file *fp, struct thread *td)
1803 struct kqueue *kq = fp->f_data;
1804 struct filedesc *fdp;
1808 int filedesc_unlock;
1810 if ((error = kqueue_acquire(fp, &kq)))
1813 filedesc_unlock = 0;
1816 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1817 ("kqueue already closing"));
1818 kq->kq_state |= KQ_CLOSING;
1819 if (kq->kq_refcnt > 1)
1820 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1822 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1825 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1826 ("kqueue's knlist not empty"));
1828 for (i = 0; i < kq->kq_knlistsize; i++) {
1829 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1830 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1831 kq->kq_state |= KQ_FLUXWAIT;
1832 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1835 kn->kn_status |= KN_INFLUX;
1837 if (!(kn->kn_status & KN_DETACHED))
1838 kn->kn_fop->f_detach(kn);
1843 if (kq->kq_knhashmask != 0) {
1844 for (i = 0; i <= kq->kq_knhashmask; i++) {
1845 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1846 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1847 kq->kq_state |= KQ_FLUXWAIT;
1848 msleep(kq, &kq->kq_lock, PSOCK,
1852 kn->kn_status |= KN_INFLUX;
1854 if (!(kn->kn_status & KN_DETACHED))
1855 kn->kn_fop->f_detach(kn);
1862 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1863 kq->kq_state |= KQ_TASKDRAIN;
1864 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1867 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1868 selwakeuppri(&kq->kq_sel, PSOCK);
1869 if (!SEL_WAITING(&kq->kq_sel))
1870 kq->kq_state &= ~KQ_SEL;
1876 * We could be called due to the knote_drop() doing fdrop(),
1877 * called from kqueue_register(). In this case the global
1878 * lock is owned, and filedesc sx is locked before, to not
1879 * take the sleepable lock after non-sleepable.
1881 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1882 FILEDESC_XLOCK(fdp);
1883 filedesc_unlock = 1;
1885 filedesc_unlock = 0;
1886 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1887 if (filedesc_unlock)
1888 FILEDESC_XUNLOCK(fdp);
1890 seldrain(&kq->kq_sel);
1891 knlist_destroy(&kq->kq_sel.si_note);
1892 mtx_destroy(&kq->kq_lock);
1895 if (kq->kq_knhash != NULL)
1896 free(kq->kq_knhash, M_KQUEUE);
1897 if (kq->kq_knlist != NULL)
1898 free(kq->kq_knlist, M_KQUEUE);
1900 funsetown(&kq->kq_sigio);
1908 kqueue_wakeup(struct kqueue *kq)
1912 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1913 kq->kq_state &= ~KQ_SLEEP;
1916 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1917 selwakeuppri(&kq->kq_sel, PSOCK);
1918 if (!SEL_WAITING(&kq->kq_sel))
1919 kq->kq_state &= ~KQ_SEL;
1921 if (!knlist_empty(&kq->kq_sel.si_note))
1922 kqueue_schedtask(kq);
1923 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1924 pgsigio(&kq->kq_sigio, SIGIO, 0);
1929 * Walk down a list of knotes, activating them if their event has triggered.
1931 * There is a possibility to optimize in the case of one kq watching another.
1932 * Instead of scheduling a task to wake it up, you could pass enough state
1933 * down the chain to make up the parent kqueue. Make this code functional
1937 knote(struct knlist *list, long hint, int lockflags)
1940 struct knote *kn, *tkn;
1947 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1949 if ((lockflags & KNF_LISTLOCKED) == 0)
1950 list->kl_lock(list->kl_lockarg);
1953 * If we unlock the list lock (and set KN_INFLUX), we can
1954 * eliminate the kqueue scheduling, but this will introduce
1955 * four lock/unlock's for each knote to test. Also, marker
1956 * would be needed to keep iteration position, since filters
1957 * or other threads could remove events.
1959 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
1962 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1964 * Do not process the influx notes, except for
1965 * the influx coming from the kq unlock in the
1966 * kqueue_scan(). In the later case, we do
1967 * not interfere with the scan, since the code
1968 * fragment in kqueue_scan() locks the knlist,
1969 * and cannot proceed until we finished.
1972 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1973 own_influx = (kn->kn_status & KN_INFLUX) == 0;
1975 kn->kn_status |= KN_INFLUX;
1977 error = kn->kn_fop->f_event(kn, hint);
1980 kn->kn_status &= ~KN_INFLUX;
1982 KNOTE_ACTIVATE(kn, 1);
1985 kn->kn_status |= KN_HASKQLOCK;
1986 if (kn->kn_fop->f_event(kn, hint))
1987 KNOTE_ACTIVATE(kn, 1);
1988 kn->kn_status &= ~KN_HASKQLOCK;
1992 if ((lockflags & KNF_LISTLOCKED) == 0)
1993 list->kl_unlock(list->kl_lockarg);
1997 * add a knote to a knlist
2000 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2002 KNL_ASSERT_LOCK(knl, islocked);
2003 KQ_NOTOWNED(kn->kn_kq);
2004 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
2005 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
2007 knl->kl_lock(knl->kl_lockarg);
2008 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2010 knl->kl_unlock(knl->kl_lockarg);
2012 kn->kn_knlist = knl;
2013 kn->kn_status &= ~KN_DETACHED;
2014 KQ_UNLOCK(kn->kn_kq);
2018 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
2020 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2021 KNL_ASSERT_LOCK(knl, knlislocked);
2022 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2024 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2025 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2027 knl->kl_lock(knl->kl_lockarg);
2028 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2029 kn->kn_knlist = NULL;
2031 knl->kl_unlock(knl->kl_lockarg);
2034 kn->kn_status |= KN_DETACHED;
2036 KQ_UNLOCK(kn->kn_kq);
2040 * remove knote from the specified knlist
2043 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2046 knlist_remove_kq(knl, kn, islocked, 0);
2050 * remove knote from the specified knlist while in f_event handler.
2053 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
2056 knlist_remove_kq(knl, kn, 1,
2057 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
2061 knlist_empty(struct knlist *knl)
2064 KNL_ASSERT_LOCKED(knl);
2065 return (SLIST_EMPTY(&knl->kl_list));
2068 static struct mtx knlist_lock;
2069 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2071 static void knlist_mtx_lock(void *arg);
2072 static void knlist_mtx_unlock(void *arg);
2075 knlist_mtx_lock(void *arg)
2078 mtx_lock((struct mtx *)arg);
2082 knlist_mtx_unlock(void *arg)
2085 mtx_unlock((struct mtx *)arg);
2089 knlist_mtx_assert_locked(void *arg)
2092 mtx_assert((struct mtx *)arg, MA_OWNED);
2096 knlist_mtx_assert_unlocked(void *arg)
2099 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2103 knlist_rw_rlock(void *arg)
2106 rw_rlock((struct rwlock *)arg);
2110 knlist_rw_runlock(void *arg)
2113 rw_runlock((struct rwlock *)arg);
2117 knlist_rw_assert_locked(void *arg)
2120 rw_assert((struct rwlock *)arg, RA_LOCKED);
2124 knlist_rw_assert_unlocked(void *arg)
2127 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2131 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2132 void (*kl_unlock)(void *),
2133 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2137 knl->kl_lockarg = &knlist_lock;
2139 knl->kl_lockarg = lock;
2141 if (kl_lock == NULL)
2142 knl->kl_lock = knlist_mtx_lock;
2144 knl->kl_lock = kl_lock;
2145 if (kl_unlock == NULL)
2146 knl->kl_unlock = knlist_mtx_unlock;
2148 knl->kl_unlock = kl_unlock;
2149 if (kl_assert_locked == NULL)
2150 knl->kl_assert_locked = knlist_mtx_assert_locked;
2152 knl->kl_assert_locked = kl_assert_locked;
2153 if (kl_assert_unlocked == NULL)
2154 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2156 knl->kl_assert_unlocked = kl_assert_unlocked;
2158 SLIST_INIT(&knl->kl_list);
2162 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2165 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2169 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2172 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2173 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2177 knlist_destroy(struct knlist *knl)
2180 KASSERT(KNLIST_EMPTY(knl),
2181 ("destroying knlist %p with knotes on it", knl));
2185 * Even if we are locked, we may need to drop the lock to allow any influx
2186 * knotes time to "settle".
2189 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2191 struct knote *kn, *kn2;
2195 KNL_ASSERT_LOCKED(knl);
2197 KNL_ASSERT_UNLOCKED(knl);
2198 again: /* need to reacquire lock since we have dropped it */
2199 knl->kl_lock(knl->kl_lockarg);
2202 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2205 if ((kn->kn_status & KN_INFLUX)) {
2209 knlist_remove_kq(knl, kn, 1, 1);
2211 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2215 /* Make sure cleared knotes disappear soon */
2216 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2222 if (!SLIST_EMPTY(&knl->kl_list)) {
2223 /* there are still KN_INFLUX remaining */
2224 kn = SLIST_FIRST(&knl->kl_list);
2227 KASSERT(kn->kn_status & KN_INFLUX,
2228 ("knote removed w/o list lock"));
2229 knl->kl_unlock(knl->kl_lockarg);
2230 kq->kq_state |= KQ_FLUXWAIT;
2231 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2237 KNL_ASSERT_LOCKED(knl);
2239 knl->kl_unlock(knl->kl_lockarg);
2240 KNL_ASSERT_UNLOCKED(knl);
2245 * Remove all knotes referencing a specified fd must be called with FILEDESC
2246 * lock. This prevents a race where a new fd comes along and occupies the
2247 * entry and we attach a knote to the fd.
2250 knote_fdclose(struct thread *td, int fd)
2252 struct filedesc *fdp = td->td_proc->p_fd;
2257 FILEDESC_XLOCK_ASSERT(fdp);
2260 * We shouldn't have to worry about new kevents appearing on fd
2261 * since filedesc is locked.
2263 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2268 while (kq->kq_knlistsize > fd &&
2269 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2270 if (kn->kn_status & KN_INFLUX) {
2271 /* someone else might be waiting on our knote */
2274 kq->kq_state |= KQ_FLUXWAIT;
2275 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2278 kn->kn_status |= KN_INFLUX;
2280 if (!(kn->kn_status & KN_DETACHED))
2281 kn->kn_fop->f_detach(kn);
2291 knote_attach(struct knote *kn, struct kqueue *kq)
2295 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2298 if (kn->kn_fop->f_isfd) {
2299 if (kn->kn_id >= kq->kq_knlistsize)
2301 list = &kq->kq_knlist[kn->kn_id];
2303 if (kq->kq_knhash == NULL)
2305 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2307 SLIST_INSERT_HEAD(list, kn, kn_link);
2312 * knote must already have been detached using the f_detach method.
2313 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2314 * to prevent other removal.
2317 knote_drop(struct knote *kn, struct thread *td)
2325 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2326 ("knote_drop called without KN_INFLUX set in kn_status"));
2329 if (kn->kn_fop->f_isfd)
2330 list = &kq->kq_knlist[kn->kn_id];
2332 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2334 if (!SLIST_EMPTY(list))
2335 SLIST_REMOVE(list, kn, knote, kn_link);
2336 if (kn->kn_status & KN_QUEUED)
2340 if (kn->kn_fop->f_isfd) {
2341 fdrop(kn->kn_fp, td);
2344 kqueue_fo_release(kn->kn_kevent.filter);
2350 knote_enqueue(struct knote *kn)
2352 struct kqueue *kq = kn->kn_kq;
2354 KQ_OWNED(kn->kn_kq);
2355 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2357 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2358 kn->kn_status |= KN_QUEUED;
2364 knote_dequeue(struct knote *kn)
2366 struct kqueue *kq = kn->kn_kq;
2368 KQ_OWNED(kn->kn_kq);
2369 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2371 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2372 kn->kn_status &= ~KN_QUEUED;
2380 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2381 NULL, NULL, UMA_ALIGN_PTR, 0);
2383 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2385 static struct knote *
2386 knote_alloc(int waitok)
2388 return ((struct knote *)uma_zalloc(knote_zone,
2389 (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2393 knote_free(struct knote *kn)
2396 uma_zfree(knote_zone, kn);
2400 * Register the kev w/ the kq specified by fd.
2403 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2407 cap_rights_t rights;
2410 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2413 if ((error = kqueue_acquire(fp, &kq)) != 0)
2416 error = kqueue_register(kq, kev, td, waitok);
2417 kqueue_release(kq, 0);