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_INITIALIZER(kq_token);
64 SYSCTL_LONG(_lwkt, OID_AUTO, kq_collisions,
65 CTLFLAG_RW, &kq_token.t_collisions, 0,
66 "Collision counter of kq_token");
68 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
70 struct kevent_copyin_args {
71 struct kevent_args *ka;
75 static int kqueue_sleep(struct kqueue *kq, struct timespec *tsp);
76 static int kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
77 struct knote *marker);
78 static int kqueue_read(struct file *fp, struct uio *uio,
79 struct ucred *cred, int flags);
80 static int kqueue_write(struct file *fp, struct uio *uio,
81 struct ucred *cred, int flags);
82 static int kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
83 struct ucred *cred, struct sysmsg *msg);
84 static int kqueue_kqfilter(struct file *fp, struct knote *kn);
85 static int kqueue_stat(struct file *fp, struct stat *st,
87 static int kqueue_close(struct file *fp);
88 static void kqueue_wakeup(struct kqueue *kq);
89 static int filter_attach(struct knote *kn);
90 static int filter_event(struct knote *kn, long hint);
95 static struct fileops kqueueops = {
96 .fo_read = kqueue_read,
97 .fo_write = kqueue_write,
98 .fo_ioctl = kqueue_ioctl,
99 .fo_kqfilter = kqueue_kqfilter,
100 .fo_stat = kqueue_stat,
101 .fo_close = kqueue_close,
102 .fo_shutdown = nofo_shutdown
105 static void knote_attach(struct knote *kn);
106 static void knote_drop(struct knote *kn);
107 static void knote_detach_and_drop(struct knote *kn);
108 static void knote_enqueue(struct knote *kn);
109 static void knote_dequeue(struct knote *kn);
110 static void knote_init(void);
111 static struct knote *knote_alloc(void);
112 static void knote_free(struct knote *kn);
114 static void filt_kqdetach(struct knote *kn);
115 static int filt_kqueue(struct knote *kn, long hint);
116 static int filt_procattach(struct knote *kn);
117 static void filt_procdetach(struct knote *kn);
118 static int filt_proc(struct knote *kn, long hint);
119 static int filt_fileattach(struct knote *kn);
120 static void filt_timerexpire(void *knx);
121 static int filt_timerattach(struct knote *kn);
122 static void filt_timerdetach(struct knote *kn);
123 static int filt_timer(struct knote *kn, long hint);
125 static struct filterops file_filtops =
126 { FILTEROP_ISFD, filt_fileattach, NULL, NULL };
127 static struct filterops kqread_filtops =
128 { FILTEROP_ISFD, NULL, filt_kqdetach, filt_kqueue };
129 static struct filterops proc_filtops =
130 { 0, filt_procattach, filt_procdetach, filt_proc };
131 static struct filterops timer_filtops =
132 { 0, filt_timerattach, filt_timerdetach, filt_timer };
134 static vm_zone_t knote_zone;
135 static int kq_ncallouts = 0;
136 static int kq_calloutmax = (4 * 1024);
137 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
138 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
139 static int kq_checkloop = 1000000;
140 SYSCTL_INT(_kern, OID_AUTO, kq_checkloop, CTLFLAG_RW,
141 &kq_checkloop, 0, "Maximum number of callouts allocated for kqueue");
143 #define KNOTE_ACTIVATE(kn) do { \
144 kn->kn_status |= KN_ACTIVE; \
145 if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
149 #define KN_HASHSIZE 64 /* XXX should be tunable */
150 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
152 extern struct filterops aio_filtops;
153 extern struct filterops sig_filtops;
156 * Table for for all system-defined filters.
158 static struct filterops *sysfilt_ops[] = {
159 &file_filtops, /* EVFILT_READ */
160 &file_filtops, /* EVFILT_WRITE */
161 &aio_filtops, /* EVFILT_AIO */
162 &file_filtops, /* EVFILT_VNODE */
163 &proc_filtops, /* EVFILT_PROC */
164 &sig_filtops, /* EVFILT_SIGNAL */
165 &timer_filtops, /* EVFILT_TIMER */
166 &file_filtops, /* EVFILT_EXCEPT */
170 filt_fileattach(struct knote *kn)
172 return (fo_kqfilter(kn->kn_fp, kn));
179 kqueue_kqfilter(struct file *fp, struct knote *kn)
181 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
183 if (kn->kn_filter != EVFILT_READ)
186 kn->kn_fop = &kqread_filtops;
187 knote_insert(&kq->kq_kqinfo.ki_note, kn);
192 filt_kqdetach(struct knote *kn)
194 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
196 knote_remove(&kq->kq_kqinfo.ki_note, kn);
201 filt_kqueue(struct knote *kn, long hint)
203 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
205 kn->kn_data = kq->kq_count;
206 return (kn->kn_data > 0);
210 filt_procattach(struct knote *kn)
216 lwkt_gettoken(&proc_token);
217 p = pfind(kn->kn_id);
218 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
219 p = zpfind(kn->kn_id);
223 lwkt_reltoken(&proc_token);
226 if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
227 lwkt_reltoken(&proc_token);
231 kn->kn_ptr.p_proc = p;
232 kn->kn_flags |= EV_CLEAR; /* automatically set */
235 * internal flag indicating registration done by kernel
237 if (kn->kn_flags & EV_FLAG1) {
238 kn->kn_data = kn->kn_sdata; /* ppid */
239 kn->kn_fflags = NOTE_CHILD;
240 kn->kn_flags &= ~EV_FLAG1;
243 knote_insert(&p->p_klist, kn);
246 * Immediately activate any exit notes if the target process is a
247 * zombie. This is necessary to handle the case where the target
248 * process, e.g. a child, dies before the kevent is negistered.
250 if (immediate && filt_proc(kn, NOTE_EXIT))
252 lwkt_reltoken(&proc_token);
258 * The knote may be attached to a different process, which may exit,
259 * leaving nothing for the knote to be attached to. So when the process
260 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
261 * it will be deleted when read out. However, as part of the knote deletion,
262 * this routine is called, so a check is needed to avoid actually performing
263 * a detach, because the original process does not exist any more.
266 filt_procdetach(struct knote *kn)
270 if (kn->kn_status & KN_DETACHED)
272 /* XXX locking? take proc_token here? */
273 p = kn->kn_ptr.p_proc;
274 knote_remove(&p->p_klist, kn);
278 filt_proc(struct knote *kn, long hint)
283 * mask off extra data
285 event = (u_int)hint & NOTE_PCTRLMASK;
288 * if the user is interested in this event, record it.
290 if (kn->kn_sfflags & event)
291 kn->kn_fflags |= event;
294 * Process is gone, so flag the event as finished. Detach the
295 * knote from the process now because the process will be poof,
298 if (event == NOTE_EXIT) {
299 struct proc *p = kn->kn_ptr.p_proc;
300 if ((kn->kn_status & KN_DETACHED) == 0) {
301 knote_remove(&p->p_klist, kn);
302 kn->kn_status |= KN_DETACHED;
303 kn->kn_data = p->p_xstat;
304 kn->kn_ptr.p_proc = NULL;
306 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
311 * process forked, and user wants to track the new process,
312 * so attach a new knote to it, and immediately report an
313 * event with the parent's pid.
315 if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
320 * register knote with new process.
322 kev.ident = hint & NOTE_PDATAMASK; /* pid */
323 kev.filter = kn->kn_filter;
324 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
325 kev.fflags = kn->kn_sfflags;
326 kev.data = kn->kn_id; /* parent */
327 kev.udata = kn->kn_kevent.udata; /* preserve udata */
328 error = kqueue_register(kn->kn_kq, &kev);
330 kn->kn_fflags |= NOTE_TRACKERR;
333 return (kn->kn_fflags != 0);
337 * The callout interlocks with callout_stop() (or should), so the
338 * knote should still be a valid structure. However the timeout
339 * can race a deletion so if KN_DELETING is set we just don't touch
343 filt_timerexpire(void *knx)
345 struct knote *kn = knx;
346 struct callout *calloutp;
350 lwkt_gettoken(&kq_token);
351 if ((kn->kn_status & KN_DELETING) == 0) {
355 if ((kn->kn_flags & EV_ONESHOT) == 0) {
356 tv.tv_sec = kn->kn_sdata / 1000;
357 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
358 tticks = tvtohz_high(&tv);
359 calloutp = (struct callout *)kn->kn_hook;
360 callout_reset(calloutp, tticks, filt_timerexpire, kn);
363 lwkt_reltoken(&kq_token);
367 * data contains amount of time to sleep, in milliseconds
370 filt_timerattach(struct knote *kn)
372 struct callout *calloutp;
376 if (kq_ncallouts >= kq_calloutmax)
380 tv.tv_sec = kn->kn_sdata / 1000;
381 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
382 tticks = tvtohz_high(&tv);
384 kn->kn_flags |= EV_CLEAR; /* automatically set */
385 MALLOC(calloutp, struct callout *, sizeof(*calloutp),
387 callout_init(calloutp);
388 kn->kn_hook = (caddr_t)calloutp;
389 callout_reset(calloutp, tticks, filt_timerexpire, kn);
395 filt_timerdetach(struct knote *kn)
397 struct callout *calloutp;
399 calloutp = (struct callout *)kn->kn_hook;
400 callout_stop(calloutp);
401 FREE(calloutp, M_KQUEUE);
406 filt_timer(struct knote *kn, long hint)
409 return (kn->kn_data != 0);
413 * Acquire a knote, return non-zero on success, 0 on failure.
415 * If we cannot acquire the knote we sleep and return 0. The knote
416 * may be stale on return in this case and the caller must restart
417 * whatever loop they are in.
421 knote_acquire(struct knote *kn)
423 if (kn->kn_status & KN_PROCESSING) {
424 kn->kn_status |= KN_WAITING | KN_REPROCESS;
425 tsleep(kn, 0, "kqepts", hz);
426 /* knote may be stale now */
429 kn->kn_status |= KN_PROCESSING;
434 * Release an acquired knote, clearing KN_PROCESSING and handling any
435 * KN_REPROCESS events.
437 * Non-zero is returned if the knote is destroyed.
441 knote_release(struct knote *kn)
443 while (kn->kn_status & KN_REPROCESS) {
444 kn->kn_status &= ~KN_REPROCESS;
445 if (kn->kn_status & KN_WAITING) {
446 kn->kn_status &= ~KN_WAITING;
449 if (kn->kn_status & KN_DELETING) {
450 knote_detach_and_drop(kn);
454 if (filter_event(kn, 0))
457 kn->kn_status &= ~KN_PROCESSING;
462 * Initialize a kqueue.
464 * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
469 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
471 TAILQ_INIT(&kq->kq_knpend);
472 TAILQ_INIT(&kq->kq_knlist);
475 SLIST_INIT(&kq->kq_kqinfo.ki_note);
479 * Terminate a kqueue. Freeing the actual kq itself is left up to the
480 * caller (it might be embedded in a lwp so we don't do it here).
482 * The kq's knlist must be completely eradicated so block on any
486 kqueue_terminate(struct kqueue *kq)
490 lwkt_gettoken(&kq_token);
491 while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
492 if (knote_acquire(kn))
493 knote_detach_and_drop(kn);
496 kfree(kq->kq_knhash, M_KQUEUE);
497 kq->kq_knhash = NULL;
498 kq->kq_knhashmask = 0;
500 lwkt_reltoken(&kq_token);
507 sys_kqueue(struct kqueue_args *uap)
509 struct thread *td = curthread;
514 error = falloc(td->td_lwp, &fp, &fd);
517 fp->f_flag = FREAD | FWRITE;
518 fp->f_type = DTYPE_KQUEUE;
519 fp->f_ops = &kqueueops;
521 kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
522 kqueue_init(kq, td->td_proc->p_fd);
525 fsetfd(kq->kq_fdp, fp, fd);
526 uap->sysmsg_result = fd;
532 * Copy 'count' items into the destination list pointed to by uap->eventlist.
535 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
537 struct kevent_copyin_args *kap;
540 kap = (struct kevent_copyin_args *)arg;
542 error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
544 kap->ka->eventlist += count;
554 * Copy at most 'max' items from the list pointed to by kap->changelist,
555 * return number of items in 'events'.
558 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
560 struct kevent_copyin_args *kap;
563 kap = (struct kevent_copyin_args *)arg;
565 count = min(kap->ka->nchanges - kap->pchanges, max);
566 error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
568 kap->ka->changelist += count;
569 kap->pchanges += count;
580 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
581 k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
582 struct timespec *tsp_in)
585 struct timespec *tsp;
586 int i, n, total, error, nerrors = 0;
588 int limit = kq_checkloop;
589 struct kevent kev[KQ_NEVENTS];
595 lwkt_gettoken(&kq_token);
598 error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
603 for (i = 0; i < n; i++) {
605 kevp->flags &= ~EV_SYSFLAGS;
606 error = kqueue_register(kq, kevp);
609 * If a registration returns an error we
610 * immediately post the error. The kevent()
611 * call itself will fail with the error if
612 * no space is available for posting.
614 * Such errors normally bypass the timeout/blocking
615 * code. However, if the copyoutfn function refuses
616 * to post the error (see sys_poll()), then we
620 kevp->flags = EV_ERROR;
623 kevent_copyoutfn(uap, kevp, 1, res);
637 * Acquire/wait for events - setup timeout
642 if (tsp->tv_sec || tsp->tv_nsec) {
644 timespecadd(tsp, &ats); /* tsp = target time */
651 * Collect as many events as we can. Sleeping on successive
652 * loops is disabled if copyoutfn has incremented (*res).
654 * The loop stops if an error occurs, all events have been
655 * scanned (the marker has been reached), or fewer than the
656 * maximum number of events is found.
658 * The copyoutfn function does not have to increment (*res) in
659 * order for the loop to continue.
661 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
665 marker.kn_filter = EVFILT_MARKER;
666 marker.kn_status = KN_PROCESSING;
667 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
668 while ((n = nevents - total) > 0) {
673 * If no events are pending sleep until timeout (if any)
674 * or an event occurs.
676 * After the sleep completes the marker is moved to the
677 * end of the list, making any received events available
680 if (kq->kq_count == 0 && *res == 0) {
681 error = kqueue_sleep(kq, tsp);
685 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
686 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
690 * Process all received events
691 * Account for all non-spurious events in our total
693 i = kqueue_scan(kq, kev, n, &marker);
696 error = kevent_copyoutfn(uap, kev, i, res);
697 total += *res - lres;
701 if (limit && --limit == 0)
702 panic("kqueue: checkloop failed i=%d", i);
705 * Normally when fewer events are returned than requested
706 * we can stop. However, if only spurious events were
707 * collected the copyout will not bump (*res) and we have
714 * Deal with an edge case where spurious events can cause
715 * a loop to occur without moving the marker. This can
716 * prevent kqueue_scan() from picking up new events which
717 * race us. We must be sure to move the marker for this
720 * NOTE: We do not want to move the marker if events
721 * were scanned because normal kqueue operations
722 * may reactivate events. Moving the marker in
723 * that case could result in duplicates for the
727 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
728 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
731 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
733 /* Timeouts do not return EWOULDBLOCK. */
734 if (error == EWOULDBLOCK)
738 lwkt_reltoken(&kq_token);
746 sys_kevent(struct kevent_args *uap)
748 struct thread *td = curthread;
749 struct proc *p = td->td_proc;
750 struct timespec ts, *tsp;
752 struct file *fp = NULL;
753 struct kevent_copyin_args *kap, ka;
757 error = copyin(uap->timeout, &ts, sizeof(ts));
765 fp = holdfp(p->p_fd, uap->fd, -1);
768 if (fp->f_type != DTYPE_KQUEUE) {
773 kq = (struct kqueue *)fp->f_data;
779 error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
780 kevent_copyin, kevent_copyout, tsp);
788 kqueue_register(struct kqueue *kq, struct kevent *kev)
790 struct filedesc *fdp = kq->kq_fdp;
791 struct filterops *fops;
792 struct file *fp = NULL;
793 struct knote *kn = NULL;
796 if (kev->filter < 0) {
797 if (kev->filter + EVFILT_SYSCOUNT < 0)
799 fops = sysfilt_ops[~kev->filter]; /* to 0-base index */
803 * filter attach routine is responsible for insuring that
804 * the identifier can be attached to it.
806 kprintf("unknown filter: %d\n", kev->filter);
810 lwkt_gettoken(&kq_token);
811 if (fops->f_flags & FILTEROP_ISFD) {
812 /* validate descriptor */
813 fp = holdfp(fdp, kev->ident, -1);
815 lwkt_reltoken(&kq_token);
820 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
821 if (kn->kn_kq == kq &&
822 kn->kn_filter == kev->filter &&
823 kn->kn_id == kev->ident) {
824 if (knote_acquire(kn) == 0)
830 if (kq->kq_knhashmask) {
833 list = &kq->kq_knhash[
834 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
836 SLIST_FOREACH(kn, list, kn_link) {
837 if (kn->kn_id == kev->ident &&
838 kn->kn_filter == kev->filter) {
839 if (knote_acquire(kn) == 0)
848 * NOTE: At this point if kn is non-NULL we will have acquired
849 * it and set KN_PROCESSING.
851 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
857 * kn now contains the matching knote, or NULL if no match
859 if (kev->flags & EV_ADD) {
871 * apply reference count to knote structure, and
872 * do not release it at the end of this routine.
876 kn->kn_sfflags = kev->fflags;
877 kn->kn_sdata = kev->data;
880 kn->kn_kevent = *kev;
883 * KN_PROCESSING prevents the knote from getting
884 * ripped out from under us while we are trying
885 * to attach it, in case the attach blocks.
887 kn->kn_status = KN_PROCESSING;
889 if ((error = filter_attach(kn)) != 0) {
890 kn->kn_status |= KN_DELETING | KN_REPROCESS;
896 * Interlock against close races which either tried
897 * to remove our knote while we were blocked or missed
898 * it entirely prior to our attachment. We do not
899 * want to end up with a knote on a closed descriptor.
901 if ((fops->f_flags & FILTEROP_ISFD) &&
902 checkfdclosed(fdp, kev->ident, kn->kn_fp)) {
903 kn->kn_status |= KN_DELETING | KN_REPROCESS;
907 * The user may change some filter values after the
908 * initial EV_ADD, but doing so will not reset any
909 * filter which have already been triggered.
911 KKASSERT(kn->kn_status & KN_PROCESSING);
912 kn->kn_sfflags = kev->fflags;
913 kn->kn_sdata = kev->data;
914 kn->kn_kevent.udata = kev->udata;
918 * Execute the filter event to immediately activate the
919 * knote if necessary. If reprocessing events are pending
920 * due to blocking above we do not run the filter here
921 * but instead let knote_release() do it. Otherwise we
922 * might run the filter on a deleted event.
924 if ((kn->kn_status & KN_REPROCESS) == 0) {
925 if (filter_event(kn, 0))
928 } else if (kev->flags & EV_DELETE) {
930 * Delete the existing knote
932 knote_detach_and_drop(kn);
937 * Disablement does not deactivate a knote here.
939 if ((kev->flags & EV_DISABLE) &&
940 ((kn->kn_status & KN_DISABLED) == 0)) {
941 kn->kn_status |= KN_DISABLED;
945 * Re-enablement may have to immediately enqueue an active knote.
947 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
948 kn->kn_status &= ~KN_DISABLED;
949 if ((kn->kn_status & KN_ACTIVE) &&
950 ((kn->kn_status & KN_QUEUED) == 0)) {
956 * Handle any required reprocessing
959 /* kn may be invalid now */
962 lwkt_reltoken(&kq_token);
969 * Block as necessary until the target time is reached.
970 * If tsp is NULL we block indefinitely. If tsp->ts_secs/nsecs are both
971 * 0 we do not block at all.
974 kqueue_sleep(struct kqueue *kq, struct timespec *tsp)
979 kq->kq_state |= KQ_SLEEP;
980 error = tsleep(kq, PCATCH, "kqread", 0);
981 } else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
985 struct timespec atx = *tsp;
989 timespecsub(&atx, &ats);
990 if (ats.tv_sec < 0) {
993 timeout = atx.tv_sec > 24 * 60 * 60 ?
994 24 * 60 * 60 * hz : tstohz_high(&atx);
995 kq->kq_state |= KQ_SLEEP;
996 error = tsleep(kq, PCATCH, "kqread", timeout);
1000 /* don't restart after signals... */
1001 if (error == ERESTART)
1008 * Scan the kqueue, return the number of active events placed in kevp up
1011 * Continuous mode events may get recycled, do not continue scanning past
1012 * marker unless no events have been collected.
1015 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
1016 struct knote *marker)
1018 struct knote *kn, local_marker;
1022 local_marker.kn_filter = EVFILT_MARKER;
1023 local_marker.kn_status = KN_PROCESSING;
1028 TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
1030 kn = TAILQ_NEXT(&local_marker, kn_tqe);
1031 if (kn->kn_filter == EVFILT_MARKER) {
1032 /* Marker reached, we are done */
1036 /* Move local marker past some other threads marker */
1037 kn = TAILQ_NEXT(kn, kn_tqe);
1038 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1039 TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
1044 * We can't skip a knote undergoing processing, otherwise
1045 * we risk not returning it when the user process expects
1046 * it should be returned. Sleep and retry.
1048 if (knote_acquire(kn) == 0)
1052 * Remove the event for processing.
1054 * WARNING! We must leave KN_QUEUED set to prevent the
1055 * event from being KNOTE_ACTIVATE()d while
1056 * the queue state is in limbo, in case we
1059 * WARNING! We must set KN_PROCESSING to avoid races
1060 * against deletion or another thread's
1063 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1067 * We have to deal with an extremely important race against
1068 * file descriptor close()s here. The file descriptor can
1069 * disappear MPSAFE, and there is a small window of
1070 * opportunity between that and the call to knote_fdclose().
1072 * If we hit that window here while doselect or dopoll is
1073 * trying to delete a spurious event they will not be able
1074 * to match up the event against a knote and will go haywire.
1076 if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
1077 checkfdclosed(kq->kq_fdp, kn->kn_kevent.ident, kn->kn_fp)) {
1078 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1081 if (kn->kn_status & KN_DISABLED) {
1083 * If disabled we ensure the event is not queued
1084 * but leave its active bit set. On re-enablement
1085 * the event may be immediately triggered.
1087 kn->kn_status &= ~KN_QUEUED;
1088 } else if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1089 (kn->kn_status & KN_DELETING) == 0 &&
1090 filter_event(kn, 0) == 0) {
1092 * If not running in one-shot mode and the event
1093 * is no longer present we ensure it is removed
1094 * from the queue and ignore it.
1096 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1101 *kevp++ = kn->kn_kevent;
1105 if (kn->kn_flags & EV_ONESHOT) {
1106 kn->kn_status &= ~KN_QUEUED;
1107 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1108 } else if (kn->kn_flags & EV_CLEAR) {
1111 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1113 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1119 * Handle any post-processing states
1123 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1130 * This could be expanded to call kqueue_scan, if desired.
1135 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1144 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1153 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1154 struct ucred *cred, struct sysmsg *msg)
1159 lwkt_gettoken(&kq_token);
1160 kq = (struct kqueue *)fp->f_data;
1165 kq->kq_state |= KQ_ASYNC;
1167 kq->kq_state &= ~KQ_ASYNC;
1171 error = fsetown(*(int *)data, &kq->kq_sigio);
1177 lwkt_reltoken(&kq_token);
1185 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1187 struct kqueue *kq = (struct kqueue *)fp->f_data;
1189 bzero((void *)st, sizeof(*st));
1190 st->st_size = kq->kq_count;
1191 st->st_blksize = sizeof(struct kevent);
1192 st->st_mode = S_IFIFO;
1200 kqueue_close(struct file *fp)
1202 struct kqueue *kq = (struct kqueue *)fp->f_data;
1204 kqueue_terminate(kq);
1207 funsetown(kq->kq_sigio);
1209 kfree(kq, M_KQUEUE);
1214 kqueue_wakeup(struct kqueue *kq)
1216 if (kq->kq_state & KQ_SLEEP) {
1217 kq->kq_state &= ~KQ_SLEEP;
1220 KNOTE(&kq->kq_kqinfo.ki_note, 0);
1224 * Calls filterops f_attach function, acquiring mplock if filter is not
1225 * marked as FILTEROP_MPSAFE.
1228 filter_attach(struct knote *kn)
1232 if (!(kn->kn_fop->f_flags & FILTEROP_MPSAFE)) {
1234 ret = kn->kn_fop->f_attach(kn);
1237 ret = kn->kn_fop->f_attach(kn);
1244 * Detach the knote and drop it, destroying the knote.
1246 * Calls filterops f_detach function, acquiring mplock if filter is not
1247 * marked as FILTEROP_MPSAFE.
1250 knote_detach_and_drop(struct knote *kn)
1252 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1253 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1254 kn->kn_fop->f_detach(kn);
1257 kn->kn_fop->f_detach(kn);
1264 * Calls filterops f_event function, acquiring mplock if filter is not
1265 * marked as FILTEROP_MPSAFE.
1267 * If the knote is in the middle of being created or deleted we cannot
1268 * safely call the filter op.
1271 filter_event(struct knote *kn, long hint)
1275 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1276 ret = kn->kn_fop->f_event(kn, hint);
1279 ret = kn->kn_fop->f_event(kn, hint);
1286 * Walk down a list of knotes, activating them if their event has triggered.
1288 * If we encounter any knotes which are undergoing processing we just mark
1289 * them for reprocessing and do not try to [re]activate the knote. However,
1290 * if a hint is being passed we have to wait and that makes things a bit
1294 knote(struct klist *list, long hint)
1298 lwkt_gettoken(&kq_token);
1300 SLIST_FOREACH(kn, list, kn_next) {
1301 if (kn->kn_status & KN_PROCESSING) {
1303 * Someone else is processing the knote, ask the
1304 * other thread to reprocess it and don't mess
1305 * with it otherwise.
1308 kn->kn_status |= KN_REPROCESS;
1313 * If the hint is non-zero we have to wait or risk
1314 * losing the state the caller is trying to update.
1316 * XXX This is a real problem, certain process
1317 * and signal filters will bump kn_data for
1318 * already-processed notes more than once if
1319 * we restart the list scan. FIXME.
1321 kn->kn_status |= KN_WAITING | KN_REPROCESS;
1322 tsleep(kn, 0, "knotec", hz);
1327 * Become the reprocessing master ourselves.
1329 * If hint is non-zer running the event is mandatory
1330 * when not deleting so do it whether reprocessing is
1333 kn->kn_status |= KN_PROCESSING;
1334 if ((kn->kn_status & KN_DELETING) == 0) {
1335 if (filter_event(kn, hint))
1338 if (knote_release(kn))
1341 lwkt_reltoken(&kq_token);
1345 * Insert knote at head of klist.
1347 * This function may only be called via a filter function and thus
1348 * kq_token should already be held and marked for processing.
1351 knote_insert(struct klist *klist, struct knote *kn)
1353 KKASSERT(kn->kn_status & KN_PROCESSING);
1354 ASSERT_LWKT_TOKEN_HELD(&kq_token);
1355 SLIST_INSERT_HEAD(klist, kn, kn_next);
1359 * Remove knote from a klist
1361 * This function may only be called via a filter function and thus
1362 * kq_token should already be held and marked for processing.
1365 knote_remove(struct klist *klist, struct knote *kn)
1367 KKASSERT(kn->kn_status & KN_PROCESSING);
1368 ASSERT_LWKT_TOKEN_HELD(&kq_token);
1369 SLIST_REMOVE(klist, kn, knote, kn_next);
1373 * Remove all knotes from a specified klist
1375 * Only called from aio.
1378 knote_empty(struct klist *list)
1382 lwkt_gettoken(&kq_token);
1383 while ((kn = SLIST_FIRST(list)) != NULL) {
1384 if (knote_acquire(kn))
1385 knote_detach_and_drop(kn);
1387 lwkt_reltoken(&kq_token);
1391 knote_assume_knotes(struct kqinfo *src, struct kqinfo *dst,
1392 struct filterops *ops, void *hook)
1396 lwkt_gettoken(&kq_token);
1397 while ((kn = SLIST_FIRST(&src->ki_note)) != NULL) {
1398 if (knote_acquire(kn)) {
1399 knote_remove(&src->ki_note, kn);
1402 knote_insert(&dst->ki_note, kn);
1404 /* kn may be invalid now */
1407 lwkt_reltoken(&kq_token);
1411 * Remove all knotes referencing a specified fd
1414 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1418 lwkt_gettoken(&kq_token);
1420 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1421 if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1422 if (knote_acquire(kn))
1423 knote_detach_and_drop(kn);
1427 lwkt_reltoken(&kq_token);
1431 * Low level attach function.
1433 * The knote should already be marked for processing.
1436 knote_attach(struct knote *kn)
1439 struct kqueue *kq = kn->kn_kq;
1441 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1442 KKASSERT(kn->kn_fp);
1443 list = &kn->kn_fp->f_klist;
1445 if (kq->kq_knhashmask == 0)
1446 kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1447 &kq->kq_knhashmask);
1448 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1450 SLIST_INSERT_HEAD(list, kn, kn_link);
1451 TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1455 * Low level drop function.
1457 * The knote should already be marked for processing.
1460 knote_drop(struct knote *kn)
1467 if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1468 list = &kn->kn_fp->f_klist;
1470 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1472 SLIST_REMOVE(list, kn, knote, kn_link);
1473 TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1474 if (kn->kn_status & KN_QUEUED)
1476 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1484 * Low level enqueue function.
1486 * The knote should already be marked for processing.
1489 knote_enqueue(struct knote *kn)
1491 struct kqueue *kq = kn->kn_kq;
1493 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1494 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1495 kn->kn_status |= KN_QUEUED;
1499 * Send SIGIO on request (typically set up as a mailbox signal)
1501 if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1502 pgsigio(kq->kq_sigio, SIGIO, 0);
1508 * Low level dequeue function.
1510 * The knote should already be marked for processing.
1513 knote_dequeue(struct knote *kn)
1515 struct kqueue *kq = kn->kn_kq;
1517 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1518 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1519 kn->kn_status &= ~KN_QUEUED;
1526 knote_zone = zinit("KNOTE", sizeof(struct knote), 0, 0, 1);
1528 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL)
1530 static struct knote *
1533 return ((struct knote *)zalloc(knote_zone));
1537 knote_free(struct knote *kn)
1539 zfree(knote_zone, kn);