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
378 if (kn->kn_flags & EV_FLAG1) {
379 kn->kn_data = kn->kn_sdata; /* ppid */
380 kn->kn_fflags = NOTE_CHILD;
381 kn->kn_flags &= ~EV_FLAG1;
385 knlist_add(&p->p_klist, kn, 1);
388 * Immediately activate any exit notes if the target process is a
389 * zombie. This is necessary to handle the case where the target
390 * process, e.g. a child, dies before the kevent is registered.
392 if (immediate && filt_proc(kn, NOTE_EXIT))
393 KNOTE_ACTIVATE(kn, 0);
401 * The knote may be attached to a different process, which may exit,
402 * leaving nothing for the knote to be attached to. So when the process
403 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
404 * it will be deleted when read out. However, as part of the knote deletion,
405 * this routine is called, so a check is needed to avoid actually performing
406 * a detach, because the original process does not exist any more.
408 /* XXX - move to kern_proc.c? */
410 filt_procdetach(struct knote *kn)
414 p = kn->kn_ptr.p_proc;
415 knlist_remove(&p->p_klist, kn, 0);
416 kn->kn_ptr.p_proc = NULL;
419 /* XXX - move to kern_proc.c? */
421 filt_proc(struct knote *kn, long hint)
426 p = kn->kn_ptr.p_proc;
427 /* Mask off extra data. */
428 event = (u_int)hint & NOTE_PCTRLMASK;
430 /* If the user is interested in this event, record it. */
431 if (kn->kn_sfflags & event)
432 kn->kn_fflags |= event;
434 /* Process is gone, so flag the event as finished. */
435 if (event == NOTE_EXIT) {
436 if (!(kn->kn_status & KN_DETACHED))
437 knlist_remove_inevent(&p->p_klist, kn);
438 kn->kn_flags |= EV_EOF | EV_ONESHOT;
439 kn->kn_ptr.p_proc = NULL;
440 if (kn->kn_fflags & NOTE_EXIT)
441 kn->kn_data = KW_EXITCODE(p->p_xexit, p->p_xsig);
442 if (kn->kn_fflags == 0)
443 kn->kn_flags |= EV_DROP;
447 return (kn->kn_fflags != 0);
451 * Called when the process forked. It mostly does the same as the
452 * knote(), activating all knotes registered to be activated when the
453 * process forked. Additionally, for each knote attached to the
454 * parent, check whether user wants to track the new process. If so
455 * attach a new knote to it, and immediately report an event with the
459 knote_fork(struct knlist *list, int pid)
468 list->kl_lock(list->kl_lockarg);
470 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
472 * XXX - Why do we skip the kn if it is _INFLUX? Does this
473 * mean we will not properly wake up some notes?
475 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX)
479 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
485 * The same as knote(), activate the event.
487 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
488 kn->kn_status |= KN_HASKQLOCK;
489 if (kn->kn_fop->f_event(kn, NOTE_FORK))
490 KNOTE_ACTIVATE(kn, 1);
491 kn->kn_status &= ~KN_HASKQLOCK;
497 * The NOTE_TRACK case. In addition to the activation
498 * of the event, we need to register new event to
499 * track the child. Drop the locks in preparation for
500 * the call to kqueue_register().
502 kn->kn_status |= KN_INFLUX;
504 list->kl_unlock(list->kl_lockarg);
507 * Activate existing knote and register a knote with
511 kev.filter = kn->kn_filter;
512 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
513 kev.fflags = kn->kn_sfflags;
514 kev.data = kn->kn_id; /* parent */
515 kev.udata = kn->kn_kevent.udata;/* preserve udata */
516 error = kqueue_register(kq, &kev, NULL, 0);
518 kn->kn_fflags |= NOTE_TRACKERR;
519 if (kn->kn_fop->f_event(kn, NOTE_FORK))
520 KNOTE_ACTIVATE(kn, 0);
522 kn->kn_status &= ~KN_INFLUX;
524 list->kl_lock(list->kl_lockarg);
526 list->kl_unlock(list->kl_lockarg);
530 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
531 * interval timer support code.
534 #define NOTE_TIMER_PRECMASK (NOTE_SECONDS|NOTE_MSECONDS|NOTE_USECONDS| \
537 static __inline sbintime_t
538 timer2sbintime(intptr_t data, int flags)
542 switch (flags & NOTE_TIMER_PRECMASK) {
546 case NOTE_MSECONDS: /* FALLTHROUGH */
561 if (data > SBT_MAX / modifier)
564 return (modifier * data);
568 filt_timerexpire(void *knx)
570 struct callout *calloutp;
575 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
577 if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
578 calloutp = (struct callout *)kn->kn_hook;
579 *kn->kn_ptr.p_nexttime += timer2sbintime(kn->kn_sdata,
581 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
582 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
587 * data contains amount of time to sleep
590 filt_timerattach(struct knote *kn)
592 struct callout *calloutp;
594 unsigned int ncallouts;
596 if ((intptr_t)kn->kn_sdata < 0)
598 if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
600 /* Only precision unit are supported in flags so far */
601 if (kn->kn_sfflags & ~NOTE_TIMER_PRECMASK)
604 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
608 ncallouts = atomic_load_explicit(&kq_ncallouts, memory_order_relaxed);
610 if (ncallouts >= kq_calloutmax)
612 } while (!atomic_compare_exchange_weak_explicit(&kq_ncallouts,
613 &ncallouts, ncallouts + 1, memory_order_relaxed,
614 memory_order_relaxed));
616 kn->kn_flags |= EV_CLEAR; /* automatically set */
617 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
618 kn->kn_ptr.p_nexttime = malloc(sizeof(sbintime_t), M_KQUEUE, M_WAITOK);
619 calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
620 callout_init(calloutp, 1);
621 kn->kn_hook = calloutp;
622 *kn->kn_ptr.p_nexttime = to + sbinuptime();
623 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
624 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
630 filt_timerdetach(struct knote *kn)
632 struct callout *calloutp;
635 calloutp = (struct callout *)kn->kn_hook;
636 callout_drain(calloutp);
637 free(calloutp, M_KQUEUE);
638 free(kn->kn_ptr.p_nexttime, M_KQUEUE);
639 old = atomic_fetch_sub_explicit(&kq_ncallouts, 1, memory_order_relaxed);
640 KASSERT(old > 0, ("Number of callouts cannot become negative"));
641 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
645 filt_timer(struct knote *kn, long hint)
648 return (kn->kn_data != 0);
652 filt_userattach(struct knote *kn)
656 * EVFILT_USER knotes are not attached to anything in the kernel.
659 if (kn->kn_fflags & NOTE_TRIGGER)
667 filt_userdetach(__unused struct knote *kn)
671 * EVFILT_USER knotes are not attached to anything in the kernel.
676 filt_user(struct knote *kn, __unused long hint)
679 return (kn->kn_hookid);
683 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
689 if (kev->fflags & NOTE_TRIGGER)
692 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
693 kev->fflags &= NOTE_FFLAGSMASK;
699 kn->kn_sfflags &= kev->fflags;
703 kn->kn_sfflags |= kev->fflags;
707 kn->kn_sfflags = kev->fflags;
711 /* XXX Return error? */
714 kn->kn_sdata = kev->data;
715 if (kev->flags & EV_CLEAR) {
723 *kev = kn->kn_kevent;
724 kev->fflags = kn->kn_sfflags;
725 kev->data = kn->kn_sdata;
726 if (kn->kn_flags & EV_CLEAR) {
734 panic("filt_usertouch() - invalid type (%ld)", type);
740 sys_kqueue(struct thread *td, struct kqueue_args *uap)
743 return (kern_kqueue(td, 0, NULL));
747 kqueue_init(struct kqueue *kq)
750 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF | MTX_DUPOK);
751 TAILQ_INIT(&kq->kq_head);
752 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
753 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
757 kern_kqueue(struct thread *td, int flags, struct filecaps *fcaps)
759 struct filedesc *fdp;
769 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES))) {
775 error = falloc_caps(td, &fp, &fd, flags, fcaps);
779 /* An extra reference on `fp' has been held for us by falloc(). */
780 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
786 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
787 FILEDESC_XUNLOCK(fdp);
789 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
792 td->td_retval[0] = fd;
795 chgkqcnt(cred->cr_ruidinfo, -1, 0);
801 #ifndef _SYS_SYSPROTO_H_
804 const struct kevent *changelist;
806 struct kevent *eventlist;
808 const struct timespec *timeout;
812 sys_kevent(struct thread *td, struct kevent_args *uap)
814 struct timespec ts, *tsp;
815 struct kevent_copyops k_ops = { uap,
822 struct uio *ktruioin = NULL;
823 struct uio *ktruioout = NULL;
826 if (uap->timeout != NULL) {
827 error = copyin(uap->timeout, &ts, sizeof(ts));
835 if (KTRPOINT(td, KTR_GENIO)) {
836 ktriov.iov_base = uap->changelist;
837 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
838 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
839 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
841 ktruioin = cloneuio(&ktruio);
842 ktriov.iov_base = uap->eventlist;
843 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
844 ktruioout = cloneuio(&ktruio);
848 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
852 if (ktruioin != NULL) {
853 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
854 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
855 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
856 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
864 * Copy 'count' items into the destination list pointed to by uap->eventlist.
867 kevent_copyout(void *arg, struct kevent *kevp, int count)
869 struct kevent_args *uap;
872 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
873 uap = (struct kevent_args *)arg;
875 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
877 uap->eventlist += count;
882 * Copy 'count' items from the list pointed to by uap->changelist.
885 kevent_copyin(void *arg, struct kevent *kevp, int count)
887 struct kevent_args *uap;
890 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
891 uap = (struct kevent_args *)arg;
893 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
895 uap->changelist += count;
900 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
901 struct kevent_copyops *k_ops, const struct timespec *timeout)
907 cap_rights_init(&rights);
909 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
911 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
912 error = fget(td, fd, &rights, &fp);
916 error = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
923 kqueue_kevent(struct kqueue *kq, struct thread *td, int nchanges, int nevents,
924 struct kevent_copyops *k_ops, const struct timespec *timeout)
926 struct kevent keva[KQ_NEVENTS];
927 struct kevent *kevp, *changes;
928 int i, n, nerrors, error;
931 while (nchanges > 0) {
932 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
933 error = k_ops->k_copyin(k_ops->arg, keva, n);
937 for (i = 0; i < n; i++) {
941 kevp->flags &= ~EV_SYSFLAGS;
942 error = kqueue_register(kq, kevp, td, 1);
943 if (error || (kevp->flags & EV_RECEIPT)) {
946 kevp->flags = EV_ERROR;
948 (void)k_ops->k_copyout(k_ops->arg, kevp, 1);
956 td->td_retval[0] = nerrors;
960 return (kqueue_scan(kq, nevents, k_ops, timeout, keva, td));
964 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
965 struct kevent_copyops *k_ops, const struct timespec *timeout)
970 error = kqueue_acquire(fp, &kq);
973 error = kqueue_kevent(kq, td, nchanges, nevents, k_ops, timeout);
974 kqueue_release(kq, 0);
979 * Performs a kevent() call on a temporarily created kqueue. This can be
980 * used to perform one-shot polling, similar to poll() and select().
983 kern_kevent_anonymous(struct thread *td, int nevents,
984 struct kevent_copyops *k_ops)
986 struct kqueue kq = {};
991 error = kqueue_kevent(&kq, td, nevents, nevents, k_ops, NULL);
992 kqueue_drain(&kq, td);
998 kqueue_add_filteropts(int filt, struct filterops *filtops)
1003 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
1005 "trying to add a filterop that is out of range: %d is beyond %d\n",
1006 ~filt, EVFILT_SYSCOUNT);
1009 mtx_lock(&filterops_lock);
1010 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
1011 sysfilt_ops[~filt].for_fop != NULL)
1014 sysfilt_ops[~filt].for_fop = filtops;
1015 sysfilt_ops[~filt].for_refcnt = 0;
1017 mtx_unlock(&filterops_lock);
1023 kqueue_del_filteropts(int filt)
1028 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1031 mtx_lock(&filterops_lock);
1032 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1033 sysfilt_ops[~filt].for_fop == NULL)
1035 else if (sysfilt_ops[~filt].for_refcnt != 0)
1038 sysfilt_ops[~filt].for_fop = &null_filtops;
1039 sysfilt_ops[~filt].for_refcnt = 0;
1041 mtx_unlock(&filterops_lock);
1046 static struct filterops *
1047 kqueue_fo_find(int filt)
1050 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1053 if (sysfilt_ops[~filt].for_nolock)
1054 return sysfilt_ops[~filt].for_fop;
1056 mtx_lock(&filterops_lock);
1057 sysfilt_ops[~filt].for_refcnt++;
1058 if (sysfilt_ops[~filt].for_fop == NULL)
1059 sysfilt_ops[~filt].for_fop = &null_filtops;
1060 mtx_unlock(&filterops_lock);
1062 return sysfilt_ops[~filt].for_fop;
1066 kqueue_fo_release(int filt)
1069 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1072 if (sysfilt_ops[~filt].for_nolock)
1075 mtx_lock(&filterops_lock);
1076 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1077 ("filter object refcount not valid on release"));
1078 sysfilt_ops[~filt].for_refcnt--;
1079 mtx_unlock(&filterops_lock);
1083 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1084 * influence if memory allocation should wait. Make sure it is 0 if you
1088 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1090 struct filterops *fops;
1092 struct knote *kn, *tkn;
1093 cap_rights_t rights;
1094 int error, filt, event;
1095 int haskqglobal, filedesc_unlock;
1101 filedesc_unlock = 0;
1104 fops = kqueue_fo_find(filt);
1108 if (kev->flags & EV_ADD) {
1110 * Prevent waiting with locks. Non-sleepable
1111 * allocation failures are handled in the loop, only
1112 * if the spare knote appears to be actually required.
1114 tkn = knote_alloc(waitok);
1121 KASSERT(td != NULL, ("td is NULL"));
1122 error = fget(td, kev->ident,
1123 cap_rights_init(&rights, CAP_EVENT), &fp);
1127 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1128 kev->ident, 0) != 0) {
1132 error = kqueue_expand(kq, fops, kev->ident, waitok);
1138 if (fp->f_type == DTYPE_KQUEUE) {
1140 * if we add some inteligence about what we are doing,
1141 * we should be able to support events on ourselves.
1142 * We need to know when we are doing this to prevent
1143 * getting both the knlist lock and the kq lock since
1144 * they are the same thing.
1146 if (fp->f_data == kq) {
1152 * Pre-lock the filedesc before the global
1153 * lock mutex, see the comment in
1156 FILEDESC_XLOCK(td->td_proc->p_fd);
1157 filedesc_unlock = 1;
1158 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1162 if (kev->ident < kq->kq_knlistsize) {
1163 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1164 if (kev->filter == kn->kn_filter)
1168 if ((kev->flags & EV_ADD) == EV_ADD)
1169 kqueue_expand(kq, fops, kev->ident, waitok);
1172 if (kq->kq_knhashmask != 0) {
1175 list = &kq->kq_knhash[
1176 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1177 SLIST_FOREACH(kn, list, kn_link)
1178 if (kev->ident == kn->kn_id &&
1179 kev->filter == kn->kn_filter)
1184 /* knote is in the process of changing, wait for it to stablize. */
1185 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1186 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1187 if (filedesc_unlock) {
1188 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1189 filedesc_unlock = 0;
1191 kq->kq_state |= KQ_FLUXWAIT;
1192 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1201 * kn now contains the matching knote, or NULL if no match
1204 if (kev->flags & EV_ADD) {
1216 * apply reference counts to knote structure, and
1217 * do not release it at the end of this routine.
1222 kn->kn_sfflags = kev->fflags;
1223 kn->kn_sdata = kev->data;
1226 kn->kn_kevent = *kev;
1227 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1228 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1229 kn->kn_status = KN_INFLUX|KN_DETACHED;
1231 error = knote_attach(kn, kq);
1238 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1245 /* No matching knote and the EV_ADD flag is not set. */
1252 if (kev->flags & EV_DELETE) {
1253 kn->kn_status |= KN_INFLUX;
1255 if (!(kn->kn_status & KN_DETACHED))
1256 kn->kn_fop->f_detach(kn);
1261 if (kev->flags & EV_FORCEONESHOT) {
1262 kn->kn_flags |= EV_ONESHOT;
1263 KNOTE_ACTIVATE(kn, 1);
1267 * The user may change some filter values after the initial EV_ADD,
1268 * but doing so will not reset any filter which has already been
1271 kn->kn_status |= KN_INFLUX | KN_SCAN;
1274 kn->kn_kevent.udata = kev->udata;
1275 if (!fops->f_isfd && fops->f_touch != NULL) {
1276 fops->f_touch(kn, kev, EVENT_REGISTER);
1278 kn->kn_sfflags = kev->fflags;
1279 kn->kn_sdata = kev->data;
1283 * We can get here with kn->kn_knlist == NULL. This can happen when
1284 * the initial attach event decides that the event is "completed"
1285 * already. i.e. filt_procattach is called on a zombie process. It
1286 * will call filt_proc which will remove it from the list, and NULL
1290 if ((kev->flags & EV_DISABLE) &&
1291 ((kn->kn_status & KN_DISABLED) == 0)) {
1292 kn->kn_status |= KN_DISABLED;
1295 if ((kn->kn_status & KN_DISABLED) == 0)
1296 event = kn->kn_fop->f_event(kn, 0);
1301 KNOTE_ACTIVATE(kn, 1);
1302 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1305 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1306 kn->kn_status &= ~KN_DISABLED;
1307 if ((kn->kn_status & KN_ACTIVE) &&
1308 ((kn->kn_status & KN_QUEUED) == 0))
1314 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1315 if (filedesc_unlock)
1316 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1321 kqueue_fo_release(filt);
1326 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1334 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1338 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1349 kqueue_release(struct kqueue *kq, int locked)
1356 if (kq->kq_refcnt == 1)
1357 wakeup(&kq->kq_refcnt);
1363 kqueue_schedtask(struct kqueue *kq)
1367 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1368 ("scheduling kqueue task while draining"));
1370 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1371 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1372 kq->kq_state |= KQ_TASKSCHED;
1377 * Expand the kq to make sure we have storage for fops/ident pair.
1379 * Return 0 on success (or no work necessary), return errno on failure.
1381 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1382 * If kqueue_register is called from a non-fd context, there usually/should
1386 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1389 struct klist *list, *tmp_knhash, *to_free;
1390 u_long tmp_knhashmask;
1393 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1400 if (kq->kq_knlistsize <= fd) {
1401 size = kq->kq_knlistsize;
1404 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1408 if (kq->kq_knlistsize > fd) {
1412 if (kq->kq_knlist != NULL) {
1413 bcopy(kq->kq_knlist, list,
1414 kq->kq_knlistsize * sizeof(*list));
1415 to_free = kq->kq_knlist;
1416 kq->kq_knlist = NULL;
1418 bzero((caddr_t)list +
1419 kq->kq_knlistsize * sizeof(*list),
1420 (size - kq->kq_knlistsize) * sizeof(*list));
1421 kq->kq_knlistsize = size;
1422 kq->kq_knlist = list;
1427 if (kq->kq_knhashmask == 0) {
1428 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1430 if (tmp_knhash == NULL)
1433 if (kq->kq_knhashmask == 0) {
1434 kq->kq_knhash = tmp_knhash;
1435 kq->kq_knhashmask = tmp_knhashmask;
1437 to_free = tmp_knhash;
1442 free(to_free, M_KQUEUE);
1449 kqueue_task(void *arg, int pending)
1457 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1460 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1462 kq->kq_state &= ~KQ_TASKSCHED;
1463 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1464 wakeup(&kq->kq_state);
1467 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1471 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1472 * We treat KN_MARKER knotes as if they are INFLUX.
1475 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1476 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1478 struct kevent *kevp;
1479 struct knote *kn, *marker;
1480 sbintime_t asbt, rsbt;
1481 int count, error, haskqglobal, influx, nkev, touch;
1493 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1494 tsp->tv_nsec >= 1000000000) {
1498 if (timespecisset(tsp)) {
1499 if (tsp->tv_sec <= INT32_MAX) {
1500 rsbt = tstosbt(*tsp);
1501 if (TIMESEL(&asbt, rsbt))
1502 asbt += tc_tick_sbt;
1503 if (asbt <= SBT_MAX - rsbt)
1507 rsbt >>= tc_precexp;
1514 marker = knote_alloc(1);
1515 marker->kn_status = KN_MARKER;
1520 if (kq->kq_count == 0) {
1522 error = EWOULDBLOCK;
1524 kq->kq_state |= KQ_SLEEP;
1525 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1526 "kqread", asbt, rsbt, C_ABSOLUTE);
1530 /* don't restart after signals... */
1531 if (error == ERESTART)
1533 else if (error == EWOULDBLOCK)
1538 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1542 kn = TAILQ_FIRST(&kq->kq_head);
1544 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1545 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1550 kq->kq_state |= KQ_FLUXWAIT;
1551 error = msleep(kq, &kq->kq_lock, PSOCK,
1556 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1557 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1558 kn->kn_status &= ~KN_QUEUED;
1564 if (count == maxevents)
1568 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1569 ("KN_INFLUX set when not suppose to be"));
1571 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1572 kn->kn_status &= ~KN_QUEUED;
1573 kn->kn_status |= KN_INFLUX;
1577 * We don't need to lock the list since we've marked
1580 if (!(kn->kn_status & KN_DETACHED))
1581 kn->kn_fop->f_detach(kn);
1585 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1586 kn->kn_status &= ~KN_QUEUED;
1587 kn->kn_status |= KN_INFLUX;
1591 * We don't need to lock the list since we've marked
1594 *kevp = kn->kn_kevent;
1595 if (!(kn->kn_status & KN_DETACHED))
1596 kn->kn_fop->f_detach(kn);
1601 kn->kn_status |= KN_INFLUX | KN_SCAN;
1603 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1604 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1606 if (kn->kn_fop->f_event(kn, 0) == 0) {
1608 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1610 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1617 touch = (!kn->kn_fop->f_isfd &&
1618 kn->kn_fop->f_touch != NULL);
1620 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1622 *kevp = kn->kn_kevent;
1624 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1625 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1627 * Manually clear knotes who weren't
1630 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1634 if (kn->kn_flags & EV_DISPATCH)
1635 kn->kn_status |= KN_DISABLED;
1636 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1639 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1641 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1646 /* we are returning a copy to the user */
1651 if (nkev == KQ_NEVENTS) {
1654 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1662 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1670 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1671 td->td_retval[0] = maxevents - count;
1677 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1678 struct ucred *active_cred, struct thread *td)
1681 * Enabling sigio causes two major problems:
1682 * 1) infinite recursion:
1683 * Synopsys: kevent is being used to track signals and have FIOASYNC
1684 * set. On receipt of a signal this will cause a kqueue to recurse
1685 * into itself over and over. Sending the sigio causes the kqueue
1686 * to become ready, which in turn posts sigio again, forever.
1687 * Solution: this can be solved by setting a flag in the kqueue that
1688 * we have a SIGIO in progress.
1689 * 2) locking problems:
1690 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1691 * us above the proc and pgrp locks.
1692 * Solution: Post a signal using an async mechanism, being sure to
1693 * record a generation count in the delivery so that we do not deliver
1694 * a signal to the wrong process.
1696 * Note, these two mechanisms are somewhat mutually exclusive!
1705 kq->kq_state |= KQ_ASYNC;
1707 kq->kq_state &= ~KQ_ASYNC;
1712 return (fsetown(*(int *)data, &kq->kq_sigio));
1715 *(int *)data = fgetown(&kq->kq_sigio);
1725 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1732 if ((error = kqueue_acquire(fp, &kq)))
1736 if (events & (POLLIN | POLLRDNORM)) {
1738 revents |= events & (POLLIN | POLLRDNORM);
1740 selrecord(td, &kq->kq_sel);
1741 if (SEL_WAITING(&kq->kq_sel))
1742 kq->kq_state |= KQ_SEL;
1745 kqueue_release(kq, 1);
1752 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1756 bzero((void *)st, sizeof *st);
1758 * We no longer return kq_count because the unlocked value is useless.
1759 * If you spent all this time getting the count, why not spend your
1760 * syscall better by calling kevent?
1762 * XXX - This is needed for libc_r.
1764 st->st_mode = S_IFIFO;
1769 kqueue_drain(struct kqueue *kq, struct thread *td)
1776 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1777 ("kqueue already closing"));
1778 kq->kq_state |= KQ_CLOSING;
1779 if (kq->kq_refcnt > 1)
1780 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1782 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1784 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1785 ("kqueue's knlist not empty"));
1787 for (i = 0; i < kq->kq_knlistsize; i++) {
1788 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1789 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1790 kq->kq_state |= KQ_FLUXWAIT;
1791 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1794 kn->kn_status |= KN_INFLUX;
1796 if (!(kn->kn_status & KN_DETACHED))
1797 kn->kn_fop->f_detach(kn);
1802 if (kq->kq_knhashmask != 0) {
1803 for (i = 0; i <= kq->kq_knhashmask; i++) {
1804 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1805 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1806 kq->kq_state |= KQ_FLUXWAIT;
1807 msleep(kq, &kq->kq_lock, PSOCK,
1811 kn->kn_status |= KN_INFLUX;
1813 if (!(kn->kn_status & KN_DETACHED))
1814 kn->kn_fop->f_detach(kn);
1821 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1822 kq->kq_state |= KQ_TASKDRAIN;
1823 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1826 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1827 selwakeuppri(&kq->kq_sel, PSOCK);
1828 if (!SEL_WAITING(&kq->kq_sel))
1829 kq->kq_state &= ~KQ_SEL;
1836 kqueue_destroy(struct kqueue *kq)
1839 KASSERT(kq->kq_fdp == NULL,
1840 ("kqueue still attached to a file descriptor"));
1841 seldrain(&kq->kq_sel);
1842 knlist_destroy(&kq->kq_sel.si_note);
1843 mtx_destroy(&kq->kq_lock);
1845 if (kq->kq_knhash != NULL)
1846 free(kq->kq_knhash, M_KQUEUE);
1847 if (kq->kq_knlist != NULL)
1848 free(kq->kq_knlist, M_KQUEUE);
1850 funsetown(&kq->kq_sigio);
1855 kqueue_close(struct file *fp, struct thread *td)
1857 struct kqueue *kq = fp->f_data;
1858 struct filedesc *fdp;
1860 int filedesc_unlock;
1862 if ((error = kqueue_acquire(fp, &kq)))
1864 kqueue_drain(kq, td);
1867 * We could be called due to the knote_drop() doing fdrop(),
1868 * called from kqueue_register(). In this case the global
1869 * lock is owned, and filedesc sx is locked before, to not
1870 * take the sleepable lock after non-sleepable.
1874 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1875 FILEDESC_XLOCK(fdp);
1876 filedesc_unlock = 1;
1878 filedesc_unlock = 0;
1879 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1880 if (filedesc_unlock)
1881 FILEDESC_XUNLOCK(fdp);
1884 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1885 crfree(kq->kq_cred);
1893 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1896 kif->kf_type = KF_TYPE_KQUEUE;
1901 kqueue_wakeup(struct kqueue *kq)
1905 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1906 kq->kq_state &= ~KQ_SLEEP;
1909 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1910 selwakeuppri(&kq->kq_sel, PSOCK);
1911 if (!SEL_WAITING(&kq->kq_sel))
1912 kq->kq_state &= ~KQ_SEL;
1914 if (!knlist_empty(&kq->kq_sel.si_note))
1915 kqueue_schedtask(kq);
1916 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1917 pgsigio(&kq->kq_sigio, SIGIO, 0);
1922 * Walk down a list of knotes, activating them if their event has triggered.
1924 * There is a possibility to optimize in the case of one kq watching another.
1925 * Instead of scheduling a task to wake it up, you could pass enough state
1926 * down the chain to make up the parent kqueue. Make this code functional
1930 knote(struct knlist *list, long hint, int lockflags)
1939 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1941 if ((lockflags & KNF_LISTLOCKED) == 0)
1942 list->kl_lock(list->kl_lockarg);
1945 * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1946 * the kqueue scheduling, but this will introduce four
1947 * lock/unlock's for each knote to test. If we do, continue to use
1948 * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1949 * only safe if you want to remove the current item, which we are
1952 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1955 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1957 * Do not process the influx notes, except for
1958 * the influx coming from the kq unlock in the
1959 * kqueue_scan(). In the later case, we do
1960 * not interfere with the scan, since the code
1961 * fragment in kqueue_scan() locks the knlist,
1962 * and cannot proceed until we finished.
1965 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1966 kn->kn_status |= KN_INFLUX;
1968 error = kn->kn_fop->f_event(kn, hint);
1970 kn->kn_status &= ~KN_INFLUX;
1972 KNOTE_ACTIVATE(kn, 1);
1975 kn->kn_status |= KN_HASKQLOCK;
1976 if (kn->kn_fop->f_event(kn, hint))
1977 KNOTE_ACTIVATE(kn, 1);
1978 kn->kn_status &= ~KN_HASKQLOCK;
1982 if ((lockflags & KNF_LISTLOCKED) == 0)
1983 list->kl_unlock(list->kl_lockarg);
1987 * add a knote to a knlist
1990 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1992 KNL_ASSERT_LOCK(knl, islocked);
1993 KQ_NOTOWNED(kn->kn_kq);
1994 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1995 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1997 knl->kl_lock(knl->kl_lockarg);
1998 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
2000 knl->kl_unlock(knl->kl_lockarg);
2002 kn->kn_knlist = knl;
2003 kn->kn_status &= ~KN_DETACHED;
2004 KQ_UNLOCK(kn->kn_kq);
2008 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
2010 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
2011 KNL_ASSERT_LOCK(knl, knlislocked);
2012 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
2014 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
2015 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
2017 knl->kl_lock(knl->kl_lockarg);
2018 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
2019 kn->kn_knlist = NULL;
2021 knl->kl_unlock(knl->kl_lockarg);
2024 kn->kn_status |= KN_DETACHED;
2026 KQ_UNLOCK(kn->kn_kq);
2030 * remove knote from the specified knlist
2033 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
2036 knlist_remove_kq(knl, kn, islocked, 0);
2040 * remove knote from the specified knlist while in f_event handler.
2043 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
2046 knlist_remove_kq(knl, kn, 1,
2047 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
2051 knlist_empty(struct knlist *knl)
2054 KNL_ASSERT_LOCKED(knl);
2055 return SLIST_EMPTY(&knl->kl_list);
2058 static struct mtx knlist_lock;
2059 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2061 static void knlist_mtx_lock(void *arg);
2062 static void knlist_mtx_unlock(void *arg);
2065 knlist_mtx_lock(void *arg)
2068 mtx_lock((struct mtx *)arg);
2072 knlist_mtx_unlock(void *arg)
2075 mtx_unlock((struct mtx *)arg);
2079 knlist_mtx_assert_locked(void *arg)
2082 mtx_assert((struct mtx *)arg, MA_OWNED);
2086 knlist_mtx_assert_unlocked(void *arg)
2089 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2093 knlist_rw_rlock(void *arg)
2096 rw_rlock((struct rwlock *)arg);
2100 knlist_rw_runlock(void *arg)
2103 rw_runlock((struct rwlock *)arg);
2107 knlist_rw_assert_locked(void *arg)
2110 rw_assert((struct rwlock *)arg, RA_LOCKED);
2114 knlist_rw_assert_unlocked(void *arg)
2117 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2121 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2122 void (*kl_unlock)(void *),
2123 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2127 knl->kl_lockarg = &knlist_lock;
2129 knl->kl_lockarg = lock;
2131 if (kl_lock == NULL)
2132 knl->kl_lock = knlist_mtx_lock;
2134 knl->kl_lock = kl_lock;
2135 if (kl_unlock == NULL)
2136 knl->kl_unlock = knlist_mtx_unlock;
2138 knl->kl_unlock = kl_unlock;
2139 if (kl_assert_locked == NULL)
2140 knl->kl_assert_locked = knlist_mtx_assert_locked;
2142 knl->kl_assert_locked = kl_assert_locked;
2143 if (kl_assert_unlocked == NULL)
2144 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2146 knl->kl_assert_unlocked = kl_assert_unlocked;
2148 SLIST_INIT(&knl->kl_list);
2152 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2155 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2159 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2162 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2163 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2167 knlist_destroy(struct knlist *knl)
2172 * if we run across this error, we need to find the offending
2173 * driver and have it call knlist_clear or knlist_delete.
2175 if (!SLIST_EMPTY(&knl->kl_list))
2176 printf("WARNING: destroying knlist w/ knotes on it!\n");
2179 knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2180 SLIST_INIT(&knl->kl_list);
2184 * Even if we are locked, we may need to drop the lock to allow any influx
2185 * knotes time to "settle".
2188 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2190 struct knote *kn, *kn2;
2194 KNL_ASSERT_LOCKED(knl);
2196 KNL_ASSERT_UNLOCKED(knl);
2197 again: /* need to reacquire lock since we have dropped it */
2198 knl->kl_lock(knl->kl_lockarg);
2201 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2204 if ((kn->kn_status & KN_INFLUX)) {
2208 knlist_remove_kq(knl, kn, 1, 1);
2210 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2214 /* Make sure cleared knotes disappear soon */
2215 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2221 if (!SLIST_EMPTY(&knl->kl_list)) {
2222 /* there are still KN_INFLUX remaining */
2223 kn = SLIST_FIRST(&knl->kl_list);
2226 KASSERT(kn->kn_status & KN_INFLUX,
2227 ("knote removed w/o list lock"));
2228 knl->kl_unlock(knl->kl_lockarg);
2229 kq->kq_state |= KQ_FLUXWAIT;
2230 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2236 KNL_ASSERT_LOCKED(knl);
2238 knl->kl_unlock(knl->kl_lockarg);
2239 KNL_ASSERT_UNLOCKED(knl);
2244 * Remove all knotes referencing a specified fd must be called with FILEDESC
2245 * lock. This prevents a race where a new fd comes along and occupies the
2246 * entry and we attach a knote to the fd.
2249 knote_fdclose(struct thread *td, int fd)
2251 struct filedesc *fdp = td->td_proc->p_fd;
2256 FILEDESC_XLOCK_ASSERT(fdp);
2259 * We shouldn't have to worry about new kevents appearing on fd
2260 * since filedesc is locked.
2262 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2267 while (kq->kq_knlistsize > fd &&
2268 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2269 if (kn->kn_status & KN_INFLUX) {
2270 /* someone else might be waiting on our knote */
2273 kq->kq_state |= KQ_FLUXWAIT;
2274 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2277 kn->kn_status |= KN_INFLUX;
2279 if (!(kn->kn_status & KN_DETACHED))
2280 kn->kn_fop->f_detach(kn);
2290 knote_attach(struct knote *kn, struct kqueue *kq)
2294 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2297 if (kn->kn_fop->f_isfd) {
2298 if (kn->kn_id >= kq->kq_knlistsize)
2300 list = &kq->kq_knlist[kn->kn_id];
2302 if (kq->kq_knhash == NULL)
2304 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2307 SLIST_INSERT_HEAD(list, kn, kn_link);
2313 * knote must already have been detached using the f_detach method.
2314 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2315 * to prevent other removal.
2318 knote_drop(struct knote *kn, struct thread *td)
2326 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2327 ("knote_drop called without KN_INFLUX set in kn_status"));
2330 if (kn->kn_fop->f_isfd)
2331 list = &kq->kq_knlist[kn->kn_id];
2333 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2335 if (!SLIST_EMPTY(list))
2336 SLIST_REMOVE(list, kn, knote, kn_link);
2337 if (kn->kn_status & KN_QUEUED)
2341 if (kn->kn_fop->f_isfd) {
2342 fdrop(kn->kn_fp, td);
2345 kqueue_fo_release(kn->kn_kevent.filter);
2351 knote_enqueue(struct knote *kn)
2353 struct kqueue *kq = kn->kn_kq;
2355 KQ_OWNED(kn->kn_kq);
2356 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2358 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2359 kn->kn_status |= KN_QUEUED;
2365 knote_dequeue(struct knote *kn)
2367 struct kqueue *kq = kn->kn_kq;
2369 KQ_OWNED(kn->kn_kq);
2370 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2372 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2373 kn->kn_status &= ~KN_QUEUED;
2381 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2382 NULL, NULL, UMA_ALIGN_PTR, 0);
2384 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2386 static struct knote *
2387 knote_alloc(int waitok)
2390 return (uma_zalloc(knote_zone, (waitok ? M_WAITOK : M_NOWAIT) |
2395 knote_free(struct knote *kn)
2398 uma_zfree(knote_zone, kn);
2402 * Register the kev w/ the kq specified by fd.
2405 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2409 cap_rights_t rights;
2412 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2415 if ((error = kqueue_acquire(fp, &kq)) != 0)
2418 error = kqueue_register(kq, kev, td, waitok);
2420 kqueue_release(kq, 0);