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 * Acquire a knote, return non-zero on success, 0 on failure.
172 * If we cannot acquire the knote we sleep and return 0. The knote
173 * may be stale on return in this case and the caller must restart
174 * whatever loop they are in.
176 * Related kq token must be held.
179 knote_acquire(struct knote *kn)
181 if (kn->kn_status & KN_PROCESSING) {
182 kn->kn_status |= KN_WAITING | KN_REPROCESS;
183 tsleep(kn, 0, "kqepts", hz);
184 /* knote may be stale now */
187 kn->kn_status |= KN_PROCESSING;
192 * Release an acquired knote, clearing KN_PROCESSING and handling any
193 * KN_REPROCESS events.
195 * Caller must be holding the related kq token
197 * Non-zero is returned if the knote is destroyed or detached.
200 knote_release(struct knote *kn)
202 while (kn->kn_status & KN_REPROCESS) {
203 kn->kn_status &= ~KN_REPROCESS;
204 if (kn->kn_status & KN_WAITING) {
205 kn->kn_status &= ~KN_WAITING;
208 if (kn->kn_status & KN_DELETING) {
209 knote_detach_and_drop(kn);
213 if (filter_event(kn, 0))
216 kn->kn_status &= ~KN_PROCESSING;
217 /* kn should not be accessed anymore */
221 filt_fileattach(struct knote *kn)
223 return (fo_kqfilter(kn->kn_fp, kn));
230 kqueue_kqfilter(struct file *fp, struct knote *kn)
232 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
234 if (kn->kn_filter != EVFILT_READ)
237 kn->kn_fop = &kqread_filtops;
238 knote_insert(&kq->kq_kqinfo.ki_note, kn);
243 filt_kqdetach(struct knote *kn)
245 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
247 knote_remove(&kq->kq_kqinfo.ki_note, kn);
252 filt_kqueue(struct knote *kn, long hint)
254 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
256 kn->kn_data = kq->kq_count;
257 return (kn->kn_data > 0);
261 filt_procattach(struct knote *kn)
267 p = pfind(kn->kn_id);
268 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
269 p = zpfind(kn->kn_id);
275 if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
281 lwkt_gettoken(&p->p_token);
282 kn->kn_ptr.p_proc = p;
283 kn->kn_flags |= EV_CLEAR; /* automatically set */
286 * internal flag indicating registration done by kernel
288 if (kn->kn_flags & EV_FLAG1) {
289 kn->kn_data = kn->kn_sdata; /* ppid */
290 kn->kn_fflags = NOTE_CHILD;
291 kn->kn_flags &= ~EV_FLAG1;
294 knote_insert(&p->p_klist, kn);
297 * Immediately activate any exit notes if the target process is a
298 * zombie. This is necessary to handle the case where the target
299 * process, e.g. a child, dies before the kevent is negistered.
301 if (immediate && filt_proc(kn, NOTE_EXIT))
303 lwkt_reltoken(&p->p_token);
310 * The knote may be attached to a different process, which may exit,
311 * leaving nothing for the knote to be attached to. So when the process
312 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
313 * it will be deleted when read out. However, as part of the knote deletion,
314 * this routine is called, so a check is needed to avoid actually performing
315 * a detach, because the original process does not exist any more.
318 filt_procdetach(struct knote *kn)
322 if (kn->kn_status & KN_DETACHED)
324 p = kn->kn_ptr.p_proc;
325 knote_remove(&p->p_klist, kn);
329 filt_proc(struct knote *kn, long hint)
334 * mask off extra data
336 event = (u_int)hint & NOTE_PCTRLMASK;
339 * if the user is interested in this event, record it.
341 if (kn->kn_sfflags & event)
342 kn->kn_fflags |= event;
345 * Process is gone, so flag the event as finished. Detach the
346 * knote from the process now because the process will be poof,
349 if (event == NOTE_EXIT) {
350 struct proc *p = kn->kn_ptr.p_proc;
351 if ((kn->kn_status & KN_DETACHED) == 0) {
353 knote_remove(&p->p_klist, kn);
354 kn->kn_status |= KN_DETACHED;
355 kn->kn_data = p->p_xstat;
356 kn->kn_ptr.p_proc = NULL;
359 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
364 * process forked, and user wants to track the new process,
365 * so attach a new knote to it, and immediately report an
366 * event with the parent's pid.
368 if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
373 * register knote with new process.
375 kev.ident = hint & NOTE_PDATAMASK; /* pid */
376 kev.filter = kn->kn_filter;
377 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
378 kev.fflags = kn->kn_sfflags;
379 kev.data = kn->kn_id; /* parent */
380 kev.udata = kn->kn_kevent.udata; /* preserve udata */
381 error = kqueue_register(kn->kn_kq, &kev);
383 kn->kn_fflags |= NOTE_TRACKERR;
386 return (kn->kn_fflags != 0);
390 filt_timerreset(struct knote *kn)
392 struct callout *calloutp;
396 tv.tv_sec = kn->kn_sdata / 1000;
397 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
398 tticks = tvtohz_high(&tv);
399 calloutp = (struct callout *)kn->kn_hook;
400 callout_reset(calloutp, tticks, filt_timerexpire, kn);
404 * The callout interlocks with callout_terminate() but can still
405 * race a deletion so if KN_DELETING is set we just don't touch
409 filt_timerexpire(void *knx)
411 struct knote *kn = knx;
412 struct kqueue *kq = kn->kn_kq;
414 lwkt_getpooltoken(kq);
417 * Open knote_acquire(), since we can't sleep in callout,
418 * however, we do need to record this expiration.
421 if (kn->kn_status & KN_PROCESSING) {
422 kn->kn_status |= KN_REPROCESS;
423 if ((kn->kn_status & KN_DELETING) == 0 &&
424 (kn->kn_flags & EV_ONESHOT) == 0)
426 lwkt_relpooltoken(kq);
429 KASSERT((kn->kn_status & KN_DELETING) == 0,
430 ("acquire a deleting knote %#x", kn->kn_status));
431 kn->kn_status |= KN_PROCESSING;
434 if ((kn->kn_flags & EV_ONESHOT) == 0)
439 lwkt_relpooltoken(kq);
443 * data contains amount of time to sleep, in milliseconds
446 filt_timerattach(struct knote *kn)
448 struct callout *calloutp;
451 prev_ncallouts = atomic_fetchadd_int(&kq_ncallouts, 1);
452 if (prev_ncallouts >= kq_calloutmax) {
453 atomic_subtract_int(&kq_ncallouts, 1);
458 kn->kn_flags |= EV_CLEAR; /* automatically set */
459 calloutp = kmalloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
460 callout_init_mp(calloutp);
461 kn->kn_hook = (caddr_t)calloutp;
468 * This function is called with the knote flagged locked but it is
469 * still possible to race a callout event due to the callback blocking.
470 * We must call callout_terminate() instead of callout_stop() to deal
474 filt_timerdetach(struct knote *kn)
476 struct callout *calloutp;
478 calloutp = (struct callout *)kn->kn_hook;
479 callout_terminate(calloutp);
480 kfree(calloutp, M_KQUEUE);
481 atomic_subtract_int(&kq_ncallouts, 1);
485 filt_timer(struct knote *kn, long hint)
488 return (kn->kn_data != 0);
495 filt_userattach(struct knote *kn)
498 if (kn->kn_fflags & NOTE_TRIGGER)
499 kn->kn_ptr.hookid = 1;
501 kn->kn_ptr.hookid = 0;
506 filt_userdetach(struct knote *kn)
512 filt_user(struct knote *kn, long hint)
514 return (kn->kn_ptr.hookid);
518 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
524 if (kev->fflags & NOTE_TRIGGER)
525 kn->kn_ptr.hookid = 1;
527 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
528 kev->fflags &= NOTE_FFLAGSMASK;
534 kn->kn_sfflags &= kev->fflags;
538 kn->kn_sfflags |= kev->fflags;
542 kn->kn_sfflags = kev->fflags;
546 /* XXX Return error? */
549 kn->kn_sdata = kev->data;
552 * This is not the correct use of EV_CLEAR in an event
553 * modification, it should have been passed as a NOTE instead.
554 * But we need to maintain compatibility with Apple & FreeBSD.
556 * Note however that EV_CLEAR can still be used when doing
557 * the initial registration of the event and works as expected
558 * (clears the event on reception).
560 if (kev->flags & EV_CLEAR) {
561 kn->kn_ptr.hookid = 0;
568 *kev = kn->kn_kevent;
569 kev->fflags = kn->kn_sfflags;
570 kev->data = kn->kn_sdata;
571 if (kn->kn_flags & EV_CLEAR) {
572 kn->kn_ptr.hookid = 0;
573 /* kn_data, kn_fflags handled by parent */
578 panic("filt_usertouch() - invalid type (%ld)", type);
584 * Initialize a kqueue.
586 * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
591 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
593 TAILQ_INIT(&kq->kq_knpend);
594 TAILQ_INIT(&kq->kq_knlist);
597 SLIST_INIT(&kq->kq_kqinfo.ki_note);
601 * Terminate a kqueue. Freeing the actual kq itself is left up to the
602 * caller (it might be embedded in a lwp so we don't do it here).
604 * The kq's knlist must be completely eradicated so block on any
608 kqueue_terminate(struct kqueue *kq)
610 struct lwkt_token *tok;
613 tok = lwkt_token_pool_lookup(kq);
615 while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
616 if (knote_acquire(kn))
617 knote_detach_and_drop(kn);
622 hashdestroy(kq->kq_knhash, M_KQUEUE, kq->kq_knhashmask);
623 kq->kq_knhash = NULL;
624 kq->kq_knhashmask = 0;
632 sys_kqueue(struct kqueue_args *uap)
634 struct thread *td = curthread;
639 error = falloc(td->td_lwp, &fp, &fd);
642 fp->f_flag = FREAD | FWRITE;
643 fp->f_type = DTYPE_KQUEUE;
644 fp->f_ops = &kqueueops;
646 kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
647 kqueue_init(kq, td->td_proc->p_fd);
650 fsetfd(kq->kq_fdp, fp, fd);
651 uap->sysmsg_result = fd;
657 * Copy 'count' items into the destination list pointed to by uap->eventlist.
660 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
662 struct kevent_copyin_args *kap;
665 kap = (struct kevent_copyin_args *)arg;
667 error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
669 kap->ka->eventlist += count;
679 * Copy at most 'max' items from the list pointed to by kap->changelist,
680 * return number of items in 'events'.
683 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
685 struct kevent_copyin_args *kap;
688 kap = (struct kevent_copyin_args *)arg;
690 count = min(kap->ka->nchanges - kap->pchanges, max);
691 error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
693 kap->ka->changelist += count;
694 kap->pchanges += count;
705 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
706 k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
707 struct timespec *tsp_in)
710 struct timespec *tsp, ats;
711 int i, n, total, error, nerrors = 0;
713 int limit = kq_checkloop;
714 struct kevent kev[KQ_NEVENTS];
716 struct lwkt_token *tok;
718 if (tsp_in == NULL || tsp_in->tv_sec || tsp_in->tv_nsec)
719 atomic_set_int(&curthread->td_mpflags, TDF_MP_BATCH_DEMARC);
726 error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
731 for (i = 0; i < n; i++) {
733 kevp->flags &= ~EV_SYSFLAGS;
734 error = kqueue_register(kq, kevp);
737 * If a registration returns an error we
738 * immediately post the error. The kevent()
739 * call itself will fail with the error if
740 * no space is available for posting.
742 * Such errors normally bypass the timeout/blocking
743 * code. However, if the copyoutfn function refuses
744 * to post the error (see sys_poll()), then we
747 if (error || (kevp->flags & EV_RECEIPT)) {
748 kevp->flags = EV_ERROR;
751 kevent_copyoutfn(uap, kevp, 1, res);
754 } else if (lres != *res) {
765 * Acquire/wait for events - setup timeout
768 if (tsp->tv_sec || tsp->tv_nsec) {
770 timespecadd(tsp, &ats); /* tsp = target time */
777 * Collect as many events as we can. Sleeping on successive
778 * loops is disabled if copyoutfn has incremented (*res).
780 * The loop stops if an error occurs, all events have been
781 * scanned (the marker has been reached), or fewer than the
782 * maximum number of events is found.
784 * The copyoutfn function does not have to increment (*res) in
785 * order for the loop to continue.
787 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
791 marker.kn_filter = EVFILT_MARKER;
792 marker.kn_status = KN_PROCESSING;
793 tok = lwkt_token_pool_lookup(kq);
795 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
797 while ((n = nevents - total) > 0) {
802 * If no events are pending sleep until timeout (if any)
803 * or an event occurs.
805 * After the sleep completes the marker is moved to the
806 * end of the list, making any received events available
809 if (kq->kq_count == 0 && *res == 0) {
814 } else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
818 struct timespec atx = *tsp;
821 timespecsub(&atx, &ats);
822 if (atx.tv_sec < 0) {
826 timeout = atx.tv_sec > 24 * 60 * 60 ?
833 if (kq->kq_count == 0) {
834 kq->kq_state |= KQ_SLEEP;
835 error = tsleep(kq, PCATCH, "kqread", timeout);
837 /* don't restart after signals... */
838 if (error == ERESTART)
845 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
846 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker,
853 * Process all received events
854 * Account for all non-spurious events in our total
856 i = kqueue_scan(kq, kev, n, &marker);
859 error = kevent_copyoutfn(uap, kev, i, res);
860 total += *res - lres;
864 if (limit && --limit == 0)
865 panic("kqueue: checkloop failed i=%d", i);
868 * Normally when fewer events are returned than requested
869 * we can stop. However, if only spurious events were
870 * collected the copyout will not bump (*res) and we have
877 * Deal with an edge case where spurious events can cause
878 * a loop to occur without moving the marker. This can
879 * prevent kqueue_scan() from picking up new events which
880 * race us. We must be sure to move the marker for this
883 * NOTE: We do not want to move the marker if events
884 * were scanned because normal kqueue operations
885 * may reactivate events. Moving the marker in
886 * that case could result in duplicates for the
891 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
892 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
897 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
900 /* Timeouts do not return EWOULDBLOCK. */
901 if (error == EWOULDBLOCK)
910 sys_kevent(struct kevent_args *uap)
912 struct thread *td = curthread;
913 struct proc *p = td->td_proc;
914 struct timespec ts, *tsp;
916 struct file *fp = NULL;
917 struct kevent_copyin_args *kap, ka;
921 error = copyin(uap->timeout, &ts, sizeof(ts));
928 fp = holdfp(p->p_fd, uap->fd, -1);
931 if (fp->f_type != DTYPE_KQUEUE) {
936 kq = (struct kqueue *)fp->f_data;
942 error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
943 kevent_copyin, kevent_copyout, tsp);
951 kqueue_register(struct kqueue *kq, struct kevent *kev)
953 struct lwkt_token *tok;
954 struct filedesc *fdp = kq->kq_fdp;
955 struct filterops *fops;
956 struct file *fp = NULL;
957 struct knote *kn = NULL;
960 if (kev->filter < 0) {
961 if (kev->filter + EVFILT_SYSCOUNT < 0)
963 fops = sysfilt_ops[~kev->filter]; /* to 0-base index */
967 * filter attach routine is responsible for insuring that
968 * the identifier can be attached to it.
973 if (fops->f_flags & FILTEROP_ISFD) {
974 /* validate descriptor */
975 fp = holdfp(fdp, kev->ident, -1);
980 tok = lwkt_token_pool_lookup(kq);
983 lwkt_getpooltoken(&fp->f_klist);
985 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
986 if (kn->kn_kq == kq &&
987 kn->kn_filter == kev->filter &&
988 kn->kn_id == kev->ident) {
989 if (knote_acquire(kn) == 0)
994 lwkt_relpooltoken(&fp->f_klist);
996 if (kq->kq_knhashmask) {
999 list = &kq->kq_knhash[
1000 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1001 lwkt_getpooltoken(list);
1003 SLIST_FOREACH(kn, list, kn_link) {
1004 if (kn->kn_id == kev->ident &&
1005 kn->kn_filter == kev->filter) {
1006 if (knote_acquire(kn) == 0)
1011 lwkt_relpooltoken(list);
1016 * NOTE: At this point if kn is non-NULL we will have acquired
1017 * it and set KN_PROCESSING.
1019 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
1025 * kn now contains the matching knote, or NULL if no match
1027 if (kev->flags & EV_ADD) {
1035 * apply reference count to knote structure, and
1036 * do not release it at the end of this routine.
1040 kn->kn_sfflags = kev->fflags;
1041 kn->kn_sdata = kev->data;
1044 kn->kn_kevent = *kev;
1047 * KN_PROCESSING prevents the knote from getting
1048 * ripped out from under us while we are trying
1049 * to attach it, in case the attach blocks.
1051 kn->kn_status = KN_PROCESSING;
1053 if ((error = filter_attach(kn)) != 0) {
1054 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1060 * Interlock against close races which either tried
1061 * to remove our knote while we were blocked or missed
1062 * it entirely prior to our attachment. We do not
1063 * want to end up with a knote on a closed descriptor.
1065 if ((fops->f_flags & FILTEROP_ISFD) &&
1066 checkfdclosed(fdp, kev->ident, kn->kn_fp)) {
1067 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1071 * The user may change some filter values after the
1072 * initial EV_ADD, but doing so will not reset any
1073 * filter which have already been triggered.
1075 KKASSERT(kn->kn_status & KN_PROCESSING);
1076 if (fops == &user_filtops) {
1077 filt_usertouch(kn, kev, EVENT_REGISTER);
1079 kn->kn_sfflags = kev->fflags;
1080 kn->kn_sdata = kev->data;
1081 kn->kn_kevent.udata = kev->udata;
1086 * Execute the filter event to immediately activate the
1087 * knote if necessary. If reprocessing events are pending
1088 * due to blocking above we do not run the filter here
1089 * but instead let knote_release() do it. Otherwise we
1090 * might run the filter on a deleted event.
1092 if ((kn->kn_status & KN_REPROCESS) == 0) {
1093 if (filter_event(kn, 0))
1096 } else if (kev->flags & EV_DELETE) {
1098 * Delete the existing knote
1100 knote_detach_and_drop(kn);
1104 * Modify an existing event.
1106 * The user may change some filter values after the
1107 * initial EV_ADD, but doing so will not reset any
1108 * filter which have already been triggered.
1110 KKASSERT(kn->kn_status & KN_PROCESSING);
1111 if (fops == &user_filtops) {
1112 filt_usertouch(kn, kev, EVENT_REGISTER);
1114 kn->kn_sfflags = kev->fflags;
1115 kn->kn_sdata = kev->data;
1116 kn->kn_kevent.udata = kev->udata;
1120 * Execute the filter event to immediately activate the
1121 * knote if necessary. If reprocessing events are pending
1122 * due to blocking above we do not run the filter here
1123 * but instead let knote_release() do it. Otherwise we
1124 * might run the filter on a deleted event.
1126 if ((kn->kn_status & KN_REPROCESS) == 0) {
1127 if (filter_event(kn, 0))
1133 * Disablement does not deactivate a knote here.
1135 if ((kev->flags & EV_DISABLE) &&
1136 ((kn->kn_status & KN_DISABLED) == 0)) {
1137 kn->kn_status |= KN_DISABLED;
1141 * Re-enablement may have to immediately enqueue an active knote.
1143 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1144 kn->kn_status &= ~KN_DISABLED;
1145 if ((kn->kn_status & KN_ACTIVE) &&
1146 ((kn->kn_status & KN_QUEUED) == 0)) {
1152 * Handle any required reprocessing
1155 /* kn may be invalid now */
1165 * Scan the kqueue, return the number of active events placed in kevp up
1168 * Continuous mode events may get recycled, do not continue scanning past
1169 * marker unless no events have been collected.
1172 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
1173 struct knote *marker)
1175 struct knote *kn, local_marker;
1179 local_marker.kn_filter = EVFILT_MARKER;
1180 local_marker.kn_status = KN_PROCESSING;
1182 lwkt_getpooltoken(kq);
1187 TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
1189 kn = TAILQ_NEXT(&local_marker, kn_tqe);
1190 if (kn->kn_filter == EVFILT_MARKER) {
1191 /* Marker reached, we are done */
1195 /* Move local marker past some other threads marker */
1196 kn = TAILQ_NEXT(kn, kn_tqe);
1197 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1198 TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
1203 * We can't skip a knote undergoing processing, otherwise
1204 * we risk not returning it when the user process expects
1205 * it should be returned. Sleep and retry.
1207 if (knote_acquire(kn) == 0)
1211 * Remove the event for processing.
1213 * WARNING! We must leave KN_QUEUED set to prevent the
1214 * event from being KNOTE_ACTIVATE()d while
1215 * the queue state is in limbo, in case we
1218 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1222 * We have to deal with an extremely important race against
1223 * file descriptor close()s here. The file descriptor can
1224 * disappear MPSAFE, and there is a small window of
1225 * opportunity between that and the call to knote_fdclose().
1227 * If we hit that window here while doselect or dopoll is
1228 * trying to delete a spurious event they will not be able
1229 * to match up the event against a knote and will go haywire.
1231 if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
1232 checkfdclosed(kq->kq_fdp, kn->kn_kevent.ident, kn->kn_fp)) {
1233 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1236 if (kn->kn_status & KN_DISABLED) {
1238 * If disabled we ensure the event is not queued
1239 * but leave its active bit set. On re-enablement
1240 * the event may be immediately triggered.
1242 kn->kn_status &= ~KN_QUEUED;
1243 } else if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1244 (kn->kn_status & KN_DELETING) == 0 &&
1245 filter_event(kn, 0) == 0) {
1247 * If not running in one-shot mode and the event
1248 * is no longer present we ensure it is removed
1249 * from the queue and ignore it.
1251 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1256 if (kn->kn_fop == &user_filtops)
1257 filt_usertouch(kn, kevp, EVENT_PROCESS);
1259 *kevp = kn->kn_kevent;
1264 if (kn->kn_flags & EV_ONESHOT) {
1265 kn->kn_status &= ~KN_QUEUED;
1266 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1268 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1269 if (kn->kn_flags & EV_CLEAR) {
1273 if (kn->kn_flags & EV_DISPATCH) {
1274 kn->kn_status |= KN_DISABLED;
1276 kn->kn_status &= ~(KN_QUEUED |
1279 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1286 * Handle any post-processing states
1290 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1292 lwkt_relpooltoken(kq);
1298 * This could be expanded to call kqueue_scan, if desired.
1303 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1312 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1321 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1322 struct ucred *cred, struct sysmsg *msg)
1324 struct lwkt_token *tok;
1328 kq = (struct kqueue *)fp->f_data;
1329 tok = lwkt_token_pool_lookup(kq);
1335 kq->kq_state |= KQ_ASYNC;
1337 kq->kq_state &= ~KQ_ASYNC;
1341 error = fsetown(*(int *)data, &kq->kq_sigio);
1355 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1357 struct kqueue *kq = (struct kqueue *)fp->f_data;
1359 bzero((void *)st, sizeof(*st));
1360 st->st_size = kq->kq_count;
1361 st->st_blksize = sizeof(struct kevent);
1362 st->st_mode = S_IFIFO;
1370 kqueue_close(struct file *fp)
1372 struct kqueue *kq = (struct kqueue *)fp->f_data;
1374 kqueue_terminate(kq);
1377 funsetown(&kq->kq_sigio);
1379 kfree(kq, M_KQUEUE);
1384 kqueue_wakeup(struct kqueue *kq)
1386 if (kq->kq_state & KQ_SLEEP) {
1387 kq->kq_state &= ~KQ_SLEEP;
1393 KNOTE(&kq->kq_kqinfo.ki_note, 0);
1397 * Calls filterops f_attach function, acquiring mplock if filter is not
1398 * marked as FILTEROP_MPSAFE.
1400 * Caller must be holding the related kq token
1403 filter_attach(struct knote *kn)
1407 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1408 ret = kn->kn_fop->f_attach(kn);
1411 ret = kn->kn_fop->f_attach(kn);
1418 * Detach the knote and drop it, destroying the knote.
1420 * Calls filterops f_detach function, acquiring mplock if filter is not
1421 * marked as FILTEROP_MPSAFE.
1423 * Caller must be holding the related kq token
1426 knote_detach_and_drop(struct knote *kn)
1428 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1429 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1430 kn->kn_fop->f_detach(kn);
1433 kn->kn_fop->f_detach(kn);
1440 * Calls filterops f_event function, acquiring mplock if filter is not
1441 * marked as FILTEROP_MPSAFE.
1443 * If the knote is in the middle of being created or deleted we cannot
1444 * safely call the filter op.
1446 * Caller must be holding the related kq token
1449 filter_event(struct knote *kn, long hint)
1453 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1454 ret = kn->kn_fop->f_event(kn, hint);
1457 ret = kn->kn_fop->f_event(kn, hint);
1464 * Walk down a list of knotes, activating them if their event has triggered.
1466 * If we encounter any knotes which are undergoing processing we just mark
1467 * them for reprocessing and do not try to [re]activate the knote. However,
1468 * if a hint is being passed we have to wait and that makes things a bit
1472 knote(struct klist *list, long hint)
1474 struct knote *kn, marker;
1476 marker.kn_filter = EVFILT_MARKER;
1477 marker.kn_status = KN_PROCESSING;
1479 lwkt_getpooltoken(list);
1480 if (SLIST_EMPTY(list)) {
1481 lwkt_relpooltoken(list);
1485 SLIST_INSERT_HEAD(list, &marker, kn_next);
1486 while ((kn = SLIST_NEXT(&marker, kn_next)) != NULL) {
1490 if (kn->kn_filter == EVFILT_MARKER) {
1492 SLIST_REMOVE(list, &marker, knote, kn_next);
1493 if (SLIST_NEXT(kn, kn_next) == NULL)
1495 SLIST_INSERT_AFTER(kn, &marker, kn_next);
1500 lwkt_getpooltoken(kq);
1502 if (kn != SLIST_NEXT(&marker, kn_next) || kn->kn_kq != kq) {
1504 * Don't move the marker; check the knote after
1507 lwkt_relpooltoken(kq);
1511 if (kn->kn_status & KN_PROCESSING) {
1513 * Someone else is processing the knote, ask the
1514 * other thread to reprocess it and don't mess
1515 * with it otherwise.
1519 * Move the marker w/ the kq token, so that
1520 * this knote will not be ripped behind our
1523 SLIST_REMOVE(list, &marker, knote, kn_next);
1524 if (SLIST_NEXT(kn, kn_next) != NULL)
1525 SLIST_INSERT_AFTER(kn, &marker, kn_next);
1528 kn->kn_status |= KN_REPROCESS;
1529 lwkt_relpooltoken(kq);
1537 * If the hint is non-zero we have to wait or risk
1538 * losing the state the caller is trying to update.
1540 kn->kn_status |= KN_WAITING | KN_REPROCESS;
1541 tsleep(kn, 0, "knotec", hz);
1544 * Don't move the marker; check this knote again,
1545 * hopefully it is still after the marker. Or it
1546 * was deleted and we would check the next knote.
1548 lwkt_relpooltoken(kq);
1553 * Become the reprocessing master ourselves.
1555 KASSERT((kn->kn_status & KN_DELETING) == 0,
1556 ("acquire a deleting knote %#x", kn->kn_status));
1557 kn->kn_status |= KN_PROCESSING;
1559 /* Move the marker */
1560 SLIST_REMOVE(list, &marker, knote, kn_next);
1561 if (SLIST_NEXT(kn, kn_next) != NULL)
1562 SLIST_INSERT_AFTER(kn, &marker, kn_next);
1567 * If hint is non-zero running the event is mandatory
1568 * so do it whether reprocessing is set or not.
1570 if (filter_event(kn, hint))
1574 lwkt_relpooltoken(kq);
1579 SLIST_REMOVE(list, &marker, knote, kn_next);
1581 lwkt_relpooltoken(list);
1585 * Insert knote at head of klist.
1587 * This function may only be called via a filter function and thus
1588 * kq_token should already be held and marked for processing.
1591 knote_insert(struct klist *klist, struct knote *kn)
1593 lwkt_getpooltoken(klist);
1594 KKASSERT(kn->kn_status & KN_PROCESSING);
1595 SLIST_INSERT_HEAD(klist, kn, kn_next);
1596 lwkt_relpooltoken(klist);
1600 * Remove knote from a klist
1602 * This function may only be called via a filter function and thus
1603 * kq_token should already be held and marked for processing.
1606 knote_remove(struct klist *klist, struct knote *kn)
1608 lwkt_getpooltoken(klist);
1609 KKASSERT(kn->kn_status & KN_PROCESSING);
1610 SLIST_REMOVE(klist, kn, knote, kn_next);
1611 lwkt_relpooltoken(klist);
1615 knote_assume_knotes(struct kqinfo *src, struct kqinfo *dst,
1616 struct filterops *ops, void *hook)
1618 struct knote *kn, marker;
1621 marker.kn_filter = EVFILT_MARKER;
1622 marker.kn_status = KN_PROCESSING;
1624 lwkt_getpooltoken(&src->ki_note);
1625 if (SLIST_EMPTY(&src->ki_note)) {
1626 lwkt_relpooltoken(&src->ki_note);
1629 lwkt_getpooltoken(&dst->ki_note);
1633 SLIST_INSERT_HEAD(&src->ki_note, &marker, kn_next);
1634 while ((kn = SLIST_NEXT(&marker, kn_next)) != NULL) {
1637 if (kn->kn_filter == EVFILT_MARKER) {
1639 SLIST_REMOVE(&src->ki_note, &marker, knote, kn_next);
1640 SLIST_INSERT_AFTER(kn, &marker, kn_next);
1645 lwkt_getpooltoken(kq);
1647 if (kn != SLIST_NEXT(&marker, kn_next) || kn->kn_kq != kq) {
1649 * Don't move the marker; check the knote after
1652 lwkt_relpooltoken(kq);
1657 SLIST_REMOVE(&src->ki_note, &marker, knote, kn_next);
1658 SLIST_INSERT_AFTER(kn, &marker, kn_next);
1661 if (knote_acquire(kn)) {
1662 knote_remove(&src->ki_note, kn);
1665 knote_insert(&dst->ki_note, kn);
1667 /* kn may be invalid now */
1669 lwkt_relpooltoken(kq);
1671 SLIST_REMOVE(&src->ki_note, &marker, knote, kn_next);
1673 /* Keep draining, until nothing left */
1677 lwkt_relpooltoken(&dst->ki_note);
1678 lwkt_relpooltoken(&src->ki_note);
1682 * Remove all knotes referencing a specified fd
1685 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1689 struct knote *kntmp;
1691 lwkt_getpooltoken(&fp->f_klist);
1693 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1694 if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1696 lwkt_getpooltoken(kq);
1698 /* temporary verification hack */
1699 SLIST_FOREACH(kntmp, &fp->f_klist, kn_link) {
1703 if (kn != kntmp || kn->kn_kq->kq_fdp != fdp ||
1704 kn->kn_id != fd || kn->kn_kq != kq) {
1705 lwkt_relpooltoken(kq);
1708 if (knote_acquire(kn))
1709 knote_detach_and_drop(kn);
1710 lwkt_relpooltoken(kq);
1714 lwkt_relpooltoken(&fp->f_klist);
1718 * Low level attach function.
1720 * The knote should already be marked for processing.
1721 * Caller must hold the related kq token.
1724 knote_attach(struct knote *kn)
1727 struct kqueue *kq = kn->kn_kq;
1729 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1730 KKASSERT(kn->kn_fp);
1731 list = &kn->kn_fp->f_klist;
1733 if (kq->kq_knhashmask == 0)
1734 kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1735 &kq->kq_knhashmask);
1736 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1738 lwkt_getpooltoken(list);
1739 SLIST_INSERT_HEAD(list, kn, kn_link);
1740 lwkt_relpooltoken(list);
1741 TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1745 * Low level drop function.
1747 * The knote should already be marked for processing.
1748 * Caller must hold the related kq token.
1751 knote_drop(struct knote *kn)
1758 if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1759 list = &kn->kn_fp->f_klist;
1761 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1763 lwkt_getpooltoken(list);
1764 SLIST_REMOVE(list, kn, knote, kn_link);
1765 lwkt_relpooltoken(list);
1766 TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1767 if (kn->kn_status & KN_QUEUED)
1769 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1777 * Low level enqueue function.
1779 * The knote should already be marked for processing.
1780 * Caller must be holding the kq token
1783 knote_enqueue(struct knote *kn)
1785 struct kqueue *kq = kn->kn_kq;
1787 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1788 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1789 kn->kn_status |= KN_QUEUED;
1793 * Send SIGIO on request (typically set up as a mailbox signal)
1795 if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1796 pgsigio(kq->kq_sigio, SIGIO, 0);
1802 * Low level dequeue function.
1804 * The knote should already be marked for processing.
1805 * Caller must be holding the kq token
1808 knote_dequeue(struct knote *kn)
1810 struct kqueue *kq = kn->kn_kq;
1812 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1813 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1814 kn->kn_status &= ~KN_QUEUED;
1818 static struct knote *
1821 return kmalloc(sizeof(struct knote), M_KQUEUE, M_WAITOK);
1825 knote_free(struct knote *kn)
1827 kfree(kn, M_KQUEUE);