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(void *arg, struct kevent *kevp, int count);
85 static int kevent_copyin(void *arg, 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_copyops *k_ops,
93 const struct timespec *timeout,
94 struct kevent *keva, struct thread *td);
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;
539 struct kevent_copyops k_ops = { uap,
544 if (uap->timeout != NULL) {
545 error = copyin(uap->timeout, &ts, sizeof(ts));
552 return (kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
557 * Copy 'count' items into the destination list pointed to by uap->eventlist.
560 kevent_copyout(void *arg, struct kevent *kevp, int count)
562 struct kevent_args *uap;
565 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
566 uap = (struct kevent_args *)arg;
568 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
570 uap->eventlist += count;
575 * Copy 'count' items from the list pointed to by uap->changelist.
578 kevent_copyin(void *arg, struct kevent *kevp, int count)
580 struct kevent_args *uap;
583 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
584 uap = (struct kevent_args *)arg;
586 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
588 uap->changelist += count;
593 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
594 struct kevent_copyops *k_ops, const struct timespec *timeout)
596 struct kevent keva[KQ_NEVENTS];
597 struct kevent *kevp, *changes;
600 int i, n, nerrors, error;
602 if ((error = fget(td, fd, &fp)) != 0)
604 if ((error = kqueue_aquire(fp, &kq)) != 0)
609 while (nchanges > 0) {
610 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
611 error = k_ops->k_copyin(k_ops->arg, keva, n);
615 for (i = 0; i < n; i++) {
617 kevp->flags &= ~EV_SYSFLAGS;
618 error = kqueue_register(kq, kevp, td, 1);
621 kevp->flags = EV_ERROR;
623 (void) k_ops->k_copyout(k_ops->arg,
635 td->td_retval[0] = nerrors;
640 error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
642 kqueue_release(kq, 0);
650 kqueue_add_filteropts(int filt, struct filterops *filtops)
654 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
656 "trying to add a filterop that is out of range: %d is beyond %d\n",
657 ~filt, EVFILT_SYSCOUNT);
660 mtx_lock(&filterops_lock);
661 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
662 sysfilt_ops[~filt].for_fop != NULL)
665 sysfilt_ops[~filt].for_fop = filtops;
666 sysfilt_ops[~filt].for_refcnt = 0;
668 mtx_unlock(&filterops_lock);
674 kqueue_del_filteropts(int filt)
679 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
682 mtx_lock(&filterops_lock);
683 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
684 sysfilt_ops[~filt].for_fop == NULL)
686 else if (sysfilt_ops[~filt].for_refcnt != 0)
689 sysfilt_ops[~filt].for_fop = &null_filtops;
690 sysfilt_ops[~filt].for_refcnt = 0;
692 mtx_unlock(&filterops_lock);
697 static struct filterops *
698 kqueue_fo_find(int filt)
701 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
704 mtx_lock(&filterops_lock);
705 sysfilt_ops[~filt].for_refcnt++;
706 if (sysfilt_ops[~filt].for_fop == NULL)
707 sysfilt_ops[~filt].for_fop = &null_filtops;
708 mtx_unlock(&filterops_lock);
710 return sysfilt_ops[~filt].for_fop;
714 kqueue_fo_release(int filt)
717 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
720 mtx_lock(&filterops_lock);
721 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
722 ("filter object refcount not valid on release"));
723 sysfilt_ops[~filt].for_refcnt--;
724 mtx_unlock(&filterops_lock);
728 * A ref to kq (obtained via kqueue_aquire) should be held. waitok will
729 * influence if memory allocation should wait. Make sure it is 0 if you
733 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
735 struct filedesc *fdp;
736 struct filterops *fops;
738 struct knote *kn, *tkn;
739 int error, filt, event;
750 fops = kqueue_fo_find(filt);
754 tkn = knote_alloc(waitok); /* prevent waiting with locks */
758 KASSERT(td != NULL, ("td is NULL"));
759 fdp = td->td_proc->p_fd;
761 /* validate descriptor */
763 if (fd < 0 || fd >= fdp->fd_nfiles ||
764 (fp = fdp->fd_ofiles[fd]) == NULL) {
765 FILEDESC_UNLOCK(fdp);
771 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
772 kev->ident, 0) != 0) {
773 /* unlock and try again */
774 FILEDESC_UNLOCK(fdp);
777 error = kqueue_expand(kq, fops, kev->ident, waitok);
783 if (fp->f_type == DTYPE_KQUEUE) {
785 * if we add some inteligence about what we are doing,
786 * we should be able to support events on ourselves.
787 * We need to know when we are doing this to prevent
788 * getting both the knlist lock and the kq lock since
789 * they are the same thing.
791 if (fp->f_data == kq) {
792 FILEDESC_UNLOCK(fdp);
797 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
800 FILEDESC_UNLOCK(fdp);
802 if (kev->ident < kq->kq_knlistsize) {
803 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
804 if (kev->filter == kn->kn_filter)
808 if ((kev->flags & EV_ADD) == EV_ADD)
809 kqueue_expand(kq, fops, kev->ident, waitok);
812 if (kq->kq_knhashmask != 0) {
815 list = &kq->kq_knhash[
816 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
817 SLIST_FOREACH(kn, list, kn_link)
818 if (kev->ident == kn->kn_id &&
819 kev->filter == kn->kn_filter)
824 /* knote is in the process of changing, wait for it to stablize. */
825 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
830 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
831 kq->kq_state |= KQ_FLUXWAIT;
832 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
836 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
843 * kn now contains the matching knote, or NULL if no match
845 if (kev->flags & EV_ADD) {
857 * apply reference counts to knote structure, and
858 * do not release it at the end of this routine.
863 kn->kn_sfflags = kev->fflags;
864 kn->kn_sdata = kev->data;
867 kn->kn_kevent = *kev;
868 kn->kn_status = KN_INFLUX|KN_DETACHED;
870 error = knote_attach(kn, kq);
877 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
884 * The user may change some filter values after the
885 * initial EV_ADD, but doing so will not reset any
886 * filter which has already been triggered.
888 kn->kn_status |= KN_INFLUX;
891 kn->kn_sfflags = kev->fflags;
892 kn->kn_sdata = kev->data;
893 kn->kn_kevent.udata = kev->udata;
897 * We can get here with kn->kn_knlist == NULL.
898 * This can happen when the initial attach event decides that
899 * the event is "completed" already. i.e. filt_procattach
900 * is called on a zombie process. It will call filt_proc
901 * which will remove it from the list, and NULL kn_knlist.
903 event = kn->kn_fop->f_event(kn, 0);
907 KNOTE_ACTIVATE(kn, 1);
908 kn->kn_status &= ~KN_INFLUX;
909 } else if (kev->flags & EV_DELETE) {
910 kn->kn_status |= KN_INFLUX;
912 if (!(kn->kn_status & KN_DETACHED))
913 kn->kn_fop->f_detach(kn);
918 if ((kev->flags & EV_DISABLE) &&
919 ((kn->kn_status & KN_DISABLED) == 0)) {
920 kn->kn_status |= KN_DISABLED;
923 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
924 kn->kn_status &= ~KN_DISABLED;
925 if ((kn->kn_status & KN_ACTIVE) &&
926 ((kn->kn_status & KN_QUEUED) == 0))
932 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
939 kqueue_fo_release(filt);
944 kqueue_aquire(struct file *fp, struct kqueue **kqp)
954 if (fp->f_type != DTYPE_KQUEUE || kq == NULL) {
960 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
974 kqueue_release(struct kqueue *kq, int locked)
981 if (kq->kq_refcnt == 1)
982 wakeup(&kq->kq_refcnt);
988 kqueue_schedtask(struct kqueue *kq)
992 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
993 ("scheduling kqueue task while draining"));
995 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
996 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
997 kq->kq_state |= KQ_TASKSCHED;
1002 * Expand the kq to make sure we have storage for fops/ident pair.
1004 * Return 0 on success (or no work necessary), return errno on failure.
1006 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1007 * If kqueue_register is called from a non-fd context, there usually/should
1011 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1014 struct klist *list, *tmp_knhash;
1015 u_long tmp_knhashmask;
1018 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1024 if (kq->kq_knlistsize <= fd) {
1025 size = kq->kq_knlistsize;
1028 MALLOC(list, struct klist *,
1029 size * sizeof list, M_KQUEUE, mflag);
1033 if (kq->kq_knlistsize > fd) {
1034 FREE(list, M_KQUEUE);
1037 if (kq->kq_knlist != NULL) {
1038 bcopy(kq->kq_knlist, list,
1039 kq->kq_knlistsize * sizeof list);
1040 FREE(kq->kq_knlist, M_KQUEUE);
1041 kq->kq_knlist = NULL;
1043 bzero((caddr_t)list +
1044 kq->kq_knlistsize * sizeof list,
1045 (size - kq->kq_knlistsize) * sizeof list);
1046 kq->kq_knlistsize = size;
1047 kq->kq_knlist = list;
1052 if (kq->kq_knhashmask == 0) {
1053 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1055 if (tmp_knhash == NULL)
1058 if (kq->kq_knhashmask == 0) {
1059 kq->kq_knhash = tmp_knhash;
1060 kq->kq_knhashmask = tmp_knhashmask;
1062 free(tmp_knhash, M_KQUEUE);
1073 kqueue_task(void *arg, int pending)
1081 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1084 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1086 kq->kq_state &= ~KQ_TASKSCHED;
1087 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1088 wakeup(&kq->kq_state);
1091 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1095 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1096 * We treat KN_MARKER knotes as if they are INFLUX.
1099 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1100 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1102 struct kevent *kevp;
1103 struct timeval atv, rtv, ttv;
1104 struct knote *kn, *marker;
1105 int count, timeout, nkev, error;
1117 TIMESPEC_TO_TIMEVAL(&atv, tsp);
1118 if (itimerfix(&atv)) {
1122 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
1125 timeout = atv.tv_sec > 24 * 60 * 60 ?
1126 24 * 60 * 60 * hz : tvtohz(&atv);
1127 getmicrouptime(&rtv);
1128 timevaladd(&atv, &rtv);
1134 marker = knote_alloc(1);
1135 if (marker == NULL) {
1139 marker->kn_status = KN_MARKER;
1144 if (atv.tv_sec || atv.tv_usec) {
1145 getmicrouptime(&rtv);
1146 if (timevalcmp(&rtv, &atv, >=))
1149 timevalsub(&ttv, &rtv);
1150 timeout = ttv.tv_sec > 24 * 60 * 60 ?
1151 24 * 60 * 60 * hz : tvtohz(&ttv);
1156 if (kq->kq_count == 0) {
1158 error = EWOULDBLOCK;
1160 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1161 kq->kq_state |= KQ_SLEEP;
1162 error = msleep(kq, &kq->kq_lock, PSOCK | PCATCH,
1167 /* don't restart after signals... */
1168 if (error == ERESTART)
1170 else if (error == EWOULDBLOCK)
1175 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1178 kn = TAILQ_FIRST(&kq->kq_head);
1180 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1181 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1182 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1183 kq->kq_state |= KQ_FLUXWAIT;
1184 error = msleep(kq, &kq->kq_lock, PSOCK,
1189 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1190 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1191 kn->kn_status &= ~KN_QUEUED;
1197 if (count == maxevents)
1201 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1202 ("KN_INFLUX set when not suppose to be"));
1204 if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1205 kn->kn_status &= ~KN_QUEUED;
1206 kn->kn_status |= KN_INFLUX;
1210 * We don't need to lock the list since we've marked
1213 *kevp = kn->kn_kevent;
1214 if (!(kn->kn_status & KN_DETACHED))
1215 kn->kn_fop->f_detach(kn);
1220 kn->kn_status |= KN_INFLUX;
1222 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1223 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1225 if (kn->kn_fop->f_event(kn, 0) == 0) {
1229 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX);
1233 *kevp = kn->kn_kevent;
1235 if (kn->kn_flags & EV_CLEAR) {
1238 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1241 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1243 kn->kn_status &= ~(KN_INFLUX);
1246 /* we are returning a copy to the user */
1251 if (nkev == KQ_NEVENTS) {
1253 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1261 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1265 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1270 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1271 td->td_retval[0] = maxevents - count;
1277 * This could be expanded to call kqueue_scan, if desired.
1281 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1282 int flags, struct thread *td)
1289 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1290 int flags, struct thread *td)
1297 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1298 struct ucred *active_cred, struct thread *td)
1301 * Enabling sigio causes two major problems:
1302 * 1) infinite recursion:
1303 * Synopsys: kevent is being used to track signals and have FIOASYNC
1304 * set. On receipt of a signal this will cause a kqueue to recurse
1305 * into itself over and over. Sending the sigio causes the kqueue
1306 * to become ready, which in turn posts sigio again, forever.
1307 * Solution: this can be solved by setting a flag in the kqueue that
1308 * we have a SIGIO in progress.
1309 * 2) locking problems:
1310 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1311 * us above the proc and pgrp locks.
1312 * Solution: Post a signal using an async mechanism, being sure to
1313 * record a generation count in the delivery so that we do not deliver
1314 * a signal to the wrong process.
1316 * Note, these two mechanisms are somewhat mutually exclusive!
1325 kq->kq_state |= KQ_ASYNC;
1327 kq->kq_state &= ~KQ_ASYNC;
1332 return (fsetown(*(int *)data, &kq->kq_sigio));
1335 *(int *)data = fgetown(&kq->kq_sigio);
1345 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1352 if ((error = kqueue_aquire(fp, &kq)))
1356 if (events & (POLLIN | POLLRDNORM)) {
1358 revents |= events & (POLLIN | POLLRDNORM);
1360 selrecord(td, &kq->kq_sel);
1361 kq->kq_state |= KQ_SEL;
1364 kqueue_release(kq, 1);
1371 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1375 bzero((void *)st, sizeof *st);
1377 * We no longer return kq_count because the unlocked value is useless.
1378 * If you spent all this time getting the count, why not spend your
1379 * syscall better by calling kevent?
1381 * XXX - This is needed for libc_r.
1383 st->st_mode = S_IFIFO;
1389 kqueue_close(struct file *fp, struct thread *td)
1391 struct kqueue *kq = fp->f_data;
1392 struct filedesc *fdp;
1397 if ((error = kqueue_aquire(fp, &kq)))
1402 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1403 ("kqueue already closing"));
1404 kq->kq_state |= KQ_CLOSING;
1405 if (kq->kq_refcnt > 1)
1406 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1408 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1411 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1412 ("kqueue's knlist not empty"));
1414 for (i = 0; i < kq->kq_knlistsize; i++) {
1415 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1416 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1417 ("KN_INFLUX set when not suppose to be"));
1418 kn->kn_status |= KN_INFLUX;
1420 if (!(kn->kn_status & KN_DETACHED))
1421 kn->kn_fop->f_detach(kn);
1426 if (kq->kq_knhashmask != 0) {
1427 for (i = 0; i <= kq->kq_knhashmask; i++) {
1428 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1429 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1430 ("KN_INFLUX set when not suppose to be"));
1431 kn->kn_status |= KN_INFLUX;
1433 if (!(kn->kn_status & KN_DETACHED))
1434 kn->kn_fop->f_detach(kn);
1441 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1442 kq->kq_state |= KQ_TASKDRAIN;
1443 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1446 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1447 kq->kq_state &= ~KQ_SEL;
1448 selwakeuppri(&kq->kq_sel, PSOCK);
1453 FILEDESC_LOCK_FAST(fdp);
1454 SLIST_REMOVE(&fdp->fd_kqlist, kq, kqueue, kq_list);
1455 FILEDESC_UNLOCK_FAST(fdp);
1457 knlist_destroy(&kq->kq_sel.si_note);
1458 mtx_destroy(&kq->kq_lock);
1461 if (kq->kq_knhash != NULL)
1462 free(kq->kq_knhash, M_KQUEUE);
1463 if (kq->kq_knlist != NULL)
1464 free(kq->kq_knlist, M_KQUEUE);
1466 funsetown(&kq->kq_sigio);
1474 kqueue_wakeup(struct kqueue *kq)
1478 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1479 kq->kq_state &= ~KQ_SLEEP;
1482 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1483 kq->kq_state &= ~KQ_SEL;
1484 selwakeuppri(&kq->kq_sel, PSOCK);
1486 if (!knlist_empty(&kq->kq_sel.si_note))
1487 kqueue_schedtask(kq);
1488 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1489 pgsigio(&kq->kq_sigio, SIGIO, 0);
1494 * Walk down a list of knotes, activating them if their event has triggered.
1496 * There is a possibility to optimize in the case of one kq watching another.
1497 * Instead of scheduling a task to wake it up, you could pass enough state
1498 * down the chain to make up the parent kqueue. Make this code functional
1502 knote(struct knlist *list, long hint, int islocked)
1510 mtx_assert(list->kl_lock, islocked ? MA_OWNED : MA_NOTOWNED);
1512 mtx_lock(list->kl_lock);
1514 * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1515 * the kqueue scheduling, but this will introduce four
1516 * lock/unlock's for each knote to test. If we do, continue to use
1517 * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1518 * only safe if you want to remove the current item, which we are
1521 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1523 if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1525 if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1526 kn->kn_status |= KN_HASKQLOCK;
1527 if (kn->kn_fop->f_event(kn, hint))
1528 KNOTE_ACTIVATE(kn, 1);
1529 kn->kn_status &= ~KN_HASKQLOCK;
1536 mtx_unlock(list->kl_lock);
1540 * add a knote to a knlist
1543 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1545 mtx_assert(knl->kl_lock, islocked ? MA_OWNED : MA_NOTOWNED);
1546 KQ_NOTOWNED(kn->kn_kq);
1547 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1548 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1550 mtx_lock(knl->kl_lock);
1551 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1553 mtx_unlock(knl->kl_lock);
1555 kn->kn_knlist = knl;
1556 kn->kn_status &= ~KN_DETACHED;
1557 KQ_UNLOCK(kn->kn_kq);
1561 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1563 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1564 mtx_assert(knl->kl_lock, knlislocked ? MA_OWNED : MA_NOTOWNED);
1565 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1567 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1568 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1570 mtx_lock(knl->kl_lock);
1571 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1572 kn->kn_knlist = NULL;
1574 mtx_unlock(knl->kl_lock);
1577 kn->kn_status |= KN_DETACHED;
1579 KQ_UNLOCK(kn->kn_kq);
1583 * remove all knotes from a specified klist
1586 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1589 knlist_remove_kq(knl, kn, islocked, 0);
1593 * remove knote from a specified klist while in f_event handler.
1596 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1599 knlist_remove_kq(knl, kn, 1,
1600 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1604 knlist_empty(struct knlist *knl)
1607 mtx_assert(knl->kl_lock, MA_OWNED);
1608 return SLIST_EMPTY(&knl->kl_list);
1611 static struct mtx knlist_lock;
1612 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1616 knlist_init(struct knlist *knl, struct mtx *mtx)
1620 knl->kl_lock = &knlist_lock;
1624 SLIST_INIT(&knl->kl_list);
1628 knlist_destroy(struct knlist *knl)
1633 * if we run across this error, we need to find the offending
1634 * driver and have it call knlist_clear.
1636 if (!SLIST_EMPTY(&knl->kl_list))
1637 printf("WARNING: destroying knlist w/ knotes on it!\n");
1640 knl->kl_lock = NULL;
1641 SLIST_INIT(&knl->kl_list);
1645 * Even if we are locked, we may need to drop the lock to allow any influx
1646 * knotes time to "settle".
1649 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
1655 mtx_assert(knl->kl_lock, MA_OWNED);
1657 mtx_assert(knl->kl_lock, MA_NOTOWNED);
1658 again: /* need to reaquire lock since we have dropped it */
1659 mtx_lock(knl->kl_lock);
1662 SLIST_FOREACH(kn, &knl->kl_list, kn_selnext) {
1665 if ((kn->kn_status & KN_INFLUX)) {
1669 knlist_remove_kq(knl, kn, 1, 1);
1671 kn->kn_status |= KN_INFLUX | KN_DETACHED;
1675 /* Make sure cleared knotes disappear soon */
1676 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
1682 if (!SLIST_EMPTY(&knl->kl_list)) {
1683 /* there are still KN_INFLUX remaining */
1684 kn = SLIST_FIRST(&knl->kl_list);
1687 KASSERT(kn->kn_status & KN_INFLUX,
1688 ("knote removed w/o list lock"));
1689 mtx_unlock(knl->kl_lock);
1690 kq->kq_state |= KQ_FLUXWAIT;
1691 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
1697 mtx_assert(knl->kl_lock, MA_OWNED);
1699 mtx_unlock(knl->kl_lock);
1700 mtx_assert(knl->kl_lock, MA_NOTOWNED);
1705 * remove all knotes referencing a specified fd
1706 * must be called with FILEDESC lock. This prevents a race where a new fd
1707 * comes along and occupies the entry and we attach a knote to the fd.
1710 knote_fdclose(struct thread *td, int fd)
1712 struct filedesc *fdp = td->td_proc->p_fd;
1717 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1720 * We shouldn't have to worry about new kevents appearing on fd
1721 * since filedesc is locked.
1723 SLIST_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
1728 while (kq->kq_knlistsize > fd &&
1729 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
1730 if (kn->kn_status & KN_INFLUX) {
1731 /* someone else might be waiting on our knote */
1734 kq->kq_state |= KQ_FLUXWAIT;
1735 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
1738 kn->kn_status |= KN_INFLUX;
1740 if (!(kn->kn_status & KN_DETACHED))
1741 kn->kn_fop->f_detach(kn);
1751 knote_attach(struct knote *kn, struct kqueue *kq)
1755 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
1758 if (kn->kn_fop->f_isfd) {
1759 if (kn->kn_id >= kq->kq_knlistsize)
1761 list = &kq->kq_knlist[kn->kn_id];
1763 if (kq->kq_knhash == NULL)
1765 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1768 SLIST_INSERT_HEAD(list, kn, kn_link);
1774 * knote must already have been detatched using the f_detach method.
1775 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
1776 * to prevent other removal.
1779 knote_drop(struct knote *kn, struct thread *td)
1787 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
1788 ("knote_drop called without KN_INFLUX set in kn_status"));
1791 if (kn->kn_fop->f_isfd)
1792 list = &kq->kq_knlist[kn->kn_id];
1794 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1796 SLIST_REMOVE(list, kn, knote, kn_link);
1797 if (kn->kn_status & KN_QUEUED)
1801 if (kn->kn_fop->f_isfd) {
1802 fdrop(kn->kn_fp, td);
1805 kqueue_fo_release(kn->kn_kevent.filter);
1811 knote_enqueue(struct knote *kn)
1813 struct kqueue *kq = kn->kn_kq;
1815 KQ_OWNED(kn->kn_kq);
1816 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1818 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1819 kn->kn_status |= KN_QUEUED;
1825 knote_dequeue(struct knote *kn)
1827 struct kqueue *kq = kn->kn_kq;
1829 KQ_OWNED(kn->kn_kq);
1830 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1832 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1833 kn->kn_status &= ~KN_QUEUED;
1841 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
1842 NULL, NULL, UMA_ALIGN_PTR, 0);
1844 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1846 static struct knote *
1847 knote_alloc(int waitok)
1849 return ((struct knote *)uma_zalloc(knote_zone,
1850 (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
1854 knote_free(struct knote *kn)
1857 uma_zfree(knote_zone, kn);