2 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
3 * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
35 #include <sys/mutex.h>
37 #include <sys/malloc.h>
38 #include <sys/unistd.h>
40 #include <sys/filedesc.h>
41 #include <sys/filio.h>
42 #include <sys/fcntl.h>
43 #include <sys/kthread.h>
44 #include <sys/selinfo.h>
45 #include <sys/queue.h>
46 #include <sys/event.h>
47 #include <sys/eventvar.h>
49 #include <sys/protosw.h>
50 #include <sys/sigio.h>
51 #include <sys/signalvar.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
55 #include <sys/sysctl.h>
56 #include <sys/sysproto.h>
57 #include <sys/syscallsubr.h>
58 #include <sys/taskqueue.h>
63 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
66 * This lock is used if multiple kq locks are required. This possibly
67 * should be made into a per proc lock.
69 static struct mtx kq_global;
70 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
71 #define KQ_GLOBAL_LOCK(lck, haslck) do { \
76 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
82 TASKQUEUE_DEFINE_THREAD(kqueue);
84 static int kevent_copyout(struct kevent **eventlist, enum uio_seg eventseg,
85 struct kevent *kevp, int count);
86 static int kqueue_aquire(struct file *fp, struct kqueue **kqp);
87 static void kqueue_release(struct kqueue *kq, int locked);
88 static int kqueue_expand(struct kqueue *kq, struct filterops *fops,
89 uintptr_t ident, int waitok);
90 static void kqueue_task(void *arg, int pending);
91 static int kqueue_scan(struct kqueue *kq, int maxevents,
92 struct kevent *eventlist, enum uio_seg eventseg,
93 const struct timespec *timeout, struct kevent *keva,
95 static void kqueue_wakeup(struct kqueue *kq);
96 static struct filterops *kqueue_fo_find(int filt);
97 static void kqueue_fo_release(int filt);
99 static fo_rdwr_t kqueue_read;
100 static fo_rdwr_t kqueue_write;
101 static fo_ioctl_t kqueue_ioctl;
102 static fo_poll_t kqueue_poll;
103 static fo_kqfilter_t kqueue_kqfilter;
104 static fo_stat_t kqueue_stat;
105 static fo_close_t kqueue_close;
107 static struct fileops kqueueops = {
108 .fo_read = kqueue_read,
109 .fo_write = kqueue_write,
110 .fo_ioctl = kqueue_ioctl,
111 .fo_poll = kqueue_poll,
112 .fo_kqfilter = kqueue_kqfilter,
113 .fo_stat = kqueue_stat,
114 .fo_close = kqueue_close,
117 static int knote_attach(struct knote *kn, struct kqueue *kq);
118 static void knote_drop(struct knote *kn, struct thread *td);
119 static void knote_enqueue(struct knote *kn);
120 static void knote_dequeue(struct knote *kn);
121 static void knote_init(void);
122 static struct knote *knote_alloc(int waitok);
123 static void knote_free(struct knote *kn);
125 static void filt_kqdetach(struct knote *kn);
126 static int filt_kqueue(struct knote *kn, long hint);
127 static int filt_procattach(struct knote *kn);
128 static void filt_procdetach(struct knote *kn);
129 static int filt_proc(struct knote *kn, long hint);
130 static int filt_fileattach(struct knote *kn);
131 static void filt_timerexpire(void *knx);
132 static int filt_timerattach(struct knote *kn);
133 static void filt_timerdetach(struct knote *kn);
134 static int filt_timer(struct knote *kn, long hint);
136 static struct filterops file_filtops =
137 { 1, filt_fileattach, NULL, NULL };
138 static struct filterops kqread_filtops =
139 { 1, NULL, filt_kqdetach, filt_kqueue };
140 /* XXX - move to kern_proc.c? */
141 static struct filterops proc_filtops =
142 { 0, filt_procattach, filt_procdetach, filt_proc };
143 static struct filterops timer_filtops =
144 { 0, filt_timerattach, filt_timerdetach, filt_timer };
146 static uma_zone_t knote_zone;
147 static int kq_ncallouts = 0;
148 static int kq_calloutmax = (4 * 1024);
149 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
150 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
152 /* XXX - ensure not KN_INFLUX?? */
153 #define KNOTE_ACTIVATE(kn, islock) do { \
155 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
157 KQ_LOCK((kn)->kn_kq); \
158 (kn)->kn_status |= KN_ACTIVE; \
159 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
160 knote_enqueue((kn)); \
162 KQ_UNLOCK((kn)->kn_kq); \
164 #define KQ_LOCK(kq) do { \
165 mtx_lock(&(kq)->kq_lock); \
167 #define KQ_FLUX_WAKEUP(kq) do { \
168 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
169 (kq)->kq_state &= ~KQ_FLUXWAIT; \
173 #define KQ_UNLOCK_FLUX(kq) do { \
174 KQ_FLUX_WAKEUP(kq); \
175 mtx_unlock(&(kq)->kq_lock); \
177 #define KQ_UNLOCK(kq) do { \
178 mtx_unlock(&(kq)->kq_lock); \
180 #define KQ_OWNED(kq) do { \
181 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
183 #define KQ_NOTOWNED(kq) do { \
184 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
186 #define KN_LIST_LOCK(kn) do { \
187 if (kn->kn_knlist != NULL) \
188 mtx_lock(kn->kn_knlist->kl_lock); \
190 #define KN_LIST_UNLOCK(kn) do { \
191 if (kn->kn_knlist != NULL) \
192 mtx_unlock(kn->kn_knlist->kl_lock); \
195 #define KN_HASHSIZE 64 /* XXX should be tunable */
196 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
199 filt_nullattach(struct knote *kn)
205 struct filterops null_filtops =
206 { 0, filt_nullattach, NULL, NULL };
208 /* XXX - make SYSINIT to add these, and move into respective modules. */
209 extern struct filterops sig_filtops;
210 extern struct filterops fs_filtops;
213 * Table for for all system-defined filters.
215 static struct mtx filterops_lock;
216 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
219 struct filterops *for_fop;
221 } sysfilt_ops[EVFILT_SYSCOUNT] = {
222 { &file_filtops }, /* EVFILT_READ */
223 { &file_filtops }, /* EVFILT_WRITE */
224 { &null_filtops }, /* EVFILT_AIO */
225 { &file_filtops }, /* EVFILT_VNODE */
226 { &proc_filtops }, /* EVFILT_PROC */
227 { &sig_filtops }, /* EVFILT_SIGNAL */
228 { &timer_filtops }, /* EVFILT_TIMER */
229 { &file_filtops }, /* EVFILT_NETDEV */
230 { &fs_filtops }, /* EVFILT_FS */
234 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
238 filt_fileattach(struct knote *kn)
241 return (fo_kqfilter(kn->kn_fp, kn));
246 kqueue_kqfilter(struct file *fp, struct knote *kn)
248 struct kqueue *kq = kn->kn_fp->f_data;
250 if (kn->kn_filter != EVFILT_READ)
253 kn->kn_status |= KN_KQUEUE;
254 kn->kn_fop = &kqread_filtops;
255 knlist_add(&kq->kq_sel.si_note, kn, 0);
261 filt_kqdetach(struct knote *kn)
263 struct kqueue *kq = kn->kn_fp->f_data;
265 knlist_remove(&kq->kq_sel.si_note, kn, 0);
270 filt_kqueue(struct knote *kn, long hint)
272 struct kqueue *kq = kn->kn_fp->f_data;
274 kn->kn_data = kq->kq_count;
275 return (kn->kn_data > 0);
278 /* XXX - move to kern_proc.c? */
280 filt_procattach(struct knote *kn)
287 p = pfind(kn->kn_id);
288 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
289 p = zpfind(kn->kn_id);
291 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
297 if ((error = p_cansee(curthread, p)))
300 kn->kn_ptr.p_proc = p;
301 kn->kn_flags |= EV_CLEAR; /* automatically set */
304 * internal flag indicating registration done by kernel
306 if (kn->kn_flags & EV_FLAG1) {
307 kn->kn_data = kn->kn_sdata; /* ppid */
308 kn->kn_fflags = NOTE_CHILD;
309 kn->kn_flags &= ~EV_FLAG1;
313 knlist_add(&p->p_klist, kn, 1);
316 * Immediately activate any exit notes if the target process is a
317 * zombie. This is necessary to handle the case where the target
318 * process, e.g. a child, dies before the kevent is registered.
320 if (immediate && filt_proc(kn, NOTE_EXIT))
321 KNOTE_ACTIVATE(kn, 0);
329 * The knote may be attached to a different process, which may exit,
330 * leaving nothing for the knote to be attached to. So when the process
331 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
332 * it will be deleted when read out. However, as part of the knote deletion,
333 * this routine is called, so a check is needed to avoid actually performing
334 * a detach, because the original process does not exist any more.
336 /* XXX - move to kern_proc.c? */
338 filt_procdetach(struct knote *kn)
342 p = kn->kn_ptr.p_proc;
343 knlist_remove(&p->p_klist, kn, 0);
344 kn->kn_ptr.p_proc = NULL;
347 /* XXX - move to kern_proc.c? */
349 filt_proc(struct knote *kn, long hint)
351 struct proc *p = kn->kn_ptr.p_proc;
355 * mask off extra data
357 event = (u_int)hint & NOTE_PCTRLMASK;
360 * if the user is interested in this event, record it.
362 if (kn->kn_sfflags & event)
363 kn->kn_fflags |= event;
366 * process is gone, so flag the event as finished.
368 if (event == NOTE_EXIT) {
369 if (!(kn->kn_status & KN_DETACHED))
370 knlist_remove_inevent(&p->p_klist, kn);
371 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
372 kn->kn_ptr.p_proc = NULL;
377 * process forked, and user wants to track the new process,
378 * so attach a new knote to it, and immediately report an
379 * event with the parent's pid.
381 if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
386 * register knote with new process.
388 kev.ident = hint & NOTE_PDATAMASK; /* pid */
389 kev.filter = kn->kn_filter;
390 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
391 kev.fflags = kn->kn_sfflags;
392 kev.data = kn->kn_id; /* parent */
393 kev.udata = kn->kn_kevent.udata; /* preserve udata */
394 error = kqueue_register(kn->kn_kq, &kev, NULL, 0);
396 kn->kn_fflags |= NOTE_TRACKERR;
399 return (kn->kn_fflags != 0);
403 timertoticks(intptr_t data)
408 tv.tv_sec = data / 1000;
409 tv.tv_usec = (data % 1000) * 1000;
410 tticks = tvtohz(&tv);
415 /* XXX - move to kern_timeout.c? */
417 filt_timerexpire(void *knx)
419 struct knote *kn = knx;
420 struct callout *calloutp;
423 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
425 if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
426 calloutp = (struct callout *)kn->kn_hook;
427 callout_reset(calloutp, timertoticks(kn->kn_sdata),
428 filt_timerexpire, kn);
433 * data contains amount of time to sleep, in milliseconds
435 /* XXX - move to kern_timeout.c? */
437 filt_timerattach(struct knote *kn)
439 struct callout *calloutp;
441 atomic_add_int(&kq_ncallouts, 1);
443 if (kq_ncallouts >= kq_calloutmax) {
444 atomic_add_int(&kq_ncallouts, -1);
448 kn->kn_flags |= EV_CLEAR; /* automatically set */
449 kn->kn_status &= ~KN_DETACHED; /* knlist_add usually sets it */
450 MALLOC(calloutp, struct callout *, sizeof(*calloutp),
452 callout_init(calloutp, CALLOUT_MPSAFE);
453 kn->kn_hook = calloutp;
454 callout_reset(calloutp, timertoticks(kn->kn_sdata), filt_timerexpire,
460 /* XXX - move to kern_timeout.c? */
462 filt_timerdetach(struct knote *kn)
464 struct callout *calloutp;
466 calloutp = (struct callout *)kn->kn_hook;
467 callout_drain(calloutp);
468 FREE(calloutp, M_KQUEUE);
469 atomic_add_int(&kq_ncallouts, -1);
470 kn->kn_status |= KN_DETACHED; /* knlist_remove usually clears it */
473 /* XXX - move to kern_timeout.c? */
475 filt_timer(struct knote *kn, long hint)
478 return (kn->kn_data != 0);
485 kqueue(struct thread *td, struct kqueue_args *uap)
487 struct filedesc *fdp;
492 fdp = td->td_proc->p_fd;
493 error = falloc(td, &fp, &fd);
497 /* An extra reference on `nfp' has been held for us by falloc(). */
498 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
499 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
500 TAILQ_INIT(&kq->kq_head);
502 knlist_init(&kq->kq_sel.si_note, &kq->kq_lock);
503 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
505 FILEDESC_LOCK_FAST(fdp);
506 SLIST_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
507 FILEDESC_UNLOCK_FAST(fdp);
510 fp->f_flag = FREAD | FWRITE;
511 fp->f_type = DTYPE_KQUEUE;
512 fp->f_ops = &kqueueops;
517 td->td_retval[0] = fd;
522 #ifndef _SYS_SYSPROTO_H_
525 const struct kevent *changelist;
527 struct kevent *eventlist;
529 const struct timespec *timeout;
536 kevent(struct thread *td, struct kevent_args *uap)
538 struct timespec ts, *tsp;
541 if (uap->timeout != NULL) {
542 error = copyin(uap->timeout, &ts, sizeof(ts));
549 return (kern_kevent(td, uap->fd, uap->changelist, uap->nchanges,
550 UIO_USERSPACE, uap->eventlist, uap->nevents, UIO_USERSPACE, tsp));
554 * Copy 'count' items into the destination list pointd to by *eventlist. The
555 * eventlist and nevents values are updated to point after the copied out
556 * item(s) upon return.
559 kevent_copyout(struct kevent **eventlist, enum uio_seg eventseg,
560 struct kevent *kevp, int count)
564 if (eventseg == UIO_USERSPACE)
565 error = copyout(kevp, *eventlist,
566 sizeof(struct kevent) * count);
568 bcopy(kevp, *eventlist, sizeof(struct kevent) * count);
576 kern_kevent(struct thread *td, int fd, struct kevent *changelist, int nchanges,
577 enum uio_seg changeseg, struct kevent *eventlist, int nevents,
578 enum uio_seg eventseg, const struct timespec *timeout)
580 struct kevent keva[KQ_NEVENTS];
581 struct kevent *kevp, *changes;
584 int i, n, nerrors, error;
586 if ((error = fget(td, fd, &fp)) != 0)
588 if ((error = kqueue_aquire(fp, &kq)) != 0)
593 while (nchanges > 0) {
594 if (changeseg == UIO_USERSPACE) {
595 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
596 error = copyin(changelist, keva, n * sizeof *keva);
601 changes = changelist;
604 for (i = 0; i < n; i++) {
606 kevp->flags &= ~EV_SYSFLAGS;
607 error = kqueue_register(kq, kevp, td, 1);
610 kevp->flags = EV_ERROR;
612 (void) kevent_copyout(&eventlist,
625 td->td_retval[0] = nerrors;
630 error = kqueue_scan(kq, nevents, eventlist, eventseg, timeout,
633 kqueue_release(kq, 0);
641 kqueue_add_filteropts(int filt, struct filterops *filtops)
645 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
647 "trying to add a filterop that is out of range: %d is beyond %d\n",
648 ~filt, EVFILT_SYSCOUNT);
651 mtx_lock(&filterops_lock);
652 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
653 sysfilt_ops[~filt].for_fop != NULL)
656 sysfilt_ops[~filt].for_fop = filtops;
657 sysfilt_ops[~filt].for_refcnt = 0;
659 mtx_unlock(&filterops_lock);
665 kqueue_del_filteropts(int filt)
670 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
673 mtx_lock(&filterops_lock);
674 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
675 sysfilt_ops[~filt].for_fop == NULL)
677 else if (sysfilt_ops[~filt].for_refcnt != 0)
680 sysfilt_ops[~filt].for_fop = &null_filtops;
681 sysfilt_ops[~filt].for_refcnt = 0;
683 mtx_unlock(&filterops_lock);
688 static struct filterops *
689 kqueue_fo_find(int filt)
692 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
695 mtx_lock(&filterops_lock);
696 sysfilt_ops[~filt].for_refcnt++;
697 if (sysfilt_ops[~filt].for_fop == NULL)
698 sysfilt_ops[~filt].for_fop = &null_filtops;
699 mtx_unlock(&filterops_lock);
701 return sysfilt_ops[~filt].for_fop;
705 kqueue_fo_release(int filt)
708 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
711 mtx_lock(&filterops_lock);
712 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
713 ("filter object refcount not valid on release"));
714 sysfilt_ops[~filt].for_refcnt--;
715 mtx_unlock(&filterops_lock);
719 * A ref to kq (obtained via kqueue_aquire) should be held. waitok will
720 * influence if memory allocation should wait. Make sure it is 0 if you
724 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
726 struct filedesc *fdp;
727 struct filterops *fops;
729 struct knote *kn, *tkn;
730 int error, filt, event;
741 fops = kqueue_fo_find(filt);
745 tkn = knote_alloc(waitok); /* prevent waiting with locks */
749 KASSERT(td != NULL, ("td is NULL"));
750 fdp = td->td_proc->p_fd;
752 /* validate descriptor */
754 if (fd < 0 || fd >= fdp->fd_nfiles ||
755 (fp = fdp->fd_ofiles[fd]) == NULL) {
756 FILEDESC_UNLOCK(fdp);
762 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
763 kev->ident, 0) != 0) {
764 /* unlock and try again */
765 FILEDESC_UNLOCK(fdp);
768 error = kqueue_expand(kq, fops, kev->ident, waitok);
774 if (fp->f_type == DTYPE_KQUEUE) {
776 * if we add some inteligence about what we are doing,
777 * we should be able to support events on ourselves.
778 * We need to know when we are doing this to prevent
779 * getting both the knlist lock and the kq lock since
780 * they are the same thing.
782 if (fp->f_data == kq) {
783 FILEDESC_UNLOCK(fdp);
788 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
791 FILEDESC_UNLOCK(fdp);
793 if (kev->ident < kq->kq_knlistsize) {
794 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
795 if (kev->filter == kn->kn_filter)
799 if ((kev->flags & EV_ADD) == EV_ADD)
800 kqueue_expand(kq, fops, kev->ident, waitok);
803 if (kq->kq_knhashmask != 0) {
806 list = &kq->kq_knhash[
807 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
808 SLIST_FOREACH(kn, list, kn_link)
809 if (kev->ident == kn->kn_id &&
810 kev->filter == kn->kn_filter)
815 /* knote is in the process of changing, wait for it to stablize. */
816 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
821 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
822 kq->kq_state |= KQ_FLUXWAIT;
823 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
827 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
834 * kn now contains the matching knote, or NULL if no match
836 if (kev->flags & EV_ADD) {
848 * apply reference counts to knote structure, and
849 * do not release it at the end of this routine.
854 kn->kn_sfflags = kev->fflags;
855 kn->kn_sdata = kev->data;
858 kn->kn_kevent = *kev;
859 kn->kn_status = KN_INFLUX|KN_DETACHED;
861 error = knote_attach(kn, kq);
868 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
875 * The user may change some filter values after the
876 * initial EV_ADD, but doing so will not reset any
877 * filter which has already been triggered.
879 kn->kn_status |= KN_INFLUX;
882 kn->kn_sfflags = kev->fflags;
883 kn->kn_sdata = kev->data;
884 kn->kn_kevent.udata = kev->udata;
888 * We can get here with kn->kn_knlist == NULL.
889 * This can happen when the initial attach event decides that
890 * the event is "completed" already. i.e. filt_procattach
891 * is called on a zombie process. It will call filt_proc
892 * which will remove it from the list, and NULL kn_knlist.
894 event = kn->kn_fop->f_event(kn, 0);
898 KNOTE_ACTIVATE(kn, 1);
899 kn->kn_status &= ~KN_INFLUX;
900 } else if (kev->flags & EV_DELETE) {
901 kn->kn_status |= KN_INFLUX;
903 if (!(kn->kn_status & KN_DETACHED))
904 kn->kn_fop->f_detach(kn);
909 if ((kev->flags & EV_DISABLE) &&
910 ((kn->kn_status & KN_DISABLED) == 0)) {
911 kn->kn_status |= KN_DISABLED;
914 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
915 kn->kn_status &= ~KN_DISABLED;
916 if ((kn->kn_status & KN_ACTIVE) &&
917 ((kn->kn_status & KN_QUEUED) == 0))
923 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
930 kqueue_fo_release(filt);
935 kqueue_aquire(struct file *fp, struct kqueue **kqp)
945 if (fp->f_type != DTYPE_KQUEUE || kq == NULL) {
951 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
965 kqueue_release(struct kqueue *kq, int locked)
972 if (kq->kq_refcnt == 1)
973 wakeup(&kq->kq_refcnt);
979 kqueue_schedtask(struct kqueue *kq)
983 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
984 ("scheduling kqueue task while draining"));
986 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
987 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
988 kq->kq_state |= KQ_TASKSCHED;
993 * Expand the kq to make sure we have storage for fops/ident pair.
995 * Return 0 on success (or no work necessary), return errno on failure.
997 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
998 * If kqueue_register is called from a non-fd context, there usually/should
1002 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1005 struct klist *list, *tmp_knhash;
1006 u_long tmp_knhashmask;
1009 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1015 if (kq->kq_knlistsize <= fd) {
1016 size = kq->kq_knlistsize;
1019 MALLOC(list, struct klist *,
1020 size * sizeof list, M_KQUEUE, mflag);
1024 if (kq->kq_knlistsize > fd) {
1025 FREE(list, M_KQUEUE);
1028 if (kq->kq_knlist != NULL) {
1029 bcopy(kq->kq_knlist, list,
1030 kq->kq_knlistsize * sizeof list);
1031 FREE(kq->kq_knlist, M_KQUEUE);
1032 kq->kq_knlist = NULL;
1034 bzero((caddr_t)list +
1035 kq->kq_knlistsize * sizeof list,
1036 (size - kq->kq_knlistsize) * sizeof list);
1037 kq->kq_knlistsize = size;
1038 kq->kq_knlist = list;
1043 if (kq->kq_knhashmask == 0) {
1044 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1046 if (tmp_knhash == NULL)
1049 if (kq->kq_knhashmask == 0) {
1050 kq->kq_knhash = tmp_knhash;
1051 kq->kq_knhashmask = tmp_knhashmask;
1053 free(tmp_knhash, M_KQUEUE);
1064 kqueue_task(void *arg, int pending)
1072 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1075 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1077 kq->kq_state &= ~KQ_TASKSCHED;
1078 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1079 wakeup(&kq->kq_state);
1082 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1086 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1087 * We treat KN_MARKER knotes as if they are INFLUX.
1090 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent *eventlist,
1091 enum uio_seg eventseg, const struct timespec *tsp, struct kevent *keva,
1094 struct kevent *kevp;
1095 struct timeval atv, rtv, ttv;
1096 struct knote *kn, *marker;
1097 int count, timeout, nkev, error;
1109 TIMESPEC_TO_TIMEVAL(&atv, tsp);
1110 if (itimerfix(&atv)) {
1114 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1117 timeout = atv.tv_sec > 24 * 60 * 60 ?
1118 24 * 60 * 60 * hz : tvtohz(&atv);
1119 getmicrouptime(&rtv);
1120 timevaladd(&atv, &rtv);
1126 marker = knote_alloc(1);
1127 if (marker == NULL) {
1131 marker->kn_status = KN_MARKER;
1136 if (atv.tv_sec || atv.tv_usec) {
1137 getmicrouptime(&rtv);
1138 if (timevalcmp(&rtv, &atv, >=))
1141 timevalsub(&ttv, &rtv);
1142 timeout = ttv.tv_sec > 24 * 60 * 60 ?
1143 24 * 60 * 60 * hz : tvtohz(&ttv);
1148 if (kq->kq_count == 0) {
1150 error = EWOULDBLOCK;
1152 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1153 kq->kq_state |= KQ_SLEEP;
1154 error = msleep(kq, &kq->kq_lock, PSOCK | PCATCH,
1159 /* don't restart after signals... */
1160 if (error == ERESTART)
1162 else if (error == EWOULDBLOCK)
1167 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1170 kn = TAILQ_FIRST(&kq->kq_head);
1172 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1173 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1174 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1175 kq->kq_state |= KQ_FLUXWAIT;
1176 error = msleep(kq, &kq->kq_lock, PSOCK,
1181 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1182 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1183 kn->kn_status &= ~KN_QUEUED;
1189 if (count == maxevents)
1193 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1194 ("KN_INFLUX set when not suppose to be"));
1196 if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1197 kn->kn_status &= ~KN_QUEUED;
1198 kn->kn_status |= KN_INFLUX;
1202 * We don't need to lock the list since we've marked
1205 *kevp = kn->kn_kevent;
1206 if (!(kn->kn_status & KN_DETACHED))
1207 kn->kn_fop->f_detach(kn);
1212 kn->kn_status |= KN_INFLUX;
1214 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1215 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1217 if (kn->kn_fop->f_event(kn, 0) == 0) {
1221 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX);
1225 *kevp = kn->kn_kevent;
1227 if (kn->kn_flags & EV_CLEAR) {
1230 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1233 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1235 kn->kn_status &= ~(KN_INFLUX);
1238 /* we are returning a copy to the user */
1243 if (nkev == KQ_NEVENTS) {
1245 error = kevent_copyout(&eventlist, eventseg, keva,
1254 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1258 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1263 error = kevent_copyout(&eventlist, eventseg, keva, nkev);
1264 td->td_retval[0] = maxevents - count;
1270 * This could be expanded to call kqueue_scan, if desired.
1274 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1275 int flags, struct thread *td)
1282 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1283 int flags, struct thread *td)
1290 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1291 struct ucred *active_cred, struct thread *td)
1294 * Enabling sigio causes two major problems:
1295 * 1) infinite recursion:
1296 * Synopsys: kevent is being used to track signals and have FIOASYNC
1297 * set. On receipt of a signal this will cause a kqueue to recurse
1298 * into itself over and over. Sending the sigio causes the kqueue
1299 * to become ready, which in turn posts sigio again, forever.
1300 * Solution: this can be solved by setting a flag in the kqueue that
1301 * we have a SIGIO in progress.
1302 * 2) locking problems:
1303 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1304 * us above the proc and pgrp locks.
1305 * Solution: Post a signal using an async mechanism, being sure to
1306 * record a generation count in the delivery so that we do not deliver
1307 * a signal to the wrong process.
1309 * Note, these two mechanisms are somewhat mutually exclusive!
1318 kq->kq_state |= KQ_ASYNC;
1320 kq->kq_state &= ~KQ_ASYNC;
1325 return (fsetown(*(int *)data, &kq->kq_sigio));
1328 *(int *)data = fgetown(&kq->kq_sigio);
1338 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1345 if ((error = kqueue_aquire(fp, &kq)))
1349 if (events & (POLLIN | POLLRDNORM)) {
1351 revents |= events & (POLLIN | POLLRDNORM);
1353 selrecord(td, &kq->kq_sel);
1354 kq->kq_state |= KQ_SEL;
1357 kqueue_release(kq, 1);
1364 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1373 kqueue_close(struct file *fp, struct thread *td)
1375 struct kqueue *kq = fp->f_data;
1376 struct filedesc *fdp;
1381 if ((error = kqueue_aquire(fp, &kq)))
1386 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1387 ("kqueue already closing"));
1388 kq->kq_state |= KQ_CLOSING;
1389 if (kq->kq_refcnt > 1)
1390 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1392 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1395 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1396 ("kqueue's knlist not empty"));
1398 for (i = 0; i < kq->kq_knlistsize; i++) {
1399 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1400 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1401 ("KN_INFLUX set when not suppose to be"));
1402 kn->kn_status |= KN_INFLUX;
1404 if (!(kn->kn_status & KN_DETACHED))
1405 kn->kn_fop->f_detach(kn);
1410 if (kq->kq_knhashmask != 0) {
1411 for (i = 0; i <= kq->kq_knhashmask; i++) {
1412 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1413 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1414 ("KN_INFLUX set when not suppose to be"));
1415 kn->kn_status |= KN_INFLUX;
1417 if (!(kn->kn_status & KN_DETACHED))
1418 kn->kn_fop->f_detach(kn);
1425 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1426 kq->kq_state |= KQ_TASKDRAIN;
1427 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1430 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1431 kq->kq_state &= ~KQ_SEL;
1432 selwakeuppri(&kq->kq_sel, PSOCK);
1437 FILEDESC_LOCK_FAST(fdp);
1438 SLIST_REMOVE(&fdp->fd_kqlist, kq, kqueue, kq_list);
1439 FILEDESC_UNLOCK_FAST(fdp);
1441 knlist_destroy(&kq->kq_sel.si_note);
1442 mtx_destroy(&kq->kq_lock);
1445 if (kq->kq_knhash != NULL)
1446 free(kq->kq_knhash, M_KQUEUE);
1447 if (kq->kq_knlist != NULL)
1448 free(kq->kq_knlist, M_KQUEUE);
1450 funsetown(&kq->kq_sigio);
1458 kqueue_wakeup(struct kqueue *kq)
1462 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1463 kq->kq_state &= ~KQ_SLEEP;
1466 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1467 kq->kq_state &= ~KQ_SEL;
1468 selwakeuppri(&kq->kq_sel, PSOCK);
1470 if (!knlist_empty(&kq->kq_sel.si_note))
1471 kqueue_schedtask(kq);
1472 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1473 pgsigio(&kq->kq_sigio, SIGIO, 0);
1478 * Walk down a list of knotes, activating them if their event has triggered.
1480 * There is a possibility to optimize in the case of one kq watching another.
1481 * Instead of scheduling a task to wake it up, you could pass enough state
1482 * down the chain to make up the parent kqueue. Make this code functional
1486 knote(struct knlist *list, long hint, int islocked)
1494 mtx_assert(list->kl_lock, islocked ? MA_OWNED : MA_NOTOWNED);
1496 mtx_lock(list->kl_lock);
1498 * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1499 * the kqueue scheduling, but this will introduce four
1500 * lock/unlock's for each knote to test. If we do, continue to use
1501 * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1502 * only safe if you want to remove the current item, which we are
1505 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1507 if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1509 if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1510 kn->kn_status |= KN_HASKQLOCK;
1511 if (kn->kn_fop->f_event(kn, hint))
1512 KNOTE_ACTIVATE(kn, 1);
1513 kn->kn_status &= ~KN_HASKQLOCK;
1520 mtx_unlock(list->kl_lock);
1524 * add a knote to a knlist
1527 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1529 mtx_assert(knl->kl_lock, islocked ? MA_OWNED : MA_NOTOWNED);
1530 KQ_NOTOWNED(kn->kn_kq);
1531 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1532 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1534 mtx_lock(knl->kl_lock);
1535 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1537 mtx_unlock(knl->kl_lock);
1539 kn->kn_knlist = knl;
1540 kn->kn_status &= ~KN_DETACHED;
1541 KQ_UNLOCK(kn->kn_kq);
1545 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1547 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1548 mtx_assert(knl->kl_lock, knlislocked ? MA_OWNED : MA_NOTOWNED);
1549 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1551 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1552 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1554 mtx_lock(knl->kl_lock);
1555 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1556 kn->kn_knlist = NULL;
1558 mtx_unlock(knl->kl_lock);
1561 kn->kn_status |= KN_DETACHED;
1563 KQ_UNLOCK(kn->kn_kq);
1567 * remove all knotes from a specified klist
1570 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1573 knlist_remove_kq(knl, kn, islocked, 0);
1577 * remove knote from a specified klist while in f_event handler.
1580 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1583 knlist_remove_kq(knl, kn, 1,
1584 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1588 knlist_empty(struct knlist *knl)
1591 mtx_assert(knl->kl_lock, MA_OWNED);
1592 return SLIST_EMPTY(&knl->kl_list);
1595 static struct mtx knlist_lock;
1596 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1600 knlist_init(struct knlist *knl, struct mtx *mtx)
1604 knl->kl_lock = &knlist_lock;
1608 SLIST_INIT(&knl->kl_list);
1612 knlist_destroy(struct knlist *knl)
1617 * if we run across this error, we need to find the offending
1618 * driver and have it call knlist_clear.
1620 if (!SLIST_EMPTY(&knl->kl_list))
1621 printf("WARNING: destroying knlist w/ knotes on it!\n");
1624 knl->kl_lock = NULL;
1625 SLIST_INIT(&knl->kl_list);
1629 * Even if we are locked, we may need to drop the lock to allow any influx
1630 * knotes time to "settle".
1633 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
1639 mtx_assert(knl->kl_lock, MA_OWNED);
1641 mtx_assert(knl->kl_lock, MA_NOTOWNED);
1642 again: /* need to reaquire lock since we have dropped it */
1643 mtx_lock(knl->kl_lock);
1646 SLIST_FOREACH(kn, &knl->kl_list, kn_selnext) {
1649 if ((kn->kn_status & KN_INFLUX)) {
1653 knlist_remove_kq(knl, kn, 1, 1);
1655 kn->kn_status |= KN_INFLUX | KN_DETACHED;
1659 /* Make sure cleared knotes disappear soon */
1660 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
1666 if (!SLIST_EMPTY(&knl->kl_list)) {
1667 /* there are still KN_INFLUX remaining */
1668 kn = SLIST_FIRST(&knl->kl_list);
1671 KASSERT(kn->kn_status & KN_INFLUX,
1672 ("knote removed w/o list lock"));
1673 mtx_unlock(knl->kl_lock);
1674 kq->kq_state |= KQ_FLUXWAIT;
1675 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
1681 mtx_assert(knl->kl_lock, MA_OWNED);
1683 mtx_unlock(knl->kl_lock);
1684 mtx_assert(knl->kl_lock, MA_NOTOWNED);
1689 * remove all knotes referencing a specified fd
1690 * must be called with FILEDESC lock. This prevents a race where a new fd
1691 * comes along and occupies the entry and we attach a knote to the fd.
1694 knote_fdclose(struct thread *td, int fd)
1696 struct filedesc *fdp = td->td_proc->p_fd;
1701 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1704 * We shouldn't have to worry about new kevents appearing on fd
1705 * since filedesc is locked.
1707 SLIST_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
1712 while (kq->kq_knlistsize > fd &&
1713 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
1714 if (kn->kn_status & KN_INFLUX) {
1715 /* someone else might be waiting on our knote */
1718 kq->kq_state |= KQ_FLUXWAIT;
1719 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
1722 kn->kn_status |= KN_INFLUX;
1724 if (!(kn->kn_status & KN_DETACHED))
1725 kn->kn_fop->f_detach(kn);
1735 knote_attach(struct knote *kn, struct kqueue *kq)
1739 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
1742 if (kn->kn_fop->f_isfd) {
1743 if (kn->kn_id >= kq->kq_knlistsize)
1745 list = &kq->kq_knlist[kn->kn_id];
1747 if (kq->kq_knhash == NULL)
1749 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1752 SLIST_INSERT_HEAD(list, kn, kn_link);
1758 * knote must already have been detatched using the f_detach method.
1759 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
1760 * to prevent other removal.
1763 knote_drop(struct knote *kn, struct thread *td)
1771 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
1772 ("knote_drop called without KN_INFLUX set in kn_status"));
1775 if (kn->kn_fop->f_isfd)
1776 list = &kq->kq_knlist[kn->kn_id];
1778 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1780 SLIST_REMOVE(list, kn, knote, kn_link);
1781 if (kn->kn_status & KN_QUEUED)
1785 if (kn->kn_fop->f_isfd) {
1786 fdrop(kn->kn_fp, td);
1789 kqueue_fo_release(kn->kn_kevent.filter);
1795 knote_enqueue(struct knote *kn)
1797 struct kqueue *kq = kn->kn_kq;
1799 KQ_OWNED(kn->kn_kq);
1800 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1802 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1803 kn->kn_status |= KN_QUEUED;
1809 knote_dequeue(struct knote *kn)
1811 struct kqueue *kq = kn->kn_kq;
1813 KQ_OWNED(kn->kn_kq);
1814 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1816 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1817 kn->kn_status &= ~KN_QUEUED;
1825 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
1826 NULL, NULL, UMA_ALIGN_PTR, 0);
1828 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1830 static struct knote *
1831 knote_alloc(int waitok)
1833 return ((struct knote *)uma_zalloc(knote_zone,
1834 (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
1838 knote_free(struct knote *kn)
1841 uma_zfree(knote_zone, kn);