2 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
3 * Copyright 2004 John-Mark Gurney <jmg@FreeBSD.org>
4 * Copyright (c) 2009 Apple, Inc.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include "opt_ktrace.h"
33 #include "opt_kqueue.h"
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/capsicum.h>
38 #include <sys/kernel.h>
40 #include <sys/mutex.h>
41 #include <sys/rwlock.h>
43 #include <sys/malloc.h>
44 #include <sys/unistd.h>
46 #include <sys/filedesc.h>
47 #include <sys/filio.h>
48 #include <sys/fcntl.h>
49 #include <sys/kthread.h>
50 #include <sys/selinfo.h>
51 #include <sys/stdatomic.h>
52 #include <sys/queue.h>
53 #include <sys/event.h>
54 #include <sys/eventvar.h>
56 #include <sys/protosw.h>
57 #include <sys/resourcevar.h>
58 #include <sys/sigio.h>
59 #include <sys/signalvar.h>
60 #include <sys/socket.h>
61 #include <sys/socketvar.h>
63 #include <sys/sysctl.h>
64 #include <sys/sysproto.h>
65 #include <sys/syscallsubr.h>
66 #include <sys/taskqueue.h>
70 #include <sys/ktrace.h>
75 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
78 * This lock is used if multiple kq locks are required. This possibly
79 * should be made into a per proc lock.
81 static struct mtx kq_global;
82 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
83 #define KQ_GLOBAL_LOCK(lck, haslck) do { \
88 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
94 TASKQUEUE_DEFINE_THREAD(kqueue);
96 static int kevent_copyout(void *arg, struct kevent *kevp, int count);
97 static int kevent_copyin(void *arg, struct kevent *kevp, int count);
98 static int kqueue_register(struct kqueue *kq, struct kevent *kev,
99 struct thread *td, int waitok);
100 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
101 static void kqueue_release(struct kqueue *kq, int locked);
102 static void kqueue_destroy(struct kqueue *kq);
103 static void kqueue_drain(struct kqueue *kq, struct thread *td);
104 static int kqueue_expand(struct kqueue *kq, struct filterops *fops,
105 uintptr_t ident, int waitok);
106 static void kqueue_task(void *arg, int pending);
107 static int kqueue_scan(struct kqueue *kq, int maxevents,
108 struct kevent_copyops *k_ops,
109 const struct timespec *timeout,
110 struct kevent *keva, struct thread *td);
111 static void kqueue_wakeup(struct kqueue *kq);
112 static struct filterops *kqueue_fo_find(int filt);
113 static void kqueue_fo_release(int filt);
115 static fo_ioctl_t kqueue_ioctl;
116 static fo_poll_t kqueue_poll;
117 static fo_kqfilter_t kqueue_kqfilter;
118 static fo_stat_t kqueue_stat;
119 static fo_close_t kqueue_close;
120 static fo_fill_kinfo_t kqueue_fill_kinfo;
122 static struct fileops kqueueops = {
123 .fo_read = invfo_rdwr,
124 .fo_write = invfo_rdwr,
125 .fo_truncate = invfo_truncate,
126 .fo_ioctl = kqueue_ioctl,
127 .fo_poll = kqueue_poll,
128 .fo_kqfilter = kqueue_kqfilter,
129 .fo_stat = kqueue_stat,
130 .fo_close = kqueue_close,
131 .fo_chmod = invfo_chmod,
132 .fo_chown = invfo_chown,
133 .fo_sendfile = invfo_sendfile,
134 .fo_fill_kinfo = kqueue_fill_kinfo,
137 static int knote_attach(struct knote *kn, struct kqueue *kq);
138 static void knote_drop(struct knote *kn, struct thread *td);
139 static void knote_enqueue(struct knote *kn);
140 static void knote_dequeue(struct knote *kn);
141 static void knote_init(void);
142 static struct knote *knote_alloc(int waitok);
143 static void knote_free(struct knote *kn);
145 static void filt_kqdetach(struct knote *kn);
146 static int filt_kqueue(struct knote *kn, long hint);
147 static int filt_procattach(struct knote *kn);
148 static void filt_procdetach(struct knote *kn);
149 static int filt_proc(struct knote *kn, long hint);
150 static int filt_fileattach(struct knote *kn);
151 static void filt_timerexpire(void *knx);
152 static int filt_timerattach(struct knote *kn);
153 static void filt_timerdetach(struct knote *kn);
154 static int filt_timer(struct knote *kn, long hint);
155 static int filt_userattach(struct knote *kn);
156 static void filt_userdetach(struct knote *kn);
157 static int filt_user(struct knote *kn, long hint);
158 static void filt_usertouch(struct knote *kn, struct kevent *kev,
161 static struct filterops file_filtops = {
163 .f_attach = filt_fileattach,
165 static struct filterops kqread_filtops = {
167 .f_detach = filt_kqdetach,
168 .f_event = filt_kqueue,
170 /* XXX - move to kern_proc.c? */
171 static struct filterops proc_filtops = {
173 .f_attach = filt_procattach,
174 .f_detach = filt_procdetach,
175 .f_event = filt_proc,
177 static struct filterops timer_filtops = {
179 .f_attach = filt_timerattach,
180 .f_detach = filt_timerdetach,
181 .f_event = filt_timer,
183 static struct filterops user_filtops = {
184 .f_attach = filt_userattach,
185 .f_detach = filt_userdetach,
186 .f_event = filt_user,
187 .f_touch = filt_usertouch,
190 static uma_zone_t knote_zone;
191 static atomic_uint kq_ncallouts = ATOMIC_VAR_INIT(0);
192 static unsigned int kq_calloutmax = 4 * 1024;
193 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
194 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
196 /* XXX - ensure not KN_INFLUX?? */
197 #define KNOTE_ACTIVATE(kn, islock) do { \
199 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
201 KQ_LOCK((kn)->kn_kq); \
202 (kn)->kn_status |= KN_ACTIVE; \
203 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
204 knote_enqueue((kn)); \
206 KQ_UNLOCK((kn)->kn_kq); \
208 #define KQ_LOCK(kq) do { \
209 mtx_lock(&(kq)->kq_lock); \
211 #define KQ_FLUX_WAKEUP(kq) do { \
212 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
213 (kq)->kq_state &= ~KQ_FLUXWAIT; \
217 #define KQ_UNLOCK_FLUX(kq) do { \
218 KQ_FLUX_WAKEUP(kq); \
219 mtx_unlock(&(kq)->kq_lock); \
221 #define KQ_UNLOCK(kq) do { \
222 mtx_unlock(&(kq)->kq_lock); \
224 #define KQ_OWNED(kq) do { \
225 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
227 #define KQ_NOTOWNED(kq) do { \
228 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
230 #define KN_LIST_LOCK(kn) do { \
231 if (kn->kn_knlist != NULL) \
232 kn->kn_knlist->kl_lock(kn->kn_knlist->kl_lockarg); \
234 #define KN_LIST_UNLOCK(kn) do { \
235 if (kn->kn_knlist != NULL) \
236 kn->kn_knlist->kl_unlock(kn->kn_knlist->kl_lockarg); \
238 #define KNL_ASSERT_LOCK(knl, islocked) do { \
240 KNL_ASSERT_LOCKED(knl); \
242 KNL_ASSERT_UNLOCKED(knl); \
245 #define KNL_ASSERT_LOCKED(knl) do { \
246 knl->kl_assert_locked((knl)->kl_lockarg); \
248 #define KNL_ASSERT_UNLOCKED(knl) do { \
249 knl->kl_assert_unlocked((knl)->kl_lockarg); \
251 #else /* !INVARIANTS */
252 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
253 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
254 #endif /* INVARIANTS */
257 #define KN_HASHSIZE 64 /* XXX should be tunable */
260 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
263 filt_nullattach(struct knote *kn)
269 struct filterops null_filtops = {
271 .f_attach = filt_nullattach,
274 /* XXX - make SYSINIT to add these, and move into respective modules. */
275 extern struct filterops sig_filtops;
276 extern struct filterops fs_filtops;
279 * Table for for all system-defined filters.
281 static struct mtx filterops_lock;
282 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
285 struct filterops *for_fop;
288 } sysfilt_ops[EVFILT_SYSCOUNT] = {
289 { &file_filtops, 1 }, /* EVFILT_READ */
290 { &file_filtops, 1 }, /* EVFILT_WRITE */
291 { &null_filtops }, /* EVFILT_AIO */
292 { &file_filtops, 1 }, /* EVFILT_VNODE */
293 { &proc_filtops, 1 }, /* EVFILT_PROC */
294 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
295 { &timer_filtops, 1 }, /* EVFILT_TIMER */
296 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
297 { &fs_filtops, 1 }, /* EVFILT_FS */
298 { &null_filtops }, /* EVFILT_LIO */
299 { &user_filtops, 1 }, /* EVFILT_USER */
300 { &null_filtops }, /* EVFILT_SENDFILE */
304 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
308 filt_fileattach(struct knote *kn)
311 return (fo_kqfilter(kn->kn_fp, kn));
316 kqueue_kqfilter(struct file *fp, struct knote *kn)
318 struct kqueue *kq = kn->kn_fp->f_data;
320 if (kn->kn_filter != EVFILT_READ)
323 kn->kn_status |= KN_KQUEUE;
324 kn->kn_fop = &kqread_filtops;
325 knlist_add(&kq->kq_sel.si_note, kn, 0);
331 filt_kqdetach(struct knote *kn)
333 struct kqueue *kq = kn->kn_fp->f_data;
335 knlist_remove(&kq->kq_sel.si_note, kn, 0);
340 filt_kqueue(struct knote *kn, long hint)
342 struct kqueue *kq = kn->kn_fp->f_data;
344 kn->kn_data = kq->kq_count;
345 return (kn->kn_data > 0);
348 /* XXX - move to kern_proc.c? */
350 filt_procattach(struct knote *kn)
357 p = pfind(kn->kn_id);
358 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
359 p = zpfind(kn->kn_id);
361 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
367 if ((error = p_cansee(curthread, p))) {
372 kn->kn_ptr.p_proc = p;
373 kn->kn_flags |= EV_CLEAR; /* automatically set */
376 * Internal flag indicating registration done by kernel for the
377 * purposes of getting a NOTE_CHILD notification.
379 if (kn->kn_flags & EV_FLAG2) {
380 kn->kn_flags &= ~EV_FLAG2;
381 kn->kn_data = kn->kn_sdata; /* ppid */
382 kn->kn_fflags = NOTE_CHILD;
383 kn->kn_sfflags &= ~NOTE_EXIT;
384 immediate = 1; /* Force immediate activation of child note. */
387 * Internal flag indicating registration done by kernel (for other than
390 if (kn->kn_flags & EV_FLAG1) {
391 kn->kn_flags &= ~EV_FLAG1;
395 knlist_add(&p->p_klist, kn, 1);
398 * Immediately activate any child notes or, in the case of a zombie
399 * target process, exit notes. The latter is necessary to handle the
400 * case where the target process, e.g. a child, dies before the kevent
403 if (immediate && filt_proc(kn, NOTE_EXIT))
404 KNOTE_ACTIVATE(kn, 0);
412 * The knote may be attached to a different process, which may exit,
413 * leaving nothing for the knote to be attached to. So when the process
414 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
415 * it will be deleted when read out. However, as part of the knote deletion,
416 * this routine is called, so a check is needed to avoid actually performing
417 * a detach, because the original process does not exist any more.
419 /* XXX - move to kern_proc.c? */
421 filt_procdetach(struct knote *kn)
425 p = kn->kn_ptr.p_proc;
426 knlist_remove(&p->p_klist, kn, 0);
427 kn->kn_ptr.p_proc = NULL;
430 /* XXX - move to kern_proc.c? */
432 filt_proc(struct knote *kn, long hint)
437 p = kn->kn_ptr.p_proc;
438 /* Mask off extra data. */
439 event = (u_int)hint & NOTE_PCTRLMASK;
441 /* If the user is interested in this event, record it. */
442 if (kn->kn_sfflags & event)
443 kn->kn_fflags |= event;
445 /* Process is gone, so flag the event as finished. */
446 if (event == NOTE_EXIT) {
447 if (!(kn->kn_status & KN_DETACHED))
448 knlist_remove_inevent(&p->p_klist, kn);
449 kn->kn_flags |= EV_EOF | EV_ONESHOT;
450 kn->kn_ptr.p_proc = NULL;
451 if (kn->kn_fflags & NOTE_EXIT)
452 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
453 if (kn->kn_fflags == 0)
454 kn->kn_flags |= EV_DROP;
458 return (kn->kn_fflags != 0);
462 * Called when the process forked. It mostly does the same as the
463 * knote(), activating all knotes registered to be activated when the
464 * process forked. Additionally, for each knote attached to the
465 * parent, check whether user wants to track the new process. If so
466 * attach a new knote to it, and immediately report an event with the
470 knote_fork(struct knlist *list, int pid)
479 list->kl_lock(list->kl_lockarg);
481 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
483 * XXX - Why do we skip the kn if it is _INFLUX? Does this
484 * mean we will not properly wake up some notes?
486 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX)
490 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
496 * The same as knote(), activate the event.
498 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
499 kn->kn_status |= KN_HASKQLOCK;
500 if (kn->kn_fop->f_event(kn, NOTE_FORK))
501 KNOTE_ACTIVATE(kn, 1);
502 kn->kn_status &= ~KN_HASKQLOCK;
508 * The NOTE_TRACK case. In addition to the activation
509 * of the event, we need to register new events to
510 * track the child. Drop the locks in preparation for
511 * the call to kqueue_register().
513 kn->kn_status |= KN_INFLUX;
515 list->kl_unlock(list->kl_lockarg);
518 * Activate existing knote and register tracking knotes with
521 * First register a knote to get just the child notice. This
522 * must be a separate note from a potential NOTE_EXIT
523 * notification since both NOTE_CHILD and NOTE_EXIT are defined
524 * to use the data field (in conflicting ways).
527 kev.filter = kn->kn_filter;
528 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_ONESHOT | EV_FLAG2;
529 kev.fflags = kn->kn_sfflags;
530 kev.data = kn->kn_id; /* parent */
531 kev.udata = kn->kn_kevent.udata;/* preserve udata */
532 error = kqueue_register(kq, &kev, NULL, 0);
534 kn->kn_fflags |= NOTE_TRACKERR;
537 * Then register another knote to track other potential events
538 * from the new process.
541 kev.filter = kn->kn_filter;
542 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
543 kev.fflags = kn->kn_sfflags;
544 kev.data = kn->kn_id; /* parent */
545 kev.udata = kn->kn_kevent.udata;/* preserve udata */
546 error = kqueue_register(kq, &kev, NULL, 0);
548 kn->kn_fflags |= NOTE_TRACKERR;
549 if (kn->kn_fop->f_event(kn, NOTE_FORK))
550 KNOTE_ACTIVATE(kn, 0);
552 kn->kn_status &= ~KN_INFLUX;
554 list->kl_lock(list->kl_lockarg);
556 list->kl_unlock(list->kl_lockarg);
560 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
561 * interval timer support code.
564 #define NOTE_TIMER_PRECMASK (NOTE_SECONDS|NOTE_MSECONDS|NOTE_USECONDS| \
567 static __inline sbintime_t
568 timer2sbintime(intptr_t data, int flags)
572 switch (flags & NOTE_TIMER_PRECMASK) {
576 case NOTE_MSECONDS: /* FALLTHROUGH */
591 if (data > SBT_MAX / modifier)
594 return (modifier * data);
598 filt_timerexpire(void *knx)
600 struct callout *calloutp;
605 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
607 if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
608 calloutp = (struct callout *)kn->kn_hook;
609 *kn->kn_ptr.p_nexttime += timer2sbintime(kn->kn_sdata,
611 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
612 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
617 * data contains amount of time to sleep
620 filt_timerattach(struct knote *kn)
622 struct callout *calloutp;
624 unsigned int ncallouts;
626 if ((intptr_t)kn->kn_sdata < 0)
628 if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
630 /* Only precision unit are supported in flags so far */
631 if (kn->kn_sfflags & ~NOTE_TIMER_PRECMASK)
634 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
638 ncallouts = atomic_load_explicit(&kq_ncallouts, memory_order_relaxed);
640 if (ncallouts >= kq_calloutmax)
642 } while (!atomic_compare_exchange_weak_explicit(&kq_ncallouts,
643 &ncallouts, ncallouts + 1, memory_order_relaxed,
644 memory_order_relaxed));
646 kn->kn_flags |= EV_CLEAR; /* automatically set */
647 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
648 kn->kn_ptr.p_nexttime = malloc(sizeof(sbintime_t), M_KQUEUE, M_WAITOK);
649 calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
650 callout_init(calloutp, 1);
651 kn->kn_hook = calloutp;
652 *kn->kn_ptr.p_nexttime = to + sbinuptime();
653 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
654 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
660 filt_timerdetach(struct knote *kn)
662 struct callout *calloutp;
665 calloutp = (struct callout *)kn->kn_hook;
666 callout_drain(calloutp);
667 free(calloutp, M_KQUEUE);
668 free(kn->kn_ptr.p_nexttime, M_KQUEUE);
669 old = atomic_fetch_sub_explicit(&kq_ncallouts, 1, memory_order_relaxed);
670 KASSERT(old > 0, ("Number of callouts cannot become negative"));
671 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
675 filt_timer(struct knote *kn, long hint)
678 return (kn->kn_data != 0);
682 filt_userattach(struct knote *kn)
686 * EVFILT_USER knotes are not attached to anything in the kernel.
689 if (kn->kn_fflags & NOTE_TRIGGER)
697 filt_userdetach(__unused struct knote *kn)
701 * EVFILT_USER knotes are not attached to anything in the kernel.
706 filt_user(struct knote *kn, __unused long hint)
709 return (kn->kn_hookid);
713 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
719 if (kev->fflags & NOTE_TRIGGER)
722 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
723 kev->fflags &= NOTE_FFLAGSMASK;
729 kn->kn_sfflags &= kev->fflags;
733 kn->kn_sfflags |= kev->fflags;
737 kn->kn_sfflags = kev->fflags;
741 /* XXX Return error? */
744 kn->kn_sdata = kev->data;
745 if (kev->flags & EV_CLEAR) {
753 *kev = kn->kn_kevent;
754 kev->fflags = kn->kn_sfflags;
755 kev->data = kn->kn_sdata;
756 if (kn->kn_flags & EV_CLEAR) {
764 panic("filt_usertouch() - invalid type (%ld)", type);
770 sys_kqueue(struct thread *td, struct kqueue_args *uap)
773 return (kern_kqueue(td, 0, NULL));
777 kqueue_init(struct kqueue *kq)
780 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
781 TAILQ_INIT(&kq->kq_head);
782 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
783 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
787 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
789 struct filedesc *fdp;
795 fdp = td->td_proc->p_fd;
797 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES)))
800 error = falloc_caps(td, &fp, &fd, flags, fcaps);
802 chgkqcnt(cred->cr_ruidinfo, -1, 0);
806 /* An extra reference on `fp' has been held for us by falloc(). */
807 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
810 kq->kq_cred = crhold(cred);
813 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
814 FILEDESC_XUNLOCK(fdp);
816 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
819 td->td_retval[0] = fd;
823 #ifndef _SYS_SYSPROTO_H_
826 const struct kevent *changelist;
828 struct kevent *eventlist;
830 const struct timespec *timeout;
834 sys_kevent(struct thread *td, struct kevent_args *uap)
836 struct timespec ts, *tsp;
837 struct kevent_copyops k_ops = { uap,
844 struct uio *ktruioin = NULL;
845 struct uio *ktruioout = NULL;
848 if (uap->timeout != NULL) {
849 error = copyin(uap->timeout, &ts, sizeof(ts));
857 if (KTRPOINT(td, KTR_GENIO)) {
858 ktriov.iov_base = uap->changelist;
859 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
860 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
861 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
863 ktruioin = cloneuio(&ktruio);
864 ktriov.iov_base = uap->eventlist;
865 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
866 ktruioout = cloneuio(&ktruio);
870 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
874 if (ktruioin != NULL) {
875 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
876 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
877 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
878 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
886 * Copy 'count' items into the destination list pointed to by uap->eventlist.
889 kevent_copyout(void *arg, struct kevent *kevp, int count)
891 struct kevent_args *uap;
894 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
895 uap = (struct kevent_args *)arg;
897 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
899 uap->eventlist += count;
904 * Copy 'count' items from the list pointed to by uap->changelist.
907 kevent_copyin(void *arg, struct kevent *kevp, int count)
909 struct kevent_args *uap;
912 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
913 uap = (struct kevent_args *)arg;
915 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
917 uap->changelist += count;
922 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
923 struct kevent_copyops *k_ops, const struct timespec *timeout)
929 cap_rights_init(&rights);
931 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
933 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
934 error = fget(td, fd, &rights, &fp);
938 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
945 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
946 struct kevent_copyops *k_ops, const struct timespec *timeout)
948 struct kevent keva[KQ_NEVENTS];
949 struct kevent *kevp, *changes;
950 int i, n, nerrors, error;
953 while (nchanges > 0) {
954 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
955 error = k_ops->k_copyin(k_ops->arg, keva, n);
959 for (i = 0; i < n; i++) {
963 kevp->flags &= ~EV_SYSFLAGS;
964 error = kqueue_register(kq, kevp, td, 1);
965 if (error || (kevp->flags & EV_RECEIPT)) {
968 kevp->flags = EV_ERROR;
970 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
978 td->td_retval[0] = nerrors;
982 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
986 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
987 struct kevent_copyops *k_ops, const struct timespec *timeout)
992 error = kqueue_acquire(fp, &kq);
995 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
996 kqueue_release(kq, 0);
1001 * Performs a kevent() call on a temporarily created kqueue. This can be
1002 * used to perform one-shot polling, similar to poll() and select().
1005 kern_kevent_anonymous(struct thread *td, int nevents,
1006 struct kevent_copyops *k_ops)
1008 struct kqueue kq = {};
1013 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
1014 kqueue_drain(&kq, td);
1015 kqueue_destroy(&kq);
1020 kqueue_add_filteropts(int filt, struct filterops *filtops)
1025 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1027 "trying to add a filterop that is out of range: %d is beyond %d\n",
1028 ~filt, EVFILT_SYSCOUNT);
1031 mtx_lock(&filterops_lock);
1032 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1033 sysfilt_ops[~filt].for_fop != NULL)
1036 sysfilt_ops[~filt].for_fop = filtops;
1037 sysfilt_ops[~filt].for_refcnt = 0;
1039 mtx_unlock(&filterops_lock);
1045 kqueue_del_filteropts(int filt)
1050 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1053 mtx_lock(&filterops_lock);
1054 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1055 sysfilt_ops[~filt].for_fop == NULL)
1057 else if (sysfilt_ops[~filt].for_refcnt != 0)
1060 sysfilt_ops[~filt].for_fop = &null_filtops;
1061 sysfilt_ops[~filt].for_refcnt = 0;
1063 mtx_unlock(&filterops_lock);
1068 static struct filterops *
1069 kqueue_fo_find(int filt)
1072 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1075 if (sysfilt_ops[~filt].for_nolock)
1076 return sysfilt_ops[~filt].for_fop;
1078 mtx_lock(&filterops_lock);
1079 sysfilt_ops[~filt].for_refcnt++;
1080 if (sysfilt_ops[~filt].for_fop == NULL)
1081 sysfilt_ops[~filt].for_fop = &null_filtops;
1082 mtx_unlock(&filterops_lock);
1084 return sysfilt_ops[~filt].for_fop;
1088 kqueue_fo_release(int filt)
1091 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1094 if (sysfilt_ops[~filt].for_nolock)
1097 mtx_lock(&filterops_lock);
1098 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1099 ("filter object refcount not valid on release"));
1100 sysfilt_ops[~filt].for_refcnt--;
1101 mtx_unlock(&filterops_lock);
1105 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1106 * influence if memory allocation should wait. Make sure it is 0 if you
1110 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1112 struct filterops *fops;
1114 struct knote *kn, *tkn;
1115 cap_rights_t rights;
1116 int error, filt, event;
1117 int haskqglobal, filedesc_unlock;
1123 filedesc_unlock = 0;
1126 fops = kqueue_fo_find(filt);
1130 if (kev->flags & EV_ADD) {
1132 * Prevent waiting with locks. Non-sleepable
1133 * allocation failures are handled in the loop, only
1134 * if the spare knote appears to be actually required.
1136 tkn = knote_alloc(waitok);
1143 KASSERT(td != NULL, ("td is NULL"));
1144 error = fget(td, kev->ident,
1145 cap_rights_init(&rights, CAP_EVENT), &fp);
1149 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1150 kev->ident, 0) != 0) {
1154 error = kqueue_expand(kq, fops, kev->ident, waitok);
1160 if (fp->f_type == DTYPE_KQUEUE) {
1162 * If we add some intelligence about what we are doing,
1163 * we should be able to support events on ourselves.
1164 * We need to know when we are doing this to prevent
1165 * getting both the knlist lock and the kq lock since
1166 * they are the same thing.
1168 if (fp->f_data == kq) {
1174 * Pre-lock the filedesc before the global
1175 * lock mutex, see the comment in
1178 FILEDESC_XLOCK(td->td_proc->p_fd);
1179 filedesc_unlock = 1;
1180 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1184 if (kev->ident < kq->kq_knlistsize) {
1185 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1186 if (kev->filter == kn->kn_filter)
1190 if ((kev->flags & EV_ADD) == EV_ADD)
1191 kqueue_expand(kq, fops, kev->ident, waitok);
1196 * If possible, find an existing knote to use for this kevent.
1198 if (kev->filter == EVFILT_PROC &&
1199 (kev->flags & (EV_FLAG1 | EV_FLAG2)) != 0) {
1200 /* This is an internal creation of a process tracking
1201 * note. Don't attempt to coalesce this with an
1205 } else if (kq->kq_knhashmask != 0) {
1208 list = &kq->kq_knhash[
1209 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1210 SLIST_FOREACH(kn, list, kn_link)
1211 if (kev->ident == kn->kn_id &&
1212 kev->filter == kn->kn_filter)
1217 /* knote is in the process of changing, wait for it to stabilize. */
1218 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1219 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1220 if (filedesc_unlock) {
1221 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1222 filedesc_unlock = 0;
1224 kq->kq_state |= KQ_FLUXWAIT;
1225 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1234 * kn now contains the matching knote, or NULL if no match
1237 if (kev->flags & EV_ADD) {
1249 * apply reference counts to knote structure, and
1250 * do not release it at the end of this routine.
1255 kn->kn_sfflags = kev->fflags;
1256 kn->kn_sdata = kev->data;
1259 kn->kn_kevent = *kev;
1260 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1261 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1262 kn->kn_status = KN_INFLUX|KN_DETACHED;
1264 error = knote_attach(kn, kq);
1271 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1278 /* No matching knote and the EV_ADD flag is not set. */
1285 if (kev->flags & EV_DELETE) {
1286 kn->kn_status |= KN_INFLUX;
1288 if (!(kn->kn_status & KN_DETACHED))
1289 kn->kn_fop->f_detach(kn);
1294 if (kev->flags & EV_FORCEONESHOT) {
1295 kn->kn_flags |= EV_ONESHOT;
1296 KNOTE_ACTIVATE(kn, 1);
1300 * The user may change some filter values after the initial EV_ADD,
1301 * but doing so will not reset any filter which has already been
1304 kn->kn_status |= KN_INFLUX | KN_SCAN;
1307 kn->kn_kevent.udata = kev->udata;
1308 if (!fops->f_isfd && fops->f_touch != NULL) {
1309 fops->f_touch(kn, kev, EVENT_REGISTER);
1311 kn->kn_sfflags = kev->fflags;
1312 kn->kn_sdata = kev->data;
1316 * We can get here with kn->kn_knlist == NULL. This can happen when
1317 * the initial attach event decides that the event is "completed"
1318 * already. i.e. filt_procattach is called on a zombie process. It
1319 * will call filt_proc which will remove it from the list, and NULL
1323 if ((kev->flags & EV_DISABLE) &&
1324 ((kn->kn_status & KN_DISABLED) == 0)) {
1325 kn->kn_status |= KN_DISABLED;
1328 if ((kn->kn_status & KN_DISABLED) == 0)
1329 event = kn->kn_fop->f_event(kn, 0);
1334 KNOTE_ACTIVATE(kn, 1);
1335 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1338 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1339 kn->kn_status &= ~KN_DISABLED;
1340 if ((kn->kn_status & KN_ACTIVE) &&
1341 ((kn->kn_status & KN_QUEUED) == 0))
1347 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1348 if (filedesc_unlock)
1349 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1354 kqueue_fo_release(filt);
1359 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1367 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1371 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1382 kqueue_release(struct kqueue *kq, int locked)
1389 if (kq->kq_refcnt == 1)
1390 wakeup(&kq->kq_refcnt);
1396 kqueue_schedtask(struct kqueue *kq)
1400 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1401 ("scheduling kqueue task while draining"));
1403 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1404 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1405 kq->kq_state |= KQ_TASKSCHED;
1410 * Expand the kq to make sure we have storage for fops/ident pair.
1412 * Return 0 on success (or no work necessary), return errno on failure.
1414 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1415 * If kqueue_register is called from a non-fd context, there usually/should
1419 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1422 struct klist *list, *tmp_knhash, *to_free;
1423 u_long tmp_knhashmask;
1426 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1433 if (kq->kq_knlistsize <= fd) {
1434 size = kq->kq_knlistsize;
1437 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1441 if (kq->kq_knlistsize > fd) {
1445 if (kq->kq_knlist != NULL) {
1446 bcopy(kq->kq_knlist, list,
1447 kq->kq_knlistsize * sizeof(*list));
1448 to_free = kq->kq_knlist;
1449 kq->kq_knlist = NULL;
1451 bzero((caddr_t)list +
1452 kq->kq_knlistsize * sizeof(*list),
1453 (size - kq->kq_knlistsize) * sizeof(*list));
1454 kq->kq_knlistsize = size;
1455 kq->kq_knlist = list;
1460 if (kq->kq_knhashmask == 0) {
1461 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1463 if (tmp_knhash == NULL)
1466 if (kq->kq_knhashmask == 0) {
1467 kq->kq_knhash = tmp_knhash;
1468 kq->kq_knhashmask = tmp_knhashmask;
1470 to_free = tmp_knhash;
1475 free(to_free, M_KQUEUE);
1482 kqueue_task(void *arg, int pending)
1490 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1493 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1495 kq->kq_state &= ~KQ_TASKSCHED;
1496 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1497 wakeup(&kq->kq_state);
1500 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1504 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1505 * We treat KN_MARKER knotes as if they are INFLUX.
1508 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1509 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1511 struct kevent *kevp;
1512 struct knote *kn, *marker;
1513 sbintime_t asbt, rsbt;
1514 int count, error, haskqglobal, influx, nkev, touch;
1526 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1527 tsp->tv_nsec >= 1000000000) {
1531 if (timespecisset(tsp)) {
1532 if (tsp->tv_sec <= INT32_MAX) {
1533 rsbt = tstosbt(*tsp);
1534 if (TIMESEL(&asbt, rsbt))
1535 asbt += tc_tick_sbt;
1536 if (asbt <= SBT_MAX - rsbt)
1540 rsbt >>= tc_precexp;
1547 marker = knote_alloc(1);
1548 marker->kn_status = KN_MARKER;
1553 if (kq->kq_count == 0) {
1555 error = EWOULDBLOCK;
1557 kq->kq_state |= KQ_SLEEP;
1558 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1559 "kqread", asbt, rsbt, C_ABSOLUTE);
1563 /* don't restart after signals... */
1564 if (error == ERESTART)
1566 else if (error == EWOULDBLOCK)
1571 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1575 kn = TAILQ_FIRST(&kq->kq_head);
1577 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1578 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1583 kq->kq_state |= KQ_FLUXWAIT;
1584 error = msleep(kq, &kq->kq_lock, PSOCK,
1589 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1590 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1591 kn->kn_status &= ~KN_QUEUED;
1597 if (count == maxevents)
1601 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1602 ("KN_INFLUX set when not suppose to be"));
1604 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1605 kn->kn_status &= ~KN_QUEUED;
1606 kn->kn_status |= KN_INFLUX;
1610 * We don't need to lock the list since we've marked
1613 if (!(kn->kn_status & KN_DETACHED))
1614 kn->kn_fop->f_detach(kn);
1618 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1619 kn->kn_status &= ~KN_QUEUED;
1620 kn->kn_status |= KN_INFLUX;
1624 * We don't need to lock the list since we've marked
1627 *kevp = kn->kn_kevent;
1628 if (!(kn->kn_status & KN_DETACHED))
1629 kn->kn_fop->f_detach(kn);
1634 kn->kn_status |= KN_INFLUX | KN_SCAN;
1636 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1637 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1639 if (kn->kn_fop->f_event(kn, 0) == 0) {
1641 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1643 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1650 touch = (!kn->kn_fop->f_isfd &&
1651 kn->kn_fop->f_touch != NULL);
1653 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1655 *kevp = kn->kn_kevent;
1657 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1658 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1660 * Manually clear knotes who weren't
1663 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1667 if (kn->kn_flags & EV_DISPATCH)
1668 kn->kn_status |= KN_DISABLED;
1669 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1672 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1674 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1679 /* we are returning a copy to the user */
1684 if (nkev == KQ_NEVENTS) {
1687 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1695 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1703 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1704 td->td_retval[0] = maxevents - count;
1710 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1711 struct ucred *active_cred, struct thread *td)
1714 * Enabling sigio causes two major problems:
1715 * 1) infinite recursion:
1716 * Synopsys: kevent is being used to track signals and have FIOASYNC
1717 * set. On receipt of a signal this will cause a kqueue to recurse
1718 * into itself over and over. Sending the sigio causes the kqueue
1719 * to become ready, which in turn posts sigio again, forever.
1720 * Solution: this can be solved by setting a flag in the kqueue that
1721 * we have a SIGIO in progress.
1722 * 2) locking problems:
1723 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1724 * us above the proc and pgrp locks.
1725 * Solution: Post a signal using an async mechanism, being sure to
1726 * record a generation count in the delivery so that we do not deliver
1727 * a signal to the wrong process.
1729 * Note, these two mechanisms are somewhat mutually exclusive!
1738 kq->kq_state |= KQ_ASYNC;
1740 kq->kq_state &= ~KQ_ASYNC;
1745 return (fsetown(*(int *)data, &kq->kq_sigio));
1748 *(int *)data = fgetown(&kq->kq_sigio);
1758 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1765 if ((error = kqueue_acquire(fp, &kq)))
1769 if (events & (POLLIN | POLLRDNORM)) {
1771 revents |= events & (POLLIN | POLLRDNORM);
1773 selrecord(td, &kq->kq_sel);
1774 if (SEL_WAITING(&kq->kq_sel))
1775 kq->kq_state |= KQ_SEL;
1778 kqueue_release(kq, 1);
1785 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1789 bzero((void *)st, sizeof *st);
1791 * We no longer return kq_count because the unlocked value is useless.
1792 * If you spent all this time getting the count, why not spend your
1793 * syscall better by calling kevent?
1795 * XXX - This is needed for libc_r.
1797 st->st_mode = S_IFIFO;
1802 kqueue_drain(struct kqueue *kq, struct thread *td)
1809 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1810 ("kqueue already closing"));
1811 kq->kq_state |= KQ_CLOSING;
1812 if (kq->kq_refcnt > 1)
1813 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1815 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1817 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1818 ("kqueue's knlist not empty"));
1820 for (i = 0; i < kq->kq_knlistsize; i++) {
1821 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1822 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1823 kq->kq_state |= KQ_FLUXWAIT;
1824 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1827 kn->kn_status |= KN_INFLUX;
1829 if (!(kn->kn_status & KN_DETACHED))
1830 kn->kn_fop->f_detach(kn);
1835 if (kq->kq_knhashmask != 0) {
1836 for (i = 0; i <= kq->kq_knhashmask; i++) {
1837 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1838 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1839 kq->kq_state |= KQ_FLUXWAIT;
1840 msleep(kq, &kq->kq_lock, PSOCK,
1844 kn->kn_status |= KN_INFLUX;
1846 if (!(kn->kn_status & KN_DETACHED))
1847 kn->kn_fop->f_detach(kn);
1854 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1855 kq->kq_state |= KQ_TASKDRAIN;
1856 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1859 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1860 selwakeuppri(&kq->kq_sel, PSOCK);
1861 if (!SEL_WAITING(&kq->kq_sel))
1862 kq->kq_state &= ~KQ_SEL;
1869 kqueue_destroy(struct kqueue *kq)
1872 KASSERT(kq->kq_fdp == NULL,
1873 ("kqueue still attached to a file descriptor"));
1874 seldrain(&kq->kq_sel);
1875 knlist_destroy(&kq->kq_sel.si_note);
1876 mtx_destroy(&kq->kq_lock);
1878 if (kq->kq_knhash != NULL)
1879 free(kq->kq_knhash, M_KQUEUE);
1880 if (kq->kq_knlist != NULL)
1881 free(kq->kq_knlist, M_KQUEUE);
1883 funsetown(&kq->kq_sigio);
1888 kqueue_close(struct file *fp, struct thread *td)
1890 struct kqueue *kq = fp->f_data;
1891 struct filedesc *fdp;
1893 int filedesc_unlock;
1895 if ((error = kqueue_acquire(fp, &kq)))
1897 kqueue_drain(kq, td);
1900 * We could be called due to the knote_drop() doing fdrop(),
1901 * called from kqueue_register(). In this case the global
1902 * lock is owned, and filedesc sx is locked before, to not
1903 * take the sleepable lock after non-sleepable.
1907 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1908 FILEDESC_XLOCK(fdp);
1909 filedesc_unlock = 1;
1911 filedesc_unlock = 0;
1912 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1913 if (filedesc_unlock)
1914 FILEDESC_XUNLOCK(fdp);
1917 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1918 crfree(kq->kq_cred);
1926 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1929 kif->kf_type = KF_TYPE_KQUEUE;
1934 kqueue_wakeup(struct kqueue *kq)
1938 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1939 kq->kq_state &= ~KQ_SLEEP;
1942 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1943 selwakeuppri(&kq->kq_sel, PSOCK);
1944 if (!SEL_WAITING(&kq->kq_sel))
1945 kq->kq_state &= ~KQ_SEL;
1947 if (!knlist_empty(&kq->kq_sel.si_note))
1948 kqueue_schedtask(kq);
1949 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1950 pgsigio(&kq->kq_sigio, SIGIO, 0);
1955 * Walk down a list of knotes, activating them if their event has triggered.
1957 * There is a possibility to optimize in the case of one kq watching another.
1958 * Instead of scheduling a task to wake it up, you could pass enough state
1959 * down the chain to make up the parent kqueue. Make this code functional
1963 knote(struct knlist *list, long hint, int lockflags)
1966 struct knote *kn, *tkn;
1972 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1974 if ((lockflags & KNF_LISTLOCKED) == 0)
1975 list->kl_lock(list->kl_lockarg);
1978 * If we unlock the list lock (and set KN_INFLUX), we can
1979 * eliminate the kqueue scheduling, but this will introduce
1980 * four lock/unlock's for each knote to test. Also, marker
1981 * would be needed to keep iteration position, since filters
1982 * or other threads could remove events.
1984 SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
1987 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1989 * Do not process the influx notes, except for
1990 * the influx coming from the kq unlock in the
1991 * kqueue_scan(). In the later case, we do
1992 * not interfere with the scan, since the code
1993 * fragment in kqueue_scan() locks the knlist,
1994 * and cannot proceed until we finished.
1997 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1998 kn->kn_status |= KN_INFLUX;
2000 error = kn->kn_fop->f_event(kn, hint);
2002 kn->kn_status &= ~KN_INFLUX;
2004 KNOTE_ACTIVATE(kn, 1);
2007 kn->kn_status |= KN_HASKQLOCK;
2008 if (kn->kn_fop->f_event(kn, hint))
2009 KNOTE_ACTIVATE(kn, 1);
2010 kn->kn_status &= ~KN_HASKQLOCK;
2014 if ((lockflags & KNF_LISTLOCKED) == 0)
2015 list->kl_unlock(list->kl_lockarg);
2019 * add a knote to a knlist
2022 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
2024 KNL_ASSERT_LOCK(knl, islocked);
2025 KQ_NOTOWNED(kn->kn_kq);
2026 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
2027 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
2029 knl->kl_lock(knl->kl_lockarg);
2030 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2032 knl->kl_unlock(knl->kl_lockarg);
2034 kn->kn_knlist = knl;
2035 kn->kn_status &= ~KN_DETACHED;
2036 KQ_UNLOCK(kn->kn_kq);
2040 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
2042 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2043 KNL_ASSERT_LOCK(knl, knlislocked);
2044 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2046 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2047 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2049 knl->kl_lock(knl->kl_lockarg);
2050 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2051 kn->kn_knlist = NULL;
2053 knl->kl_unlock(knl->kl_lockarg);
2056 kn->kn_status |= KN_DETACHED;
2058 KQ_UNLOCK(kn->kn_kq);
2062 * remove knote from the specified knlist
2065 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2068 knlist_remove_kq(knl, kn, islocked, 0);
2072 * remove knote from the specified knlist while in f_event handler.
2075 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
2078 knlist_remove_kq(knl, kn, 1,
2079 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
2083 knlist_empty(struct knlist *knl)
2086 KNL_ASSERT_LOCKED(knl);
2087 return SLIST_EMPTY(&knl->kl_list);
2090 static struct mtx knlist_lock;
2091 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2093 static void knlist_mtx_lock(void *arg);
2094 static void knlist_mtx_unlock(void *arg);
2097 knlist_mtx_lock(void *arg)
2100 mtx_lock((struct mtx *)arg);
2104 knlist_mtx_unlock(void *arg)
2107 mtx_unlock((struct mtx *)arg);
2111 knlist_mtx_assert_locked(void *arg)
2114 mtx_assert((struct mtx *)arg, MA_OWNED);
2118 knlist_mtx_assert_unlocked(void *arg)
2121 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2125 knlist_rw_rlock(void *arg)
2128 rw_rlock((struct rwlock *)arg);
2132 knlist_rw_runlock(void *arg)
2135 rw_runlock((struct rwlock *)arg);
2139 knlist_rw_assert_locked(void *arg)
2142 rw_assert((struct rwlock *)arg, RA_LOCKED);
2146 knlist_rw_assert_unlocked(void *arg)
2149 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2153 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2154 void (*kl_unlock)(void *),
2155 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2159 knl->kl_lockarg = &knlist_lock;
2161 knl->kl_lockarg = lock;
2163 if (kl_lock == NULL)
2164 knl->kl_lock = knlist_mtx_lock;
2166 knl->kl_lock = kl_lock;
2167 if (kl_unlock == NULL)
2168 knl->kl_unlock = knlist_mtx_unlock;
2170 knl->kl_unlock = kl_unlock;
2171 if (kl_assert_locked == NULL)
2172 knl->kl_assert_locked = knlist_mtx_assert_locked;
2174 knl->kl_assert_locked = kl_assert_locked;
2175 if (kl_assert_unlocked == NULL)
2176 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2178 knl->kl_assert_unlocked = kl_assert_unlocked;
2180 SLIST_INIT(&knl->kl_list);
2184 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2187 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2191 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2194 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2195 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2199 knlist_destroy(struct knlist *knl)
2204 * if we run across this error, we need to find the offending
2205 * driver and have it call knlist_clear or knlist_delete.
2207 if (!SLIST_EMPTY(&knl->kl_list))
2208 printf("WARNING: destroying knlist w/ knotes on it!\n");
2211 knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2212 SLIST_INIT(&knl->kl_list);
2216 * Even if we are locked, we may need to drop the lock to allow any influx
2217 * knotes time to "settle".
2220 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2222 struct knote *kn, *kn2;
2226 KNL_ASSERT_LOCKED(knl);
2228 KNL_ASSERT_UNLOCKED(knl);
2229 again: /* need to reacquire lock since we have dropped it */
2230 knl->kl_lock(knl->kl_lockarg);
2233 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2236 if ((kn->kn_status & KN_INFLUX)) {
2240 knlist_remove_kq(knl, kn, 1, 1);
2242 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2246 /* Make sure cleared knotes disappear soon */
2247 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2253 if (!SLIST_EMPTY(&knl->kl_list)) {
2254 /* there are still KN_INFLUX remaining */
2255 kn = SLIST_FIRST(&knl->kl_list);
2258 KASSERT(kn->kn_status & KN_INFLUX,
2259 ("knote removed w/o list lock"));
2260 knl->kl_unlock(knl->kl_lockarg);
2261 kq->kq_state |= KQ_FLUXWAIT;
2262 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2268 KNL_ASSERT_LOCKED(knl);
2270 knl->kl_unlock(knl->kl_lockarg);
2271 KNL_ASSERT_UNLOCKED(knl);
2276 * Remove all knotes referencing a specified fd must be called with FILEDESC
2277 * lock. This prevents a race where a new fd comes along and occupies the
2278 * entry and we attach a knote to the fd.
2281 knote_fdclose(struct thread *td, int fd)
2283 struct filedesc *fdp = td->td_proc->p_fd;
2288 FILEDESC_XLOCK_ASSERT(fdp);
2291 * We shouldn't have to worry about new kevents appearing on fd
2292 * since filedesc is locked.
2294 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2299 while (kq->kq_knlistsize > fd &&
2300 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2301 if (kn->kn_status & KN_INFLUX) {
2302 /* someone else might be waiting on our knote */
2305 kq->kq_state |= KQ_FLUXWAIT;
2306 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2309 kn->kn_status |= KN_INFLUX;
2311 if (!(kn->kn_status & KN_DETACHED))
2312 kn->kn_fop->f_detach(kn);
2322 knote_attach(struct knote *kn, struct kqueue *kq)
2326 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2329 if (kn->kn_fop->f_isfd) {
2330 if (kn->kn_id >= kq->kq_knlistsize)
2332 list = &kq->kq_knlist[kn->kn_id];
2334 if (kq->kq_knhash == NULL)
2336 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2339 SLIST_INSERT_HEAD(list, kn, kn_link);
2345 * knote must already have been detached using the f_detach method.
2346 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2347 * to prevent other removal.
2350 knote_drop(struct knote *kn, struct thread *td)
2358 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2359 ("knote_drop called without KN_INFLUX set in kn_status"));
2362 if (kn->kn_fop->f_isfd)
2363 list = &kq->kq_knlist[kn->kn_id];
2365 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2367 if (!SLIST_EMPTY(list))
2368 SLIST_REMOVE(list, kn, knote, kn_link);
2369 if (kn->kn_status & KN_QUEUED)
2373 if (kn->kn_fop->f_isfd) {
2374 fdrop(kn->kn_fp, td);
2377 kqueue_fo_release(kn->kn_kevent.filter);
2383 knote_enqueue(struct knote *kn)
2385 struct kqueue *kq = kn->kn_kq;
2387 KQ_OWNED(kn->kn_kq);
2388 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2390 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2391 kn->kn_status |= KN_QUEUED;
2397 knote_dequeue(struct knote *kn)
2399 struct kqueue *kq = kn->kn_kq;
2401 KQ_OWNED(kn->kn_kq);
2402 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2404 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2405 kn->kn_status &= ~KN_QUEUED;
2413 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2414 NULL, NULL, UMA_ALIGN_PTR, 0);
2416 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2418 static struct knote *
2419 knote_alloc(int waitok)
2422 return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2427 knote_free(struct knote *kn)
2430 uma_zfree(knote_zone, kn);
2434 * Register the kev w/ the kq specified by fd.
2437 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2441 cap_rights_t rights;
2444 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2447 if ((error = kqueue_acquire(fp, &kq)) != 0)
2450 error = kqueue_register(kq, kev, td, waitok);
2452 kqueue_release(kq, 0);