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 int kqueue_expand(struct kqueue *kq, struct filterops *fops,
103 uintptr_t ident, int waitok);
104 static void kqueue_task(void *arg, int pending);
105 static int kqueue_scan(struct kqueue *kq, int maxevents,
106 struct kevent_copyops *k_ops,
107 const struct timespec *timeout,
108 struct kevent *keva, struct thread *td);
109 static void kqueue_wakeup(struct kqueue *kq);
110 static struct filterops *kqueue_fo_find(int filt);
111 static void kqueue_fo_release(int filt);
113 static fo_ioctl_t kqueue_ioctl;
114 static fo_poll_t kqueue_poll;
115 static fo_kqfilter_t kqueue_kqfilter;
116 static fo_stat_t kqueue_stat;
117 static fo_close_t kqueue_close;
118 static fo_fill_kinfo_t kqueue_fill_kinfo;
120 static struct fileops kqueueops = {
121 .fo_read = invfo_rdwr,
122 .fo_write = invfo_rdwr,
123 .fo_truncate = invfo_truncate,
124 .fo_ioctl = kqueue_ioctl,
125 .fo_poll = kqueue_poll,
126 .fo_kqfilter = kqueue_kqfilter,
127 .fo_stat = kqueue_stat,
128 .fo_close = kqueue_close,
129 .fo_chmod = invfo_chmod,
130 .fo_chown = invfo_chown,
131 .fo_sendfile = invfo_sendfile,
132 .fo_fill_kinfo = kqueue_fill_kinfo,
135 static int knote_attach(struct knote *kn, struct kqueue *kq);
136 static void knote_drop(struct knote *kn, struct thread *td);
137 static void knote_enqueue(struct knote *kn);
138 static void knote_dequeue(struct knote *kn);
139 static void knote_init(void);
140 static struct knote *knote_alloc(int waitok);
141 static void knote_free(struct knote *kn);
143 static void filt_kqdetach(struct knote *kn);
144 static int filt_kqueue(struct knote *kn, long hint);
145 static int filt_procattach(struct knote *kn);
146 static void filt_procdetach(struct knote *kn);
147 static int filt_proc(struct knote *kn, long hint);
148 static int filt_fileattach(struct knote *kn);
149 static void filt_timerexpire(void *knx);
150 static int filt_timerattach(struct knote *kn);
151 static void filt_timerdetach(struct knote *kn);
152 static int filt_timer(struct knote *kn, long hint);
153 static int filt_userattach(struct knote *kn);
154 static void filt_userdetach(struct knote *kn);
155 static int filt_user(struct knote *kn, long hint);
156 static void filt_usertouch(struct knote *kn, struct kevent *kev,
159 static struct filterops file_filtops = {
161 .f_attach = filt_fileattach,
163 static struct filterops kqread_filtops = {
165 .f_detach = filt_kqdetach,
166 .f_event = filt_kqueue,
168 /* XXX - move to kern_proc.c? */
169 static struct filterops proc_filtops = {
171 .f_attach = filt_procattach,
172 .f_detach = filt_procdetach,
173 .f_event = filt_proc,
175 static struct filterops timer_filtops = {
177 .f_attach = filt_timerattach,
178 .f_detach = filt_timerdetach,
179 .f_event = filt_timer,
181 static struct filterops user_filtops = {
182 .f_attach = filt_userattach,
183 .f_detach = filt_userdetach,
184 .f_event = filt_user,
185 .f_touch = filt_usertouch,
188 static uma_zone_t knote_zone;
189 static atomic_uint kq_ncallouts = ATOMIC_VAR_INIT(0);
190 static unsigned int kq_calloutmax = 4 * 1024;
191 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
192 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
194 /* XXX - ensure not KN_INFLUX?? */
195 #define KNOTE_ACTIVATE(kn, islock) do { \
197 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
199 KQ_LOCK((kn)->kn_kq); \
200 (kn)->kn_status |= KN_ACTIVE; \
201 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
202 knote_enqueue((kn)); \
204 KQ_UNLOCK((kn)->kn_kq); \
206 #define KQ_LOCK(kq) do { \
207 mtx_lock(&(kq)->kq_lock); \
209 #define KQ_FLUX_WAKEUP(kq) do { \
210 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
211 (kq)->kq_state &= ~KQ_FLUXWAIT; \
215 #define KQ_UNLOCK_FLUX(kq) do { \
216 KQ_FLUX_WAKEUP(kq); \
217 mtx_unlock(&(kq)->kq_lock); \
219 #define KQ_UNLOCK(kq) do { \
220 mtx_unlock(&(kq)->kq_lock); \
222 #define KQ_OWNED(kq) do { \
223 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
225 #define KQ_NOTOWNED(kq) do { \
226 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
228 #define KN_LIST_LOCK(kn) do { \
229 if (kn->kn_knlist != NULL) \
230 kn->kn_knlist->kl_lock(kn->kn_knlist->kl_lockarg); \
232 #define KN_LIST_UNLOCK(kn) do { \
233 if (kn->kn_knlist != NULL) \
234 kn->kn_knlist->kl_unlock(kn->kn_knlist->kl_lockarg); \
236 #define KNL_ASSERT_LOCK(knl, islocked) do { \
238 KNL_ASSERT_LOCKED(knl); \
240 KNL_ASSERT_UNLOCKED(knl); \
243 #define KNL_ASSERT_LOCKED(knl) do { \
244 knl->kl_assert_locked((knl)->kl_lockarg); \
246 #define KNL_ASSERT_UNLOCKED(knl) do { \
247 knl->kl_assert_unlocked((knl)->kl_lockarg); \
249 #else /* !INVARIANTS */
250 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
251 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
252 #endif /* INVARIANTS */
255 #define KN_HASHSIZE 64 /* XXX should be tunable */
258 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
261 filt_nullattach(struct knote *kn)
267 struct filterops null_filtops = {
269 .f_attach = filt_nullattach,
272 /* XXX - make SYSINIT to add these, and move into respective modules. */
273 extern struct filterops sig_filtops;
274 extern struct filterops fs_filtops;
277 * Table for for all system-defined filters.
279 static struct mtx filterops_lock;
280 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
283 struct filterops *for_fop;
286 } sysfilt_ops[EVFILT_SYSCOUNT] = {
287 { &file_filtops, 1 }, /* EVFILT_READ */
288 { &file_filtops, 1 }, /* EVFILT_WRITE */
289 { &null_filtops }, /* EVFILT_AIO */
290 { &file_filtops, 1 }, /* EVFILT_VNODE */
291 { &proc_filtops, 1 }, /* EVFILT_PROC */
292 { &sig_filtops, 1 }, /* EVFILT_SIGNAL */
293 { &timer_filtops, 1 }, /* EVFILT_TIMER */
294 { &file_filtops, 1 }, /* EVFILT_PROCDESC */
295 { &fs_filtops, 1 }, /* EVFILT_FS */
296 { &null_filtops }, /* EVFILT_LIO */
297 { &user_filtops, 1 }, /* EVFILT_USER */
298 { &null_filtops }, /* EVFILT_SENDFILE */
302 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
306 filt_fileattach(struct knote *kn)
309 return (fo_kqfilter(kn->kn_fp, kn));
314 kqueue_kqfilter(struct file *fp, struct knote *kn)
316 struct kqueue *kq = kn->kn_fp->f_data;
318 if (kn->kn_filter != EVFILT_READ)
321 kn->kn_status |= KN_KQUEUE;
322 kn->kn_fop = &kqread_filtops;
323 knlist_add(&kq->kq_sel.si_note, kn, 0);
329 filt_kqdetach(struct knote *kn)
331 struct kqueue *kq = kn->kn_fp->f_data;
333 knlist_remove(&kq->kq_sel.si_note, kn, 0);
338 filt_kqueue(struct knote *kn, long hint)
340 struct kqueue *kq = kn->kn_fp->f_data;
342 kn->kn_data = kq->kq_count;
343 return (kn->kn_data > 0);
346 /* XXX - move to kern_proc.c? */
348 filt_procattach(struct knote *kn)
355 p = pfind(kn->kn_id);
356 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
357 p = zpfind(kn->kn_id);
359 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
365 if ((error = p_cansee(curthread, p))) {
370 kn->kn_ptr.p_proc = p;
371 kn->kn_flags |= EV_CLEAR; /* automatically set */
374 * internal flag indicating registration done by kernel
376 if (kn->kn_flags & EV_FLAG1) {
377 kn->kn_data = kn->kn_sdata; /* ppid */
378 kn->kn_fflags = NOTE_CHILD;
379 kn->kn_flags &= ~EV_FLAG1;
383 knlist_add(&p->p_klist, kn, 1);
386 * Immediately activate any exit notes if the target process is a
387 * zombie. This is necessary to handle the case where the target
388 * process, e.g. a child, dies before the kevent is registered.
390 if (immediate && filt_proc(kn, NOTE_EXIT))
391 KNOTE_ACTIVATE(kn, 0);
399 * The knote may be attached to a different process, which may exit,
400 * leaving nothing for the knote to be attached to. So when the process
401 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
402 * it will be deleted when read out. However, as part of the knote deletion,
403 * this routine is called, so a check is needed to avoid actually performing
404 * a detach, because the original process does not exist any more.
406 /* XXX - move to kern_proc.c? */
408 filt_procdetach(struct knote *kn)
412 p = kn->kn_ptr.p_proc;
413 knlist_remove(&p->p_klist, kn, 0);
414 kn->kn_ptr.p_proc = NULL;
417 /* XXX - move to kern_proc.c? */
419 filt_proc(struct knote *kn, long hint)
424 p = kn->kn_ptr.p_proc;
425 /* Mask off extra data. */
426 event = (u_int)hint & NOTE_PCTRLMASK;
428 /* If the user is interested in this event, record it. */
429 if (kn->kn_sfflags & event)
430 kn->kn_fflags |= event;
432 /* Process is gone, so flag the event as finished. */
433 if (event == NOTE_EXIT) {
434 if (!(kn->kn_status & KN_DETACHED))
435 knlist_remove_inevent(&p->p_klist, kn);
436 kn->kn_flags |= EV_EOF | EV_ONESHOT;
437 kn->kn_ptr.p_proc = NULL;
438 if (kn->kn_fflags & NOTE_EXIT)
439 kn->kn_data = p->p_xstat;
440 if (kn->kn_fflags == 0)
441 kn->kn_flags |= EV_DROP;
445 return (kn->kn_fflags != 0);
449 * Called when the process forked. It mostly does the same as the
450 * knote(), activating all knotes registered to be activated when the
451 * process forked. Additionally, for each knote attached to the
452 * parent, check whether user wants to track the new process. If so
453 * attach a new knote to it, and immediately report an event with the
457 knote_fork(struct knlist *list, int pid)
466 list->kl_lock(list->kl_lockarg);
468 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
470 * XXX - Why do we skip the kn if it is _INFLUX? Does this
471 * mean we will not properly wake up some notes?
473 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX)
477 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
483 * The same as knote(), activate the event.
485 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
486 kn->kn_status |= KN_HASKQLOCK;
487 if (kn->kn_fop->f_event(kn, NOTE_FORK))
488 KNOTE_ACTIVATE(kn, 1);
489 kn->kn_status &= ~KN_HASKQLOCK;
495 * The NOTE_TRACK case. In addition to the activation
496 * of the event, we need to register new event to
497 * track the child. Drop the locks in preparation for
498 * the call to kqueue_register().
500 kn->kn_status |= KN_INFLUX;
502 list->kl_unlock(list->kl_lockarg);
505 * Activate existing knote and register a knote with
509 kev.filter = kn->kn_filter;
510 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
511 kev.fflags = kn->kn_sfflags;
512 kev.data = kn->kn_id; /* parent */
513 kev.udata = kn->kn_kevent.udata;/* preserve udata */
514 error = kqueue_register(kq, &kev, NULL, 0);
516 kn->kn_fflags |= NOTE_TRACKERR;
517 if (kn->kn_fop->f_event(kn, NOTE_FORK))
518 KNOTE_ACTIVATE(kn, 0);
520 kn->kn_status &= ~KN_INFLUX;
522 list->kl_lock(list->kl_lockarg);
524 list->kl_unlock(list->kl_lockarg);
528 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
529 * interval timer support code.
532 #define NOTE_TIMER_PRECMASK (NOTE_SECONDS|NOTE_MSECONDS|NOTE_USECONDS| \
535 static __inline sbintime_t
536 timer2sbintime(intptr_t data, int flags)
540 switch (flags & NOTE_TIMER_PRECMASK) {
544 case NOTE_MSECONDS: /* FALLTHROUGH */
559 if (data > SBT_MAX / modifier)
562 return (modifier * data);
566 filt_timerexpire(void *knx)
568 struct callout *calloutp;
573 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
575 if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
576 calloutp = (struct callout *)kn->kn_hook;
577 *kn->kn_ptr.p_nexttime += timer2sbintime(kn->kn_sdata,
579 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
580 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
585 * data contains amount of time to sleep
588 filt_timerattach(struct knote *kn)
590 struct callout *calloutp;
592 unsigned int ncallouts;
594 if ((intptr_t)kn->kn_sdata < 0)
596 if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
598 /* Only precision unit are supported in flags so far */
599 if (kn->kn_sfflags & ~NOTE_TIMER_PRECMASK)
602 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
606 ncallouts = atomic_load_explicit(&kq_ncallouts, memory_order_relaxed);
608 if (ncallouts >= kq_calloutmax)
610 } while (!atomic_compare_exchange_weak_explicit(&kq_ncallouts,
611 &ncallouts, ncallouts + 1, memory_order_relaxed,
612 memory_order_relaxed));
614 kn->kn_flags |= EV_CLEAR; /* automatically set */
615 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
616 kn->kn_ptr.p_nexttime = malloc(sizeof(sbintime_t), M_KQUEUE, M_WAITOK);
617 calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
618 callout_init(calloutp, 1);
619 kn->kn_hook = calloutp;
620 *kn->kn_ptr.p_nexttime = to + sbinuptime();
621 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
622 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
628 filt_timerdetach(struct knote *kn)
630 struct callout *calloutp;
633 calloutp = (struct callout *)kn->kn_hook;
634 callout_drain(calloutp);
635 free(calloutp, M_KQUEUE);
636 free(kn->kn_ptr.p_nexttime, M_KQUEUE);
637 old = atomic_fetch_sub_explicit(&kq_ncallouts, 1, memory_order_relaxed);
638 KASSERT(old > 0, ("Number of callouts cannot become negative"));
639 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
643 filt_timer(struct knote *kn, long hint)
646 return (kn->kn_data != 0);
650 filt_userattach(struct knote *kn)
654 * EVFILT_USER knotes are not attached to anything in the kernel.
657 if (kn->kn_fflags & NOTE_TRIGGER)
665 filt_userdetach(__unused struct knote *kn)
669 * EVFILT_USER knotes are not attached to anything in the kernel.
674 filt_user(struct knote *kn, __unused long hint)
677 return (kn->kn_hookid);
681 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
687 if (kev->fflags & NOTE_TRIGGER)
690 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
691 kev->fflags &= NOTE_FFLAGSMASK;
697 kn->kn_sfflags &= kev->fflags;
701 kn->kn_sfflags |= kev->fflags;
705 kn->kn_sfflags = kev->fflags;
709 /* XXX Return error? */
712 kn->kn_sdata = kev->data;
713 if (kev->flags & EV_CLEAR) {
721 *kev = kn->kn_kevent;
722 kev->fflags = kn->kn_sfflags;
723 kev->data = kn->kn_sdata;
724 if (kn->kn_flags & EV_CLEAR) {
732 panic("filt_usertouch() - invalid type (%ld)", type);
738 sys_kqueue(struct thread *td, struct kqueue_args *uap)
740 struct filedesc *fdp;
751 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td->td_proc,
760 error = falloc(td, &fp, &fd, 0);
764 /* An extra reference on `fp' has been held for us by falloc(). */
765 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
766 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
767 TAILQ_INIT(&kq->kq_head);
770 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
771 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
774 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
775 FILEDESC_XUNLOCK(fdp);
777 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
780 td->td_retval[0] = fd;
783 chgkqcnt(cred->cr_ruidinfo, -1, 0);
789 #ifndef _SYS_SYSPROTO_H_
792 const struct kevent *changelist;
794 struct kevent *eventlist;
796 const struct timespec *timeout;
800 sys_kevent(struct thread *td, struct kevent_args *uap)
802 struct timespec ts, *tsp;
803 struct kevent_copyops k_ops = { uap,
810 struct uio *ktruioin = NULL;
811 struct uio *ktruioout = NULL;
814 if (uap->timeout != NULL) {
815 error = copyin(uap->timeout, &ts, sizeof(ts));
823 if (KTRPOINT(td, KTR_GENIO)) {
824 ktriov.iov_base = uap->changelist;
825 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
826 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
827 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
829 ktruioin = cloneuio(&ktruio);
830 ktriov.iov_base = uap->eventlist;
831 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
832 ktruioout = cloneuio(&ktruio);
836 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
840 if (ktruioin != NULL) {
841 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
842 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
843 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
844 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
852 * Copy 'count' items into the destination list pointed to by uap->eventlist.
855 kevent_copyout(void *arg, struct kevent *kevp, int count)
857 struct kevent_args *uap;
860 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
861 uap = (struct kevent_args *)arg;
863 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
865 uap->eventlist += count;
870 * Copy 'count' items from the list pointed to by uap->changelist.
873 kevent_copyin(void *arg, struct kevent *kevp, int count)
875 struct kevent_args *uap;
878 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
879 uap = (struct kevent_args *)arg;
881 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
883 uap->changelist += count;
888 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
889 struct kevent_copyops *k_ops, const struct timespec *timeout)
891 struct kevent keva[KQ_NEVENTS];
892 struct kevent *kevp, *changes;
896 int i, n, nerrors, error;
898 cap_rights_init(&rights);
900 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
902 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
903 error = fget(td, fd, &rights, &fp);
907 error = kqueue_acquire(fp, &kq);
913 while (nchanges > 0) {
914 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
915 error = k_ops->k_copyin(k_ops->arg, keva, n);
919 for (i = 0; i < n; i++) {
923 kevp->flags &= ~EV_SYSFLAGS;
924 error = kqueue_register(kq, kevp, td, 1);
925 if (error || (kevp->flags & EV_RECEIPT)) {
927 kevp->flags = EV_ERROR;
929 (void) k_ops->k_copyout(k_ops->arg,
941 td->td_retval[0] = nerrors;
946 error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
948 kqueue_release(kq, 0);
955 kqueue_add_filteropts(int filt, struct filterops *filtops)
960 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
962 "trying to add a filterop that is out of range: %d is beyond %d\n",
963 ~filt, EVFILT_SYSCOUNT);
966 mtx_lock(&filterops_lock);
967 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
968 sysfilt_ops[~filt].for_fop != NULL)
971 sysfilt_ops[~filt].for_fop = filtops;
972 sysfilt_ops[~filt].for_refcnt = 0;
974 mtx_unlock(&filterops_lock);
980 kqueue_del_filteropts(int filt)
985 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
988 mtx_lock(&filterops_lock);
989 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
990 sysfilt_ops[~filt].for_fop == NULL)
992 else if (sysfilt_ops[~filt].for_refcnt != 0)
995 sysfilt_ops[~filt].for_fop = &null_filtops;
996 sysfilt_ops[~filt].for_refcnt = 0;
998 mtx_unlock(&filterops_lock);
1003 static struct filterops *
1004 kqueue_fo_find(int filt)
1007 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1010 if (sysfilt_ops[~filt].for_nolock)
1011 return sysfilt_ops[~filt].for_fop;
1013 mtx_lock(&filterops_lock);
1014 sysfilt_ops[~filt].for_refcnt++;
1015 if (sysfilt_ops[~filt].for_fop == NULL)
1016 sysfilt_ops[~filt].for_fop = &null_filtops;
1017 mtx_unlock(&filterops_lock);
1019 return sysfilt_ops[~filt].for_fop;
1023 kqueue_fo_release(int filt)
1026 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1029 if (sysfilt_ops[~filt].for_nolock)
1032 mtx_lock(&filterops_lock);
1033 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1034 ("filter object refcount not valid on release"));
1035 sysfilt_ops[~filt].for_refcnt--;
1036 mtx_unlock(&filterops_lock);
1040 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1041 * influence if memory allocation should wait. Make sure it is 0 if you
1045 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1047 struct filterops *fops;
1049 struct knote *kn, *tkn;
1050 cap_rights_t rights;
1051 int error, filt, event;
1052 int haskqglobal, filedesc_unlock;
1058 filedesc_unlock = 0;
1061 fops = kqueue_fo_find(filt);
1065 if (kev->flags & EV_ADD)
1066 tkn = knote_alloc(waitok); /* prevent waiting with locks */
1072 KASSERT(td != NULL, ("td is NULL"));
1073 error = fget(td, kev->ident,
1074 cap_rights_init(&rights, CAP_EVENT), &fp);
1078 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1079 kev->ident, 0) != 0) {
1083 error = kqueue_expand(kq, fops, kev->ident, waitok);
1089 if (fp->f_type == DTYPE_KQUEUE) {
1091 * if we add some inteligence about what we are doing,
1092 * we should be able to support events on ourselves.
1093 * We need to know when we are doing this to prevent
1094 * getting both the knlist lock and the kq lock since
1095 * they are the same thing.
1097 if (fp->f_data == kq) {
1103 * Pre-lock the filedesc before the global
1104 * lock mutex, see the comment in
1107 FILEDESC_XLOCK(td->td_proc->p_fd);
1108 filedesc_unlock = 1;
1109 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1113 if (kev->ident < kq->kq_knlistsize) {
1114 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1115 if (kev->filter == kn->kn_filter)
1119 if ((kev->flags & EV_ADD) == EV_ADD)
1120 kqueue_expand(kq, fops, kev->ident, waitok);
1123 if (kq->kq_knhashmask != 0) {
1126 list = &kq->kq_knhash[
1127 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1128 SLIST_FOREACH(kn, list, kn_link)
1129 if (kev->ident == kn->kn_id &&
1130 kev->filter == kn->kn_filter)
1135 /* knote is in the process of changing, wait for it to stablize. */
1136 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1137 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1138 if (filedesc_unlock) {
1139 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1140 filedesc_unlock = 0;
1142 kq->kq_state |= KQ_FLUXWAIT;
1143 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1152 * kn now contains the matching knote, or NULL if no match
1155 if (kev->flags & EV_ADD) {
1167 * apply reference counts to knote structure, and
1168 * do not release it at the end of this routine.
1173 kn->kn_sfflags = kev->fflags;
1174 kn->kn_sdata = kev->data;
1177 kn->kn_kevent = *kev;
1178 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1179 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1180 kn->kn_status = KN_INFLUX|KN_DETACHED;
1182 error = knote_attach(kn, kq);
1189 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1196 /* No matching knote and the EV_ADD flag is not set. */
1203 if (kev->flags & EV_DELETE) {
1204 kn->kn_status |= KN_INFLUX;
1206 if (!(kn->kn_status & KN_DETACHED))
1207 kn->kn_fop->f_detach(kn);
1212 if (kev->flags & EV_FORCEONESHOT) {
1213 kn->kn_flags |= EV_ONESHOT;
1214 KNOTE_ACTIVATE(kn, 1);
1218 * The user may change some filter values after the initial EV_ADD,
1219 * but doing so will not reset any filter which has already been
1222 kn->kn_status |= KN_INFLUX | KN_SCAN;
1225 kn->kn_kevent.udata = kev->udata;
1226 if (!fops->f_isfd && fops->f_touch != NULL) {
1227 fops->f_touch(kn, kev, EVENT_REGISTER);
1229 kn->kn_sfflags = kev->fflags;
1230 kn->kn_sdata = kev->data;
1234 * We can get here with kn->kn_knlist == NULL. This can happen when
1235 * the initial attach event decides that the event is "completed"
1236 * already. i.e. filt_procattach is called on a zombie process. It
1237 * will call filt_proc which will remove it from the list, and NULL
1241 if ((kev->flags & EV_DISABLE) &&
1242 ((kn->kn_status & KN_DISABLED) == 0)) {
1243 kn->kn_status |= KN_DISABLED;
1246 if ((kn->kn_status & KN_DISABLED) == 0)
1247 event = kn->kn_fop->f_event(kn, 0);
1252 KNOTE_ACTIVATE(kn, 1);
1253 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1256 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1257 kn->kn_status &= ~KN_DISABLED;
1258 if ((kn->kn_status & KN_ACTIVE) &&
1259 ((kn->kn_status & KN_QUEUED) == 0))
1265 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1266 if (filedesc_unlock)
1267 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1273 kqueue_fo_release(filt);
1278 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1286 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1290 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1301 kqueue_release(struct kqueue *kq, int locked)
1308 if (kq->kq_refcnt == 1)
1309 wakeup(&kq->kq_refcnt);
1315 kqueue_schedtask(struct kqueue *kq)
1319 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1320 ("scheduling kqueue task while draining"));
1322 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1323 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1324 kq->kq_state |= KQ_TASKSCHED;
1329 * Expand the kq to make sure we have storage for fops/ident pair.
1331 * Return 0 on success (or no work necessary), return errno on failure.
1333 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1334 * If kqueue_register is called from a non-fd context, there usually/should
1338 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1341 struct klist *list, *tmp_knhash, *to_free;
1342 u_long tmp_knhashmask;
1345 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1352 if (kq->kq_knlistsize <= fd) {
1353 size = kq->kq_knlistsize;
1356 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1360 if (kq->kq_knlistsize > fd) {
1364 if (kq->kq_knlist != NULL) {
1365 bcopy(kq->kq_knlist, list,
1366 kq->kq_knlistsize * sizeof(*list));
1367 to_free = kq->kq_knlist;
1368 kq->kq_knlist = NULL;
1370 bzero((caddr_t)list +
1371 kq->kq_knlistsize * sizeof(*list),
1372 (size - kq->kq_knlistsize) * sizeof(*list));
1373 kq->kq_knlistsize = size;
1374 kq->kq_knlist = list;
1379 if (kq->kq_knhashmask == 0) {
1380 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1382 if (tmp_knhash == NULL)
1385 if (kq->kq_knhashmask == 0) {
1386 kq->kq_knhash = tmp_knhash;
1387 kq->kq_knhashmask = tmp_knhashmask;
1389 to_free = tmp_knhash;
1394 free(to_free, M_KQUEUE);
1401 kqueue_task(void *arg, int pending)
1409 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1412 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1414 kq->kq_state &= ~KQ_TASKSCHED;
1415 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1416 wakeup(&kq->kq_state);
1419 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1423 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1424 * We treat KN_MARKER knotes as if they are INFLUX.
1427 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1428 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1430 struct kevent *kevp;
1431 struct knote *kn, *marker;
1432 sbintime_t asbt, rsbt;
1433 int count, error, haskqglobal, influx, nkev, touch;
1445 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1446 tsp->tv_nsec >= 1000000000) {
1450 if (timespecisset(tsp)) {
1451 if (tsp->tv_sec <= INT32_MAX) {
1452 rsbt = tstosbt(*tsp);
1453 if (TIMESEL(&asbt, rsbt))
1454 asbt += tc_tick_sbt;
1455 if (asbt <= SBT_MAX - rsbt)
1459 rsbt >>= tc_precexp;
1466 marker = knote_alloc(1);
1467 if (marker == NULL) {
1471 marker->kn_status = KN_MARKER;
1476 if (kq->kq_count == 0) {
1478 error = EWOULDBLOCK;
1480 kq->kq_state |= KQ_SLEEP;
1481 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1482 "kqread", asbt, rsbt, C_ABSOLUTE);
1486 /* don't restart after signals... */
1487 if (error == ERESTART)
1489 else if (error == EWOULDBLOCK)
1494 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1498 kn = TAILQ_FIRST(&kq->kq_head);
1500 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1501 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1506 kq->kq_state |= KQ_FLUXWAIT;
1507 error = msleep(kq, &kq->kq_lock, PSOCK,
1512 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1513 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1514 kn->kn_status &= ~KN_QUEUED;
1520 if (count == maxevents)
1524 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1525 ("KN_INFLUX set when not suppose to be"));
1527 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1528 kn->kn_status &= ~KN_QUEUED;
1529 kn->kn_status |= KN_INFLUX;
1533 * We don't need to lock the list since we've marked
1536 if (!(kn->kn_status & KN_DETACHED))
1537 kn->kn_fop->f_detach(kn);
1541 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1542 kn->kn_status &= ~KN_QUEUED;
1543 kn->kn_status |= KN_INFLUX;
1547 * We don't need to lock the list since we've marked
1550 *kevp = kn->kn_kevent;
1551 if (!(kn->kn_status & KN_DETACHED))
1552 kn->kn_fop->f_detach(kn);
1557 kn->kn_status |= KN_INFLUX | KN_SCAN;
1559 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1560 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1562 if (kn->kn_fop->f_event(kn, 0) == 0) {
1564 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1566 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1573 touch = (!kn->kn_fop->f_isfd &&
1574 kn->kn_fop->f_touch != NULL);
1576 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1578 *kevp = kn->kn_kevent;
1580 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1581 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1583 * Manually clear knotes who weren't
1586 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1590 if (kn->kn_flags & EV_DISPATCH)
1591 kn->kn_status |= KN_DISABLED;
1592 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1595 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1597 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1602 /* we are returning a copy to the user */
1607 if (nkev == KQ_NEVENTS) {
1610 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1618 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1626 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1627 td->td_retval[0] = maxevents - count;
1633 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1634 struct ucred *active_cred, struct thread *td)
1637 * Enabling sigio causes two major problems:
1638 * 1) infinite recursion:
1639 * Synopsys: kevent is being used to track signals and have FIOASYNC
1640 * set. On receipt of a signal this will cause a kqueue to recurse
1641 * into itself over and over. Sending the sigio causes the kqueue
1642 * to become ready, which in turn posts sigio again, forever.
1643 * Solution: this can be solved by setting a flag in the kqueue that
1644 * we have a SIGIO in progress.
1645 * 2) locking problems:
1646 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1647 * us above the proc and pgrp locks.
1648 * Solution: Post a signal using an async mechanism, being sure to
1649 * record a generation count in the delivery so that we do not deliver
1650 * a signal to the wrong process.
1652 * Note, these two mechanisms are somewhat mutually exclusive!
1661 kq->kq_state |= KQ_ASYNC;
1663 kq->kq_state &= ~KQ_ASYNC;
1668 return (fsetown(*(int *)data, &kq->kq_sigio));
1671 *(int *)data = fgetown(&kq->kq_sigio);
1681 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1688 if ((error = kqueue_acquire(fp, &kq)))
1692 if (events & (POLLIN | POLLRDNORM)) {
1694 revents |= events & (POLLIN | POLLRDNORM);
1696 selrecord(td, &kq->kq_sel);
1697 if (SEL_WAITING(&kq->kq_sel))
1698 kq->kq_state |= KQ_SEL;
1701 kqueue_release(kq, 1);
1708 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1712 bzero((void *)st, sizeof *st);
1714 * We no longer return kq_count because the unlocked value is useless.
1715 * If you spent all this time getting the count, why not spend your
1716 * syscall better by calling kevent?
1718 * XXX - This is needed for libc_r.
1720 st->st_mode = S_IFIFO;
1726 kqueue_close(struct file *fp, struct thread *td)
1728 struct kqueue *kq = fp->f_data;
1729 struct filedesc *fdp;
1733 int filedesc_unlock;
1735 if ((error = kqueue_acquire(fp, &kq)))
1738 filedesc_unlock = 0;
1741 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1742 ("kqueue already closing"));
1743 kq->kq_state |= KQ_CLOSING;
1744 if (kq->kq_refcnt > 1)
1745 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1747 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1750 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1751 ("kqueue's knlist not empty"));
1753 for (i = 0; i < kq->kq_knlistsize; i++) {
1754 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1755 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1756 kq->kq_state |= KQ_FLUXWAIT;
1757 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1760 kn->kn_status |= KN_INFLUX;
1762 if (!(kn->kn_status & KN_DETACHED))
1763 kn->kn_fop->f_detach(kn);
1768 if (kq->kq_knhashmask != 0) {
1769 for (i = 0; i <= kq->kq_knhashmask; i++) {
1770 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1771 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1772 kq->kq_state |= KQ_FLUXWAIT;
1773 msleep(kq, &kq->kq_lock, PSOCK,
1777 kn->kn_status |= KN_INFLUX;
1779 if (!(kn->kn_status & KN_DETACHED))
1780 kn->kn_fop->f_detach(kn);
1787 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1788 kq->kq_state |= KQ_TASKDRAIN;
1789 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1792 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1793 selwakeuppri(&kq->kq_sel, PSOCK);
1794 if (!SEL_WAITING(&kq->kq_sel))
1795 kq->kq_state &= ~KQ_SEL;
1801 * We could be called due to the knote_drop() doing fdrop(),
1802 * called from kqueue_register(). In this case the global
1803 * lock is owned, and filedesc sx is locked before, to not
1804 * take the sleepable lock after non-sleepable.
1806 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1807 FILEDESC_XLOCK(fdp);
1808 filedesc_unlock = 1;
1810 filedesc_unlock = 0;
1811 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1812 if (filedesc_unlock)
1813 FILEDESC_XUNLOCK(fdp);
1815 seldrain(&kq->kq_sel);
1816 knlist_destroy(&kq->kq_sel.si_note);
1817 mtx_destroy(&kq->kq_lock);
1820 if (kq->kq_knhash != NULL)
1821 free(kq->kq_knhash, M_KQUEUE);
1822 if (kq->kq_knlist != NULL)
1823 free(kq->kq_knlist, M_KQUEUE);
1825 funsetown(&kq->kq_sigio);
1826 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1827 crfree(kq->kq_cred);
1835 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1838 kif->kf_type = KF_TYPE_KQUEUE;
1843 kqueue_wakeup(struct kqueue *kq)
1847 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1848 kq->kq_state &= ~KQ_SLEEP;
1851 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1852 selwakeuppri(&kq->kq_sel, PSOCK);
1853 if (!SEL_WAITING(&kq->kq_sel))
1854 kq->kq_state &= ~KQ_SEL;
1856 if (!knlist_empty(&kq->kq_sel.si_note))
1857 kqueue_schedtask(kq);
1858 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1859 pgsigio(&kq->kq_sigio, SIGIO, 0);
1864 * Walk down a list of knotes, activating them if their event has triggered.
1866 * There is a possibility to optimize in the case of one kq watching another.
1867 * Instead of scheduling a task to wake it up, you could pass enough state
1868 * down the chain to make up the parent kqueue. Make this code functional
1872 knote(struct knlist *list, long hint, int lockflags)
1881 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1883 if ((lockflags & KNF_LISTLOCKED) == 0)
1884 list->kl_lock(list->kl_lockarg);
1887 * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1888 * the kqueue scheduling, but this will introduce four
1889 * lock/unlock's for each knote to test. If we do, continue to use
1890 * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1891 * only safe if you want to remove the current item, which we are
1894 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1897 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1899 * Do not process the influx notes, except for
1900 * the influx coming from the kq unlock in the
1901 * kqueue_scan(). In the later case, we do
1902 * not interfere with the scan, since the code
1903 * fragment in kqueue_scan() locks the knlist,
1904 * and cannot proceed until we finished.
1907 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1908 kn->kn_status |= KN_INFLUX;
1910 error = kn->kn_fop->f_event(kn, hint);
1912 kn->kn_status &= ~KN_INFLUX;
1914 KNOTE_ACTIVATE(kn, 1);
1917 kn->kn_status |= KN_HASKQLOCK;
1918 if (kn->kn_fop->f_event(kn, hint))
1919 KNOTE_ACTIVATE(kn, 1);
1920 kn->kn_status &= ~KN_HASKQLOCK;
1924 if ((lockflags & KNF_LISTLOCKED) == 0)
1925 list->kl_unlock(list->kl_lockarg);
1929 * add a knote to a knlist
1932 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1934 KNL_ASSERT_LOCK(knl, islocked);
1935 KQ_NOTOWNED(kn->kn_kq);
1936 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1937 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1939 knl->kl_lock(knl->kl_lockarg);
1940 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1942 knl->kl_unlock(knl->kl_lockarg);
1944 kn->kn_knlist = knl;
1945 kn->kn_status &= ~KN_DETACHED;
1946 KQ_UNLOCK(kn->kn_kq);
1950 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1952 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1953 KNL_ASSERT_LOCK(knl, knlislocked);
1954 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1956 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1957 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1959 knl->kl_lock(knl->kl_lockarg);
1960 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1961 kn->kn_knlist = NULL;
1963 knl->kl_unlock(knl->kl_lockarg);
1966 kn->kn_status |= KN_DETACHED;
1968 KQ_UNLOCK(kn->kn_kq);
1972 * remove knote from the specified knlist
1975 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1978 knlist_remove_kq(knl, kn, islocked, 0);
1982 * remove knote from the specified knlist while in f_event handler.
1985 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1988 knlist_remove_kq(knl, kn, 1,
1989 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1993 knlist_empty(struct knlist *knl)
1996 KNL_ASSERT_LOCKED(knl);
1997 return SLIST_EMPTY(&knl->kl_list);
2000 static struct mtx knlist_lock;
2001 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2003 static void knlist_mtx_lock(void *arg);
2004 static void knlist_mtx_unlock(void *arg);
2007 knlist_mtx_lock(void *arg)
2010 mtx_lock((struct mtx *)arg);
2014 knlist_mtx_unlock(void *arg)
2017 mtx_unlock((struct mtx *)arg);
2021 knlist_mtx_assert_locked(void *arg)
2024 mtx_assert((struct mtx *)arg, MA_OWNED);
2028 knlist_mtx_assert_unlocked(void *arg)
2031 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2035 knlist_rw_rlock(void *arg)
2038 rw_rlock((struct rwlock *)arg);
2042 knlist_rw_runlock(void *arg)
2045 rw_runlock((struct rwlock *)arg);
2049 knlist_rw_assert_locked(void *arg)
2052 rw_assert((struct rwlock *)arg, RA_LOCKED);
2056 knlist_rw_assert_unlocked(void *arg)
2059 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2063 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2064 void (*kl_unlock)(void *),
2065 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2069 knl->kl_lockarg = &knlist_lock;
2071 knl->kl_lockarg = lock;
2073 if (kl_lock == NULL)
2074 knl->kl_lock = knlist_mtx_lock;
2076 knl->kl_lock = kl_lock;
2077 if (kl_unlock == NULL)
2078 knl->kl_unlock = knlist_mtx_unlock;
2080 knl->kl_unlock = kl_unlock;
2081 if (kl_assert_locked == NULL)
2082 knl->kl_assert_locked = knlist_mtx_assert_locked;
2084 knl->kl_assert_locked = kl_assert_locked;
2085 if (kl_assert_unlocked == NULL)
2086 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2088 knl->kl_assert_unlocked = kl_assert_unlocked;
2090 SLIST_INIT(&knl->kl_list);
2094 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2097 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2101 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2104 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2105 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2109 knlist_destroy(struct knlist *knl)
2114 * if we run across this error, we need to find the offending
2115 * driver and have it call knlist_clear or knlist_delete.
2117 if (!SLIST_EMPTY(&knl->kl_list))
2118 printf("WARNING: destroying knlist w/ knotes on it!\n");
2121 knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2122 SLIST_INIT(&knl->kl_list);
2126 * Even if we are locked, we may need to drop the lock to allow any influx
2127 * knotes time to "settle".
2130 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2132 struct knote *kn, *kn2;
2136 KNL_ASSERT_LOCKED(knl);
2138 KNL_ASSERT_UNLOCKED(knl);
2139 again: /* need to reacquire lock since we have dropped it */
2140 knl->kl_lock(knl->kl_lockarg);
2143 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2146 if ((kn->kn_status & KN_INFLUX)) {
2150 knlist_remove_kq(knl, kn, 1, 1);
2152 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2156 /* Make sure cleared knotes disappear soon */
2157 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2163 if (!SLIST_EMPTY(&knl->kl_list)) {
2164 /* there are still KN_INFLUX remaining */
2165 kn = SLIST_FIRST(&knl->kl_list);
2168 KASSERT(kn->kn_status & KN_INFLUX,
2169 ("knote removed w/o list lock"));
2170 knl->kl_unlock(knl->kl_lockarg);
2171 kq->kq_state |= KQ_FLUXWAIT;
2172 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2178 KNL_ASSERT_LOCKED(knl);
2180 knl->kl_unlock(knl->kl_lockarg);
2181 KNL_ASSERT_UNLOCKED(knl);
2186 * Remove all knotes referencing a specified fd must be called with FILEDESC
2187 * lock. This prevents a race where a new fd comes along and occupies the
2188 * entry and we attach a knote to the fd.
2191 knote_fdclose(struct thread *td, int fd)
2193 struct filedesc *fdp = td->td_proc->p_fd;
2198 FILEDESC_XLOCK_ASSERT(fdp);
2201 * We shouldn't have to worry about new kevents appearing on fd
2202 * since filedesc is locked.
2204 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2209 while (kq->kq_knlistsize > fd &&
2210 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2211 if (kn->kn_status & KN_INFLUX) {
2212 /* someone else might be waiting on our knote */
2215 kq->kq_state |= KQ_FLUXWAIT;
2216 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2219 kn->kn_status |= KN_INFLUX;
2221 if (!(kn->kn_status & KN_DETACHED))
2222 kn->kn_fop->f_detach(kn);
2232 knote_attach(struct knote *kn, struct kqueue *kq)
2236 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2239 if (kn->kn_fop->f_isfd) {
2240 if (kn->kn_id >= kq->kq_knlistsize)
2242 list = &kq->kq_knlist[kn->kn_id];
2244 if (kq->kq_knhash == NULL)
2246 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2249 SLIST_INSERT_HEAD(list, kn, kn_link);
2255 * knote must already have been detached using the f_detach method.
2256 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2257 * to prevent other removal.
2260 knote_drop(struct knote *kn, struct thread *td)
2268 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2269 ("knote_drop called without KN_INFLUX set in kn_status"));
2272 if (kn->kn_fop->f_isfd)
2273 list = &kq->kq_knlist[kn->kn_id];
2275 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2277 if (!SLIST_EMPTY(list))
2278 SLIST_REMOVE(list, kn, knote, kn_link);
2279 if (kn->kn_status & KN_QUEUED)
2283 if (kn->kn_fop->f_isfd) {
2284 fdrop(kn->kn_fp, td);
2287 kqueue_fo_release(kn->kn_kevent.filter);
2293 knote_enqueue(struct knote *kn)
2295 struct kqueue *kq = kn->kn_kq;
2297 KQ_OWNED(kn->kn_kq);
2298 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2300 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2301 kn->kn_status |= KN_QUEUED;
2307 knote_dequeue(struct knote *kn)
2309 struct kqueue *kq = kn->kn_kq;
2311 KQ_OWNED(kn->kn_kq);
2312 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2314 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2315 kn->kn_status &= ~KN_QUEUED;
2323 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2324 NULL, NULL, UMA_ALIGN_PTR, 0);
2326 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2328 static struct knote *
2329 knote_alloc(int waitok)
2331 return ((struct knote *)uma_zalloc(knote_zone,
2332 (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2336 knote_free(struct knote *kn)
2339 uma_zfree(knote_zone, kn);
2343 * Register the kev w/ the kq specified by fd.
2346 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2350 cap_rights_t rights;
2353 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2356 if ((error = kqueue_acquire(fp, &kq)) != 0)
2359 error = kqueue_register(kq, kev, td, waitok);
2361 kqueue_release(kq, 0);