2 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * $FreeBSD: src/sys/kern/kern_event.c,v 1.2.2.10 2004/04/04 07:03:14 cperciva Exp $
27 * $DragonFly: src/sys/kern/kern_event.c,v 1.33 2007/02/03 17:05:57 corecode Exp $
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
34 #include <sys/malloc.h>
35 #include <sys/unistd.h>
38 #include <sys/fcntl.h>
39 #include <sys/queue.h>
40 #include <sys/event.h>
41 #include <sys/eventvar.h>
42 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #include <sys/socketvar.h>
46 #include <sys/sysctl.h>
47 #include <sys/sysproto.h>
48 #include <sys/thread.h>
50 #include <sys/signalvar.h>
51 #include <sys/filio.h>
54 #include <sys/thread2.h>
55 #include <sys/file2.h>
56 #include <sys/mplock2.h>
58 #include <vm/vm_zone.h>
61 * Global token for kqueue subsystem
63 struct lwkt_token kq_token = LWKT_TOKEN_UP_INITIALIZER(kq_token);
65 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
67 struct kevent_copyin_args {
68 struct kevent_args *ka;
72 static int kqueue_sleep(struct kqueue *kq, struct timespec *tsp);
73 static int kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
74 struct knote *marker);
75 static int kqueue_read(struct file *fp, struct uio *uio,
76 struct ucred *cred, int flags);
77 static int kqueue_write(struct file *fp, struct uio *uio,
78 struct ucred *cred, int flags);
79 static int kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
80 struct ucred *cred, struct sysmsg *msg);
81 static int kqueue_kqfilter(struct file *fp, struct knote *kn);
82 static int kqueue_stat(struct file *fp, struct stat *st,
84 static int kqueue_close(struct file *fp);
85 static void kqueue_wakeup(struct kqueue *kq);
86 static int filter_attach(struct knote *kn);
87 static int filter_event(struct knote *kn, long hint);
92 static struct fileops kqueueops = {
93 .fo_read = kqueue_read,
94 .fo_write = kqueue_write,
95 .fo_ioctl = kqueue_ioctl,
96 .fo_kqfilter = kqueue_kqfilter,
97 .fo_stat = kqueue_stat,
98 .fo_close = kqueue_close,
99 .fo_shutdown = nofo_shutdown
102 static void knote_attach(struct knote *kn);
103 static void knote_drop(struct knote *kn);
104 static void knote_detach_and_drop(struct knote *kn);
105 static void knote_enqueue(struct knote *kn);
106 static void knote_dequeue(struct knote *kn);
107 static void knote_init(void);
108 static struct knote *knote_alloc(void);
109 static void knote_free(struct knote *kn);
111 static void filt_kqdetach(struct knote *kn);
112 static int filt_kqueue(struct knote *kn, long hint);
113 static int filt_procattach(struct knote *kn);
114 static void filt_procdetach(struct knote *kn);
115 static int filt_proc(struct knote *kn, long hint);
116 static int filt_fileattach(struct knote *kn);
117 static void filt_timerexpire(void *knx);
118 static int filt_timerattach(struct knote *kn);
119 static void filt_timerdetach(struct knote *kn);
120 static int filt_timer(struct knote *kn, long hint);
122 static struct filterops file_filtops =
123 { FILTEROP_ISFD, filt_fileattach, NULL, NULL };
124 static struct filterops kqread_filtops =
125 { FILTEROP_ISFD, NULL, filt_kqdetach, filt_kqueue };
126 static struct filterops proc_filtops =
127 { 0, filt_procattach, filt_procdetach, filt_proc };
128 static struct filterops timer_filtops =
129 { 0, filt_timerattach, filt_timerdetach, filt_timer };
131 static vm_zone_t knote_zone;
132 static int kq_ncallouts = 0;
133 static int kq_calloutmax = (4 * 1024);
134 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
135 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
136 static int kq_checkloop = 1000000;
137 SYSCTL_INT(_kern, OID_AUTO, kq_checkloop, CTLFLAG_RW,
138 &kq_checkloop, 0, "Maximum number of callouts allocated for kqueue");
140 #define KNOTE_ACTIVATE(kn) do { \
141 kn->kn_status |= KN_ACTIVE; \
142 if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
146 #define KN_HASHSIZE 64 /* XXX should be tunable */
147 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
149 extern struct filterops aio_filtops;
150 extern struct filterops sig_filtops;
153 * Table for for all system-defined filters.
155 static struct filterops *sysfilt_ops[] = {
156 &file_filtops, /* EVFILT_READ */
157 &file_filtops, /* EVFILT_WRITE */
158 &aio_filtops, /* EVFILT_AIO */
159 &file_filtops, /* EVFILT_VNODE */
160 &proc_filtops, /* EVFILT_PROC */
161 &sig_filtops, /* EVFILT_SIGNAL */
162 &timer_filtops, /* EVFILT_TIMER */
163 &file_filtops, /* EVFILT_EXCEPT */
167 filt_fileattach(struct knote *kn)
169 return (fo_kqfilter(kn->kn_fp, kn));
176 kqueue_kqfilter(struct file *fp, struct knote *kn)
178 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
180 if (kn->kn_filter != EVFILT_READ)
183 kn->kn_fop = &kqread_filtops;
184 knote_insert(&kq->kq_kqinfo.ki_note, kn);
189 filt_kqdetach(struct knote *kn)
191 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
193 knote_remove(&kq->kq_kqinfo.ki_note, kn);
198 filt_kqueue(struct knote *kn, long hint)
200 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
202 kn->kn_data = kq->kq_count;
203 return (kn->kn_data > 0);
207 filt_procattach(struct knote *kn)
213 lwkt_gettoken(&proc_token);
214 p = pfind(kn->kn_id);
215 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
216 p = zpfind(kn->kn_id);
220 lwkt_reltoken(&proc_token);
223 if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
224 lwkt_reltoken(&proc_token);
228 kn->kn_ptr.p_proc = p;
229 kn->kn_flags |= EV_CLEAR; /* automatically set */
232 * internal flag indicating registration done by kernel
234 if (kn->kn_flags & EV_FLAG1) {
235 kn->kn_data = kn->kn_sdata; /* ppid */
236 kn->kn_fflags = NOTE_CHILD;
237 kn->kn_flags &= ~EV_FLAG1;
240 knote_insert(&p->p_klist, kn);
243 * Immediately activate any exit notes if the target process is a
244 * zombie. This is necessary to handle the case where the target
245 * process, e.g. a child, dies before the kevent is negistered.
247 if (immediate && filt_proc(kn, NOTE_EXIT))
249 lwkt_reltoken(&proc_token);
255 * The knote may be attached to a different process, which may exit,
256 * leaving nothing for the knote to be attached to. So when the process
257 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
258 * it will be deleted when read out. However, as part of the knote deletion,
259 * this routine is called, so a check is needed to avoid actually performing
260 * a detach, because the original process does not exist any more.
263 filt_procdetach(struct knote *kn)
267 if (kn->kn_status & KN_DETACHED)
269 /* XXX locking? take proc_token here? */
270 p = kn->kn_ptr.p_proc;
271 knote_remove(&p->p_klist, kn);
275 filt_proc(struct knote *kn, long hint)
280 * mask off extra data
282 event = (u_int)hint & NOTE_PCTRLMASK;
285 * if the user is interested in this event, record it.
287 if (kn->kn_sfflags & event)
288 kn->kn_fflags |= event;
291 * Process is gone, so flag the event as finished. Detach the
292 * knote from the process now because the process will be poof,
295 if (event == NOTE_EXIT) {
296 struct proc *p = kn->kn_ptr.p_proc;
297 if ((kn->kn_status & KN_DETACHED) == 0) {
298 knote_remove(&p->p_klist, kn);
299 kn->kn_status |= KN_DETACHED;
300 kn->kn_data = p->p_xstat;
301 kn->kn_ptr.p_proc = NULL;
303 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
308 * process forked, and user wants to track the new process,
309 * so attach a new knote to it, and immediately report an
310 * event with the parent's pid.
312 if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
317 * register knote with new process.
319 kev.ident = hint & NOTE_PDATAMASK; /* pid */
320 kev.filter = kn->kn_filter;
321 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
322 kev.fflags = kn->kn_sfflags;
323 kev.data = kn->kn_id; /* parent */
324 kev.udata = kn->kn_kevent.udata; /* preserve udata */
325 error = kqueue_register(kn->kn_kq, &kev);
327 kn->kn_fflags |= NOTE_TRACKERR;
330 return (kn->kn_fflags != 0);
334 filt_timerexpire(void *knx)
336 struct knote *kn = knx;
337 struct callout *calloutp;
341 lwkt_gettoken(&kq_token);
346 if ((kn->kn_flags & EV_ONESHOT) == 0) {
347 tv.tv_sec = kn->kn_sdata / 1000;
348 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
349 tticks = tvtohz_high(&tv);
350 calloutp = (struct callout *)kn->kn_hook;
351 callout_reset(calloutp, tticks, filt_timerexpire, kn);
354 lwkt_reltoken(&kq_token);
358 * data contains amount of time to sleep, in milliseconds
361 filt_timerattach(struct knote *kn)
363 struct callout *calloutp;
367 if (kq_ncallouts >= kq_calloutmax)
371 tv.tv_sec = kn->kn_sdata / 1000;
372 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
373 tticks = tvtohz_high(&tv);
375 kn->kn_flags |= EV_CLEAR; /* automatically set */
376 MALLOC(calloutp, struct callout *, sizeof(*calloutp),
378 callout_init(calloutp);
379 kn->kn_hook = (caddr_t)calloutp;
380 callout_reset(calloutp, tticks, filt_timerexpire, kn);
386 filt_timerdetach(struct knote *kn)
388 struct callout *calloutp;
390 calloutp = (struct callout *)kn->kn_hook;
391 callout_stop(calloutp);
392 FREE(calloutp, M_KQUEUE);
397 filt_timer(struct knote *kn, long hint)
400 return (kn->kn_data != 0);
404 * Initialize a kqueue.
406 * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
411 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
413 TAILQ_INIT(&kq->kq_knpend);
414 TAILQ_INIT(&kq->kq_knlist);
417 SLIST_INIT(&kq->kq_kqinfo.ki_note);
421 * Terminate a kqueue. Freeing the actual kq itself is left up to the
422 * caller (it might be embedded in a lwp so we don't do it here).
425 kqueue_terminate(struct kqueue *kq)
429 lwkt_gettoken(&kq_token);
430 while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL)
431 knote_detach_and_drop(kn);
434 kfree(kq->kq_knhash, M_KQUEUE);
435 kq->kq_knhash = NULL;
436 kq->kq_knhashmask = 0;
438 lwkt_reltoken(&kq_token);
445 sys_kqueue(struct kqueue_args *uap)
447 struct thread *td = curthread;
452 error = falloc(td->td_lwp, &fp, &fd);
455 fp->f_flag = FREAD | FWRITE;
456 fp->f_type = DTYPE_KQUEUE;
457 fp->f_ops = &kqueueops;
459 kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
460 kqueue_init(kq, td->td_proc->p_fd);
463 fsetfd(kq->kq_fdp, fp, fd);
464 uap->sysmsg_result = fd;
470 * Copy 'count' items into the destination list pointed to by uap->eventlist.
473 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
475 struct kevent_copyin_args *kap;
478 kap = (struct kevent_copyin_args *)arg;
480 error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
482 kap->ka->eventlist += count;
492 * Copy at most 'max' items from the list pointed to by kap->changelist,
493 * return number of items in 'events'.
496 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
498 struct kevent_copyin_args *kap;
501 kap = (struct kevent_copyin_args *)arg;
503 count = min(kap->ka->nchanges - kap->pchanges, max);
504 error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
506 kap->ka->changelist += count;
507 kap->pchanges += count;
518 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
519 k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
520 struct timespec *tsp_in)
523 struct timespec *tsp;
524 int i, n, total, error, nerrors = 0;
526 int limit = kq_checkloop;
527 struct kevent kev[KQ_NEVENTS];
533 lwkt_gettoken(&kq_token);
536 error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
541 for (i = 0; i < n; i++) {
543 kevp->flags &= ~EV_SYSFLAGS;
544 error = kqueue_register(kq, kevp);
547 * If a registration returns an error we
548 * immediately post the error. The kevent()
549 * call itself will fail with the error if
550 * no space is available for posting.
552 * Such errors normally bypass the timeout/blocking
553 * code. However, if the copyoutfn function refuses
554 * to post the error (see sys_poll()), then we
558 kevp->flags = EV_ERROR;
561 kevent_copyoutfn(uap, kevp, 1, res);
575 * Acquire/wait for events - setup timeout
580 if (tsp->tv_sec || tsp->tv_nsec) {
582 timespecadd(tsp, &ats); /* tsp = target time */
589 * Collect as many events as we can. Sleeping on successive
590 * loops is disabled if copyoutfn has incremented (*res).
592 * The loop stops if an error occurs, all events have been
593 * scanned (the marker has been reached), or fewer than the
594 * maximum number of events is found.
596 * The copyoutfn function does not have to increment (*res) in
597 * order for the loop to continue.
599 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
603 marker.kn_filter = EVFILT_MARKER;
604 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
605 while ((n = nevents - total) > 0) {
610 * If no events are pending sleep until timeout (if any)
611 * or an event occurs.
613 * After the sleep completes the marker is moved to the
614 * end of the list, making any received events available
617 if (kq->kq_count == 0 && *res == 0) {
618 error = kqueue_sleep(kq, tsp);
622 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
623 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
627 * Process all received events
628 * Account for all non-spurious events in our total
630 i = kqueue_scan(kq, kev, n, &marker);
633 error = kevent_copyoutfn(uap, kev, i, res);
634 total += *res - lres;
638 if (limit && --limit == 0)
639 panic("kqueue: checkloop failed i=%d", i);
642 * Normally when fewer events are returned than requested
643 * we can stop. However, if only spurious events were
644 * collected the copyout will not bump (*res) and we have
651 * Deal with an edge case where spurious events can cause
652 * a loop to occur without moving the marker. This can
653 * prevent kqueue_scan() from picking up new events which
654 * race us. We must be sure to move the marker for this
657 * NOTE: We do not want to move the marker if events
658 * were scanned because normal kqueue operations
659 * may reactivate events. Moving the marker in
660 * that case could result in duplicates for the
664 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
665 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
668 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
670 /* Timeouts do not return EWOULDBLOCK. */
671 if (error == EWOULDBLOCK)
675 lwkt_reltoken(&kq_token);
683 sys_kevent(struct kevent_args *uap)
685 struct thread *td = curthread;
686 struct proc *p = td->td_proc;
687 struct timespec ts, *tsp;
689 struct file *fp = NULL;
690 struct kevent_copyin_args *kap, ka;
694 error = copyin(uap->timeout, &ts, sizeof(ts));
702 fp = holdfp(p->p_fd, uap->fd, -1);
705 if (fp->f_type != DTYPE_KQUEUE) {
710 kq = (struct kqueue *)fp->f_data;
716 error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
717 kevent_copyin, kevent_copyout, tsp);
725 kqueue_register(struct kqueue *kq, struct kevent *kev)
727 struct filedesc *fdp = kq->kq_fdp;
728 struct filterops *fops;
729 struct file *fp = NULL;
730 struct knote *kn = NULL;
733 if (kev->filter < 0) {
734 if (kev->filter + EVFILT_SYSCOUNT < 0)
736 fops = sysfilt_ops[~kev->filter]; /* to 0-base index */
740 * filter attach routine is responsible for insuring that
741 * the identifier can be attached to it.
743 kprintf("unknown filter: %d\n", kev->filter);
747 lwkt_gettoken(&kq_token);
748 if (fops->f_flags & FILTEROP_ISFD) {
749 /* validate descriptor */
750 fp = holdfp(fdp, kev->ident, -1);
752 lwkt_reltoken(&kq_token);
756 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
757 if (kn->kn_kq == kq &&
758 kn->kn_filter == kev->filter &&
759 kn->kn_id == kev->ident) {
764 if (kq->kq_knhashmask) {
767 list = &kq->kq_knhash[
768 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
769 SLIST_FOREACH(kn, list, kn_link) {
770 if (kn->kn_id == kev->ident &&
771 kn->kn_filter == kev->filter)
777 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
783 * kn now contains the matching knote, or NULL if no match
785 if (kev->flags & EV_ADD) {
797 * apply reference count to knote structure, and
798 * do not release it at the end of this routine.
802 kn->kn_sfflags = kev->fflags;
803 kn->kn_sdata = kev->data;
806 kn->kn_kevent = *kev;
809 * Interlock against creation/deletion races due
810 * to f_attach() blocking. knote_attach() will set
814 if ((error = filter_attach(kn)) != 0) {
815 kn->kn_status |= KN_DELETING;
819 kn->kn_status &= ~KN_CREATING;
822 * Interlock against close races which remove our
823 * knotes. We do not want to end up with a knote
824 * on a closed descriptor.
826 if ((fops->f_flags & FILTEROP_ISFD) &&
827 (error = checkfdclosed(fdp, kev->ident, kn->kn_fp)) != 0) {
828 knote_detach_and_drop(kn);
833 * The user may change some filter values after the
834 * initial EV_ADD, but doing so will not reset any
835 * filter which have already been triggered.
837 kn->kn_sfflags = kev->fflags;
838 kn->kn_sdata = kev->data;
839 kn->kn_kevent.udata = kev->udata;
842 if (filter_event(kn, 0))
844 } else if (kev->flags & EV_DELETE) {
845 knote_detach_and_drop(kn);
849 if ((kev->flags & EV_DISABLE) &&
850 ((kn->kn_status & KN_DISABLED) == 0)) {
851 kn->kn_status |= KN_DISABLED;
854 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
855 kn->kn_status &= ~KN_DISABLED;
856 if ((kn->kn_status & KN_ACTIVE) &&
857 ((kn->kn_status & KN_QUEUED) == 0))
862 lwkt_reltoken(&kq_token);
869 * Block as necessary until the target time is reached.
870 * If tsp is NULL we block indefinitely. If tsp->ts_secs/nsecs are both
871 * 0 we do not block at all.
874 kqueue_sleep(struct kqueue *kq, struct timespec *tsp)
879 kq->kq_state |= KQ_SLEEP;
880 error = tsleep(kq, PCATCH, "kqread", 0);
881 } else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
885 struct timespec atx = *tsp;
889 timespecsub(&atx, &ats);
890 if (ats.tv_sec < 0) {
893 timeout = atx.tv_sec > 24 * 60 * 60 ?
894 24 * 60 * 60 * hz : tstohz_high(&atx);
895 kq->kq_state |= KQ_SLEEP;
896 error = tsleep(kq, PCATCH, "kqread", timeout);
900 /* don't restart after signals... */
901 if (error == ERESTART)
908 * Scan the kqueue, return the number of active events placed in kevp up
911 * Continuous mode events may get recycled, do not continue scanning past
912 * marker unless no events have been collected.
915 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
916 struct knote *marker)
918 struct knote *kn, local_marker;
922 local_marker.kn_filter = EVFILT_MARKER;
927 TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
929 kn = TAILQ_NEXT(&local_marker, kn_tqe);
930 if (kn->kn_filter == EVFILT_MARKER) {
931 /* Marker reached, we are done */
935 /* Move local marker past some other threads marker */
936 kn = TAILQ_NEXT(kn, kn_tqe);
937 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
938 TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
943 * Remove the event for processing.
945 * WARNING! We must leave KN_QUEUED set to prevent the
946 * event from being KNOTE()d again while we
947 * potentially block in the filter function.
949 * This protects the knote from everything except
952 * WARNING! KN_PROCESSING is meant to handle any cases
953 * that leaving KN_QUEUED set does not.
955 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
957 kn->kn_status |= KN_PROCESSING;
960 * Even though close/dup2 will clean out pending knotes this
961 * code is MPSAFE and it is possible to race a close inbetween
962 * the removal of its descriptor and the clearing out of the
965 * In this case we must ensure that the knote is not queued
966 * to knpend or we risk an infinite kernel loop calling
967 * kscan, because the select/poll code will not be able to
970 if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
971 checkfdclosed(kq->kq_fdp, kn->kn_kevent.ident, kn->kn_fp)) {
972 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
978 * If disabled we ensure the event is not queued but leave
979 * its active bit set. On re-enablement the event may be
980 * immediately triggered.
982 if (kn->kn_status & KN_DISABLED) {
983 kn->kn_status &= ~(KN_QUEUED | KN_PROCESSING);
988 * If not running in one-shot mode and the event is no
989 * longer present we ensure it is removed from the queue and
992 if ((kn->kn_flags & EV_ONESHOT) == 0 &&
993 filter_event(kn, 0) == 0) {
994 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
999 *kevp++ = kn->kn_kevent;
1004 * Post-event action on the note
1006 if (kn->kn_flags & EV_ONESHOT) {
1007 kn->kn_status &= ~(KN_QUEUED | KN_PROCESSING);
1008 knote_detach_and_drop(kn);
1009 } else if (kn->kn_flags & EV_CLEAR) {
1012 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE |
1015 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1017 kn->kn_status &= ~KN_PROCESSING;
1020 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1027 * This could be expanded to call kqueue_scan, if desired.
1032 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1041 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1050 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1051 struct ucred *cred, struct sysmsg *msg)
1056 lwkt_gettoken(&kq_token);
1057 kq = (struct kqueue *)fp->f_data;
1062 kq->kq_state |= KQ_ASYNC;
1064 kq->kq_state &= ~KQ_ASYNC;
1068 error = fsetown(*(int *)data, &kq->kq_sigio);
1074 lwkt_reltoken(&kq_token);
1082 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1084 struct kqueue *kq = (struct kqueue *)fp->f_data;
1086 bzero((void *)st, sizeof(*st));
1087 st->st_size = kq->kq_count;
1088 st->st_blksize = sizeof(struct kevent);
1089 st->st_mode = S_IFIFO;
1097 kqueue_close(struct file *fp)
1099 struct kqueue *kq = (struct kqueue *)fp->f_data;
1101 kqueue_terminate(kq);
1104 funsetown(kq->kq_sigio);
1106 kfree(kq, M_KQUEUE);
1111 kqueue_wakeup(struct kqueue *kq)
1113 if (kq->kq_state & KQ_SLEEP) {
1114 kq->kq_state &= ~KQ_SLEEP;
1117 KNOTE(&kq->kq_kqinfo.ki_note, 0);
1121 * Calls filterops f_attach function, acquiring mplock if filter is not
1122 * marked as FILTEROP_MPSAFE.
1125 filter_attach(struct knote *kn)
1129 if (!(kn->kn_fop->f_flags & FILTEROP_MPSAFE)) {
1131 ret = kn->kn_fop->f_attach(kn);
1134 ret = kn->kn_fop->f_attach(kn);
1141 * Detach the knote and drop it, destroying the knote.
1143 * Calls filterops f_detach function, acquiring mplock if filter is not
1144 * marked as FILTEROP_MPSAFE.
1146 * This can race due to the MP lock and/or locks acquired by f_detach,
1147 * so we interlock with KN_DELETING. It is also possible to race
1148 * a create for the same reason if userland tries to delete the knote
1149 * before the create is complete.
1152 knote_detach_and_drop(struct knote *kn)
1154 if (kn->kn_status & (KN_CREATING | KN_DELETING))
1156 kn->kn_status |= KN_DELETING;
1158 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1159 kn->kn_fop->f_detach(kn);
1162 kn->kn_fop->f_detach(kn);
1169 * Calls filterops f_event function, acquiring mplock if filter is not
1170 * marked as FILTEROP_MPSAFE.
1172 * If the knote is in the middle of being created or deleted we cannot
1173 * safely call the filter op.
1176 filter_event(struct knote *kn, long hint)
1180 if (kn->kn_status & (KN_CREATING | KN_DELETING))
1183 if (!(kn->kn_fop->f_flags & FILTEROP_MPSAFE)) {
1185 ret = kn->kn_fop->f_event(kn, hint);
1188 ret = kn->kn_fop->f_event(kn, hint);
1195 * walk down a list of knotes, activating them if their event has triggered.
1198 knote(struct klist *list, long hint)
1202 lwkt_gettoken(&kq_token);
1203 SLIST_FOREACH(kn, list, kn_next) {
1204 if (filter_event(kn, hint))
1207 lwkt_reltoken(&kq_token);
1211 * insert knote at head of klist
1213 * Requires: kq_token
1216 knote_insert(struct klist *klist, struct knote *kn)
1218 lwkt_gettoken(&kq_token);
1219 SLIST_INSERT_HEAD(klist, kn, kn_next);
1220 lwkt_reltoken(&kq_token);
1224 * remove knote from a klist
1226 * Requires: kq_token
1229 knote_remove(struct klist *klist, struct knote *kn)
1231 lwkt_gettoken(&kq_token);
1232 SLIST_REMOVE(klist, kn, knote, kn_next);
1233 lwkt_reltoken(&kq_token);
1237 * remove all knotes from a specified klist
1240 knote_empty(struct klist *list)
1244 lwkt_gettoken(&kq_token);
1245 while ((kn = SLIST_FIRST(list)) != NULL)
1246 knote_detach_and_drop(kn);
1247 lwkt_reltoken(&kq_token);
1251 * remove all knotes referencing a specified fd
1254 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1258 lwkt_gettoken(&kq_token);
1260 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1261 if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1262 knote_detach_and_drop(kn);
1266 lwkt_reltoken(&kq_token);
1270 knote_attach(struct knote *kn)
1273 struct kqueue *kq = kn->kn_kq;
1275 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1276 KKASSERT(kn->kn_fp);
1277 list = &kn->kn_fp->f_klist;
1279 if (kq->kq_knhashmask == 0)
1280 kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1281 &kq->kq_knhashmask);
1282 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1284 SLIST_INSERT_HEAD(list, kn, kn_link);
1285 TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1286 kn->kn_status = KN_CREATING;
1290 knote_drop(struct knote *kn)
1297 if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1298 list = &kn->kn_fp->f_klist;
1300 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1302 SLIST_REMOVE(list, kn, knote, kn_link);
1303 TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1304 if (kn->kn_status & KN_QUEUED)
1306 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1314 knote_enqueue(struct knote *kn)
1316 struct kqueue *kq = kn->kn_kq;
1318 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1320 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1321 kn->kn_status |= KN_QUEUED;
1325 * Send SIGIO on request (typically set up as a mailbox signal)
1327 if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1328 pgsigio(kq->kq_sigio, SIGIO, 0);
1334 knote_dequeue(struct knote *kn)
1336 struct kqueue *kq = kn->kn_kq;
1338 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1339 KKASSERT((kn->kn_status & KN_PROCESSING) == 0);
1341 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1342 kn->kn_status &= ~KN_QUEUED;
1349 knote_zone = zinit("KNOTE", sizeof(struct knote), 0, 0, 1);
1351 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1353 static struct knote *
1356 return ((struct knote *)zalloc(knote_zone));
1360 knote_free(struct knote *kn)
1362 zfree(knote_zone, kn);