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 $
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/kernel.h>
33 #include <sys/malloc.h>
34 #include <sys/unistd.h>
37 #include <sys/fcntl.h>
38 #include <sys/queue.h>
39 #include <sys/event.h>
40 #include <sys/eventvar.h>
41 #include <sys/protosw.h>
42 #include <sys/socket.h>
43 #include <sys/socketvar.h>
45 #include <sys/sysctl.h>
46 #include <sys/sysproto.h>
47 #include <sys/thread.h>
49 #include <sys/signalvar.h>
50 #include <sys/filio.h>
53 #include <sys/thread2.h>
54 #include <sys/file2.h>
55 #include <sys/mplock2.h>
57 #define EVENT_REGISTER 1
58 #define EVENT_PROCESS 2
60 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
62 struct kevent_copyin_args {
63 struct kevent_args *ka;
67 static int kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
68 struct knote *marker);
69 static int kqueue_read(struct file *fp, struct uio *uio,
70 struct ucred *cred, int flags);
71 static int kqueue_write(struct file *fp, struct uio *uio,
72 struct ucred *cred, int flags);
73 static int kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
74 struct ucred *cred, struct sysmsg *msg);
75 static int kqueue_kqfilter(struct file *fp, struct knote *kn);
76 static int kqueue_stat(struct file *fp, struct stat *st,
78 static int kqueue_close(struct file *fp);
79 static void kqueue_wakeup(struct kqueue *kq);
80 static int filter_attach(struct knote *kn);
81 static int filter_event(struct knote *kn, long hint);
86 static struct fileops kqueueops = {
87 .fo_read = kqueue_read,
88 .fo_write = kqueue_write,
89 .fo_ioctl = kqueue_ioctl,
90 .fo_kqfilter = kqueue_kqfilter,
91 .fo_stat = kqueue_stat,
92 .fo_close = kqueue_close,
93 .fo_shutdown = nofo_shutdown
96 static void knote_attach(struct knote *kn);
97 static void knote_drop(struct knote *kn);
98 static void knote_detach_and_drop(struct knote *kn);
99 static void knote_enqueue(struct knote *kn);
100 static void knote_dequeue(struct knote *kn);
101 static struct knote *knote_alloc(void);
102 static void knote_free(struct knote *kn);
104 static void filt_kqdetach(struct knote *kn);
105 static int filt_kqueue(struct knote *kn, long hint);
106 static int filt_procattach(struct knote *kn);
107 static void filt_procdetach(struct knote *kn);
108 static int filt_proc(struct knote *kn, long hint);
109 static int filt_fileattach(struct knote *kn);
110 static void filt_timerexpire(void *knx);
111 static int filt_timerattach(struct knote *kn);
112 static void filt_timerdetach(struct knote *kn);
113 static int filt_timer(struct knote *kn, long hint);
114 static int filt_userattach(struct knote *kn);
115 static void filt_userdetach(struct knote *kn);
116 static int filt_user(struct knote *kn, long hint);
117 static void filt_usertouch(struct knote *kn, struct kevent *kev,
120 static struct filterops file_filtops =
121 { FILTEROP_ISFD | FILTEROP_MPSAFE, filt_fileattach, NULL, NULL };
122 static struct filterops kqread_filtops =
123 { FILTEROP_ISFD | FILTEROP_MPSAFE, NULL, filt_kqdetach, filt_kqueue };
124 static struct filterops proc_filtops =
125 { 0, filt_procattach, filt_procdetach, filt_proc };
126 static struct filterops timer_filtops =
127 { FILTEROP_MPSAFE, filt_timerattach, filt_timerdetach, filt_timer };
128 static struct filterops user_filtops =
129 { FILTEROP_MPSAFE, filt_userattach, filt_userdetach, filt_user };
131 static int kq_ncallouts = 0;
132 static int kq_calloutmax = (4 * 1024);
133 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
134 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
135 static int kq_checkloop = 1000000;
136 SYSCTL_INT(_kern, OID_AUTO, kq_checkloop, CTLFLAG_RW,
137 &kq_checkloop, 0, "Maximum number of loops for kqueue scan");
138 static int kq_wakeup_one = 1;
139 SYSCTL_INT(_kern, OID_AUTO, kq_wakeup_one, CTLFLAG_RW,
140 &kq_wakeup_one, 0, "Wakeup only one kqueue scanner");
142 #define KNOTE_ACTIVATE(kn) do { \
143 kn->kn_status |= KN_ACTIVE; \
144 if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
148 #define KN_HASHSIZE 64 /* XXX should be tunable */
149 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
151 extern struct filterops aio_filtops;
152 extern struct filterops sig_filtops;
155 * Table for for all system-defined filters.
157 static struct filterops *sysfilt_ops[] = {
158 &file_filtops, /* EVFILT_READ */
159 &file_filtops, /* EVFILT_WRITE */
160 &aio_filtops, /* EVFILT_AIO */
161 &file_filtops, /* EVFILT_VNODE */
162 &proc_filtops, /* EVFILT_PROC */
163 &sig_filtops, /* EVFILT_SIGNAL */
164 &timer_filtops, /* EVFILT_TIMER */
165 &file_filtops, /* EVFILT_EXCEPT */
166 &user_filtops, /* EVFILT_USER */
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 p = pfind(kn->kn_id);
217 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
218 p = zpfind(kn->kn_id);
224 if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
230 lwkt_gettoken(&p->p_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(&p->p_token);
259 * The knote may be attached to a different process, which may exit,
260 * leaving nothing for the knote to be attached to. So when the process
261 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
262 * it will be deleted when read out. However, as part of the knote deletion,
263 * this routine is called, so a check is needed to avoid actually performing
264 * a detach, because the original process does not exist any more.
267 filt_procdetach(struct knote *kn)
271 if (kn->kn_status & KN_DETACHED)
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) {
302 knote_remove(&p->p_klist, kn);
303 kn->kn_status |= KN_DETACHED;
304 kn->kn_data = p->p_xstat;
305 kn->kn_ptr.p_proc = NULL;
308 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
313 * process forked, and user wants to track the new process,
314 * so attach a new knote to it, and immediately report an
315 * event with the parent's pid.
317 if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
322 * register knote with new process.
324 kev.ident = hint & NOTE_PDATAMASK; /* pid */
325 kev.filter = kn->kn_filter;
326 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
327 kev.fflags = kn->kn_sfflags;
328 kev.data = kn->kn_id; /* parent */
329 kev.udata = kn->kn_kevent.udata; /* preserve udata */
330 error = kqueue_register(kn->kn_kq, &kev);
332 kn->kn_fflags |= NOTE_TRACKERR;
335 return (kn->kn_fflags != 0);
339 * The callout interlocks with callout_terminate() but can still
340 * race a deletion so if KN_DELETING is set we just don't touch
344 filt_timerexpire(void *knx)
346 struct lwkt_token *tok;
347 struct knote *kn = knx;
348 struct callout *calloutp;
352 tok = lwkt_token_pool_lookup(kn->kn_kq);
354 if ((kn->kn_status & KN_DELETING) == 0) {
358 if ((kn->kn_flags & EV_ONESHOT) == 0) {
359 tv.tv_sec = kn->kn_sdata / 1000;
360 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
361 tticks = tvtohz_high(&tv);
362 calloutp = (struct callout *)kn->kn_hook;
363 callout_reset(calloutp, tticks, filt_timerexpire, kn);
370 * data contains amount of time to sleep, in milliseconds
373 filt_timerattach(struct knote *kn)
375 struct callout *calloutp;
380 prev_ncallouts = atomic_fetchadd_int(&kq_ncallouts, 1);
381 if (prev_ncallouts >= kq_calloutmax) {
382 atomic_subtract_int(&kq_ncallouts, 1);
387 tv.tv_sec = kn->kn_sdata / 1000;
388 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
389 tticks = tvtohz_high(&tv);
391 kn->kn_flags |= EV_CLEAR; /* automatically set */
392 calloutp = kmalloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
393 callout_init_mp(calloutp);
394 kn->kn_hook = (caddr_t)calloutp;
395 callout_reset(calloutp, tticks, filt_timerexpire, kn);
401 * This function is called with the knote flagged locked but it is
402 * still possible to race a callout event due to the callback blocking.
403 * We must call callout_terminate() instead of callout_stop() to deal
407 filt_timerdetach(struct knote *kn)
409 struct callout *calloutp;
411 calloutp = (struct callout *)kn->kn_hook;
412 callout_terminate(calloutp);
413 kfree(calloutp, M_KQUEUE);
414 atomic_subtract_int(&kq_ncallouts, 1);
418 filt_timer(struct knote *kn, long hint)
421 return (kn->kn_data != 0);
428 filt_userattach(struct knote *kn)
431 if (kn->kn_fflags & NOTE_TRIGGER)
432 kn->kn_ptr.hookid = 1;
434 kn->kn_ptr.hookid = 0;
439 filt_userdetach(struct knote *kn)
445 filt_user(struct knote *kn, long hint)
447 return (kn->kn_ptr.hookid);
451 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
457 if (kev->fflags & NOTE_TRIGGER)
458 kn->kn_ptr.hookid = 1;
460 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
461 kev->fflags &= NOTE_FFLAGSMASK;
467 kn->kn_sfflags &= kev->fflags;
471 kn->kn_sfflags |= kev->fflags;
475 kn->kn_sfflags = kev->fflags;
479 /* XXX Return error? */
482 kn->kn_sdata = kev->data;
485 * This is not the correct use of EV_CLEAR in an event
486 * modification, it should have been passed as a NOTE instead.
487 * But we need to maintain compatibility with Apple & FreeBSD.
489 * Note however that EV_CLEAR can still be used when doing
490 * the initial registration of the event and works as expected
491 * (clears the event on reception).
493 if (kev->flags & EV_CLEAR) {
494 kn->kn_ptr.hookid = 0;
501 *kev = kn->kn_kevent;
502 kev->fflags = kn->kn_sfflags;
503 kev->data = kn->kn_sdata;
504 if (kn->kn_flags & EV_CLEAR) {
505 kn->kn_ptr.hookid = 0;
506 /* kn_data, kn_fflags handled by parent */
511 panic("filt_usertouch() - invalid type (%ld)", type);
517 * Acquire a knote, return non-zero on success, 0 on failure.
519 * If we cannot acquire the knote we sleep and return 0. The knote
520 * may be stale on return in this case and the caller must restart
521 * whatever loop they are in.
523 * Related kq token must be held.
526 knote_acquire(struct knote *kn)
528 if (kn->kn_status & KN_PROCESSING) {
529 kn->kn_status |= KN_WAITING | KN_REPROCESS;
530 tsleep(kn, 0, "kqepts", hz);
531 /* knote may be stale now */
534 kn->kn_status |= KN_PROCESSING;
539 * Release an acquired knote, clearing KN_PROCESSING and handling any
540 * KN_REPROCESS events.
542 * Caller must be holding the related kq token
544 * Non-zero is returned if the knote is destroyed or detached.
547 knote_release(struct knote *kn)
549 while (kn->kn_status & KN_REPROCESS) {
550 kn->kn_status &= ~KN_REPROCESS;
551 if (kn->kn_status & KN_WAITING) {
552 kn->kn_status &= ~KN_WAITING;
555 if (kn->kn_status & KN_DELETING) {
556 knote_detach_and_drop(kn);
560 if (filter_event(kn, 0))
563 kn->kn_status &= ~KN_PROCESSING;
564 if (kn->kn_status & KN_DETACHED)
571 * Initialize a kqueue.
573 * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
578 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
580 TAILQ_INIT(&kq->kq_knpend);
581 TAILQ_INIT(&kq->kq_knlist);
584 SLIST_INIT(&kq->kq_kqinfo.ki_note);
588 * Terminate a kqueue. Freeing the actual kq itself is left up to the
589 * caller (it might be embedded in a lwp so we don't do it here).
591 * The kq's knlist must be completely eradicated so block on any
595 kqueue_terminate(struct kqueue *kq)
597 struct lwkt_token *tok;
600 tok = lwkt_token_pool_lookup(kq);
602 while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
603 if (knote_acquire(kn))
604 knote_detach_and_drop(kn);
609 hashdestroy(kq->kq_knhash, M_KQUEUE, kq->kq_knhashmask);
610 kq->kq_knhash = NULL;
611 kq->kq_knhashmask = 0;
619 sys_kqueue(struct kqueue_args *uap)
621 struct thread *td = curthread;
626 error = falloc(td->td_lwp, &fp, &fd);
629 fp->f_flag = FREAD | FWRITE;
630 fp->f_type = DTYPE_KQUEUE;
631 fp->f_ops = &kqueueops;
633 kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
634 kqueue_init(kq, td->td_proc->p_fd);
637 fsetfd(kq->kq_fdp, fp, fd);
638 uap->sysmsg_result = fd;
644 * Copy 'count' items into the destination list pointed to by uap->eventlist.
647 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
649 struct kevent_copyin_args *kap;
652 kap = (struct kevent_copyin_args *)arg;
654 error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
656 kap->ka->eventlist += count;
666 * Copy at most 'max' items from the list pointed to by kap->changelist,
667 * return number of items in 'events'.
670 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
672 struct kevent_copyin_args *kap;
675 kap = (struct kevent_copyin_args *)arg;
677 count = min(kap->ka->nchanges - kap->pchanges, max);
678 error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
680 kap->ka->changelist += count;
681 kap->pchanges += count;
692 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
693 k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
694 struct timespec *tsp_in)
697 struct timespec *tsp, ats;
698 int i, n, total, error, nerrors = 0;
700 int limit = kq_checkloop;
701 struct kevent kev[KQ_NEVENTS];
703 struct lwkt_token *tok;
705 if (tsp_in == NULL || tsp_in->tv_sec || tsp_in->tv_nsec)
706 atomic_set_int(&curthread->td_mpflags, TDF_MP_BATCH_DEMARC);
713 error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
718 for (i = 0; i < n; i++) {
720 kevp->flags &= ~EV_SYSFLAGS;
721 error = kqueue_register(kq, kevp);
724 * If a registration returns an error we
725 * immediately post the error. The kevent()
726 * call itself will fail with the error if
727 * no space is available for posting.
729 * Such errors normally bypass the timeout/blocking
730 * code. However, if the copyoutfn function refuses
731 * to post the error (see sys_poll()), then we
734 if (error || (kevp->flags & EV_RECEIPT)) {
735 kevp->flags = EV_ERROR;
738 kevent_copyoutfn(uap, kevp, 1, res);
741 } else if (lres != *res) {
752 * Acquire/wait for events - setup timeout
755 if (tsp->tv_sec || tsp->tv_nsec) {
757 timespecadd(tsp, &ats); /* tsp = target time */
764 * Collect as many events as we can. Sleeping on successive
765 * loops is disabled if copyoutfn has incremented (*res).
767 * The loop stops if an error occurs, all events have been
768 * scanned (the marker has been reached), or fewer than the
769 * maximum number of events is found.
771 * The copyoutfn function does not have to increment (*res) in
772 * order for the loop to continue.
774 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
778 marker.kn_filter = EVFILT_MARKER;
779 marker.kn_status = KN_PROCESSING;
780 tok = lwkt_token_pool_lookup(kq);
782 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
784 while ((n = nevents - total) > 0) {
789 * If no events are pending sleep until timeout (if any)
790 * or an event occurs.
792 * After the sleep completes the marker is moved to the
793 * end of the list, making any received events available
796 if (kq->kq_count == 0 && *res == 0) {
801 } else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
805 struct timespec atx = *tsp;
808 timespecsub(&atx, &ats);
809 if (atx.tv_sec < 0) {
813 timeout = atx.tv_sec > 24 * 60 * 60 ?
820 if (kq->kq_count == 0) {
821 kq->kq_state |= KQ_SLEEP;
822 error = tsleep(kq, PCATCH, "kqread", timeout);
824 /* don't restart after signals... */
825 if (error == ERESTART)
832 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
833 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker,
840 * Process all received events
841 * Account for all non-spurious events in our total
843 i = kqueue_scan(kq, kev, n, &marker);
846 error = kevent_copyoutfn(uap, kev, i, res);
847 total += *res - lres;
851 if (limit && --limit == 0)
852 panic("kqueue: checkloop failed i=%d", i);
855 * Normally when fewer events are returned than requested
856 * we can stop. However, if only spurious events were
857 * collected the copyout will not bump (*res) and we have
864 * Deal with an edge case where spurious events can cause
865 * a loop to occur without moving the marker. This can
866 * prevent kqueue_scan() from picking up new events which
867 * race us. We must be sure to move the marker for this
870 * NOTE: We do not want to move the marker if events
871 * were scanned because normal kqueue operations
872 * may reactivate events. Moving the marker in
873 * that case could result in duplicates for the
878 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
879 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
884 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
887 /* Timeouts do not return EWOULDBLOCK. */
888 if (error == EWOULDBLOCK)
897 sys_kevent(struct kevent_args *uap)
899 struct thread *td = curthread;
900 struct proc *p = td->td_proc;
901 struct timespec ts, *tsp;
903 struct file *fp = NULL;
904 struct kevent_copyin_args *kap, ka;
908 error = copyin(uap->timeout, &ts, sizeof(ts));
915 fp = holdfp(p->p_fd, uap->fd, -1);
918 if (fp->f_type != DTYPE_KQUEUE) {
923 kq = (struct kqueue *)fp->f_data;
929 error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
930 kevent_copyin, kevent_copyout, tsp);
938 kqueue_register(struct kqueue *kq, struct kevent *kev)
940 struct lwkt_token *tok;
941 struct filedesc *fdp = kq->kq_fdp;
942 struct filterops *fops;
943 struct file *fp = NULL;
944 struct knote *kn = NULL;
947 if (kev->filter < 0) {
948 if (kev->filter + EVFILT_SYSCOUNT < 0)
950 fops = sysfilt_ops[~kev->filter]; /* to 0-base index */
954 * filter attach routine is responsible for insuring that
955 * the identifier can be attached to it.
960 tok = lwkt_token_pool_lookup(kq);
962 if (fops->f_flags & FILTEROP_ISFD) {
963 /* validate descriptor */
964 fp = holdfp(fdp, kev->ident, -1);
969 lwkt_getpooltoken(&fp->f_klist);
971 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
972 if (kn->kn_kq == kq &&
973 kn->kn_filter == kev->filter &&
974 kn->kn_id == kev->ident) {
975 if (knote_acquire(kn) == 0)
980 lwkt_relpooltoken(&fp->f_klist);
982 if (kq->kq_knhashmask) {
985 list = &kq->kq_knhash[
986 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
987 lwkt_getpooltoken(list);
989 SLIST_FOREACH(kn, list, kn_link) {
990 if (kn->kn_id == kev->ident &&
991 kn->kn_filter == kev->filter) {
992 if (knote_acquire(kn) == 0)
997 lwkt_relpooltoken(list);
1002 * NOTE: At this point if kn is non-NULL we will have acquired
1003 * it and set KN_PROCESSING.
1005 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
1011 * kn now contains the matching knote, or NULL if no match
1013 if (kev->flags & EV_ADD) {
1021 * apply reference count to knote structure, and
1022 * do not release it at the end of this routine.
1026 kn->kn_sfflags = kev->fflags;
1027 kn->kn_sdata = kev->data;
1030 kn->kn_kevent = *kev;
1033 * KN_PROCESSING prevents the knote from getting
1034 * ripped out from under us while we are trying
1035 * to attach it, in case the attach blocks.
1037 kn->kn_status = KN_PROCESSING;
1039 if ((error = filter_attach(kn)) != 0) {
1040 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1046 * Interlock against close races which either tried
1047 * to remove our knote while we were blocked or missed
1048 * it entirely prior to our attachment. We do not
1049 * want to end up with a knote on a closed descriptor.
1051 if ((fops->f_flags & FILTEROP_ISFD) &&
1052 checkfdclosed(fdp, kev->ident, kn->kn_fp)) {
1053 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1057 * The user may change some filter values after the
1058 * initial EV_ADD, but doing so will not reset any
1059 * filter which have already been triggered.
1061 KKASSERT(kn->kn_status & KN_PROCESSING);
1062 if (fops == &user_filtops) {
1063 filt_usertouch(kn, kev, EVENT_REGISTER);
1065 kn->kn_sfflags = kev->fflags;
1066 kn->kn_sdata = kev->data;
1067 kn->kn_kevent.udata = kev->udata;
1072 * Execute the filter event to immediately activate the
1073 * knote if necessary. If reprocessing events are pending
1074 * due to blocking above we do not run the filter here
1075 * but instead let knote_release() do it. Otherwise we
1076 * might run the filter on a deleted event.
1078 if ((kn->kn_status & KN_REPROCESS) == 0) {
1079 if (filter_event(kn, 0))
1082 } else if (kev->flags & EV_DELETE) {
1084 * Delete the existing knote
1086 knote_detach_and_drop(kn);
1090 * Modify an existing event.
1092 * The user may change some filter values after the
1093 * initial EV_ADD, but doing so will not reset any
1094 * filter which have already been triggered.
1096 KKASSERT(kn->kn_status & KN_PROCESSING);
1097 if (fops == &user_filtops) {
1098 filt_usertouch(kn, kev, EVENT_REGISTER);
1100 kn->kn_sfflags = kev->fflags;
1101 kn->kn_sdata = kev->data;
1102 kn->kn_kevent.udata = kev->udata;
1106 * Execute the filter event to immediately activate the
1107 * knote if necessary. If reprocessing events are pending
1108 * due to blocking above we do not run the filter here
1109 * but instead let knote_release() do it. Otherwise we
1110 * might run the filter on a deleted event.
1112 if ((kn->kn_status & KN_REPROCESS) == 0) {
1113 if (filter_event(kn, 0))
1119 * Disablement does not deactivate a knote here.
1121 if ((kev->flags & EV_DISABLE) &&
1122 ((kn->kn_status & KN_DISABLED) == 0)) {
1123 kn->kn_status |= KN_DISABLED;
1127 * Re-enablement may have to immediately enqueue an active knote.
1129 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1130 kn->kn_status &= ~KN_DISABLED;
1131 if ((kn->kn_status & KN_ACTIVE) &&
1132 ((kn->kn_status & KN_QUEUED) == 0)) {
1138 * Handle any required reprocessing
1141 /* kn may be invalid now */
1151 * Scan the kqueue, return the number of active events placed in kevp up
1154 * Continuous mode events may get recycled, do not continue scanning past
1155 * marker unless no events have been collected.
1158 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
1159 struct knote *marker)
1161 struct knote *kn, local_marker;
1165 local_marker.kn_filter = EVFILT_MARKER;
1166 local_marker.kn_status = KN_PROCESSING;
1168 lwkt_getpooltoken(kq);
1173 TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
1175 kn = TAILQ_NEXT(&local_marker, kn_tqe);
1176 if (kn->kn_filter == EVFILT_MARKER) {
1177 /* Marker reached, we are done */
1181 /* Move local marker past some other threads marker */
1182 kn = TAILQ_NEXT(kn, kn_tqe);
1183 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1184 TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
1189 * We can't skip a knote undergoing processing, otherwise
1190 * we risk not returning it when the user process expects
1191 * it should be returned. Sleep and retry.
1193 if (knote_acquire(kn) == 0)
1197 * Remove the event for processing.
1199 * WARNING! We must leave KN_QUEUED set to prevent the
1200 * event from being KNOTE_ACTIVATE()d while
1201 * the queue state is in limbo, in case we
1204 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1208 * We have to deal with an extremely important race against
1209 * file descriptor close()s here. The file descriptor can
1210 * disappear MPSAFE, and there is a small window of
1211 * opportunity between that and the call to knote_fdclose().
1213 * If we hit that window here while doselect or dopoll is
1214 * trying to delete a spurious event they will not be able
1215 * to match up the event against a knote and will go haywire.
1217 if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
1218 checkfdclosed(kq->kq_fdp, kn->kn_kevent.ident, kn->kn_fp)) {
1219 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1222 if (kn->kn_status & KN_DISABLED) {
1224 * If disabled we ensure the event is not queued
1225 * but leave its active bit set. On re-enablement
1226 * the event may be immediately triggered.
1228 kn->kn_status &= ~KN_QUEUED;
1229 } else if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1230 (kn->kn_status & KN_DELETING) == 0 &&
1231 filter_event(kn, 0) == 0) {
1233 * If not running in one-shot mode and the event
1234 * is no longer present we ensure it is removed
1235 * from the queue and ignore it.
1237 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1242 if (kn->kn_fop == &user_filtops)
1243 filt_usertouch(kn, kevp, EVENT_PROCESS);
1245 *kevp = kn->kn_kevent;
1250 if (kn->kn_flags & EV_ONESHOT) {
1251 kn->kn_status &= ~KN_QUEUED;
1252 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1254 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1255 if (kn->kn_flags & EV_CLEAR) {
1259 if (kn->kn_flags & EV_DISPATCH) {
1260 kn->kn_status |= KN_DISABLED;
1262 kn->kn_status &= ~(KN_QUEUED |
1265 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1272 * Handle any post-processing states
1276 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1278 lwkt_relpooltoken(kq);
1284 * This could be expanded to call kqueue_scan, if desired.
1289 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1298 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1307 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1308 struct ucred *cred, struct sysmsg *msg)
1310 struct lwkt_token *tok;
1314 kq = (struct kqueue *)fp->f_data;
1315 tok = lwkt_token_pool_lookup(kq);
1321 kq->kq_state |= KQ_ASYNC;
1323 kq->kq_state &= ~KQ_ASYNC;
1327 error = fsetown(*(int *)data, &kq->kq_sigio);
1341 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1343 struct kqueue *kq = (struct kqueue *)fp->f_data;
1345 bzero((void *)st, sizeof(*st));
1346 st->st_size = kq->kq_count;
1347 st->st_blksize = sizeof(struct kevent);
1348 st->st_mode = S_IFIFO;
1356 kqueue_close(struct file *fp)
1358 struct kqueue *kq = (struct kqueue *)fp->f_data;
1360 kqueue_terminate(kq);
1363 funsetown(&kq->kq_sigio);
1365 kfree(kq, M_KQUEUE);
1370 kqueue_wakeup(struct kqueue *kq)
1372 if (kq->kq_state & KQ_SLEEP) {
1373 kq->kq_state &= ~KQ_SLEEP;
1379 KNOTE(&kq->kq_kqinfo.ki_note, 0);
1383 * Calls filterops f_attach function, acquiring mplock if filter is not
1384 * marked as FILTEROP_MPSAFE.
1386 * Caller must be holding the related kq token
1389 filter_attach(struct knote *kn)
1393 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1394 ret = kn->kn_fop->f_attach(kn);
1397 ret = kn->kn_fop->f_attach(kn);
1404 * Detach the knote and drop it, destroying the knote.
1406 * Calls filterops f_detach function, acquiring mplock if filter is not
1407 * marked as FILTEROP_MPSAFE.
1409 * Caller must be holding the related kq token
1412 knote_detach_and_drop(struct knote *kn)
1414 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1415 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1416 kn->kn_fop->f_detach(kn);
1419 kn->kn_fop->f_detach(kn);
1426 * Calls filterops f_event function, acquiring mplock if filter is not
1427 * marked as FILTEROP_MPSAFE.
1429 * If the knote is in the middle of being created or deleted we cannot
1430 * safely call the filter op.
1432 * Caller must be holding the related kq token
1435 filter_event(struct knote *kn, long hint)
1439 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1440 ret = kn->kn_fop->f_event(kn, hint);
1443 ret = kn->kn_fop->f_event(kn, hint);
1450 * Walk down a list of knotes, activating them if their event has triggered.
1452 * If we encounter any knotes which are undergoing processing we just mark
1453 * them for reprocessing and do not try to [re]activate the knote. However,
1454 * if a hint is being passed we have to wait and that makes things a bit
1458 knote(struct klist *list, long hint)
1462 struct knote *kntmp;
1464 lwkt_getpooltoken(list);
1466 SLIST_FOREACH(kn, list, kn_next) {
1468 lwkt_getpooltoken(kq);
1470 /* temporary verification hack */
1471 SLIST_FOREACH(kntmp, list, kn_next) {
1475 if (kn != kntmp || kn->kn_kq != kq) {
1476 lwkt_relpooltoken(kq);
1480 if (kn->kn_status & KN_PROCESSING) {
1482 * Someone else is processing the knote, ask the
1483 * other thread to reprocess it and don't mess
1484 * with it otherwise.
1487 kn->kn_status |= KN_REPROCESS;
1488 lwkt_relpooltoken(kq);
1493 * If the hint is non-zero we have to wait or risk
1494 * losing the state the caller is trying to update.
1496 * XXX This is a real problem, certain process
1497 * and signal filters will bump kn_data for
1498 * already-processed notes more than once if
1499 * we restart the list scan. FIXME.
1501 kn->kn_status |= KN_WAITING | KN_REPROCESS;
1502 tsleep(kn, 0, "knotec", hz);
1503 lwkt_relpooltoken(kq);
1508 * Become the reprocessing master ourselves.
1510 * If hint is non-zero running the event is mandatory
1511 * when not deleting so do it whether reprocessing is
1514 kn->kn_status |= KN_PROCESSING;
1515 if ((kn->kn_status & KN_DELETING) == 0) {
1516 if (filter_event(kn, hint))
1519 if (knote_release(kn)) {
1520 lwkt_relpooltoken(kq);
1523 lwkt_relpooltoken(kq);
1525 lwkt_relpooltoken(list);
1529 * Insert knote at head of klist.
1531 * This function may only be called via a filter function and thus
1532 * kq_token should already be held and marked for processing.
1535 knote_insert(struct klist *klist, struct knote *kn)
1537 lwkt_getpooltoken(klist);
1538 KKASSERT(kn->kn_status & KN_PROCESSING);
1539 SLIST_INSERT_HEAD(klist, kn, kn_next);
1540 lwkt_relpooltoken(klist);
1544 * Remove knote from a klist
1546 * This function may only be called via a filter function and thus
1547 * kq_token should already be held and marked for processing.
1550 knote_remove(struct klist *klist, struct knote *kn)
1552 lwkt_getpooltoken(klist);
1553 KKASSERT(kn->kn_status & KN_PROCESSING);
1554 SLIST_REMOVE(klist, kn, knote, kn_next);
1555 lwkt_relpooltoken(klist);
1560 * Remove all knotes from a specified klist
1562 * Only called from aio.
1565 knote_empty(struct klist *list)
1569 lwkt_gettoken(&kq_token);
1570 while ((kn = SLIST_FIRST(list)) != NULL) {
1571 if (knote_acquire(kn))
1572 knote_detach_and_drop(kn);
1574 lwkt_reltoken(&kq_token);
1579 knote_assume_knotes(struct kqinfo *src, struct kqinfo *dst,
1580 struct filterops *ops, void *hook)
1585 lwkt_getpooltoken(&src->ki_note);
1586 lwkt_getpooltoken(&dst->ki_note);
1587 while ((kn = SLIST_FIRST(&src->ki_note)) != NULL) {
1589 lwkt_getpooltoken(kq);
1590 if (SLIST_FIRST(&src->ki_note) != kn || kn->kn_kq != kq) {
1591 lwkt_relpooltoken(kq);
1594 if (knote_acquire(kn)) {
1595 knote_remove(&src->ki_note, kn);
1598 knote_insert(&dst->ki_note, kn);
1600 /* kn may be invalid now */
1602 lwkt_relpooltoken(kq);
1604 lwkt_relpooltoken(&dst->ki_note);
1605 lwkt_relpooltoken(&src->ki_note);
1609 * Remove all knotes referencing a specified fd
1612 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1616 struct knote *kntmp;
1618 lwkt_getpooltoken(&fp->f_klist);
1620 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1621 if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1623 lwkt_getpooltoken(kq);
1625 /* temporary verification hack */
1626 SLIST_FOREACH(kntmp, &fp->f_klist, kn_link) {
1630 if (kn != kntmp || kn->kn_kq->kq_fdp != fdp ||
1631 kn->kn_id != fd || kn->kn_kq != kq) {
1632 lwkt_relpooltoken(kq);
1635 if (knote_acquire(kn))
1636 knote_detach_and_drop(kn);
1637 lwkt_relpooltoken(kq);
1641 lwkt_relpooltoken(&fp->f_klist);
1645 * Low level attach function.
1647 * The knote should already be marked for processing.
1648 * Caller must hold the related kq token.
1651 knote_attach(struct knote *kn)
1654 struct kqueue *kq = kn->kn_kq;
1656 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1657 KKASSERT(kn->kn_fp);
1658 list = &kn->kn_fp->f_klist;
1660 if (kq->kq_knhashmask == 0)
1661 kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1662 &kq->kq_knhashmask);
1663 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1665 lwkt_getpooltoken(list);
1666 SLIST_INSERT_HEAD(list, kn, kn_link);
1667 lwkt_relpooltoken(list);
1668 TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1672 * Low level drop function.
1674 * The knote should already be marked for processing.
1675 * Caller must hold the related kq token.
1678 knote_drop(struct knote *kn)
1685 if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1686 list = &kn->kn_fp->f_klist;
1688 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1690 lwkt_getpooltoken(list);
1691 SLIST_REMOVE(list, kn, knote, kn_link);
1692 lwkt_relpooltoken(list);
1693 TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1694 if (kn->kn_status & KN_QUEUED)
1696 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1704 * Low level enqueue function.
1706 * The knote should already be marked for processing.
1707 * Caller must be holding the kq token
1710 knote_enqueue(struct knote *kn)
1712 struct kqueue *kq = kn->kn_kq;
1714 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1715 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1716 kn->kn_status |= KN_QUEUED;
1720 * Send SIGIO on request (typically set up as a mailbox signal)
1722 if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1723 pgsigio(kq->kq_sigio, SIGIO, 0);
1729 * Low level dequeue function.
1731 * The knote should already be marked for processing.
1732 * Caller must be holding the kq token
1735 knote_dequeue(struct knote *kn)
1737 struct kqueue *kq = kn->kn_kq;
1739 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1740 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1741 kn->kn_status &= ~KN_QUEUED;
1745 static struct knote *
1748 return kmalloc(sizeof(struct knote), M_KQUEUE, M_WAITOK);
1752 knote_free(struct knote *kn)
1754 kfree(kn, M_KQUEUE);