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)
741 return (kern_kqueue(td, 0));
745 kern_kqueue(struct thread *td, int flags)
747 struct filedesc *fdp;
757 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_KQUEUES))) {
763 error = falloc(td, &fp, &fd, flags);
767 /* An extra reference on `fp' has been held for us by falloc(). */
768 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
769 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
770 TAILQ_INIT(&kq->kq_head);
773 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
774 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
777 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
778 FILEDESC_XUNLOCK(fdp);
780 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
783 td->td_retval[0] = fd;
786 chgkqcnt(cred->cr_ruidinfo, -1, 0);
792 #ifndef _SYS_SYSPROTO_H_
795 const struct kevent *changelist;
797 struct kevent *eventlist;
799 const struct timespec *timeout;
803 sys_kevent(struct thread *td, struct kevent_args *uap)
805 struct timespec ts, *tsp;
806 struct kevent_copyops k_ops = { uap,
813 struct uio *ktruioin = NULL;
814 struct uio *ktruioout = NULL;
817 if (uap->timeout != NULL) {
818 error = copyin(uap->timeout, &ts, sizeof(ts));
826 if (KTRPOINT(td, KTR_GENIO)) {
827 ktriov.iov_base = uap->changelist;
828 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
829 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
830 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
832 ktruioin = cloneuio(&ktruio);
833 ktriov.iov_base = uap->eventlist;
834 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
835 ktruioout = cloneuio(&ktruio);
839 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
843 if (ktruioin != NULL) {
844 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
845 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
846 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
847 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
855 * Copy 'count' items into the destination list pointed to by uap->eventlist.
858 kevent_copyout(void *arg, struct kevent *kevp, int count)
860 struct kevent_args *uap;
863 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
864 uap = (struct kevent_args *)arg;
866 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
868 uap->eventlist += count;
873 * Copy 'count' items from the list pointed to by uap->changelist.
876 kevent_copyin(void *arg, struct kevent *kevp, int count)
878 struct kevent_args *uap;
881 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
882 uap = (struct kevent_args *)arg;
884 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
886 uap->changelist += count;
891 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
892 struct kevent_copyops *k_ops, const struct timespec *timeout)
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 = kern_kevent_fp(td, fp, nchanges, nevents, k_ops, timeout);
914 kern_kevent_fp(struct thread *td, struct file *fp, int nchanges, int nevents,
915 struct kevent_copyops *k_ops, const struct timespec *timeout)
917 struct kevent keva[KQ_NEVENTS];
918 struct kevent *kevp, *changes;
920 int i, n, nerrors, error;
922 error = kqueue_acquire(fp, &kq);
928 while (nchanges > 0) {
929 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
930 error = k_ops->k_copyin(k_ops->arg, keva, n);
934 for (i = 0; i < n; i++) {
938 kevp->flags &= ~EV_SYSFLAGS;
939 error = kqueue_register(kq, kevp, td, 1);
940 if (error || (kevp->flags & EV_RECEIPT)) {
942 kevp->flags = EV_ERROR;
944 (void) k_ops->k_copyout(k_ops->arg,
956 td->td_retval[0] = nerrors;
961 error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
963 kqueue_release(kq, 0);
968 kqueue_add_filteropts(int filt, struct filterops *filtops)
973 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
975 "trying to add a filterop that is out of range: %d is beyond %d\n",
976 ~filt, EVFILT_SYSCOUNT);
979 mtx_lock(&filterops_lock);
980 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
981 sysfilt_ops[~filt].for_fop != NULL)
984 sysfilt_ops[~filt].for_fop = filtops;
985 sysfilt_ops[~filt].for_refcnt = 0;
987 mtx_unlock(&filterops_lock);
993 kqueue_del_filteropts(int filt)
998 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1001 mtx_lock(&filterops_lock);
1002 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
1003 sysfilt_ops[~filt].for_fop == NULL)
1005 else if (sysfilt_ops[~filt].for_refcnt != 0)
1008 sysfilt_ops[~filt].for_fop = &null_filtops;
1009 sysfilt_ops[~filt].for_refcnt = 0;
1011 mtx_unlock(&filterops_lock);
1016 static struct filterops *
1017 kqueue_fo_find(int filt)
1020 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1023 if (sysfilt_ops[~filt].for_nolock)
1024 return sysfilt_ops[~filt].for_fop;
1026 mtx_lock(&filterops_lock);
1027 sysfilt_ops[~filt].for_refcnt++;
1028 if (sysfilt_ops[~filt].for_fop == NULL)
1029 sysfilt_ops[~filt].for_fop = &null_filtops;
1030 mtx_unlock(&filterops_lock);
1032 return sysfilt_ops[~filt].for_fop;
1036 kqueue_fo_release(int filt)
1039 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1042 if (sysfilt_ops[~filt].for_nolock)
1045 mtx_lock(&filterops_lock);
1046 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1047 ("filter object refcount not valid on release"));
1048 sysfilt_ops[~filt].for_refcnt--;
1049 mtx_unlock(&filterops_lock);
1053 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1054 * influence if memory allocation should wait. Make sure it is 0 if you
1058 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1060 struct filterops *fops;
1062 struct knote *kn, *tkn;
1063 cap_rights_t rights;
1064 int error, filt, event;
1065 int haskqglobal, filedesc_unlock;
1071 filedesc_unlock = 0;
1074 fops = kqueue_fo_find(filt);
1078 if (kev->flags & EV_ADD)
1079 tkn = knote_alloc(waitok); /* prevent waiting with locks */
1085 KASSERT(td != NULL, ("td is NULL"));
1086 error = fget(td, kev->ident,
1087 cap_rights_init(&rights, CAP_EVENT), &fp);
1091 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1092 kev->ident, 0) != 0) {
1096 error = kqueue_expand(kq, fops, kev->ident, waitok);
1102 if (fp->f_type == DTYPE_KQUEUE) {
1104 * if we add some inteligence about what we are doing,
1105 * we should be able to support events on ourselves.
1106 * We need to know when we are doing this to prevent
1107 * getting both the knlist lock and the kq lock since
1108 * they are the same thing.
1110 if (fp->f_data == kq) {
1116 * Pre-lock the filedesc before the global
1117 * lock mutex, see the comment in
1120 FILEDESC_XLOCK(td->td_proc->p_fd);
1121 filedesc_unlock = 1;
1122 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1126 if (kev->ident < kq->kq_knlistsize) {
1127 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1128 if (kev->filter == kn->kn_filter)
1132 if ((kev->flags & EV_ADD) == EV_ADD)
1133 kqueue_expand(kq, fops, kev->ident, waitok);
1136 if (kq->kq_knhashmask != 0) {
1139 list = &kq->kq_knhash[
1140 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1141 SLIST_FOREACH(kn, list, kn_link)
1142 if (kev->ident == kn->kn_id &&
1143 kev->filter == kn->kn_filter)
1148 /* knote is in the process of changing, wait for it to stablize. */
1149 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1150 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1151 if (filedesc_unlock) {
1152 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1153 filedesc_unlock = 0;
1155 kq->kq_state |= KQ_FLUXWAIT;
1156 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1165 * kn now contains the matching knote, or NULL if no match
1168 if (kev->flags & EV_ADD) {
1180 * apply reference counts to knote structure, and
1181 * do not release it at the end of this routine.
1186 kn->kn_sfflags = kev->fflags;
1187 kn->kn_sdata = kev->data;
1190 kn->kn_kevent = *kev;
1191 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1192 EV_ENABLE | EV_DISABLE | EV_FORCEONESHOT);
1193 kn->kn_status = KN_INFLUX|KN_DETACHED;
1195 error = knote_attach(kn, kq);
1202 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1209 /* No matching knote and the EV_ADD flag is not set. */
1216 if (kev->flags & EV_DELETE) {
1217 kn->kn_status |= KN_INFLUX;
1219 if (!(kn->kn_status & KN_DETACHED))
1220 kn->kn_fop->f_detach(kn);
1225 if (kev->flags & EV_FORCEONESHOT) {
1226 kn->kn_flags |= EV_ONESHOT;
1227 KNOTE_ACTIVATE(kn, 1);
1231 * The user may change some filter values after the initial EV_ADD,
1232 * but doing so will not reset any filter which has already been
1235 kn->kn_status |= KN_INFLUX | KN_SCAN;
1238 kn->kn_kevent.udata = kev->udata;
1239 if (!fops->f_isfd && fops->f_touch != NULL) {
1240 fops->f_touch(kn, kev, EVENT_REGISTER);
1242 kn->kn_sfflags = kev->fflags;
1243 kn->kn_sdata = kev->data;
1247 * We can get here with kn->kn_knlist == NULL. This can happen when
1248 * the initial attach event decides that the event is "completed"
1249 * already. i.e. filt_procattach is called on a zombie process. It
1250 * will call filt_proc which will remove it from the list, and NULL
1254 if ((kev->flags & EV_DISABLE) &&
1255 ((kn->kn_status & KN_DISABLED) == 0)) {
1256 kn->kn_status |= KN_DISABLED;
1259 if ((kn->kn_status & KN_DISABLED) == 0)
1260 event = kn->kn_fop->f_event(kn, 0);
1265 KNOTE_ACTIVATE(kn, 1);
1266 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1269 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1270 kn->kn_status &= ~KN_DISABLED;
1271 if ((kn->kn_status & KN_ACTIVE) &&
1272 ((kn->kn_status & KN_QUEUED) == 0))
1278 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1279 if (filedesc_unlock)
1280 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1286 kqueue_fo_release(filt);
1291 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1299 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1303 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1314 kqueue_release(struct kqueue *kq, int locked)
1321 if (kq->kq_refcnt == 1)
1322 wakeup(&kq->kq_refcnt);
1328 kqueue_schedtask(struct kqueue *kq)
1332 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1333 ("scheduling kqueue task while draining"));
1335 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1336 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1337 kq->kq_state |= KQ_TASKSCHED;
1342 * Expand the kq to make sure we have storage for fops/ident pair.
1344 * Return 0 on success (or no work necessary), return errno on failure.
1346 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1347 * If kqueue_register is called from a non-fd context, there usually/should
1351 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1354 struct klist *list, *tmp_knhash, *to_free;
1355 u_long tmp_knhashmask;
1358 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1365 if (kq->kq_knlistsize <= fd) {
1366 size = kq->kq_knlistsize;
1369 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1373 if (kq->kq_knlistsize > fd) {
1377 if (kq->kq_knlist != NULL) {
1378 bcopy(kq->kq_knlist, list,
1379 kq->kq_knlistsize * sizeof(*list));
1380 to_free = kq->kq_knlist;
1381 kq->kq_knlist = NULL;
1383 bzero((caddr_t)list +
1384 kq->kq_knlistsize * sizeof(*list),
1385 (size - kq->kq_knlistsize) * sizeof(*list));
1386 kq->kq_knlistsize = size;
1387 kq->kq_knlist = list;
1392 if (kq->kq_knhashmask == 0) {
1393 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1395 if (tmp_knhash == NULL)
1398 if (kq->kq_knhashmask == 0) {
1399 kq->kq_knhash = tmp_knhash;
1400 kq->kq_knhashmask = tmp_knhashmask;
1402 to_free = tmp_knhash;
1407 free(to_free, M_KQUEUE);
1414 kqueue_task(void *arg, int pending)
1422 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1425 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1427 kq->kq_state &= ~KQ_TASKSCHED;
1428 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1429 wakeup(&kq->kq_state);
1432 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1436 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1437 * We treat KN_MARKER knotes as if they are INFLUX.
1440 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1441 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1443 struct kevent *kevp;
1444 struct knote *kn, *marker;
1445 sbintime_t asbt, rsbt;
1446 int count, error, haskqglobal, influx, nkev, touch;
1458 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1459 tsp->tv_nsec >= 1000000000) {
1463 if (timespecisset(tsp)) {
1464 if (tsp->tv_sec <= INT32_MAX) {
1465 rsbt = tstosbt(*tsp);
1466 if (TIMESEL(&asbt, rsbt))
1467 asbt += tc_tick_sbt;
1468 if (asbt <= SBT_MAX - rsbt)
1472 rsbt >>= tc_precexp;
1479 marker = knote_alloc(1);
1480 if (marker == NULL) {
1484 marker->kn_status = KN_MARKER;
1489 if (kq->kq_count == 0) {
1491 error = EWOULDBLOCK;
1493 kq->kq_state |= KQ_SLEEP;
1494 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1495 "kqread", asbt, rsbt, C_ABSOLUTE);
1499 /* don't restart after signals... */
1500 if (error == ERESTART)
1502 else if (error == EWOULDBLOCK)
1507 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1511 kn = TAILQ_FIRST(&kq->kq_head);
1513 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1514 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1519 kq->kq_state |= KQ_FLUXWAIT;
1520 error = msleep(kq, &kq->kq_lock, PSOCK,
1525 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1526 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1527 kn->kn_status &= ~KN_QUEUED;
1533 if (count == maxevents)
1537 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1538 ("KN_INFLUX set when not suppose to be"));
1540 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1541 kn->kn_status &= ~KN_QUEUED;
1542 kn->kn_status |= KN_INFLUX;
1546 * We don't need to lock the list since we've marked
1549 if (!(kn->kn_status & KN_DETACHED))
1550 kn->kn_fop->f_detach(kn);
1554 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1555 kn->kn_status &= ~KN_QUEUED;
1556 kn->kn_status |= KN_INFLUX;
1560 * We don't need to lock the list since we've marked
1563 *kevp = kn->kn_kevent;
1564 if (!(kn->kn_status & KN_DETACHED))
1565 kn->kn_fop->f_detach(kn);
1570 kn->kn_status |= KN_INFLUX | KN_SCAN;
1572 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1573 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1575 if (kn->kn_fop->f_event(kn, 0) == 0) {
1577 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1579 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1586 touch = (!kn->kn_fop->f_isfd &&
1587 kn->kn_fop->f_touch != NULL);
1589 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1591 *kevp = kn->kn_kevent;
1593 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1594 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1596 * Manually clear knotes who weren't
1599 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1603 if (kn->kn_flags & EV_DISPATCH)
1604 kn->kn_status |= KN_DISABLED;
1605 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1608 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1610 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1615 /* we are returning a copy to the user */
1620 if (nkev == KQ_NEVENTS) {
1623 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1631 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1639 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1640 td->td_retval[0] = maxevents - count;
1646 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1647 struct ucred *active_cred, struct thread *td)
1650 * Enabling sigio causes two major problems:
1651 * 1) infinite recursion:
1652 * Synopsys: kevent is being used to track signals and have FIOASYNC
1653 * set. On receipt of a signal this will cause a kqueue to recurse
1654 * into itself over and over. Sending the sigio causes the kqueue
1655 * to become ready, which in turn posts sigio again, forever.
1656 * Solution: this can be solved by setting a flag in the kqueue that
1657 * we have a SIGIO in progress.
1658 * 2) locking problems:
1659 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1660 * us above the proc and pgrp locks.
1661 * Solution: Post a signal using an async mechanism, being sure to
1662 * record a generation count in the delivery so that we do not deliver
1663 * a signal to the wrong process.
1665 * Note, these two mechanisms are somewhat mutually exclusive!
1674 kq->kq_state |= KQ_ASYNC;
1676 kq->kq_state &= ~KQ_ASYNC;
1681 return (fsetown(*(int *)data, &kq->kq_sigio));
1684 *(int *)data = fgetown(&kq->kq_sigio);
1694 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1701 if ((error = kqueue_acquire(fp, &kq)))
1705 if (events & (POLLIN | POLLRDNORM)) {
1707 revents |= events & (POLLIN | POLLRDNORM);
1709 selrecord(td, &kq->kq_sel);
1710 if (SEL_WAITING(&kq->kq_sel))
1711 kq->kq_state |= KQ_SEL;
1714 kqueue_release(kq, 1);
1721 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1725 bzero((void *)st, sizeof *st);
1727 * We no longer return kq_count because the unlocked value is useless.
1728 * If you spent all this time getting the count, why not spend your
1729 * syscall better by calling kevent?
1731 * XXX - This is needed for libc_r.
1733 st->st_mode = S_IFIFO;
1739 kqueue_close(struct file *fp, struct thread *td)
1741 struct kqueue *kq = fp->f_data;
1742 struct filedesc *fdp;
1746 int filedesc_unlock;
1748 if ((error = kqueue_acquire(fp, &kq)))
1751 filedesc_unlock = 0;
1754 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1755 ("kqueue already closing"));
1756 kq->kq_state |= KQ_CLOSING;
1757 if (kq->kq_refcnt > 1)
1758 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1760 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1763 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1764 ("kqueue's knlist not empty"));
1766 for (i = 0; i < kq->kq_knlistsize; i++) {
1767 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1768 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1769 kq->kq_state |= KQ_FLUXWAIT;
1770 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1773 kn->kn_status |= KN_INFLUX;
1775 if (!(kn->kn_status & KN_DETACHED))
1776 kn->kn_fop->f_detach(kn);
1781 if (kq->kq_knhashmask != 0) {
1782 for (i = 0; i <= kq->kq_knhashmask; i++) {
1783 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1784 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1785 kq->kq_state |= KQ_FLUXWAIT;
1786 msleep(kq, &kq->kq_lock, PSOCK,
1790 kn->kn_status |= KN_INFLUX;
1792 if (!(kn->kn_status & KN_DETACHED))
1793 kn->kn_fop->f_detach(kn);
1800 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1801 kq->kq_state |= KQ_TASKDRAIN;
1802 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1805 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1806 selwakeuppri(&kq->kq_sel, PSOCK);
1807 if (!SEL_WAITING(&kq->kq_sel))
1808 kq->kq_state &= ~KQ_SEL;
1814 * We could be called due to the knote_drop() doing fdrop(),
1815 * called from kqueue_register(). In this case the global
1816 * lock is owned, and filedesc sx is locked before, to not
1817 * take the sleepable lock after non-sleepable.
1819 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1820 FILEDESC_XLOCK(fdp);
1821 filedesc_unlock = 1;
1823 filedesc_unlock = 0;
1824 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1825 if (filedesc_unlock)
1826 FILEDESC_XUNLOCK(fdp);
1828 seldrain(&kq->kq_sel);
1829 knlist_destroy(&kq->kq_sel.si_note);
1830 mtx_destroy(&kq->kq_lock);
1833 if (kq->kq_knhash != NULL)
1834 free(kq->kq_knhash, M_KQUEUE);
1835 if (kq->kq_knlist != NULL)
1836 free(kq->kq_knlist, M_KQUEUE);
1838 funsetown(&kq->kq_sigio);
1839 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1840 crfree(kq->kq_cred);
1848 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1851 kif->kf_type = KF_TYPE_KQUEUE;
1856 kqueue_wakeup(struct kqueue *kq)
1860 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1861 kq->kq_state &= ~KQ_SLEEP;
1864 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1865 selwakeuppri(&kq->kq_sel, PSOCK);
1866 if (!SEL_WAITING(&kq->kq_sel))
1867 kq->kq_state &= ~KQ_SEL;
1869 if (!knlist_empty(&kq->kq_sel.si_note))
1870 kqueue_schedtask(kq);
1871 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1872 pgsigio(&kq->kq_sigio, SIGIO, 0);
1877 * Walk down a list of knotes, activating them if their event has triggered.
1879 * There is a possibility to optimize in the case of one kq watching another.
1880 * Instead of scheduling a task to wake it up, you could pass enough state
1881 * down the chain to make up the parent kqueue. Make this code functional
1885 knote(struct knlist *list, long hint, int lockflags)
1894 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1896 if ((lockflags & KNF_LISTLOCKED) == 0)
1897 list->kl_lock(list->kl_lockarg);
1900 * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1901 * the kqueue scheduling, but this will introduce four
1902 * lock/unlock's for each knote to test. If we do, continue to use
1903 * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1904 * only safe if you want to remove the current item, which we are
1907 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1910 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1912 * Do not process the influx notes, except for
1913 * the influx coming from the kq unlock in the
1914 * kqueue_scan(). In the later case, we do
1915 * not interfere with the scan, since the code
1916 * fragment in kqueue_scan() locks the knlist,
1917 * and cannot proceed until we finished.
1920 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1921 kn->kn_status |= KN_INFLUX;
1923 error = kn->kn_fop->f_event(kn, hint);
1925 kn->kn_status &= ~KN_INFLUX;
1927 KNOTE_ACTIVATE(kn, 1);
1930 kn->kn_status |= KN_HASKQLOCK;
1931 if (kn->kn_fop->f_event(kn, hint))
1932 KNOTE_ACTIVATE(kn, 1);
1933 kn->kn_status &= ~KN_HASKQLOCK;
1937 if ((lockflags & KNF_LISTLOCKED) == 0)
1938 list->kl_unlock(list->kl_lockarg);
1942 * add a knote to a knlist
1945 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1947 KNL_ASSERT_LOCK(knl, islocked);
1948 KQ_NOTOWNED(kn->kn_kq);
1949 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1950 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1952 knl->kl_lock(knl->kl_lockarg);
1953 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1955 knl->kl_unlock(knl->kl_lockarg);
1957 kn->kn_knlist = knl;
1958 kn->kn_status &= ~KN_DETACHED;
1959 KQ_UNLOCK(kn->kn_kq);
1963 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1965 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1966 KNL_ASSERT_LOCK(knl, knlislocked);
1967 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1969 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1970 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1972 knl->kl_lock(knl->kl_lockarg);
1973 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1974 kn->kn_knlist = NULL;
1976 knl->kl_unlock(knl->kl_lockarg);
1979 kn->kn_status |= KN_DETACHED;
1981 KQ_UNLOCK(kn->kn_kq);
1985 * remove knote from the specified knlist
1988 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1991 knlist_remove_kq(knl, kn, islocked, 0);
1995 * remove knote from the specified knlist while in f_event handler.
1998 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
2001 knlist_remove_kq(knl, kn, 1,
2002 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
2006 knlist_empty(struct knlist *knl)
2009 KNL_ASSERT_LOCKED(knl);
2010 return SLIST_EMPTY(&knl->kl_list);
2013 static struct mtx knlist_lock;
2014 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
2016 static void knlist_mtx_lock(void *arg);
2017 static void knlist_mtx_unlock(void *arg);
2020 knlist_mtx_lock(void *arg)
2023 mtx_lock((struct mtx *)arg);
2027 knlist_mtx_unlock(void *arg)
2030 mtx_unlock((struct mtx *)arg);
2034 knlist_mtx_assert_locked(void *arg)
2037 mtx_assert((struct mtx *)arg, MA_OWNED);
2041 knlist_mtx_assert_unlocked(void *arg)
2044 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2048 knlist_rw_rlock(void *arg)
2051 rw_rlock((struct rwlock *)arg);
2055 knlist_rw_runlock(void *arg)
2058 rw_runlock((struct rwlock *)arg);
2062 knlist_rw_assert_locked(void *arg)
2065 rw_assert((struct rwlock *)arg, RA_LOCKED);
2069 knlist_rw_assert_unlocked(void *arg)
2072 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2076 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2077 void (*kl_unlock)(void *),
2078 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2082 knl->kl_lockarg = &knlist_lock;
2084 knl->kl_lockarg = lock;
2086 if (kl_lock == NULL)
2087 knl->kl_lock = knlist_mtx_lock;
2089 knl->kl_lock = kl_lock;
2090 if (kl_unlock == NULL)
2091 knl->kl_unlock = knlist_mtx_unlock;
2093 knl->kl_unlock = kl_unlock;
2094 if (kl_assert_locked == NULL)
2095 knl->kl_assert_locked = knlist_mtx_assert_locked;
2097 knl->kl_assert_locked = kl_assert_locked;
2098 if (kl_assert_unlocked == NULL)
2099 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2101 knl->kl_assert_unlocked = kl_assert_unlocked;
2103 SLIST_INIT(&knl->kl_list);
2107 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2110 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2114 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2117 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2118 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2122 knlist_destroy(struct knlist *knl)
2127 * if we run across this error, we need to find the offending
2128 * driver and have it call knlist_clear or knlist_delete.
2130 if (!SLIST_EMPTY(&knl->kl_list))
2131 printf("WARNING: destroying knlist w/ knotes on it!\n");
2134 knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2135 SLIST_INIT(&knl->kl_list);
2139 * Even if we are locked, we may need to drop the lock to allow any influx
2140 * knotes time to "settle".
2143 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2145 struct knote *kn, *kn2;
2149 KNL_ASSERT_LOCKED(knl);
2151 KNL_ASSERT_UNLOCKED(knl);
2152 again: /* need to reacquire lock since we have dropped it */
2153 knl->kl_lock(knl->kl_lockarg);
2156 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2159 if ((kn->kn_status & KN_INFLUX)) {
2163 knlist_remove_kq(knl, kn, 1, 1);
2165 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2169 /* Make sure cleared knotes disappear soon */
2170 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2176 if (!SLIST_EMPTY(&knl->kl_list)) {
2177 /* there are still KN_INFLUX remaining */
2178 kn = SLIST_FIRST(&knl->kl_list);
2181 KASSERT(kn->kn_status & KN_INFLUX,
2182 ("knote removed w/o list lock"));
2183 knl->kl_unlock(knl->kl_lockarg);
2184 kq->kq_state |= KQ_FLUXWAIT;
2185 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2191 KNL_ASSERT_LOCKED(knl);
2193 knl->kl_unlock(knl->kl_lockarg);
2194 KNL_ASSERT_UNLOCKED(knl);
2199 * Remove all knotes referencing a specified fd must be called with FILEDESC
2200 * lock. This prevents a race where a new fd comes along and occupies the
2201 * entry and we attach a knote to the fd.
2204 knote_fdclose(struct thread *td, int fd)
2206 struct filedesc *fdp = td->td_proc->p_fd;
2211 FILEDESC_XLOCK_ASSERT(fdp);
2214 * We shouldn't have to worry about new kevents appearing on fd
2215 * since filedesc is locked.
2217 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2222 while (kq->kq_knlistsize > fd &&
2223 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2224 if (kn->kn_status & KN_INFLUX) {
2225 /* someone else might be waiting on our knote */
2228 kq->kq_state |= KQ_FLUXWAIT;
2229 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2232 kn->kn_status |= KN_INFLUX;
2234 if (!(kn->kn_status & KN_DETACHED))
2235 kn->kn_fop->f_detach(kn);
2245 knote_attach(struct knote *kn, struct kqueue *kq)
2249 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2252 if (kn->kn_fop->f_isfd) {
2253 if (kn->kn_id >= kq->kq_knlistsize)
2255 list = &kq->kq_knlist[kn->kn_id];
2257 if (kq->kq_knhash == NULL)
2259 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2262 SLIST_INSERT_HEAD(list, kn, kn_link);
2268 * knote must already have been detached using the f_detach method.
2269 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2270 * to prevent other removal.
2273 knote_drop(struct knote *kn, struct thread *td)
2281 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2282 ("knote_drop called without KN_INFLUX set in kn_status"));
2285 if (kn->kn_fop->f_isfd)
2286 list = &kq->kq_knlist[kn->kn_id];
2288 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2290 if (!SLIST_EMPTY(list))
2291 SLIST_REMOVE(list, kn, knote, kn_link);
2292 if (kn->kn_status & KN_QUEUED)
2296 if (kn->kn_fop->f_isfd) {
2297 fdrop(kn->kn_fp, td);
2300 kqueue_fo_release(kn->kn_kevent.filter);
2306 knote_enqueue(struct knote *kn)
2308 struct kqueue *kq = kn->kn_kq;
2310 KQ_OWNED(kn->kn_kq);
2311 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2313 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2314 kn->kn_status |= KN_QUEUED;
2320 knote_dequeue(struct knote *kn)
2322 struct kqueue *kq = kn->kn_kq;
2324 KQ_OWNED(kn->kn_kq);
2325 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2327 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2328 kn->kn_status &= ~KN_QUEUED;
2336 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2337 NULL, NULL, UMA_ALIGN_PTR, 0);
2339 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2341 static struct knote *
2342 knote_alloc(int waitok)
2344 return ((struct knote *)uma_zalloc(knote_zone,
2345 (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2349 knote_free(struct knote *kn)
2352 uma_zfree(knote_zone, kn);
2356 * Register the kev w/ the kq specified by fd.
2359 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2363 cap_rights_t rights;
2366 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2369 if ((error = kqueue_acquire(fp, &kq)) != 0)
2372 error = kqueue_register(kq, kev, td, waitok);
2374 kqueue_release(kq, 0);