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 #define KNOTE_CACHE_MAX 8
69 struct knote_cache_list {
70 struct klist knote_cache;
74 static int kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
75 struct knote *marker);
76 static int kqueue_read(struct file *fp, struct uio *uio,
77 struct ucred *cred, int flags);
78 static int kqueue_write(struct file *fp, struct uio *uio,
79 struct ucred *cred, int flags);
80 static int kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
81 struct ucred *cred, struct sysmsg *msg);
82 static int kqueue_kqfilter(struct file *fp, struct knote *kn);
83 static int kqueue_stat(struct file *fp, struct stat *st,
85 static int kqueue_close(struct file *fp);
86 static void kqueue_wakeup(struct kqueue *kq);
87 static int filter_attach(struct knote *kn);
88 static int filter_event(struct knote *kn, long hint);
93 static struct fileops kqueueops = {
94 .fo_read = kqueue_read,
95 .fo_write = kqueue_write,
96 .fo_ioctl = kqueue_ioctl,
97 .fo_kqfilter = kqueue_kqfilter,
98 .fo_stat = kqueue_stat,
99 .fo_close = kqueue_close,
100 .fo_shutdown = nofo_shutdown
103 static void knote_attach(struct knote *kn);
104 static void knote_drop(struct knote *kn);
105 static void knote_detach_and_drop(struct knote *kn);
106 static void knote_enqueue(struct knote *kn);
107 static void knote_dequeue(struct knote *kn);
108 static struct knote *knote_alloc(void);
109 static void knote_free(struct knote *kn);
111 static void filt_kqdetach(struct knote *kn);
112 static int filt_kqueue(struct knote *kn, long hint);
113 static int filt_procattach(struct knote *kn);
114 static void filt_procdetach(struct knote *kn);
115 static int filt_proc(struct knote *kn, long hint);
116 static int filt_fileattach(struct knote *kn);
117 static void filt_timerexpire(void *knx);
118 static int filt_timerattach(struct knote *kn);
119 static void filt_timerdetach(struct knote *kn);
120 static int filt_timer(struct knote *kn, long hint);
121 static int filt_userattach(struct knote *kn);
122 static void filt_userdetach(struct knote *kn);
123 static int filt_user(struct knote *kn, long hint);
124 static void filt_usertouch(struct knote *kn, struct kevent *kev,
127 static struct filterops file_filtops =
128 { FILTEROP_ISFD | FILTEROP_MPSAFE, filt_fileattach, NULL, NULL };
129 static struct filterops kqread_filtops =
130 { FILTEROP_ISFD | FILTEROP_MPSAFE, NULL, filt_kqdetach, filt_kqueue };
131 static struct filterops proc_filtops =
132 { 0, filt_procattach, filt_procdetach, filt_proc };
133 static struct filterops timer_filtops =
134 { FILTEROP_MPSAFE, filt_timerattach, filt_timerdetach, filt_timer };
135 static struct filterops user_filtops =
136 { FILTEROP_MPSAFE, filt_userattach, filt_userdetach, filt_user };
138 static int kq_ncallouts = 0;
139 static int kq_calloutmax = (4 * 1024);
140 SYSCTL_INT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
141 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
142 static int kq_checkloop = 1000000;
143 SYSCTL_INT(_kern, OID_AUTO, kq_checkloop, CTLFLAG_RW,
144 &kq_checkloop, 0, "Maximum number of loops for kqueue scan");
146 #define KNOTE_ACTIVATE(kn) do { \
147 kn->kn_status |= KN_ACTIVE; \
148 if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
152 #define KN_HASHSIZE 64 /* XXX should be tunable */
153 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
155 extern struct filterops aio_filtops;
156 extern struct filterops sig_filtops;
159 * Table for for all system-defined filters.
161 static struct filterops *sysfilt_ops[] = {
162 &file_filtops, /* EVFILT_READ */
163 &file_filtops, /* EVFILT_WRITE */
164 &aio_filtops, /* EVFILT_AIO */
165 &file_filtops, /* EVFILT_VNODE */
166 &proc_filtops, /* EVFILT_PROC */
167 &sig_filtops, /* EVFILT_SIGNAL */
168 &timer_filtops, /* EVFILT_TIMER */
169 &file_filtops, /* EVFILT_EXCEPT */
170 &user_filtops, /* EVFILT_USER */
173 static struct knote_cache_list knote_cache_lists[MAXCPU];
176 * Acquire a knote, return non-zero on success, 0 on failure.
178 * If we cannot acquire the knote we sleep and return 0. The knote
179 * may be stale on return in this case and the caller must restart
180 * whatever loop they are in.
182 * Related kq token must be held.
185 knote_acquire(struct knote *kn)
187 if (kn->kn_status & KN_PROCESSING) {
188 kn->kn_status |= KN_WAITING | KN_REPROCESS;
189 tsleep(kn, 0, "kqepts", hz);
190 /* knote may be stale now */
193 kn->kn_status |= KN_PROCESSING;
198 * Release an acquired knote, clearing KN_PROCESSING and handling any
199 * KN_REPROCESS events.
201 * Caller must be holding the related kq token
203 * Non-zero is returned if the knote is destroyed or detached.
206 knote_release(struct knote *kn)
208 while (kn->kn_status & KN_REPROCESS) {
209 kn->kn_status &= ~KN_REPROCESS;
210 if (kn->kn_status & KN_WAITING) {
211 kn->kn_status &= ~KN_WAITING;
214 if (kn->kn_status & KN_DELETING) {
215 knote_detach_and_drop(kn);
219 if (filter_event(kn, 0))
222 kn->kn_status &= ~KN_PROCESSING;
223 /* kn should not be accessed anymore */
227 filt_fileattach(struct knote *kn)
229 return (fo_kqfilter(kn->kn_fp, kn));
236 kqueue_kqfilter(struct file *fp, struct knote *kn)
238 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
240 if (kn->kn_filter != EVFILT_READ)
243 kn->kn_fop = &kqread_filtops;
244 knote_insert(&kq->kq_kqinfo.ki_note, kn);
249 filt_kqdetach(struct knote *kn)
251 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
253 knote_remove(&kq->kq_kqinfo.ki_note, kn);
258 filt_kqueue(struct knote *kn, long hint)
260 struct kqueue *kq = (struct kqueue *)kn->kn_fp->f_data;
262 kn->kn_data = kq->kq_count;
263 return (kn->kn_data > 0);
267 filt_procattach(struct knote *kn)
273 p = pfind(kn->kn_id);
274 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
275 p = zpfind(kn->kn_id);
281 if (!PRISON_CHECK(curthread->td_ucred, p->p_ucred)) {
287 lwkt_gettoken(&p->p_token);
288 kn->kn_ptr.p_proc = p;
289 kn->kn_flags |= EV_CLEAR; /* automatically set */
292 * internal flag indicating registration done by kernel
294 if (kn->kn_flags & EV_FLAG1) {
295 kn->kn_data = kn->kn_sdata; /* ppid */
296 kn->kn_fflags = NOTE_CHILD;
297 kn->kn_flags &= ~EV_FLAG1;
300 knote_insert(&p->p_klist, kn);
303 * Immediately activate any exit notes if the target process is a
304 * zombie. This is necessary to handle the case where the target
305 * process, e.g. a child, dies before the kevent is negistered.
307 if (immediate && filt_proc(kn, NOTE_EXIT))
309 lwkt_reltoken(&p->p_token);
316 * The knote may be attached to a different process, which may exit,
317 * leaving nothing for the knote to be attached to. So when the process
318 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
319 * it will be deleted when read out. However, as part of the knote deletion,
320 * this routine is called, so a check is needed to avoid actually performing
321 * a detach, because the original process does not exist any more.
324 filt_procdetach(struct knote *kn)
328 if (kn->kn_status & KN_DETACHED)
330 p = kn->kn_ptr.p_proc;
331 knote_remove(&p->p_klist, kn);
335 filt_proc(struct knote *kn, long hint)
340 * mask off extra data
342 event = (u_int)hint & NOTE_PCTRLMASK;
345 * if the user is interested in this event, record it.
347 if (kn->kn_sfflags & event)
348 kn->kn_fflags |= event;
351 * Process is gone, so flag the event as finished. Detach the
352 * knote from the process now because the process will be poof,
355 if (event == NOTE_EXIT) {
356 struct proc *p = kn->kn_ptr.p_proc;
357 if ((kn->kn_status & KN_DETACHED) == 0) {
359 knote_remove(&p->p_klist, kn);
360 kn->kn_status |= KN_DETACHED;
361 kn->kn_data = p->p_xstat;
362 kn->kn_ptr.p_proc = NULL;
365 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
370 * process forked, and user wants to track the new process,
371 * so attach a new knote to it, and immediately report an
372 * event with the parent's pid.
374 if ((event == NOTE_FORK) && (kn->kn_sfflags & NOTE_TRACK)) {
379 * register knote with new process.
381 kev.ident = hint & NOTE_PDATAMASK; /* pid */
382 kev.filter = kn->kn_filter;
383 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
384 kev.fflags = kn->kn_sfflags;
385 kev.data = kn->kn_id; /* parent */
386 kev.udata = kn->kn_kevent.udata; /* preserve udata */
387 error = kqueue_register(kn->kn_kq, &kev);
389 kn->kn_fflags |= NOTE_TRACKERR;
392 return (kn->kn_fflags != 0);
396 filt_timerreset(struct knote *kn)
398 struct callout *calloutp;
402 tv.tv_sec = kn->kn_sdata / 1000;
403 tv.tv_usec = (kn->kn_sdata % 1000) * 1000;
404 tticks = tvtohz_high(&tv);
405 calloutp = (struct callout *)kn->kn_hook;
406 callout_reset(calloutp, tticks, filt_timerexpire, kn);
410 * The callout interlocks with callout_terminate() but can still
411 * race a deletion so if KN_DELETING is set we just don't touch
415 filt_timerexpire(void *knx)
417 struct knote *kn = knx;
418 struct kqueue *kq = kn->kn_kq;
420 lwkt_getpooltoken(kq);
423 * Open knote_acquire(), since we can't sleep in callout,
424 * however, we do need to record this expiration.
427 if (kn->kn_status & KN_PROCESSING) {
428 kn->kn_status |= KN_REPROCESS;
429 if ((kn->kn_status & KN_DELETING) == 0 &&
430 (kn->kn_flags & EV_ONESHOT) == 0)
432 lwkt_relpooltoken(kq);
435 KASSERT((kn->kn_status & KN_DELETING) == 0,
436 ("acquire a deleting knote %#x", kn->kn_status));
437 kn->kn_status |= KN_PROCESSING;
440 if ((kn->kn_flags & EV_ONESHOT) == 0)
445 lwkt_relpooltoken(kq);
449 * data contains amount of time to sleep, in milliseconds
452 filt_timerattach(struct knote *kn)
454 struct callout *calloutp;
457 prev_ncallouts = atomic_fetchadd_int(&kq_ncallouts, 1);
458 if (prev_ncallouts >= kq_calloutmax) {
459 atomic_subtract_int(&kq_ncallouts, 1);
464 kn->kn_flags |= EV_CLEAR; /* automatically set */
465 calloutp = kmalloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
466 callout_init_mp(calloutp);
467 kn->kn_hook = (caddr_t)calloutp;
474 * This function is called with the knote flagged locked but it is
475 * still possible to race a callout event due to the callback blocking.
476 * We must call callout_terminate() instead of callout_stop() to deal
480 filt_timerdetach(struct knote *kn)
482 struct callout *calloutp;
484 calloutp = (struct callout *)kn->kn_hook;
485 callout_terminate(calloutp);
486 kfree(calloutp, M_KQUEUE);
487 atomic_subtract_int(&kq_ncallouts, 1);
491 filt_timer(struct knote *kn, long hint)
494 return (kn->kn_data != 0);
501 filt_userattach(struct knote *kn)
504 if (kn->kn_fflags & NOTE_TRIGGER)
505 kn->kn_ptr.hookid = 1;
507 kn->kn_ptr.hookid = 0;
512 filt_userdetach(struct knote *kn)
518 filt_user(struct knote *kn, long hint)
520 return (kn->kn_ptr.hookid);
524 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
530 if (kev->fflags & NOTE_TRIGGER)
531 kn->kn_ptr.hookid = 1;
533 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
534 kev->fflags &= NOTE_FFLAGSMASK;
540 kn->kn_sfflags &= kev->fflags;
544 kn->kn_sfflags |= kev->fflags;
548 kn->kn_sfflags = kev->fflags;
552 /* XXX Return error? */
555 kn->kn_sdata = kev->data;
558 * This is not the correct use of EV_CLEAR in an event
559 * modification, it should have been passed as a NOTE instead.
560 * But we need to maintain compatibility with Apple & FreeBSD.
562 * Note however that EV_CLEAR can still be used when doing
563 * the initial registration of the event and works as expected
564 * (clears the event on reception).
566 if (kev->flags & EV_CLEAR) {
567 kn->kn_ptr.hookid = 0;
574 *kev = kn->kn_kevent;
575 kev->fflags = kn->kn_sfflags;
576 kev->data = kn->kn_sdata;
577 if (kn->kn_flags & EV_CLEAR) {
578 kn->kn_ptr.hookid = 0;
579 /* kn_data, kn_fflags handled by parent */
584 panic("filt_usertouch() - invalid type (%ld)", type);
590 * Initialize a kqueue.
592 * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
597 kqueue_init(struct kqueue *kq, struct filedesc *fdp)
599 TAILQ_INIT(&kq->kq_knpend);
600 TAILQ_INIT(&kq->kq_knlist);
603 SLIST_INIT(&kq->kq_kqinfo.ki_note);
607 * Terminate a kqueue. Freeing the actual kq itself is left up to the
608 * caller (it might be embedded in a lwp so we don't do it here).
610 * The kq's knlist must be completely eradicated so block on any
614 kqueue_terminate(struct kqueue *kq)
618 lwkt_getpooltoken(kq);
619 while ((kn = TAILQ_FIRST(&kq->kq_knlist)) != NULL) {
620 if (knote_acquire(kn))
621 knote_detach_and_drop(kn);
623 lwkt_relpooltoken(kq);
626 hashdestroy(kq->kq_knhash, M_KQUEUE, kq->kq_knhashmask);
627 kq->kq_knhash = NULL;
628 kq->kq_knhashmask = 0;
636 sys_kqueue(struct kqueue_args *uap)
638 struct thread *td = curthread;
643 error = falloc(td->td_lwp, &fp, &fd);
646 fp->f_flag = FREAD | FWRITE;
647 fp->f_type = DTYPE_KQUEUE;
648 fp->f_ops = &kqueueops;
650 kq = kmalloc(sizeof(struct kqueue), M_KQUEUE, M_WAITOK | M_ZERO);
651 kqueue_init(kq, td->td_proc->p_fd);
654 fsetfd(kq->kq_fdp, fp, fd);
655 uap->sysmsg_result = fd;
661 * Copy 'count' items into the destination list pointed to by uap->eventlist.
664 kevent_copyout(void *arg, struct kevent *kevp, int count, int *res)
666 struct kevent_copyin_args *kap;
669 kap = (struct kevent_copyin_args *)arg;
671 error = copyout(kevp, kap->ka->eventlist, count * sizeof(*kevp));
673 kap->ka->eventlist += count;
683 * Copy at most 'max' items from the list pointed to by kap->changelist,
684 * return number of items in 'events'.
687 kevent_copyin(void *arg, struct kevent *kevp, int max, int *events)
689 struct kevent_copyin_args *kap;
692 kap = (struct kevent_copyin_args *)arg;
694 count = min(kap->ka->nchanges - kap->pchanges, max);
695 error = copyin(kap->ka->changelist, kevp, count * sizeof *kevp);
697 kap->ka->changelist += count;
698 kap->pchanges += count;
709 kern_kevent(struct kqueue *kq, int nevents, int *res, void *uap,
710 k_copyin_fn kevent_copyinfn, k_copyout_fn kevent_copyoutfn,
711 struct timespec *tsp_in)
714 struct timespec *tsp, ats;
715 int i, n, total, error, nerrors = 0;
717 int limit = kq_checkloop;
718 struct kevent kev[KQ_NEVENTS];
720 struct lwkt_token *tok;
722 if (tsp_in == NULL || tsp_in->tv_sec || tsp_in->tv_nsec)
723 atomic_set_int(&curthread->td_mpflags, TDF_MP_BATCH_DEMARC);
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
751 if (error || (kevp->flags & EV_RECEIPT)) {
752 kevp->flags = EV_ERROR;
755 kevent_copyoutfn(uap, kevp, 1, res);
758 } else if (lres != *res) {
769 * Acquire/wait for events - setup timeout
772 if (tsp->tv_sec || tsp->tv_nsec) {
774 timespecadd(tsp, &ats); /* tsp = target time */
781 * Collect as many events as we can. Sleeping on successive
782 * loops is disabled if copyoutfn has incremented (*res).
784 * The loop stops if an error occurs, all events have been
785 * scanned (the marker has been reached), or fewer than the
786 * maximum number of events is found.
788 * The copyoutfn function does not have to increment (*res) in
789 * order for the loop to continue.
791 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
795 marker.kn_filter = EVFILT_MARKER;
796 marker.kn_status = KN_PROCESSING;
797 tok = lwkt_token_pool_lookup(kq);
799 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
801 while ((n = nevents - total) > 0) {
806 * If no events are pending sleep until timeout (if any)
807 * or an event occurs.
809 * After the sleep completes the marker is moved to the
810 * end of the list, making any received events available
813 if (kq->kq_count == 0 && *res == 0) {
818 } else if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) {
822 struct timespec atx = *tsp;
825 timespecsub(&atx, &ats);
826 if (atx.tv_sec < 0) {
830 timeout = atx.tv_sec > 24 * 60 * 60 ?
837 if (kq->kq_count == 0) {
839 if (__predict_false(kq->kq_sleep_cnt == 0)) {
841 * Guard against possible wrapping. And
842 * set it to 2, so that kqueue_wakeup()
843 * can wake everyone up.
845 kq->kq_sleep_cnt = 2;
847 error = tsleep(kq, PCATCH, "kqread", timeout);
849 /* don't restart after signals... */
850 if (error == ERESTART)
857 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
858 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker,
865 * Process all received events
866 * Account for all non-spurious events in our total
868 i = kqueue_scan(kq, kev, n, &marker);
871 error = kevent_copyoutfn(uap, kev, i, res);
872 total += *res - lres;
876 if (limit && --limit == 0)
877 panic("kqueue: checkloop failed i=%d", i);
880 * Normally when fewer events are returned than requested
881 * we can stop. However, if only spurious events were
882 * collected the copyout will not bump (*res) and we have
889 * Deal with an edge case where spurious events can cause
890 * a loop to occur without moving the marker. This can
891 * prevent kqueue_scan() from picking up new events which
892 * race us. We must be sure to move the marker for this
895 * NOTE: We do not want to move the marker if events
896 * were scanned because normal kqueue operations
897 * may reactivate events. Moving the marker in
898 * that case could result in duplicates for the
903 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
904 TAILQ_INSERT_TAIL(&kq->kq_knpend, &marker, kn_tqe);
909 TAILQ_REMOVE(&kq->kq_knpend, &marker, kn_tqe);
912 /* Timeouts do not return EWOULDBLOCK. */
913 if (error == EWOULDBLOCK)
922 sys_kevent(struct kevent_args *uap)
924 struct thread *td = curthread;
925 struct proc *p = td->td_proc;
926 struct timespec ts, *tsp;
928 struct file *fp = NULL;
929 struct kevent_copyin_args *kap, ka;
933 error = copyin(uap->timeout, &ts, sizeof(ts));
940 fp = holdfp(p->p_fd, uap->fd, -1);
943 if (fp->f_type != DTYPE_KQUEUE) {
948 kq = (struct kqueue *)fp->f_data;
954 error = kern_kevent(kq, uap->nevents, &uap->sysmsg_result, kap,
955 kevent_copyin, kevent_copyout, tsp);
963 kqueue_register(struct kqueue *kq, struct kevent *kev)
965 struct filedesc *fdp = kq->kq_fdp;
966 struct klist *list = NULL;
967 struct filterops *fops;
968 struct file *fp = NULL;
969 struct knote *kn = NULL;
972 struct knote_cache_list *cache_list;
974 if (kev->filter < 0) {
975 if (kev->filter + EVFILT_SYSCOUNT < 0)
977 fops = sysfilt_ops[~kev->filter]; /* to 0-base index */
981 * filter attach routine is responsible for insuring that
982 * the identifier can be attached to it.
987 if (fops->f_flags & FILTEROP_ISFD) {
988 /* validate descriptor */
989 fp = holdfp(fdp, kev->ident, -1);
994 cache_list = &knote_cache_lists[mycpuid];
995 if (SLIST_EMPTY(&cache_list->knote_cache)) {
996 struct knote *new_kn;
998 new_kn = knote_alloc();
999 SLIST_INSERT_HEAD(&cache_list->knote_cache, new_kn, kn_link);
1000 cache_list->knote_cache_cnt++;
1004 lwkt_getpooltoken(kq);
1007 * Make sure that only one thread can register event on this kqueue,
1008 * so that we would not suffer any race, even if the registration
1009 * blocked, i.e. kq token was released, and the kqueue was shared
1010 * between threads (this should be rare though).
1012 while (__predict_false(kq->kq_regtd != NULL && kq->kq_regtd != td)) {
1013 kq->kq_state |= KQ_REGWAIT;
1014 tsleep(&kq->kq_regtd, 0, "kqreg", 0);
1016 if (__predict_false(kq->kq_regtd != NULL)) {
1017 /* Recursive calling of kqueue_register() */
1020 /* Owner of the kq_regtd, i.e. td != NULL */
1025 list = &fp->f_klist;
1026 } else if (kq->kq_knhashmask) {
1027 list = &kq->kq_knhash[
1028 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1031 lwkt_getpooltoken(list);
1033 SLIST_FOREACH(kn, list, kn_link) {
1034 if (kn->kn_kq == kq &&
1035 kn->kn_filter == kev->filter &&
1036 kn->kn_id == kev->ident) {
1037 if (knote_acquire(kn) == 0)
1042 lwkt_relpooltoken(list);
1046 * NOTE: At this point if kn is non-NULL we will have acquired
1047 * it and set KN_PROCESSING.
1049 if (kn == NULL && ((kev->flags & EV_ADD) == 0)) {
1055 * kn now contains the matching knote, or NULL if no match
1057 if (kev->flags & EV_ADD) {
1059 kn = SLIST_FIRST(&cache_list->knote_cache);
1063 SLIST_REMOVE_HEAD(&cache_list->knote_cache,
1065 cache_list->knote_cache_cnt--;
1072 * apply reference count to knote structure, and
1073 * do not release it at the end of this routine.
1077 kn->kn_sfflags = kev->fflags;
1078 kn->kn_sdata = kev->data;
1081 kn->kn_kevent = *kev;
1084 * KN_PROCESSING prevents the knote from getting
1085 * ripped out from under us while we are trying
1086 * to attach it, in case the attach blocks.
1088 kn->kn_status = KN_PROCESSING;
1090 if ((error = filter_attach(kn)) != 0) {
1091 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1097 * Interlock against close races which either tried
1098 * to remove our knote while we were blocked or missed
1099 * it entirely prior to our attachment. We do not
1100 * want to end up with a knote on a closed descriptor.
1102 if ((fops->f_flags & FILTEROP_ISFD) &&
1103 checkfdclosed(fdp, kev->ident, kn->kn_fp)) {
1104 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1108 * The user may change some filter values after the
1109 * initial EV_ADD, but doing so will not reset any
1110 * filter which have already been triggered.
1112 KKASSERT(kn->kn_status & KN_PROCESSING);
1113 if (fops == &user_filtops) {
1114 filt_usertouch(kn, kev, EVENT_REGISTER);
1116 kn->kn_sfflags = kev->fflags;
1117 kn->kn_sdata = kev->data;
1118 kn->kn_kevent.udata = kev->udata;
1123 * Execute the filter event to immediately activate the
1124 * knote if necessary. If reprocessing events are pending
1125 * due to blocking above we do not run the filter here
1126 * but instead let knote_release() do it. Otherwise we
1127 * might run the filter on a deleted event.
1129 if ((kn->kn_status & KN_REPROCESS) == 0) {
1130 if (filter_event(kn, 0))
1133 } else if (kev->flags & EV_DELETE) {
1135 * Delete the existing knote
1137 knote_detach_and_drop(kn);
1141 * Modify an existing event.
1143 * The user may change some filter values after the
1144 * initial EV_ADD, but doing so will not reset any
1145 * filter which have already been triggered.
1147 KKASSERT(kn->kn_status & KN_PROCESSING);
1148 if (fops == &user_filtops) {
1149 filt_usertouch(kn, kev, EVENT_REGISTER);
1151 kn->kn_sfflags = kev->fflags;
1152 kn->kn_sdata = kev->data;
1153 kn->kn_kevent.udata = kev->udata;
1157 * Execute the filter event to immediately activate the
1158 * knote if necessary. If reprocessing events are pending
1159 * due to blocking above we do not run the filter here
1160 * but instead let knote_release() do it. Otherwise we
1161 * might run the filter on a deleted event.
1163 if ((kn->kn_status & KN_REPROCESS) == 0) {
1164 if (filter_event(kn, 0))
1170 * Disablement does not deactivate a knote here.
1172 if ((kev->flags & EV_DISABLE) &&
1173 ((kn->kn_status & KN_DISABLED) == 0)) {
1174 kn->kn_status |= KN_DISABLED;
1178 * Re-enablement may have to immediately enqueue an active knote.
1180 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1181 kn->kn_status &= ~KN_DISABLED;
1182 if ((kn->kn_status & KN_ACTIVE) &&
1183 ((kn->kn_status & KN_QUEUED) == 0)) {
1189 * Handle any required reprocessing
1192 /* kn may be invalid now */
1195 if (td != NULL) { /* Owner of the kq_regtd */
1196 kq->kq_regtd = NULL;
1197 if (__predict_false(kq->kq_state & KQ_REGWAIT)) {
1198 kq->kq_state &= ~KQ_REGWAIT;
1199 wakeup(&kq->kq_regtd);
1202 lwkt_relpooltoken(kq);
1209 * Scan the kqueue, return the number of active events placed in kevp up
1212 * Continuous mode events may get recycled, do not continue scanning past
1213 * marker unless no events have been collected.
1216 kqueue_scan(struct kqueue *kq, struct kevent *kevp, int count,
1217 struct knote *marker)
1219 struct knote *kn, local_marker;
1223 local_marker.kn_filter = EVFILT_MARKER;
1224 local_marker.kn_status = KN_PROCESSING;
1226 lwkt_getpooltoken(kq);
1231 TAILQ_INSERT_HEAD(&kq->kq_knpend, &local_marker, kn_tqe);
1233 kn = TAILQ_NEXT(&local_marker, kn_tqe);
1234 if (kn->kn_filter == EVFILT_MARKER) {
1235 /* Marker reached, we are done */
1239 /* Move local marker past some other threads marker */
1240 kn = TAILQ_NEXT(kn, kn_tqe);
1241 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1242 TAILQ_INSERT_BEFORE(kn, &local_marker, kn_tqe);
1247 * We can't skip a knote undergoing processing, otherwise
1248 * we risk not returning it when the user process expects
1249 * it should be returned. Sleep and retry.
1251 if (knote_acquire(kn) == 0)
1255 * Remove the event for processing.
1257 * WARNING! We must leave KN_QUEUED set to prevent the
1258 * event from being KNOTE_ACTIVATE()d while
1259 * the queue state is in limbo, in case we
1262 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1266 * We have to deal with an extremely important race against
1267 * file descriptor close()s here. The file descriptor can
1268 * disappear MPSAFE, and there is a small window of
1269 * opportunity between that and the call to knote_fdclose().
1271 * If we hit that window here while doselect or dopoll is
1272 * trying to delete a spurious event they will not be able
1273 * to match up the event against a knote and will go haywire.
1275 if ((kn->kn_fop->f_flags & FILTEROP_ISFD) &&
1276 checkfdclosed(kq->kq_fdp, kn->kn_kevent.ident, kn->kn_fp)) {
1277 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1280 if (kn->kn_status & KN_DISABLED) {
1282 * If disabled we ensure the event is not queued
1283 * but leave its active bit set. On re-enablement
1284 * the event may be immediately triggered.
1286 kn->kn_status &= ~KN_QUEUED;
1287 } else if ((kn->kn_flags & EV_ONESHOT) == 0 &&
1288 (kn->kn_status & KN_DELETING) == 0 &&
1289 filter_event(kn, 0) == 0) {
1291 * If not running in one-shot mode and the event
1292 * is no longer present we ensure it is removed
1293 * from the queue and ignore it.
1295 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1300 if (kn->kn_fop == &user_filtops)
1301 filt_usertouch(kn, kevp, EVENT_PROCESS);
1303 *kevp = kn->kn_kevent;
1308 if (kn->kn_flags & EV_ONESHOT) {
1309 kn->kn_status &= ~KN_QUEUED;
1310 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1312 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1313 if (kn->kn_flags & EV_CLEAR) {
1317 if (kn->kn_flags & EV_DISPATCH) {
1318 kn->kn_status |= KN_DISABLED;
1320 kn->kn_status &= ~(KN_QUEUED |
1323 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1330 * Handle any post-processing states
1334 TAILQ_REMOVE(&kq->kq_knpend, &local_marker, kn_tqe);
1336 lwkt_relpooltoken(kq);
1342 * This could be expanded to call kqueue_scan, if desired.
1347 kqueue_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1356 kqueue_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
1365 kqueue_ioctl(struct file *fp, u_long com, caddr_t data,
1366 struct ucred *cred, struct sysmsg *msg)
1371 kq = (struct kqueue *)fp->f_data;
1372 lwkt_getpooltoken(kq);
1376 kq->kq_state |= KQ_ASYNC;
1378 kq->kq_state &= ~KQ_ASYNC;
1382 error = fsetown(*(int *)data, &kq->kq_sigio);
1388 lwkt_relpooltoken(kq);
1396 kqueue_stat(struct file *fp, struct stat *st, struct ucred *cred)
1398 struct kqueue *kq = (struct kqueue *)fp->f_data;
1400 bzero((void *)st, sizeof(*st));
1401 st->st_size = kq->kq_count;
1402 st->st_blksize = sizeof(struct kevent);
1403 st->st_mode = S_IFIFO;
1411 kqueue_close(struct file *fp)
1413 struct kqueue *kq = (struct kqueue *)fp->f_data;
1415 kqueue_terminate(kq);
1418 funsetown(&kq->kq_sigio);
1420 kfree(kq, M_KQUEUE);
1425 kqueue_wakeup(struct kqueue *kq)
1427 if (kq->kq_sleep_cnt) {
1428 u_int sleep_cnt = kq->kq_sleep_cnt;
1430 kq->kq_sleep_cnt = 0;
1436 KNOTE(&kq->kq_kqinfo.ki_note, 0);
1440 * Calls filterops f_attach function, acquiring mplock if filter is not
1441 * marked as FILTEROP_MPSAFE.
1443 * Caller must be holding the related kq token
1446 filter_attach(struct knote *kn)
1450 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1451 ret = kn->kn_fop->f_attach(kn);
1454 ret = kn->kn_fop->f_attach(kn);
1461 * Detach the knote and drop it, destroying the knote.
1463 * Calls filterops f_detach function, acquiring mplock if filter is not
1464 * marked as FILTEROP_MPSAFE.
1466 * Caller must be holding the related kq token
1469 knote_detach_and_drop(struct knote *kn)
1471 kn->kn_status |= KN_DELETING | KN_REPROCESS;
1472 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1473 kn->kn_fop->f_detach(kn);
1476 kn->kn_fop->f_detach(kn);
1483 * Calls filterops f_event function, acquiring mplock if filter is not
1484 * marked as FILTEROP_MPSAFE.
1486 * If the knote is in the middle of being created or deleted we cannot
1487 * safely call the filter op.
1489 * Caller must be holding the related kq token
1492 filter_event(struct knote *kn, long hint)
1496 if (kn->kn_fop->f_flags & FILTEROP_MPSAFE) {
1497 ret = kn->kn_fop->f_event(kn, hint);
1500 ret = kn->kn_fop->f_event(kn, hint);
1507 * Walk down a list of knotes, activating them if their event has triggered.
1509 * If we encounter any knotes which are undergoing processing we just mark
1510 * them for reprocessing and do not try to [re]activate the knote. However,
1511 * if a hint is being passed we have to wait and that makes things a bit
1515 knote(struct klist *list, long hint)
1517 struct knote *kn, marker;
1519 marker.kn_filter = EVFILT_MARKER;
1520 marker.kn_status = KN_PROCESSING;
1522 lwkt_getpooltoken(list);
1523 if (SLIST_EMPTY(list)) {
1524 lwkt_relpooltoken(list);
1528 SLIST_INSERT_HEAD(list, &marker, kn_next);
1529 while ((kn = SLIST_NEXT(&marker, kn_next)) != NULL) {
1533 if (kn->kn_filter == EVFILT_MARKER) {
1535 SLIST_REMOVE(list, &marker, knote, kn_next);
1536 if (SLIST_NEXT(kn, kn_next) == NULL)
1538 SLIST_INSERT_AFTER(kn, &marker, kn_next);
1543 lwkt_getpooltoken(kq);
1545 if (kn != SLIST_NEXT(&marker, kn_next) || kn->kn_kq != kq) {
1547 * Don't move the marker; check the knote after
1550 lwkt_relpooltoken(kq);
1554 if (kn->kn_status & KN_PROCESSING) {
1556 * Someone else is processing the knote, ask the
1557 * other thread to reprocess it and don't mess
1558 * with it otherwise.
1562 * Move the marker w/ the kq token, so that
1563 * this knote will not be ripped behind our
1566 SLIST_REMOVE(list, &marker, knote, kn_next);
1567 if (SLIST_NEXT(kn, kn_next) != NULL)
1568 SLIST_INSERT_AFTER(kn, &marker, kn_next);
1571 kn->kn_status |= KN_REPROCESS;
1572 lwkt_relpooltoken(kq);
1580 * If the hint is non-zero we have to wait or risk
1581 * losing the state the caller is trying to update.
1583 kn->kn_status |= KN_WAITING | KN_REPROCESS;
1584 tsleep(kn, 0, "knotec", hz);
1587 * Don't move the marker; check this knote again,
1588 * hopefully it is still after the marker. Or it
1589 * was deleted and we would check the next knote.
1591 lwkt_relpooltoken(kq);
1596 * Become the reprocessing master ourselves.
1598 KASSERT((kn->kn_status & KN_DELETING) == 0,
1599 ("acquire a deleting knote %#x", kn->kn_status));
1600 kn->kn_status |= KN_PROCESSING;
1602 /* Move the marker */
1603 SLIST_REMOVE(list, &marker, knote, kn_next);
1604 if (SLIST_NEXT(kn, kn_next) != NULL)
1605 SLIST_INSERT_AFTER(kn, &marker, kn_next);
1610 * If hint is non-zero running the event is mandatory
1611 * so do it whether reprocessing is set or not.
1613 if (filter_event(kn, hint))
1617 lwkt_relpooltoken(kq);
1622 SLIST_REMOVE(list, &marker, knote, kn_next);
1624 lwkt_relpooltoken(list);
1628 * Insert knote at head of klist.
1630 * This function may only be called via a filter function and thus
1631 * kq_token should already be held and marked for processing.
1634 knote_insert(struct klist *klist, struct knote *kn)
1636 lwkt_getpooltoken(klist);
1637 KKASSERT(kn->kn_status & KN_PROCESSING);
1638 SLIST_INSERT_HEAD(klist, kn, kn_next);
1639 lwkt_relpooltoken(klist);
1643 * Remove knote from a klist
1645 * This function may only be called via a filter function and thus
1646 * kq_token should already be held and marked for processing.
1649 knote_remove(struct klist *klist, struct knote *kn)
1651 lwkt_getpooltoken(klist);
1652 KKASSERT(kn->kn_status & KN_PROCESSING);
1653 SLIST_REMOVE(klist, kn, knote, kn_next);
1654 lwkt_relpooltoken(klist);
1658 knote_assume_knotes(struct kqinfo *src, struct kqinfo *dst,
1659 struct filterops *ops, void *hook)
1661 struct knote *kn, marker;
1664 marker.kn_filter = EVFILT_MARKER;
1665 marker.kn_status = KN_PROCESSING;
1667 lwkt_getpooltoken(&src->ki_note);
1668 if (SLIST_EMPTY(&src->ki_note)) {
1669 lwkt_relpooltoken(&src->ki_note);
1672 lwkt_getpooltoken(&dst->ki_note);
1676 SLIST_INSERT_HEAD(&src->ki_note, &marker, kn_next);
1677 while ((kn = SLIST_NEXT(&marker, kn_next)) != NULL) {
1680 if (kn->kn_filter == EVFILT_MARKER) {
1682 SLIST_REMOVE(&src->ki_note, &marker, knote, kn_next);
1683 SLIST_INSERT_AFTER(kn, &marker, kn_next);
1688 lwkt_getpooltoken(kq);
1690 if (kn != SLIST_NEXT(&marker, kn_next) || kn->kn_kq != kq) {
1692 * Don't move the marker; check the knote after
1695 lwkt_relpooltoken(kq);
1700 SLIST_REMOVE(&src->ki_note, &marker, knote, kn_next);
1701 SLIST_INSERT_AFTER(kn, &marker, kn_next);
1704 if (knote_acquire(kn)) {
1705 knote_remove(&src->ki_note, kn);
1708 knote_insert(&dst->ki_note, kn);
1710 /* kn may be invalid now */
1712 lwkt_relpooltoken(kq);
1714 SLIST_REMOVE(&src->ki_note, &marker, knote, kn_next);
1716 /* Keep draining, until nothing left */
1720 lwkt_relpooltoken(&dst->ki_note);
1721 lwkt_relpooltoken(&src->ki_note);
1725 * Remove all knotes referencing a specified fd
1728 knote_fdclose(struct file *fp, struct filedesc *fdp, int fd)
1732 struct knote *kntmp;
1734 lwkt_getpooltoken(&fp->f_klist);
1736 SLIST_FOREACH(kn, &fp->f_klist, kn_link) {
1737 if (kn->kn_kq->kq_fdp == fdp && kn->kn_id == fd) {
1739 lwkt_getpooltoken(kq);
1741 /* temporary verification hack */
1742 SLIST_FOREACH(kntmp, &fp->f_klist, kn_link) {
1746 if (kn != kntmp || kn->kn_kq->kq_fdp != fdp ||
1747 kn->kn_id != fd || kn->kn_kq != kq) {
1748 lwkt_relpooltoken(kq);
1751 if (knote_acquire(kn))
1752 knote_detach_and_drop(kn);
1753 lwkt_relpooltoken(kq);
1757 lwkt_relpooltoken(&fp->f_klist);
1761 * Low level attach function.
1763 * The knote should already be marked for processing.
1764 * Caller must hold the related kq token.
1767 knote_attach(struct knote *kn)
1770 struct kqueue *kq = kn->kn_kq;
1772 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1773 KKASSERT(kn->kn_fp);
1774 list = &kn->kn_fp->f_klist;
1776 if (kq->kq_knhashmask == 0)
1777 kq->kq_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1778 &kq->kq_knhashmask);
1779 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1781 lwkt_getpooltoken(list);
1782 SLIST_INSERT_HEAD(list, kn, kn_link);
1783 lwkt_relpooltoken(list);
1784 TAILQ_INSERT_HEAD(&kq->kq_knlist, kn, kn_kqlink);
1788 * Low level drop function.
1790 * The knote should already be marked for processing.
1791 * Caller must hold the related kq token.
1794 knote_drop(struct knote *kn)
1801 if (kn->kn_fop->f_flags & FILTEROP_ISFD)
1802 list = &kn->kn_fp->f_klist;
1804 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
1806 lwkt_getpooltoken(list);
1807 SLIST_REMOVE(list, kn, knote, kn_link);
1808 lwkt_relpooltoken(list);
1809 TAILQ_REMOVE(&kq->kq_knlist, kn, kn_kqlink);
1810 if (kn->kn_status & KN_QUEUED)
1812 if (kn->kn_fop->f_flags & FILTEROP_ISFD) {
1820 * Low level enqueue function.
1822 * The knote should already be marked for processing.
1823 * Caller must be holding the kq token
1826 knote_enqueue(struct knote *kn)
1828 struct kqueue *kq = kn->kn_kq;
1830 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
1831 TAILQ_INSERT_TAIL(&kq->kq_knpend, kn, kn_tqe);
1832 kn->kn_status |= KN_QUEUED;
1836 * Send SIGIO on request (typically set up as a mailbox signal)
1838 if (kq->kq_sigio && (kq->kq_state & KQ_ASYNC) && kq->kq_count == 1)
1839 pgsigio(kq->kq_sigio, SIGIO, 0);
1845 * Low level dequeue function.
1847 * The knote should already be marked for processing.
1848 * Caller must be holding the kq token
1851 knote_dequeue(struct knote *kn)
1853 struct kqueue *kq = kn->kn_kq;
1855 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
1856 TAILQ_REMOVE(&kq->kq_knpend, kn, kn_tqe);
1857 kn->kn_status &= ~KN_QUEUED;
1861 static struct knote *
1864 return kmalloc(sizeof(struct knote), M_KQUEUE, M_WAITOK);
1868 knote_free(struct knote *kn)
1870 struct knote_cache_list *cache_list;
1872 cache_list = &knote_cache_lists[mycpuid];
1873 if (cache_list->knote_cache_cnt < KNOTE_CACHE_MAX) {
1874 SLIST_INSERT_HEAD(&cache_list->knote_cache, kn, kn_link);
1875 cache_list->knote_cache_cnt++;
1878 kfree(kn, M_KQUEUE);