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
61 * Global token for kqueue subsystem
64 struct lwkt_token kq_token = LWKT_TOKEN_INITIALIZER(kq_token);
65 SYSCTL_LONG(_lwkt, OID_AUTO, kq_collisions,
66 CTLFLAG_RW, &kq_token.t_collisions, 0,
67 "Collision counter of kq_token");
70 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
72 struct kevent_copyin_args {
73 struct kevent_args *ka;
77 static int kqueue_sleep(struct kqueue *kq, struct timespec *tsp);
78 static int kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
79 struct knote *marker);
80 static int kqueue_read(struct file *fp, struct uio *uio,
81 struct ucred *cred, int flags);
82 static int kqueue_write(struct file *fp, struct uio *uio,
83 struct ucred *cred, int flags);
84 static int kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
85 struct ucred *cred, struct sysmsg *msg);
86 static int kqueue_kqfilter(struct file *fp, struct knote *kn);
87 static int kqueue_stat(struct file *fp, struct stat *st,
89 static int kqueue_close(struct file *fp);
90 static void kqueue_wakeup(struct kqueue *kq);
91 static int filter_attach(struct knote *kn);
92 static int filter_event(struct knote *kn, long hint);
97 static struct fileops kqueueops = {
98 .fo_read = kqueue_read,
99 .fo_write = kqueue_write,
100 .fo_ioctl = kqueue_ioctl,
101 .fo_kqfilter = kqueue_kqfilter,
102 .fo_stat = kqueue_stat,
103 .fo_close = kqueue_close,
104 .fo_shutdown = nofo_shutdown
107 static void knote_attach(struct knote *kn);
108 static void knote_drop(struct knote *kn);
109 static void knote_detach_and_drop(struct knote *kn);
110 static void knote_enqueue(struct knote *kn);
111 static void knote_dequeue(struct knote *kn);
112 static struct knote *knote_alloc(void);
113 static void knote_free(struct knote *kn);
115 static void filt_kqdetach(struct knote *kn);
116 static int filt_kqueue(struct knote *kn, long hint);
117 static int filt_procattach(struct knote *kn);
118 static void filt_procdetach(struct knote *kn);
119 static int filt_proc(struct knote *kn, long hint);
120 static int filt_fileattach(struct knote *kn);
121 static void filt_timerexpire(void *knx);
122 static int filt_timerattach(struct knote *kn);
123 static void filt_timerdetach(struct knote *kn);
124 static int filt_timer(struct knote *kn, long hint);
125 static int filt_userattach(struct knote *kn);
126 static void filt_userdetach(struct knote *kn);
127 static int filt_user(struct knote *kn, long hint);
128 static void filt_usertouch(struct knote *kn, struct kevent *kev,
131 static struct filterops file_filtops =
132 { FILTEROP_ISFD | FILTEROP_MPSAFE, filt_fileattach, NULL, NULL };
133 static struct filterops kqread_filtops =
134 { FILTEROP_ISFD | FILTEROP_MPSAFE, NULL, filt_kqdetach, filt_kqueue };
135 static struct filterops proc_filtops =
136 { 0, filt_procattach, filt_procdetach, filt_proc };
137 static struct filterops timer_filtops =
138 { 0, filt_timerattach, filt_timerdetach, filt_timer };
139 static struct filterops user_filtops =
140 { 0, filt_userattach, filt_userdetach, filt_user };
142 static int kq_ncallouts = 0;
143 static int kq_calloutmax = (4 * 1024);
144 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
145 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
146 static int kq_checkloop = 1000000;
147 SYSCTL_INT(_kern, OID_AUTO, kq_checkloop, CTLFLAG_RW,
148 &kq_checkloop, 0, "Maximum number of callouts allocated for kqueue");
150 #define KNOTE_ACTIVATE(kn) do { \
151 kn->kn_status |= KN_ACTIVE; \
152 if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
156 #define KN_HASHSIZE 64 /* XXX should be tunable */
157 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
159 extern struct filterops aio_filtops;
160 extern struct filterops sig_filtops;
163 * Table for for all system-defined filters.
165 static struct filterops *sysfilt_ops[] = {
166 &file_filtops, /* EVFILT_READ */
167 &file_filtops, /* EVFILT_WRITE */
168 &aio_filtops, /* EVFILT_AIO */
169 &file_filtops, /* EVFILT_VNODE */
170 &proc_filtops, /* EVFILT_PROC */
171 &sig_filtops, /* EVFILT_SIGNAL */
172 &timer_filtops, /* EVFILT_TIMER */
173 &file_filtops, /* EVFILT_EXCEPT */
174 &user_filtops, /* EVFILT_USER */
178 filt_fileattach(struct knote *kn)
180 return (fo_kqfilter(kn->kn_fp, kn));
187 kqueue_kqfilter(struct file *fp, struct knote *kn)
189 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
191 if (kn->kn_filter != EVFILT_READ)
194 kn->kn_fop = &kqread_filtops;
195 knote_insert(&kq->kq_kqinfo.ki_note, kn);
200 filt_kqdetach(struct knote *kn)
202 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
204 knote_remove(&kq->kq_kqinfo.ki_note, kn);
209 filt_kqueue(struct knote *kn, long hint)
211 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
213 kn->kn_data = kq->kq_count;
214 return (kn->kn_data > 0);
218 filt_procattach(struct knote *kn)
224 p = pfind(kn->kn_id);
225 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
226 p = zpfind(kn->kn_id);
232 if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
238 lwkt_gettoken(&p->p_token);
239 kn->kn_ptr.p_proc = p;
240 kn->kn_flags |= EV_CLEAR; /* automatically set */
243 * internal flag indicating registration done by kernel
245 if (kn->kn_flags & EV_FLAG1) {
246 kn->kn_data = kn->kn_sdata; /* ppid */
247 kn->kn_fflags = NOTE_CHILD;
248 kn->kn_flags &= ~EV_FLAG1;
251 knote_insert(&p->p_klist, kn);
254 * Immediately activate any exit notes if the target process is a
255 * zombie. This is necessary to handle the case where the target
256 * process, e.g. a child, dies before the kevent is negistered.
258 if (immediate && filt_proc(kn, NOTE_EXIT))
260 lwkt_reltoken(&p->p_token);
267 * The knote may be attached to a different process, which may exit,
268 * leaving nothing for the knote to be attached to. So when the process
269 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
270 * it will be deleted when read out. However, as part of the knote deletion,
271 * this routine is called, so a check is needed to avoid actually performing
272 * a detach, because the original process does not exist any more.
275 filt_procdetach(struct knote *kn)
279 if (kn->kn_status & KN_DETACHED)
281 p = kn->kn_ptr.p_proc;
282 knote_remove(&p->p_klist, kn);
286 filt_proc(struct knote *kn, long hint)
291 * mask off extra data
293 event = (u_int)hint & NOTE_PCTRLMASK;
296 * if the user is interested in this event, record it.
298 if (kn->kn_sfflags & event)
299 kn->kn_fflags |= event;
302 * Process is gone, so flag the event as finished. Detach the
303 * knote from the process now because the process will be poof,
306 if (event == NOTE_EXIT) {
307 struct proc *p = kn->kn_ptr.p_proc;
308 if ((kn->kn_status & KN_DETACHED) == 0) {
310 knote_remove(&p->p_klist, kn);
311 kn->kn_status |= KN_DETACHED;
312 kn->kn_data = p->p_xstat;
313 kn->kn_ptr.p_proc = NULL;
316 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
321 * process forked, and user wants to track the new process,
322 * so attach a new knote to it, and immediately report an
323 * event with the parent's pid.
325 if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
330 * register knote with new process.
332 kev.ident = hint & NOTE_PDATAMASK; /* pid */
333 kev.filter = kn->kn_filter;
334 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
335 kev.fflags = kn->kn_sfflags;
336 kev.data = kn->kn_id; /* parent */
337 kev.udata = kn->kn_kevent.udata; /* preserve udata */
338 error = kqueue_register(kn->kn_kq, &kev);
340 kn->kn_fflags |= NOTE_TRACKERR;
343 return (kn->kn_fflags != 0);
347 * The callout interlocks with callout_terminate() but can still
348 * race a deletion so if KN_DELETING is set we just don't touch
352 filt_timerexpire(void *knx)
354 struct lwkt_token *tok;
355 struct knote *kn = knx;
356 struct callout *calloutp;
360 tok = lwkt_token_pool_lookup(kn->kn_kq);
362 if ((kn->kn_status & KN_DELETING) == 0) {
366 if ((kn->kn_flags & EV_ONESHOT) == 0) {
367 tv.tv_sec = kn->kn_sdata / 1000;
368 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
369 tticks = tvtohz_high(&tv);
370 calloutp = (struct callout *)kn->kn_hook;
371 callout_reset(calloutp, tticks, filt_timerexpire, kn);
378 * data contains amount of time to sleep, in milliseconds
381 filt_timerattach(struct knote *kn)
383 struct callout *calloutp;
387 if (kq_ncallouts >= kq_calloutmax) {
393 tv.tv_sec = kn->kn_sdata / 1000;
394 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
395 tticks = tvtohz_high(&tv);
397 kn->kn_flags |= EV_CLEAR; /* automatically set */
398 calloutp = kmalloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
399 callout_init(calloutp);
400 kn->kn_hook = (caddr_t)calloutp;
401 callout_reset(calloutp, tticks, filt_timerexpire, kn);
407 * This function is called with the knote flagged locked but it is
408 * still possible to race a callout event due to the callback blocking.
409 * We must call callout_terminate() instead of callout_stop() to deal
413 filt_timerdetach(struct knote *kn)
415 struct callout *calloutp;
417 calloutp = (struct callout *)kn->kn_hook;
418 callout_terminate(calloutp);
419 kfree(calloutp, M_KQUEUE);
424 filt_timer(struct knote *kn, long hint)
427 return (kn->kn_data != 0);
434 filt_userattach(struct knote *kn)
437 if (kn->kn_fflags & NOTE_TRIGGER)
438 kn->kn_ptr.hookid = 1;
440 kn->kn_ptr.hookid = 0;
445 * This function is called with the knote flagged locked but it is
446 * still possible to race a callout event due to the callback blocking.
447 * We must call callout_terminate() instead of callout_stop() to deal
451 filt_userdetach(struct knote *kn)
457 filt_user(struct knote *kn, long hint)
459 return (kn->kn_ptr.hookid);
463 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
469 if (kev->fflags & NOTE_TRIGGER)
470 kn->kn_ptr.hookid = 1;
472 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
473 kev->fflags &= NOTE_FFLAGSMASK;
479 kn->kn_sfflags &= kev->fflags;
483 kn->kn_sfflags |= kev->fflags;
487 kn->kn_sfflags = kev->fflags;
491 /* XXX Return error? */
494 kn->kn_sdata = kev->data;
497 * This is not the correct use of EV_CLEAR in an event
498 * modification, it should have been passed as a NOTE instead.
499 * But we need to maintain compatibility with Apple & FreeBSD.
501 * Note however that EV_CLEAR can still be used when doing
502 * the initial registration of the event and works as expected
503 * (clears the event on reception).
505 if (kev->flags & EV_CLEAR) {
506 kn->kn_ptr.hookid = 0;
513 *kev = kn->kn_kevent;
514 kev->fflags = kn->kn_sfflags;
515 kev->data = kn->kn_sdata;
516 if (kn->kn_flags & EV_CLEAR) {
517 kn->kn_ptr.hookid = 0;
518 /* kn_data, kn_fflags handled by parent */
523 panic("filt_usertouch() - invalid type (%ld)", type);
529 * Acquire a knote, return non-zero on success, 0 on failure.
531 * If we cannot acquire the knote we sleep and return 0. The knote
532 * may be stale on return in this case and the caller must restart
533 * whatever loop they are in.
535 * Related kq token must be held.
539 knote_acquire(struct knote *kn)
541 if (kn->kn_status & KN_PROCESSING) {
542 kn->kn_status |= KN_WAITING | KN_REPROCESS;
543 tsleep(kn, 0, "kqepts", hz);
544 /* knote may be stale now */
547 kn->kn_status |= KN_PROCESSING;
552 * Release an acquired knote, clearing KN_PROCESSING and handling any
553 * KN_REPROCESS events.
555 * Caller must be holding the related kq token
557 * Non-zero is returned if the knote is destroyed or detached.
561 knote_release(struct knote *kn)
563 while (kn->kn_status & KN_REPROCESS) {
564 kn->kn_status &= ~KN_REPROCESS;
565 if (kn->kn_status & KN_WAITING) {
566 kn->kn_status &= ~KN_WAITING;
569 if (kn->kn_status & KN_DELETING) {
570 knote_detach_and_drop(kn);
574 if (filter_event(kn, 0))
577 if (kn->kn_status & KN_DETACHED) {
578 kn->kn_status &= ~KN_PROCESSING;
581 kn->kn_status &= ~KN_PROCESSING;
587 * Initialize a kqueue.
589 * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
594 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
596 TAILQ_INIT(&kq->kq_knpend);
597 TAILQ_INIT(&kq->kq_knlist);
600 SLIST_INIT(&kq->kq_kqinfo.ki_note);
604 * Terminate a kqueue. Freeing the actual kq itself is left up to the
605 * caller (it might be embedded in a lwp so we don't do it here).
607 * The kq's knlist must be completely eradicated so block on any
611 kqueue_terminate(struct kqueue *kq)
613 struct lwkt_token *tok;
616 tok = lwkt_token_pool_lookup(kq);
618 while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
619 if (knote_acquire(kn))
620 knote_detach_and_drop(kn);
623 hashdestroy(kq->kq_knhash, M_KQUEUE, kq->kq_knhashmask);
624 kq->kq_knhash = NULL;
625 kq->kq_knhashmask = 0;
634 sys_kqueue(struct kqueue_args *uap)
636 struct thread *td = curthread;
641 error = falloc(td->td_lwp, &fp, &fd);
644 fp->f_flag = FREAD | FWRITE;
645 fp->f_type = DTYPE_KQUEUE;
646 fp->f_ops = &kqueueops;
648 kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
649 kqueue_init(kq, td->td_proc->p_fd);
652 fsetfd(kq->kq_fdp, fp, fd);
653 uap->sysmsg_result = fd;
659 * Copy 'count' items into the destination list pointed to by uap->eventlist.
662 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
664 struct kevent_copyin_args *kap;
667 kap = (struct kevent_copyin_args *)arg;
669 error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
671 kap->ka->eventlist += count;
681 * Copy at most 'max' items from the list pointed to by kap->changelist,
682 * return number of items in 'events'.
685 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
687 struct kevent_copyin_args *kap;
690 kap = (struct kevent_copyin_args *)arg;
692 count = min(kap->ka->nchanges - kap->pchanges, max);
693 error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
695 kap->ka->changelist += count;
696 kap->pchanges += count;
707 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
708 k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
709 struct timespec *tsp_in)
712 struct timespec *tsp;
713 int i, n, total, error, nerrors = 0;
715 int limit = kq_checkloop;
716 struct kevent kev[KQ_NEVENTS];
718 struct lwkt_token *tok;
720 if (tsp_in == NULL || tsp_in->tv_sec || tsp_in->tv_nsec)
721 atomic_set_int(&curthread->td_mpflags, TDF_MP_BATCH_DEMARC);
726 tok = lwkt_token_pool_lookup(kq);
730 error = kevent_copyinfn(uap, kev, KQ_NEVENTS, &n);
735 for (i = 0; i < n; i++) {
737 kevp->flags &= ~EV_SYSFLAGS;
738 error = kqueue_register(kq, kevp);
741 * If a registration returns an error we
742 * immediately post the error. The kevent()
743 * call itself will fail with the error if
744 * no space is available for posting.
746 * Such errors normally bypass the timeout/blocking
747 * code. However, if the copyoutfn function refuses
748 * to post the error (see sys_poll()), then we
752 kevp->flags = EV_ERROR;
755 kevent_copyoutfn(uap, kevp, 1, res);
758 } else if (lres != *res) {
771 * Acquire/wait for events - setup timeout
776 if (tsp->tv_sec || tsp->tv_nsec) {
778 timespecadd(tsp, &ats); /* tsp = target time */
785 * Collect as many events as we can. Sleeping on successive
786 * loops is disabled if copyoutfn has incremented (*res).
788 * The loop stops if an error occurs, all events have been
789 * scanned (the marker has been reached), or fewer than the
790 * maximum number of events is found.
792 * The copyoutfn function does not have to increment (*res) in
793 * order for the loop to continue.
795 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
799 marker.kn_filter = EVFILT_MARKER;
800 marker.kn_status = KN_PROCESSING;
801 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
802 while ((n = nevents - total) > 0) {
807 * If no events are pending sleep until timeout (if any)
808 * or an event occurs.
810 * After the sleep completes the marker is moved to the
811 * end of the list, making any received events available
814 if (kq->kq_count == 0 && *res == 0) {
815 error = kqueue_sleep(kq, tsp);
819 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
820 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
824 * Process all received events
825 * Account for all non-spurious events in our total
827 i = kqueue_scan(kq, kev, n, &marker);
830 error = kevent_copyoutfn(uap, kev, i, res);
831 total += *res - lres;
835 if (limit && --limit == 0)
836 panic("kqueue: checkloop failed i=%d", i);
839 * Normally when fewer events are returned than requested
840 * we can stop. However, if only spurious events were
841 * collected the copyout will not bump (*res) and we have
848 * Deal with an edge case where spurious events can cause
849 * a loop to occur without moving the marker. This can
850 * prevent kqueue_scan() from picking up new events which
851 * race us. We must be sure to move the marker for this
854 * NOTE: We do not want to move the marker if events
855 * were scanned because normal kqueue operations
856 * may reactivate events. Moving the marker in
857 * that case could result in duplicates for the
861 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
862 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
865 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
867 /* Timeouts do not return EWOULDBLOCK. */
868 if (error == EWOULDBLOCK)
880 sys_kevent(struct kevent_args *uap)
882 struct thread *td = curthread;
883 struct proc *p = td->td_proc;
884 struct timespec ts, *tsp;
886 struct file *fp = NULL;
887 struct kevent_copyin_args *kap, ka;
891 error = copyin(uap->timeout, &ts, sizeof(ts));
898 fp = holdfp(p->p_fd, uap->fd, -1);
901 if (fp->f_type != DTYPE_KQUEUE) {
906 kq = (struct kqueue *)fp->f_data;
912 error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
913 kevent_copyin, kevent_copyout, tsp);
921 kqueue_register(struct kqueue *kq, struct kevent *kev)
923 struct lwkt_token *tok;
924 struct filedesc *fdp = kq->kq_fdp;
925 struct filterops *fops;
926 struct file *fp = NULL;
927 struct knote *kn = NULL;
930 if (kev->filter < 0) {
931 if (kev->filter + EVFILT_SYSCOUNT < 0)
933 fops = sysfilt_ops[~kev->filter]; /* to 0-base index */
937 * filter attach routine is responsible for insuring that
938 * the identifier can be attached to it.
943 tok = lwkt_token_pool_lookup(kq);
945 if (fops->f_flags & FILTEROP_ISFD) {
946 /* validate descriptor */
947 fp = holdfp(fdp, kev->ident, -1);
952 lwkt_getpooltoken(&fp->f_klist);
954 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
955 if (kn->kn_kq == kq &&
956 kn->kn_filter == kev->filter &&
957 kn->kn_id == kev->ident) {
958 if (knote_acquire(kn) == 0)
963 lwkt_relpooltoken(&fp->f_klist);
965 if (kq->kq_knhashmask) {
968 list = &kq->kq_knhash[
969 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
970 lwkt_getpooltoken(list);
972 SLIST_FOREACH(kn, list, kn_link) {
973 if (kn->kn_id == kev->ident &&
974 kn->kn_filter == kev->filter) {
975 if (knote_acquire(kn) == 0)
980 lwkt_relpooltoken(list);
985 * NOTE: At this point if kn is non-NULL we will have acquired
986 * it and set KN_PROCESSING.
988 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
994 * kn now contains the matching knote, or NULL if no match
996 if (kev->flags & EV_ADD) {
1008 * apply reference count to knote structure, and
1009 * do not release it at the end of this routine.
1013 kn->kn_sfflags = kev->fflags;
1014 kn->kn_sdata = kev->data;
1017 kn->kn_kevent = *kev;
1020 * KN_PROCESSING prevents the knote from getting
1021 * ripped out from under us while we are trying
1022 * to attach it, in case the attach blocks.
1024 kn->kn_status = KN_PROCESSING;
1026 if ((error = filter_attach(kn)) != 0) {
1027 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1033 * Interlock against close races which either tried
1034 * to remove our knote while we were blocked or missed
1035 * it entirely prior to our attachment. We do not
1036 * want to end up with a knote on a closed descriptor.
1038 if ((fops->f_flags & FILTEROP_ISFD) &&
1039 checkfdclosed(fdp, kev->ident, kn->kn_fp)) {
1040 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1044 * The user may change some filter values after the
1045 * initial EV_ADD, but doing so will not reset any
1046 * filter which have already been triggered.
1048 KKASSERT(kn->kn_status & KN_PROCESSING);
1049 if (fops == &user_filtops) {
1050 filt_usertouch(kn, kev, EVENT_REGISTER);
1052 kn->kn_sfflags = kev->fflags;
1053 kn->kn_sdata = kev->data;
1054 kn->kn_kevent.udata = kev->udata;
1059 * Execute the filter event to immediately activate the
1060 * knote if necessary. If reprocessing events are pending
1061 * due to blocking above we do not run the filter here
1062 * but instead let knote_release() do it. Otherwise we
1063 * might run the filter on a deleted event.
1065 if ((kn->kn_status & KN_REPROCESS) == 0) {
1066 if (filter_event(kn, 0))
1069 } else if (kev->flags & EV_DELETE) {
1071 * Delete the existing knote
1073 knote_detach_and_drop(kn);
1077 * Modify an existing event.
1079 * The user may change some filter values after the
1080 * initial EV_ADD, but doing so will not reset any
1081 * filter which have already been triggered.
1083 KKASSERT(kn->kn_status & KN_PROCESSING);
1084 if (fops == &user_filtops) {
1085 filt_usertouch(kn, kev, EVENT_REGISTER);
1087 kn->kn_sfflags = kev->fflags;
1088 kn->kn_sdata = kev->data;
1089 kn->kn_kevent.udata = kev->udata;
1093 * Execute the filter event to immediately activate the
1094 * knote if necessary. If reprocessing events are pending
1095 * due to blocking above we do not run the filter here
1096 * but instead let knote_release() do it. Otherwise we
1097 * might run the filter on a deleted event.
1099 if ((kn->kn_status & KN_REPROCESS) == 0) {
1100 if (filter_event(kn, 0))
1106 * Disablement does not deactivate a knote here.
1108 if ((kev->flags & EV_DISABLE) &&
1109 ((kn->kn_status & KN_DISABLED) == 0)) {
1110 kn->kn_status |= KN_DISABLED;
1114 * Re-enablement may have to immediately enqueue an active knote.
1116 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1117 kn->kn_status &= ~KN_DISABLED;
1118 if ((kn->kn_status & KN_ACTIVE) &&
1119 ((kn->kn_status & KN_QUEUED) == 0)) {
1125 * Handle any required reprocessing
1128 /* kn may be invalid now */
1138 * Block as necessary until the target time is reached.
1139 * If tsp is NULL we block indefinitely. If tsp->ts_secs/nsecs are both
1140 * 0 we do not block at all.
1142 * Caller must be holding the kq token.
1145 kqueue_sleep(struct kqueue *kq, struct timespec *tsp)
1150 kq->kq_state |= KQ_SLEEP;
1151 error = tsleep(kq, PCATCH, "kqread", 0);
1152 } else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
1153 error = EWOULDBLOCK;
1155 struct timespec ats;
1156 struct timespec atx = *tsp;
1159 getnanouptime(&ats);
1160 timespecsub(&atx, &ats);
1161 if (ats.tv_sec < 0) {
1162 error = EWOULDBLOCK;
1164 timeout = atx.tv_sec > 24 * 60 * 60 ?
1165 24 * 60 * 60 * hz : tstohz_high(&atx);
1166 kq->kq_state |= KQ_SLEEP;
1167 error = tsleep(kq, PCATCH, "kqread", timeout);
1171 /* don't restart after signals... */
1172 if (error == ERESTART)
1179 * Scan the kqueue, return the number of active events placed in kevp up
1182 * Continuous mode events may get recycled, do not continue scanning past
1183 * marker unless no events have been collected.
1185 * Caller must be holding the kq token
1188 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
1189 struct knote *marker)
1191 struct knote *kn, local_marker;
1195 local_marker.kn_filter = EVFILT_MARKER;
1196 local_marker.kn_status = KN_PROCESSING;
1201 TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
1203 kn = TAILQ_NEXT(&local_marker, kn_tqe);
1204 if (kn->kn_filter == EVFILT_MARKER) {
1205 /* Marker reached, we are done */
1209 /* Move local marker past some other threads marker */
1210 kn = TAILQ_NEXT(kn, kn_tqe);
1211 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1212 TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
1217 * We can't skip a knote undergoing processing, otherwise
1218 * we risk not returning it when the user process expects
1219 * it should be returned. Sleep and retry.
1221 if (knote_acquire(kn) == 0)
1225 * Remove the event for processing.
1227 * WARNING! We must leave KN_QUEUED set to prevent the
1228 * event from being KNOTE_ACTIVATE()d while
1229 * the queue state is in limbo, in case we
1232 * WARNING! We must set KN_PROCESSING to avoid races
1233 * against deletion or another thread's
1236 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1240 * We have to deal with an extremely important race against
1241 * file descriptor close()s here. The file descriptor can
1242 * disappear MPSAFE, and there is a small window of
1243 * opportunity between that and the call to knote_fdclose().
1245 * If we hit that window here while doselect or dopoll is
1246 * trying to delete a spurious event they will not be able
1247 * to match up the event against a knote and will go haywire.
1249 if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
1250 checkfdclosed(kq->kq_fdp, kn->kn_kevent.ident, kn->kn_fp)) {
1251 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1254 if (kn->kn_status & KN_DISABLED) {
1256 * If disabled we ensure the event is not queued
1257 * but leave its active bit set. On re-enablement
1258 * the event may be immediately triggered.
1260 kn->kn_status &= ~KN_QUEUED;
1261 } else if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1262 (kn->kn_status & KN_DELETING) == 0 &&
1263 filter_event(kn, 0) == 0) {
1265 * If not running in one-shot mode and the event
1266 * is no longer present we ensure it is removed
1267 * from the queue and ignore it.
1269 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1274 if (kn->kn_fop == &user_filtops)
1275 filt_usertouch(kn, kevp, EVENT_PROCESS);
1277 *kevp = kn->kn_kevent;
1282 if (kn->kn_flags & EV_ONESHOT) {
1283 kn->kn_status &= ~KN_QUEUED;
1284 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1286 if (kn->kn_flags & EV_CLEAR) {
1289 kn->kn_status &= ~(KN_QUEUED |
1292 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1299 * Handle any post-processing states
1303 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1310 * This could be expanded to call kqueue_scan, if desired.
1315 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1324 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1333 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1334 struct ucred *cred, struct sysmsg *msg)
1336 struct lwkt_token *tok;
1340 kq = (struct kqueue *)fp->f_data;
1341 tok = lwkt_token_pool_lookup(kq);
1347 kq->kq_state |= KQ_ASYNC;
1349 kq->kq_state &= ~KQ_ASYNC;
1353 error = fsetown(*(int *)data, &kq->kq_sigio);
1367 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1369 struct kqueue *kq = (struct kqueue *)fp->f_data;
1371 bzero((void *)st, sizeof(*st));
1372 st->st_size = kq->kq_count;
1373 st->st_blksize = sizeof(struct kevent);
1374 st->st_mode = S_IFIFO;
1382 kqueue_close(struct file *fp)
1384 struct kqueue *kq = (struct kqueue *)fp->f_data;
1386 kqueue_terminate(kq);
1389 funsetown(&kq->kq_sigio);
1391 kfree(kq, M_KQUEUE);
1396 kqueue_wakeup(struct kqueue *kq)
1398 if (kq->kq_state & KQ_SLEEP) {
1399 kq->kq_state &= ~KQ_SLEEP;
1402 KNOTE(&kq->kq_kqinfo.ki_note, 0);
1406 * Calls filterops f_attach function, acquiring mplock if filter is not
1407 * marked as FILTEROP_MPSAFE.
1409 * Caller must be holding the related kq token
1412 filter_attach(struct knote *kn)
1416 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1417 ret = kn->kn_fop->f_attach(kn);
1420 ret = kn->kn_fop->f_attach(kn);
1427 * Detach the knote and drop it, destroying the knote.
1429 * Calls filterops f_detach function, acquiring mplock if filter is not
1430 * marked as FILTEROP_MPSAFE.
1432 * Caller must be holding the related kq token
1435 knote_detach_and_drop(struct knote *kn)
1437 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1438 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1439 kn->kn_fop->f_detach(kn);
1442 kn->kn_fop->f_detach(kn);
1449 * Calls filterops f_event function, acquiring mplock if filter is not
1450 * marked as FILTEROP_MPSAFE.
1452 * If the knote is in the middle of being created or deleted we cannot
1453 * safely call the filter op.
1455 * Caller must be holding the related kq token
1458 filter_event(struct knote *kn, long hint)
1462 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1463 ret = kn->kn_fop->f_event(kn, hint);
1466 ret = kn->kn_fop->f_event(kn, hint);
1473 * Walk down a list of knotes, activating them if their event has triggered.
1475 * If we encounter any knotes which are undergoing processing we just mark
1476 * them for reprocessing and do not try to [re]activate the knote. However,
1477 * if a hint is being passed we have to wait and that makes things a bit
1481 knote(struct klist *list, long hint)
1485 struct knote *kntmp;
1487 lwkt_getpooltoken(list);
1489 SLIST_FOREACH(kn, list, kn_next) {
1491 lwkt_getpooltoken(kq);
1493 /* temporary verification hack */
1494 SLIST_FOREACH(kntmp, list, kn_next) {
1498 if (kn != kntmp || kn->kn_kq != kq) {
1499 lwkt_relpooltoken(kq);
1503 if (kn->kn_status & KN_PROCESSING) {
1505 * Someone else is processing the knote, ask the
1506 * other thread to reprocess it and don't mess
1507 * with it otherwise.
1510 kn->kn_status |= KN_REPROCESS;
1511 lwkt_relpooltoken(kq);
1516 * If the hint is non-zero we have to wait or risk
1517 * losing the state the caller is trying to update.
1519 * XXX This is a real problem, certain process
1520 * and signal filters will bump kn_data for
1521 * already-processed notes more than once if
1522 * we restart the list scan. FIXME.
1524 kn->kn_status |= KN_WAITING | KN_REPROCESS;
1525 tsleep(kn, 0, "knotec", hz);
1526 lwkt_relpooltoken(kq);
1531 * Become the reprocessing master ourselves.
1533 * If hint is non-zero running the event is mandatory
1534 * when not deleting so do it whether reprocessing is
1537 kn->kn_status |= KN_PROCESSING;
1538 if ((kn->kn_status & KN_DELETING) == 0) {
1539 if (filter_event(kn, hint))
1542 if (knote_release(kn)) {
1543 lwkt_relpooltoken(kq);
1546 lwkt_relpooltoken(kq);
1548 lwkt_relpooltoken(list);
1552 * Insert knote at head of klist.
1554 * This function may only be called via a filter function and thus
1555 * kq_token should already be held and marked for processing.
1558 knote_insert(struct klist *klist, struct knote *kn)
1560 lwkt_getpooltoken(klist);
1561 KKASSERT(kn->kn_status & KN_PROCESSING);
1562 SLIST_INSERT_HEAD(klist, kn, kn_next);
1563 lwkt_relpooltoken(klist);
1567 * Remove knote from a klist
1569 * This function may only be called via a filter function and thus
1570 * kq_token should already be held and marked for processing.
1573 knote_remove(struct klist *klist, struct knote *kn)
1575 lwkt_getpooltoken(klist);
1576 KKASSERT(kn->kn_status & KN_PROCESSING);
1577 SLIST_REMOVE(klist, kn, knote, kn_next);
1578 lwkt_relpooltoken(klist);
1583 * Remove all knotes from a specified klist
1585 * Only called from aio.
1588 knote_empty(struct klist *list)
1592 lwkt_gettoken(&kq_token);
1593 while ((kn = SLIST_FIRST(list)) != NULL) {
1594 if (knote_acquire(kn))
1595 knote_detach_and_drop(kn);
1597 lwkt_reltoken(&kq_token);
1602 knote_assume_knotes(struct kqinfo *src, struct kqinfo *dst,
1603 struct filterops *ops, void *hook)
1608 lwkt_getpooltoken(&src->ki_note);
1609 lwkt_getpooltoken(&dst->ki_note);
1610 while ((kn = SLIST_FIRST(&src->ki_note)) != NULL) {
1612 lwkt_getpooltoken(kq);
1613 if (SLIST_FIRST(&src->ki_note) != kn || kn->kn_kq != kq) {
1614 lwkt_relpooltoken(kq);
1617 if (knote_acquire(kn)) {
1618 knote_remove(&src->ki_note, kn);
1621 knote_insert(&dst->ki_note, kn);
1623 /* kn may be invalid now */
1625 lwkt_relpooltoken(kq);
1627 lwkt_relpooltoken(&dst->ki_note);
1628 lwkt_relpooltoken(&src->ki_note);
1632 * Remove all knotes referencing a specified fd
1635 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1639 struct knote *kntmp;
1641 lwkt_getpooltoken(&fp->f_klist);
1643 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1644 if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1646 lwkt_getpooltoken(kq);
1648 /* temporary verification hack */
1649 SLIST_FOREACH(kntmp, &fp->f_klist, kn_link) {
1653 if (kn != kntmp || kn->kn_kq->kq_fdp != fdp ||
1654 kn->kn_id != fd || kn->kn_kq != kq) {
1655 lwkt_relpooltoken(kq);
1658 if (knote_acquire(kn))
1659 knote_detach_and_drop(kn);
1660 lwkt_relpooltoken(kq);
1664 lwkt_relpooltoken(&fp->f_klist);
1668 * Low level attach function.
1670 * The knote should already be marked for processing.
1671 * Caller must hold the related kq token.
1674 knote_attach(struct knote *kn)
1677 struct kqueue *kq = kn->kn_kq;
1679 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1680 KKASSERT(kn->kn_fp);
1681 list = &kn->kn_fp->f_klist;
1683 if (kq->kq_knhashmask == 0)
1684 kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1685 &kq->kq_knhashmask);
1686 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1688 lwkt_getpooltoken(list);
1689 SLIST_INSERT_HEAD(list, kn, kn_link);
1690 TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1691 lwkt_relpooltoken(list);
1695 * Low level drop function.
1697 * The knote should already be marked for processing.
1698 * Caller must hold the related kq token.
1701 knote_drop(struct knote *kn)
1708 if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1709 list = &kn->kn_fp->f_klist;
1711 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1713 lwkt_getpooltoken(list);
1714 SLIST_REMOVE(list, kn, knote, kn_link);
1715 TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1716 if (kn->kn_status & KN_QUEUED)
1718 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1723 lwkt_relpooltoken(list);
1727 * Low level enqueue function.
1729 * The knote should already be marked for processing.
1730 * Caller must be holding the kq token
1733 knote_enqueue(struct knote *kn)
1735 struct kqueue *kq = kn->kn_kq;
1737 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1738 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1739 kn->kn_status |= KN_QUEUED;
1743 * Send SIGIO on request (typically set up as a mailbox signal)
1745 if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1746 pgsigio(kq->kq_sigio, SIGIO, 0);
1752 * Low level dequeue function.
1754 * The knote should already be marked for processing.
1755 * Caller must be holding the kq token
1758 knote_dequeue(struct knote *kn)
1760 struct kqueue *kq = kn->kn_kq;
1762 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1763 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1764 kn->kn_status &= ~KN_QUEUED;
1768 static struct knote *
1771 return kmalloc(sizeof(struct knote), M_KQUEUE, M_WAITOK);
1775 knote_free(struct knote *kn)
1777 kfree(kn, M_KQUEUE);