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_detach_and_drop_locked(struct knote *kn);
106 static void knote_enqueue(struct knote *kn);
107 static void knote_dequeue(struct knote *kn);
108 static void knote_init(void);
109 static struct knote *knote_alloc(void);
110 static void knote_free(struct knote *kn);
112 static void filt_kqdetach(struct knote *kn);
113 static int filt_kqueue(struct knote *kn, long hint);
114 static int filt_procattach(struct knote *kn);
115 static void filt_procdetach(struct knote *kn);
116 static int filt_proc(struct knote *kn, long hint);
117 static int filt_fileattach(struct knote *kn);
118 static void filt_timerexpire(void *knx);
119 static int filt_timerattach(struct knote *kn);
120 static void filt_timerdetach(struct knote *kn);
121 static int filt_timer(struct knote *kn, long hint);
123 static struct filterops file_filtops =
124 { FILTEROP_ISFD, filt_fileattach, NULL, NULL };
125 static struct filterops kqread_filtops =
126 { FILTEROP_ISFD, NULL, filt_kqdetach, filt_kqueue };
127 static struct filterops proc_filtops =
128 { 0, filt_procattach, filt_procdetach, filt_proc };
129 static struct filterops timer_filtops =
130 { 0, filt_timerattach, filt_timerdetach, filt_timer };
132 static vm_zone_t knote_zone;
133 static int kq_ncallouts = 0;
134 static int kq_calloutmax = (4 * 1024);
135 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
136 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
137 static int kq_checkloop = 1000000;
138 SYSCTL_INT(_kern, OID_AUTO, kq_checkloop, CTLFLAG_RW,
139 &kq_checkloop, 0, "Maximum number of callouts allocated for kqueue");
141 #define KNOTE_ACTIVATE(kn) do { \
142 kn->kn_status |= KN_ACTIVE; \
143 if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
147 #define KN_HASHSIZE 64 /* XXX should be tunable */
148 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
150 extern struct filterops aio_filtops;
151 extern struct filterops sig_filtops;
154 * Table for for all system-defined filters.
156 static struct filterops *sysfilt_ops[] = {
157 &file_filtops, /* EVFILT_READ */
158 &file_filtops, /* EVFILT_WRITE */
159 &aio_filtops, /* EVFILT_AIO */
160 &file_filtops, /* EVFILT_VNODE */
161 &proc_filtops, /* EVFILT_PROC */
162 &sig_filtops, /* EVFILT_SIGNAL */
163 &timer_filtops, /* EVFILT_TIMER */
164 &file_filtops, /* EVFILT_EXCEPT */
168 filt_fileattach(struct knote *kn)
170 return (fo_kqfilter(kn->kn_fp, kn));
177 kqueue_kqfilter(struct file *fp, struct knote *kn)
179 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
181 if (kn->kn_filter != EVFILT_READ)
184 kn->kn_fop = &kqread_filtops;
185 knote_insert(&kq->kq_kqinfo.ki_note, kn);
190 filt_kqdetach(struct knote *kn)
192 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
194 knote_remove(&kq->kq_kqinfo.ki_note, kn);
199 filt_kqueue(struct knote *kn, long hint)
201 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
203 kn->kn_data = kq->kq_count;
204 return (kn->kn_data > 0);
208 filt_procattach(struct knote *kn)
214 lwkt_gettoken(&proc_token);
215 p = pfind(kn->kn_id);
216 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
217 p = zpfind(kn->kn_id);
221 lwkt_reltoken(&proc_token);
224 if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
225 lwkt_reltoken(&proc_token);
229 kn->kn_ptr.p_proc = p;
230 kn->kn_flags |= EV_CLEAR; /* automatically set */
233 * internal flag indicating registration done by kernel
235 if (kn->kn_flags & EV_FLAG1) {
236 kn->kn_data = kn->kn_sdata; /* ppid */
237 kn->kn_fflags = NOTE_CHILD;
238 kn->kn_flags &= ~EV_FLAG1;
241 knote_insert(&p->p_klist, kn);
244 * Immediately activate any exit notes if the target process is a
245 * zombie. This is necessary to handle the case where the target
246 * process, e.g. a child, dies before the kevent is negistered.
248 if (immediate && filt_proc(kn, NOTE_EXIT))
250 lwkt_reltoken(&proc_token);
256 * The knote may be attached to a different process, which may exit,
257 * leaving nothing for the knote to be attached to. So when the process
258 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
259 * it will be deleted when read out. However, as part of the knote deletion,
260 * this routine is called, so a check is needed to avoid actually performing
261 * a detach, because the original process does not exist any more.
264 filt_procdetach(struct knote *kn)
268 if (kn->kn_status & KN_DETACHED)
270 /* XXX locking? take proc_token here? */
271 p = kn->kn_ptr.p_proc;
272 knote_remove(&p->p_klist, kn);
276 filt_proc(struct knote *kn, long hint)
281 * mask off extra data
283 event = (u_int)hint & NOTE_PCTRLMASK;
286 * if the user is interested in this event, record it.
288 if (kn->kn_sfflags & event)
289 kn->kn_fflags |= event;
292 * Process is gone, so flag the event as finished. Detach the
293 * knote from the process now because the process will be poof,
296 if (event == NOTE_EXIT) {
297 struct proc *p = kn->kn_ptr.p_proc;
298 if ((kn->kn_status & KN_DETACHED) == 0) {
299 knote_remove(&p->p_klist, kn);
300 kn->kn_status |= KN_DETACHED;
301 kn->kn_data = p->p_xstat;
302 kn->kn_ptr.p_proc = NULL;
304 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
309 * process forked, and user wants to track the new process,
310 * so attach a new knote to it, and immediately report an
311 * event with the parent's pid.
313 if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
318 * register knote with new process.
320 kev.ident = hint & NOTE_PDATAMASK; /* pid */
321 kev.filter = kn->kn_filter;
322 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
323 kev.fflags = kn->kn_sfflags;
324 kev.data = kn->kn_id; /* parent */
325 kev.udata = kn->kn_kevent.udata; /* preserve udata */
326 error = kqueue_register(kn->kn_kq, &kev);
328 kn->kn_fflags |= NOTE_TRACKERR;
331 return (kn->kn_fflags != 0);
335 filt_timerexpire(void *knx)
337 struct knote *kn = knx;
338 struct callout *calloutp;
342 lwkt_gettoken(&kq_token);
347 if ((kn->kn_flags & EV_ONESHOT) == 0) {
348 tv.tv_sec = kn->kn_sdata / 1000;
349 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
350 tticks = tvtohz_high(&tv);
351 calloutp = (struct callout *)kn->kn_hook;
352 callout_reset(calloutp, tticks, filt_timerexpire, kn);
355 lwkt_reltoken(&kq_token);
359 * data contains amount of time to sleep, in milliseconds
362 filt_timerattach(struct knote *kn)
364 struct callout *calloutp;
368 if (kq_ncallouts >= kq_calloutmax)
372 tv.tv_sec = kn->kn_sdata / 1000;
373 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
374 tticks = tvtohz_high(&tv);
376 kn->kn_flags |= EV_CLEAR; /* automatically set */
377 MALLOC(calloutp, struct callout *, sizeof(*calloutp),
379 callout_init(calloutp);
380 kn->kn_hook = (caddr_t)calloutp;
381 callout_reset(calloutp, tticks, filt_timerexpire, kn);
387 filt_timerdetach(struct knote *kn)
389 struct callout *calloutp;
391 calloutp = (struct callout *)kn->kn_hook;
392 callout_stop(calloutp);
393 FREE(calloutp, M_KQUEUE);
398 filt_timer(struct knote *kn, long hint)
401 return (kn->kn_data != 0);
405 * Initialize a kqueue.
407 * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
412 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
414 TAILQ_INIT(&kq->kq_knpend);
415 TAILQ_INIT(&kq->kq_knlist);
418 SLIST_INIT(&kq->kq_kqinfo.ki_note);
422 * Terminate a kqueue. Freeing the actual kq itself is left up to the
423 * caller (it might be embedded in a lwp so we don't do it here).
425 * The kq's knlist must be completely eradicated so block on any
429 kqueue_terminate(struct kqueue *kq)
433 lwkt_gettoken(&kq_token);
434 while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
435 if (kn->kn_status & KN_PROCESSING) {
436 kn->kn_status |= KN_WAITING | KN_REPROCESS;
437 tsleep(kn, 0, "kqtrms", hz);
440 knote_detach_and_drop(kn);
443 kfree(kq->kq_knhash, M_KQUEUE);
444 kq->kq_knhash = NULL;
445 kq->kq_knhashmask = 0;
447 lwkt_reltoken(&kq_token);
454 sys_kqueue(struct kqueue_args *uap)
456 struct thread *td = curthread;
461 error = falloc(td->td_lwp, &fp, &fd);
464 fp->f_flag = FREAD | FWRITE;
465 fp->f_type = DTYPE_KQUEUE;
466 fp->f_ops = &kqueueops;
468 kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
469 kqueue_init(kq, td->td_proc->p_fd);
472 fsetfd(kq->kq_fdp, fp, fd);
473 uap->sysmsg_result = fd;
479 * Copy 'count' items into the destination list pointed to by uap->eventlist.
482 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
484 struct kevent_copyin_args *kap;
487 kap = (struct kevent_copyin_args *)arg;
489 error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
491 kap->ka->eventlist += count;
501 * Copy at most 'max' items from the list pointed to by kap->changelist,
502 * return number of items in 'events'.
505 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
507 struct kevent_copyin_args *kap;
510 kap = (struct kevent_copyin_args *)arg;
512 count = min(kap->ka->nchanges - kap->pchanges, max);
513 error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
515 kap->ka->changelist += count;
516 kap->pchanges += count;
527 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
528 k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
529 struct timespec *tsp_in)
532 struct timespec *tsp;
533 int i, n, total, error, nerrors = 0;
535 int limit = kq_checkloop;
536 struct kevent kev[KQ_NEVENTS];
542 lwkt_gettoken(&kq_token);
545 error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
550 for (i = 0; i < n; i++) {
552 kevp->flags &= ~EV_SYSFLAGS;
553 error = kqueue_register(kq, kevp);
556 * If a registration returns an error we
557 * immediately post the error. The kevent()
558 * call itself will fail with the error if
559 * no space is available for posting.
561 * Such errors normally bypass the timeout/blocking
562 * code. However, if the copyoutfn function refuses
563 * to post the error (see sys_poll()), then we
567 kevp->flags = EV_ERROR;
570 kevent_copyoutfn(uap, kevp, 1, res);
584 * Acquire/wait for events - setup timeout
589 if (tsp->tv_sec || tsp->tv_nsec) {
591 timespecadd(tsp, &ats); /* tsp = target time */
598 * Collect as many events as we can. Sleeping on successive
599 * loops is disabled if copyoutfn has incremented (*res).
601 * The loop stops if an error occurs, all events have been
602 * scanned (the marker has been reached), or fewer than the
603 * maximum number of events is found.
605 * The copyoutfn function does not have to increment (*res) in
606 * order for the loop to continue.
608 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
612 marker.kn_filter = EVFILT_MARKER;
613 marker.kn_status = KN_PROCESSING;
614 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
615 while ((n = nevents - total) > 0) {
620 * If no events are pending sleep until timeout (if any)
621 * or an event occurs.
623 * After the sleep completes the marker is moved to the
624 * end of the list, making any received events available
627 if (kq->kq_count == 0 && *res == 0) {
628 error = kqueue_sleep(kq, tsp);
632 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
633 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
637 * Process all received events
638 * Account for all non-spurious events in our total
640 i = kqueue_scan(kq, kev, n, &marker);
643 error = kevent_copyoutfn(uap, kev, i, res);
644 total += *res - lres;
648 if (limit && --limit == 0)
649 panic("kqueue: checkloop failed i=%d", i);
652 * Normally when fewer events are returned than requested
653 * we can stop. However, if only spurious events were
654 * collected the copyout will not bump (*res) and we have
661 * Deal with an edge case where spurious events can cause
662 * a loop to occur without moving the marker. This can
663 * prevent kqueue_scan() from picking up new events which
664 * race us. We must be sure to move the marker for this
667 * NOTE: We do not want to move the marker if events
668 * were scanned because normal kqueue operations
669 * may reactivate events. Moving the marker in
670 * that case could result in duplicates for the
674 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
675 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
678 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
680 /* Timeouts do not return EWOULDBLOCK. */
681 if (error == EWOULDBLOCK)
685 lwkt_reltoken(&kq_token);
693 sys_kevent(struct kevent_args *uap)
695 struct thread *td = curthread;
696 struct proc *p = td->td_proc;
697 struct timespec ts, *tsp;
699 struct file *fp = NULL;
700 struct kevent_copyin_args *kap, ka;
704 error = copyin(uap->timeout, &ts, sizeof(ts));
712 fp = holdfp(p->p_fd, uap->fd, -1);
715 if (fp->f_type != DTYPE_KQUEUE) {
720 kq = (struct kqueue *)fp->f_data;
726 error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
727 kevent_copyin, kevent_copyout, tsp);
735 kqueue_register(struct kqueue *kq, struct kevent *kev)
737 struct filedesc *fdp = kq->kq_fdp;
738 struct filterops *fops;
739 struct file *fp = NULL;
740 struct knote *kn = NULL;
743 if (kev->filter < 0) {
744 if (kev->filter + EVFILT_SYSCOUNT < 0)
746 fops = sysfilt_ops[~kev->filter]; /* to 0-base index */
750 * filter attach routine is responsible for insuring that
751 * the identifier can be attached to it.
753 kprintf("unknown filter: %d\n", kev->filter);
757 lwkt_gettoken(&kq_token);
758 if (fops->f_flags & FILTEROP_ISFD) {
759 /* validate descriptor */
760 fp = holdfp(fdp, kev->ident, -1);
762 lwkt_reltoken(&kq_token);
766 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
767 if (kn->kn_kq == kq &&
768 kn->kn_filter == kev->filter &&
769 kn->kn_id == kev->ident) {
774 if (kq->kq_knhashmask) {
777 list = &kq->kq_knhash[
778 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
779 SLIST_FOREACH(kn, list, kn_link) {
780 if (kn->kn_id == kev->ident &&
781 kn->kn_filter == kev->filter)
787 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
793 * kn now contains the matching knote, or NULL if no match
795 if (kev->flags & EV_ADD) {
807 * apply reference count to knote structure, and
808 * do not release it at the end of this routine.
812 kn->kn_sfflags = kev->fflags;
813 kn->kn_sdata = kev->data;
816 kn->kn_kevent = *kev;
819 * KN_PROCESSING prevents the knote from getting
820 * ripped out from under us while we are trying
821 * to attach it, in case the attach blocks.
823 kn->kn_status = KN_PROCESSING;
825 if ((error = filter_attach(kn)) != 0) {
826 kn->kn_status |= KN_DELETING;
832 * Interlock against close races which either tried
833 * to remove our knote while we were blocked or missed
834 * it entirely prior to our attachment. We do not
835 * want to end up with a knote on a closed descriptor.
837 if ((fops->f_flags & FILTEROP_ISFD) &&
838 checkfdclosed(fdp, kev->ident, kn->kn_fp)) {
839 kn->kn_status |= KN_DELETING;
843 * The user may change some filter values after the
844 * initial EV_ADD, but doing so will not reset any
845 * filter which have already been triggered.
847 kn->kn_status |= KN_PROCESSING;
848 kn->kn_sfflags = kev->fflags;
849 kn->kn_sdata = kev->data;
850 kn->kn_kevent.udata = kev->udata;
854 * Execute the filter event to immediately activate the
855 * knote if necessary. We still own KN_PROCESSING so
856 * process any KN_REPROCESS races as well.
859 if (kn->kn_status & KN_DELETING) {
861 knote_detach_and_drop_locked(kn);
864 if (filter_event(kn, 0))
866 if ((kn->kn_status & KN_REPROCESS) == 0)
868 if (kn->kn_status & KN_WAITING) {
869 kn->kn_status &= ~KN_WAITING;
872 kn->kn_status &= ~KN_REPROCESS;
874 kn->kn_status &= ~KN_PROCESSING;
875 } else if (kev->flags & EV_DELETE) {
877 * Attempt to delete the existing knote
879 knote_detach_and_drop(kn);
884 * Disablement does not deactivate a knote here.
886 if ((kev->flags & EV_DISABLE) &&
887 ((kn->kn_status & KN_DISABLED) == 0)) {
888 kn->kn_status |= KN_DISABLED;
892 * Re-enablement may have to immediately enqueue an active knote.
894 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
895 kn->kn_status &= ~KN_DISABLED;
896 if ((kn->kn_status & KN_ACTIVE) &&
897 ((kn->kn_status & KN_QUEUED) == 0)) {
903 lwkt_reltoken(&kq_token);
910 * Block as necessary until the target time is reached.
911 * If tsp is NULL we block indefinitely. If tsp->ts_secs/nsecs are both
912 * 0 we do not block at all.
915 kqueue_sleep(struct kqueue *kq, struct timespec *tsp)
920 kq->kq_state |= KQ_SLEEP;
921 error = tsleep(kq, PCATCH, "kqread", 0);
922 } else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
926 struct timespec atx = *tsp;
930 timespecsub(&atx, &ats);
931 if (ats.tv_sec < 0) {
934 timeout = atx.tv_sec > 24 * 60 * 60 ?
935 24 * 60 * 60 * hz : tstohz_high(&atx);
936 kq->kq_state |= KQ_SLEEP;
937 error = tsleep(kq, PCATCH, "kqread", timeout);
941 /* don't restart after signals... */
942 if (error == ERESTART)
949 * Scan the kqueue, return the number of active events placed in kevp up
952 * Continuous mode events may get recycled, do not continue scanning past
953 * marker unless no events have been collected.
956 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
957 struct knote *marker)
959 struct knote *kn, local_marker;
963 local_marker.kn_filter = EVFILT_MARKER;
964 local_marker.kn_status = KN_PROCESSING;
969 TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
971 kn = TAILQ_NEXT(&local_marker, kn_tqe);
972 if (kn->kn_filter == EVFILT_MARKER) {
973 /* Marker reached, we are done */
977 /* Move local marker past some other threads marker */
978 kn = TAILQ_NEXT(kn, kn_tqe);
979 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
980 TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
985 * We can't skip a knote undergoing processing, otherwise
986 * we risk not returning it when the user process expects
987 * it should be returned. Sleep and retry.
989 if (kn->kn_status & KN_PROCESSING) {
990 kn->kn_status |= KN_WAITING | KN_REPROCESS;
991 tsleep(kn, 0, "kqepts", hz);
996 * Remove the event for processing.
998 * WARNING! We must leave KN_QUEUED set to prevent the
999 * event from being KNOTE_ACTIVATE()d while
1000 * the queue state is in limbo, in case we
1003 * WARNING! We must set KN_PROCESSING to avoid races
1004 * against deletion or another thread's
1007 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1009 kn->kn_status |= KN_PROCESSING;
1012 * We have to deal with an extremely important race against
1013 * file descriptor close()s here. The file descriptor can
1014 * disappear MPSAFE, and there is a small window of
1015 * opportunity between that and the call to knote_fdclose().
1017 * If we hit that window here while doselect or dopoll is
1018 * trying to delete a spurious event they will not be able
1019 * to match up the event against a knote and will go haywire.
1021 if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
1022 checkfdclosed(kq->kq_fdp, kn->kn_kevent.ident, kn->kn_fp)) {
1023 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1026 if (kn->kn_status & KN_DISABLED) {
1028 * If disabled we ensure the event is not queued
1029 * but leave its active bit set. On re-enablement
1030 * the event may be immediately triggered.
1032 kn->kn_status &= ~KN_QUEUED;
1033 } else if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1034 filter_event(kn, 0) == 0) {
1036 * If not running in one-shot mode and the event
1037 * is no longer present we ensure it is removed
1038 * from the queue and ignore it.
1040 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1045 *kevp++ = kn->kn_kevent;
1049 if (kn->kn_flags & EV_ONESHOT) {
1050 kn->kn_status &= ~KN_QUEUED;
1051 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1052 } else if (kn->kn_flags & EV_CLEAR) {
1055 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1057 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1063 * Handle any post-processing states
1065 while (kn->kn_status & KN_REPROCESS) {
1066 kn->kn_status &= ~KN_REPROCESS;
1067 if (kn->kn_status & KN_DELETING) {
1068 knote_detach_and_drop_locked(kn);
1071 if (kn->kn_status & KN_WAITING) {
1072 kn->kn_status &= ~KN_WAITING;
1075 if (filter_event(kn, 0))
1078 kn->kn_status &= ~KN_PROCESSING;
1082 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1089 * This could be expanded to call kqueue_scan, if desired.
1094 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1103 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1112 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1113 struct ucred *cred, struct sysmsg *msg)
1118 lwkt_gettoken(&kq_token);
1119 kq = (struct kqueue *)fp->f_data;
1124 kq->kq_state |= KQ_ASYNC;
1126 kq->kq_state &= ~KQ_ASYNC;
1130 error = fsetown(*(int *)data, &kq->kq_sigio);
1136 lwkt_reltoken(&kq_token);
1144 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1146 struct kqueue *kq = (struct kqueue *)fp->f_data;
1148 bzero((void *)st, sizeof(*st));
1149 st->st_size = kq->kq_count;
1150 st->st_blksize = sizeof(struct kevent);
1151 st->st_mode = S_IFIFO;
1159 kqueue_close(struct file *fp)
1161 struct kqueue *kq = (struct kqueue *)fp->f_data;
1163 kqueue_terminate(kq);
1166 funsetown(kq->kq_sigio);
1168 kfree(kq, M_KQUEUE);
1173 kqueue_wakeup(struct kqueue *kq)
1175 if (kq->kq_state & KQ_SLEEP) {
1176 kq->kq_state &= ~KQ_SLEEP;
1179 KNOTE(&kq->kq_kqinfo.ki_note, 0);
1183 * Calls filterops f_attach function, acquiring mplock if filter is not
1184 * marked as FILTEROP_MPSAFE.
1187 filter_attach(struct knote *kn)
1191 if (!(kn->kn_fop->f_flags & FILTEROP_MPSAFE)) {
1193 ret = kn->kn_fop->f_attach(kn);
1196 ret = kn->kn_fop->f_attach(kn);
1203 * Detach the knote and drop it, destroying the knote.
1205 * Calls filterops f_detach function, acquiring mplock if filter is not
1206 * marked as FILTEROP_MPSAFE.
1209 knote_detach_and_drop(struct knote *kn)
1212 * If someone else is procesing the knote we cannot destroy it now,
1213 * flag the request and return.
1215 if (kn->kn_status & KN_PROCESSING) {
1216 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1219 kn->kn_status |= KN_PROCESSING | KN_DELETING;
1220 knote_detach_and_drop_locked(kn);
1224 knote_detach_and_drop_locked(struct knote *kn)
1226 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1227 kn->kn_fop->f_detach(kn);
1230 kn->kn_fop->f_detach(kn);
1237 * Calls filterops f_event function, acquiring mplock if filter is not
1238 * marked as FILTEROP_MPSAFE.
1240 * If the knote is in the middle of being created or deleted we cannot
1241 * safely call the filter op.
1244 filter_event(struct knote *kn, long hint)
1248 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1249 ret = kn->kn_fop->f_event(kn, hint);
1252 ret = kn->kn_fop->f_event(kn, hint);
1259 * Walk down a list of knotes, activating them if their event has triggered.
1261 * If we encounter any knotes which are undergoing processing we just mark
1262 * them for reprocessing and do not try to [re]activate the knote. However,
1263 * if a hint is being passed we have to wait and that makes things a bit
1267 knote(struct klist *list, long hint)
1271 lwkt_gettoken(&kq_token);
1273 SLIST_FOREACH(kn, list, kn_next) {
1274 if (kn->kn_status & KN_PROCESSING) {
1276 * Someone else is processing the knote, ask the
1277 * other thread to reprocess it and don't mess
1278 * with it otherwise.
1281 kn->kn_status |= KN_REPROCESS;
1286 * If the note is not empty we have to wait.
1288 * XXX This is a real problem, certain process
1289 * and signal filters will bump kn_data for
1290 * already-processed notes more than once if
1291 * we restart the list scan. FIXME.
1293 kprintf("Warning: knote() on busy "
1294 "knote (ev=%d hint=%08lx)\n",
1295 kn->kn_filter, hint);
1296 kn->kn_status |= KN_WAITING | KN_REPROCESS;
1297 tsleep(kn, 0, "knotec", hz);
1302 * Become the reprocessing master ourselves.
1304 kn->kn_status |= KN_PROCESSING;
1305 if (filter_event(kn, hint))
1307 while (kn->kn_status & KN_REPROCESS) {
1308 kn->kn_status &= ~KN_REPROCESS;
1309 if (kn->kn_status & KN_DELETING) {
1310 knote_detach_and_drop_locked(kn);
1313 if (kn->kn_status & KN_WAITING) {
1314 kn->kn_status &= ~KN_WAITING;
1317 if (filter_event(kn, hint))
1320 kn->kn_status &= ~KN_PROCESSING;
1322 lwkt_reltoken(&kq_token);
1326 * Insert knote at head of klist.
1328 * This function may only be called via a filter function and thus
1329 * kq_token should already be held and marked for processing.
1332 knote_insert(struct klist *klist, struct knote *kn)
1334 KKASSERT(kn->kn_status & KN_PROCESSING);
1335 ASSERT_LWKT_TOKEN_HELD(&kq_token);
1336 SLIST_INSERT_HEAD(klist, kn, kn_next);
1340 * Remove knote from a klist
1342 * This function may only be called via a filter function and thus
1343 * kq_token should already be held and marked for processing.
1346 knote_remove(struct klist *klist, struct knote *kn)
1348 KKASSERT(kn->kn_status & KN_PROCESSING);
1349 ASSERT_LWKT_TOKEN_HELD(&kq_token);
1350 SLIST_REMOVE(klist, kn, knote, kn_next);
1354 * Remove all knotes from a specified klist
1356 * Only called from aio.
1359 knote_empty(struct klist *list)
1363 lwkt_gettoken(&kq_token);
1364 while ((kn = SLIST_FIRST(list)) != NULL) {
1365 if (kn->kn_status & KN_PROCESSING) {
1366 kn->kn_status |= KN_WAITING | KN_REPROCESS;
1367 tsleep(kn, 0, "kqepts", hz);
1370 knote_detach_and_drop(kn);
1372 lwkt_reltoken(&kq_token);
1376 * remove all knotes referencing a specified fd
1379 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1383 lwkt_gettoken(&kq_token);
1385 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1386 if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1387 if (kn->kn_status & KN_PROCESSING) {
1388 kn->kn_status |= KN_WAITING | KN_REPROCESS;
1389 tsleep(kn, 0, "kqepts", hz);
1391 knote_detach_and_drop(kn);
1396 lwkt_reltoken(&kq_token);
1400 * Low level attach function.
1402 * The knote should already be marked for processing.
1405 knote_attach(struct knote *kn)
1408 struct kqueue *kq = kn->kn_kq;
1410 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1411 KKASSERT(kn->kn_fp);
1412 list = &kn->kn_fp->f_klist;
1414 if (kq->kq_knhashmask == 0)
1415 kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1416 &kq->kq_knhashmask);
1417 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1419 SLIST_INSERT_HEAD(list, kn, kn_link);
1420 TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1424 * Low level drop function.
1426 * The knote should already be marked for processing.
1429 knote_drop(struct knote *kn)
1436 if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1437 list = &kn->kn_fp->f_klist;
1439 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1441 SLIST_REMOVE(list, kn, knote, kn_link);
1442 TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1443 if (kn->kn_status & KN_QUEUED)
1445 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1453 * Low level enqueue function.
1455 * The knote should already be marked for processing.
1458 knote_enqueue(struct knote *kn)
1460 struct kqueue *kq = kn->kn_kq;
1462 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1463 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1464 kn->kn_status |= KN_QUEUED;
1468 * Send SIGIO on request (typically set up as a mailbox signal)
1470 if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1471 pgsigio(kq->kq_sigio, SIGIO, 0);
1477 * Low level dequeue function.
1479 * The knote should already be marked for processing.
1482 knote_dequeue(struct knote *kn)
1484 struct kqueue *kq = kn->kn_kq;
1486 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1487 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1488 kn->kn_status &= ~KN_QUEUED;
1495 knote_zone = zinit("KNOTE", sizeof(struct knote), 0, 0, 1);
1497 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1499 static struct knote *
1502 return ((struct knote *)zalloc(knote_zone));
1506 knote_free(struct knote *kn)
1508 zfree(knote_zone, kn);