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>
69 #include <sys/ktrace.h>
74 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
77 * This lock is used if multiple kq locks are required. This possibly
78 * should be made into a per proc lock.
80 static struct mtx kq_global;
81 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
82 #define KQ_GLOBAL_LOCK(lck, haslck) do { \
87 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
93 TASKQUEUE_DEFINE_THREAD(kqueue);
95 static int kevent_copyout(void *arg, struct kevent *kevp, int count);
96 static int kevent_copyin(void *arg, struct kevent *kevp, int count);
97 static int kqueue_register(struct kqueue *kq, struct kevent *kev,
98 struct thread *td, int waitok);
99 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
100 static void kqueue_release(struct kqueue *kq, int locked);
101 static int kqueue_expand(struct kqueue *kq, struct filterops *fops,
102 uintptr_t ident, int waitok);
103 static void kqueue_task(void *arg, int pending);
104 static int kqueue_scan(struct kqueue *kq, int maxevents,
105 struct kevent_copyops *k_ops,
106 const struct timespec *timeout,
107 struct kevent *keva, struct thread *td);
108 static void kqueue_wakeup(struct kqueue *kq);
109 static struct filterops *kqueue_fo_find(int filt);
110 static void kqueue_fo_release(int filt);
112 static fo_ioctl_t kqueue_ioctl;
113 static fo_poll_t kqueue_poll;
114 static fo_kqfilter_t kqueue_kqfilter;
115 static fo_stat_t kqueue_stat;
116 static fo_close_t kqueue_close;
118 static struct fileops kqueueops = {
119 .fo_read = invfo_rdwr,
120 .fo_write = invfo_rdwr,
121 .fo_truncate = invfo_truncate,
122 .fo_ioctl = kqueue_ioctl,
123 .fo_poll = kqueue_poll,
124 .fo_kqfilter = kqueue_kqfilter,
125 .fo_stat = kqueue_stat,
126 .fo_close = kqueue_close,
127 .fo_chmod = invfo_chmod,
128 .fo_chown = invfo_chown,
129 .fo_sendfile = invfo_sendfile,
132 static int knote_attach(struct knote *kn, struct kqueue *kq);
133 static void knote_drop(struct knote *kn, struct thread *td);
134 static void knote_enqueue(struct knote *kn);
135 static void knote_dequeue(struct knote *kn);
136 static void knote_init(void);
137 static struct knote *knote_alloc(int waitok);
138 static void knote_free(struct knote *kn);
140 static void filt_kqdetach(struct knote *kn);
141 static int filt_kqueue(struct knote *kn, long hint);
142 static int filt_procattach(struct knote *kn);
143 static void filt_procdetach(struct knote *kn);
144 static int filt_proc(struct knote *kn, long hint);
145 static int filt_fileattach(struct knote *kn);
146 static void filt_timerexpire(void *knx);
147 static int filt_timerattach(struct knote *kn);
148 static void filt_timerdetach(struct knote *kn);
149 static int filt_timer(struct knote *kn, long hint);
150 static int filt_userattach(struct knote *kn);
151 static void filt_userdetach(struct knote *kn);
152 static int filt_user(struct knote *kn, long hint);
153 static void filt_usertouch(struct knote *kn, struct kevent *kev,
156 static struct filterops file_filtops = {
158 .f_attach = filt_fileattach,
160 static struct filterops kqread_filtops = {
162 .f_detach = filt_kqdetach,
163 .f_event = filt_kqueue,
165 /* XXX - move to kern_proc.c? */
166 static struct filterops proc_filtops = {
168 .f_attach = filt_procattach,
169 .f_detach = filt_procdetach,
170 .f_event = filt_proc,
172 static struct filterops timer_filtops = {
174 .f_attach = filt_timerattach,
175 .f_detach = filt_timerdetach,
176 .f_event = filt_timer,
178 static struct filterops user_filtops = {
179 .f_attach = filt_userattach,
180 .f_detach = filt_userdetach,
181 .f_event = filt_user,
182 .f_touch = filt_usertouch,
185 static uma_zone_t knote_zone;
186 static atomic_uint kq_ncallouts = ATOMIC_VAR_INIT(0);
187 static unsigned int kq_calloutmax = 4 * 1024;
188 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
189 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
191 /* XXX - ensure not KN_INFLUX?? */
192 #define KNOTE_ACTIVATE(kn, islock) do { \
194 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
196 KQ_LOCK((kn)->kn_kq); \
197 (kn)->kn_status |= KN_ACTIVE; \
198 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
199 knote_enqueue((kn)); \
201 KQ_UNLOCK((kn)->kn_kq); \
203 #define KQ_LOCK(kq) do { \
204 mtx_lock(&(kq)->kq_lock); \
206 #define KQ_FLUX_WAKEUP(kq) do { \
207 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
208 (kq)->kq_state &= ~KQ_FLUXWAIT; \
212 #define KQ_UNLOCK_FLUX(kq) do { \
213 KQ_FLUX_WAKEUP(kq); \
214 mtx_unlock(&(kq)->kq_lock); \
216 #define KQ_UNLOCK(kq) do { \
217 mtx_unlock(&(kq)->kq_lock); \
219 #define KQ_OWNED(kq) do { \
220 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
222 #define KQ_NOTOWNED(kq) do { \
223 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
225 #define KN_LIST_LOCK(kn) do { \
226 if (kn->kn_knlist != NULL) \
227 kn->kn_knlist->kl_lock(kn->kn_knlist->kl_lockarg); \
229 #define KN_LIST_UNLOCK(kn) do { \
230 if (kn->kn_knlist != NULL) \
231 kn->kn_knlist->kl_unlock(kn->kn_knlist->kl_lockarg); \
233 #define KNL_ASSERT_LOCK(knl, islocked) do { \
235 KNL_ASSERT_LOCKED(knl); \
237 KNL_ASSERT_UNLOCKED(knl); \
240 #define KNL_ASSERT_LOCKED(knl) do { \
241 knl->kl_assert_locked((knl)->kl_lockarg); \
243 #define KNL_ASSERT_UNLOCKED(knl) do { \
244 knl->kl_assert_unlocked((knl)->kl_lockarg); \
246 #else /* !INVARIANTS */
247 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
248 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
249 #endif /* INVARIANTS */
252 #define KN_HASHSIZE 64 /* XXX should be tunable */
255 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
258 filt_nullattach(struct knote *kn)
264 struct filterops null_filtops = {
266 .f_attach = filt_nullattach,
269 /* XXX - make SYSINIT to add these, and move into respective modules. */
270 extern struct filterops sig_filtops;
271 extern struct filterops fs_filtops;
274 * Table for for all system-defined filters.
276 static struct mtx filterops_lock;
277 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
280 struct filterops *for_fop;
282 } sysfilt_ops[EVFILT_SYSCOUNT] = {
283 { &file_filtops }, /* EVFILT_READ */
284 { &file_filtops }, /* EVFILT_WRITE */
285 { &null_filtops }, /* EVFILT_AIO */
286 { &file_filtops }, /* EVFILT_VNODE */
287 { &proc_filtops }, /* EVFILT_PROC */
288 { &sig_filtops }, /* EVFILT_SIGNAL */
289 { &timer_filtops }, /* EVFILT_TIMER */
290 { &file_filtops }, /* EVFILT_PROCDESC */
291 { &fs_filtops }, /* EVFILT_FS */
292 { &null_filtops }, /* EVFILT_LIO */
293 { &user_filtops }, /* EVFILT_USER */
294 { &null_filtops }, /* EVFILT_SENDFILE */
298 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
302 filt_fileattach(struct knote *kn)
305 return (fo_kqfilter(kn->kn_fp, kn));
310 kqueue_kqfilter(struct file *fp, struct knote *kn)
312 struct kqueue *kq = kn->kn_fp->f_data;
314 if (kn->kn_filter != EVFILT_READ)
317 kn->kn_status |= KN_KQUEUE;
318 kn->kn_fop = &kqread_filtops;
319 knlist_add(&kq->kq_sel.si_note, kn, 0);
325 filt_kqdetach(struct knote *kn)
327 struct kqueue *kq = kn->kn_fp->f_data;
329 knlist_remove(&kq->kq_sel.si_note, kn, 0);
334 filt_kqueue(struct knote *kn, long hint)
336 struct kqueue *kq = kn->kn_fp->f_data;
338 kn->kn_data = kq->kq_count;
339 return (kn->kn_data > 0);
342 /* XXX - move to kern_proc.c? */
344 filt_procattach(struct knote *kn)
351 p = pfind(kn->kn_id);
352 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
353 p = zpfind(kn->kn_id);
355 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
361 if ((error = p_cansee(curthread, p))) {
366 kn->kn_ptr.p_proc = p;
367 kn->kn_flags |= EV_CLEAR; /* automatically set */
370 * internal flag indicating registration done by kernel
372 if (kn->kn_flags & EV_FLAG1) {
373 kn->kn_data = kn->kn_sdata; /* ppid */
374 kn->kn_fflags = NOTE_CHILD;
375 kn->kn_flags &= ~EV_FLAG1;
379 knlist_add(&p->p_klist, kn, 1);
382 * Immediately activate any exit notes if the target process is a
383 * zombie. This is necessary to handle the case where the target
384 * process, e.g. a child, dies before the kevent is registered.
386 if (immediate && filt_proc(kn, NOTE_EXIT))
387 KNOTE_ACTIVATE(kn, 0);
395 * The knote may be attached to a different process, which may exit,
396 * leaving nothing for the knote to be attached to. So when the process
397 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
398 * it will be deleted when read out. However, as part of the knote deletion,
399 * this routine is called, so a check is needed to avoid actually performing
400 * a detach, because the original process does not exist any more.
402 /* XXX - move to kern_proc.c? */
404 filt_procdetach(struct knote *kn)
408 p = kn->kn_ptr.p_proc;
409 knlist_remove(&p->p_klist, kn, 0);
410 kn->kn_ptr.p_proc = NULL;
413 /* XXX - move to kern_proc.c? */
415 filt_proc(struct knote *kn, long hint)
420 p = kn->kn_ptr.p_proc;
421 /* Mask off extra data. */
422 event = (u_int)hint & NOTE_PCTRLMASK;
424 /* If the user is interested in this event, record it. */
425 if (kn->kn_sfflags & event)
426 kn->kn_fflags |= event;
428 /* Process is gone, so flag the event as finished. */
429 if (event == NOTE_EXIT) {
430 if (!(kn->kn_status & KN_DETACHED))
431 knlist_remove_inevent(&p->p_klist, kn);
432 kn->kn_flags |= EV_EOF | EV_ONESHOT;
433 kn->kn_ptr.p_proc = NULL;
434 if (kn->kn_fflags & NOTE_EXIT)
435 kn->kn_data = p->p_xstat;
436 if (kn->kn_fflags == 0)
437 kn->kn_flags |= EV_DROP;
441 return (kn->kn_fflags != 0);
445 * Called when the process forked. It mostly does the same as the
446 * knote(), activating all knotes registered to be activated when the
447 * process forked. Additionally, for each knote attached to the
448 * parent, check whether user wants to track the new process. If so
449 * attach a new knote to it, and immediately report an event with the
453 knote_fork(struct knlist *list, int pid)
462 list->kl_lock(list->kl_lockarg);
464 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
465 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX)
469 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
475 * The same as knote(), activate the event.
477 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
478 kn->kn_status |= KN_HASKQLOCK;
479 if (kn->kn_fop->f_event(kn, NOTE_FORK))
480 KNOTE_ACTIVATE(kn, 1);
481 kn->kn_status &= ~KN_HASKQLOCK;
487 * The NOTE_TRACK case. In addition to the activation
488 * of the event, we need to register new event to
489 * track the child. Drop the locks in preparation for
490 * the call to kqueue_register().
492 kn->kn_status |= KN_INFLUX;
494 list->kl_unlock(list->kl_lockarg);
497 * Activate existing knote and register a knote with
501 kev.filter = kn->kn_filter;
502 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
503 kev.fflags = kn->kn_sfflags;
504 kev.data = kn->kn_id; /* parent */
505 kev.udata = kn->kn_kevent.udata;/* preserve udata */
506 error = kqueue_register(kq, &kev, NULL, 0);
508 kn->kn_fflags |= NOTE_TRACKERR;
509 if (kn->kn_fop->f_event(kn, NOTE_FORK))
510 KNOTE_ACTIVATE(kn, 0);
512 kn->kn_status &= ~KN_INFLUX;
514 list->kl_lock(list->kl_lockarg);
516 list->kl_unlock(list->kl_lockarg);
520 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
521 * interval timer support code.
524 #define NOTE_TIMER_PRECMASK (NOTE_SECONDS|NOTE_MSECONDS|NOTE_USECONDS| \
527 static __inline sbintime_t
528 timer2sbintime(intptr_t data, int flags)
532 switch (flags & NOTE_TIMER_PRECMASK) {
536 case NOTE_MSECONDS: /* FALLTHROUGH */
551 if (data > SBT_MAX / modifier)
554 return (modifier * data);
558 filt_timerexpire(void *knx)
560 struct callout *calloutp;
565 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
567 if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
568 calloutp = (struct callout *)kn->kn_hook;
569 callout_reset_sbt_on(calloutp,
570 timer2sbintime(kn->kn_sdata, kn->kn_sfflags), 0,
571 filt_timerexpire, kn, PCPU_GET(cpuid), 0);
576 * data contains amount of time to sleep
579 filt_timerattach(struct knote *kn)
581 struct callout *calloutp;
583 unsigned int ncallouts;
585 if ((intptr_t)kn->kn_sdata < 0)
587 if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
589 /* Only precision unit are supported in flags so far */
590 if (kn->kn_sfflags & ~NOTE_TIMER_PRECMASK)
593 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
597 ncallouts = atomic_load_explicit(&kq_ncallouts, memory_order_relaxed);
599 if (ncallouts >= kq_calloutmax)
601 } while (!atomic_compare_exchange_weak_explicit(&kq_ncallouts,
602 &ncallouts, ncallouts + 1, memory_order_relaxed,
603 memory_order_relaxed));
605 kn->kn_flags |= EV_CLEAR; /* automatically set */
606 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
607 calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
608 callout_init(calloutp, CALLOUT_MPSAFE);
609 kn->kn_hook = calloutp;
610 callout_reset_sbt_on(calloutp, to, 0,
611 filt_timerexpire, kn, PCPU_GET(cpuid), 0);
617 filt_timerdetach(struct knote *kn)
619 struct callout *calloutp;
622 calloutp = (struct callout *)kn->kn_hook;
623 callout_drain(calloutp);
624 free(calloutp, M_KQUEUE);
625 old = atomic_fetch_sub_explicit(&kq_ncallouts, 1, memory_order_relaxed);
626 KASSERT(old > 0, ("Number of callouts cannot become negative"));
627 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
631 filt_timer(struct knote *kn, long hint)
634 return (kn->kn_data != 0);
638 filt_userattach(struct knote *kn)
642 * EVFILT_USER knotes are not attached to anything in the kernel.
645 if (kn->kn_fflags & NOTE_TRIGGER)
653 filt_userdetach(__unused struct knote *kn)
657 * EVFILT_USER knotes are not attached to anything in the kernel.
662 filt_user(struct knote *kn, __unused long hint)
665 return (kn->kn_hookid);
669 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
675 if (kev->fflags & NOTE_TRIGGER)
678 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
679 kev->fflags &= NOTE_FFLAGSMASK;
685 kn->kn_sfflags &= kev->fflags;
689 kn->kn_sfflags |= kev->fflags;
693 kn->kn_sfflags = kev->fflags;
697 /* XXX Return error? */
700 kn->kn_sdata = kev->data;
701 if (kev->flags & EV_CLEAR) {
709 *kev = kn->kn_kevent;
710 kev->fflags = kn->kn_sfflags;
711 kev->data = kn->kn_sdata;
712 if (kn->kn_flags & EV_CLEAR) {
720 panic("filt_usertouch() - invalid type (%ld)", type);
726 sys_kqueue(struct thread *td, struct kqueue_args *uap)
728 struct filedesc *fdp;
739 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td->td_proc,
748 error = falloc(td, &fp, &fd, 0);
752 /* An extra reference on `fp' has been held for us by falloc(). */
753 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
754 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
755 TAILQ_INIT(&kq->kq_head);
758 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
759 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
762 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
763 FILEDESC_XUNLOCK(fdp);
765 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
768 td->td_retval[0] = fd;
771 chgkqcnt(cred->cr_ruidinfo, -1, 0);
777 #ifndef _SYS_SYSPROTO_H_
780 const struct kevent *changelist;
782 struct kevent *eventlist;
784 const struct timespec *timeout;
788 sys_kevent(struct thread *td, struct kevent_args *uap)
790 struct timespec ts, *tsp;
791 struct kevent_copyops k_ops = { uap,
798 struct uio *ktruioin = NULL;
799 struct uio *ktruioout = NULL;
802 if (uap->timeout != NULL) {
803 error = copyin(uap->timeout, &ts, sizeof(ts));
811 if (KTRPOINT(td, KTR_GENIO)) {
812 ktriov.iov_base = uap->changelist;
813 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
814 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
815 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
817 ktruioin = cloneuio(&ktruio);
818 ktriov.iov_base = uap->eventlist;
819 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
820 ktruioout = cloneuio(&ktruio);
824 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
828 if (ktruioin != NULL) {
829 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
830 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
831 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
832 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
840 * Copy 'count' items into the destination list pointed to by uap->eventlist.
843 kevent_copyout(void *arg, struct kevent *kevp, int count)
845 struct kevent_args *uap;
848 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
849 uap = (struct kevent_args *)arg;
851 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
853 uap->eventlist += count;
858 * Copy 'count' items from the list pointed to by uap->changelist.
861 kevent_copyin(void *arg, struct kevent *kevp, int count)
863 struct kevent_args *uap;
866 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
867 uap = (struct kevent_args *)arg;
869 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
871 uap->changelist += count;
876 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
877 struct kevent_copyops *k_ops, const struct timespec *timeout)
879 struct kevent keva[KQ_NEVENTS];
880 struct kevent *kevp, *changes;
884 int i, n, nerrors, error;
886 cap_rights_init(&rights);
888 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
890 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
891 error = fget(td, fd, &rights, &fp);
895 error = kqueue_acquire(fp, &kq);
901 while (nchanges > 0) {
902 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
903 error = k_ops->k_copyin(k_ops->arg, keva, n);
907 for (i = 0; i < n; i++) {
911 kevp->flags &= ~EV_SYSFLAGS;
912 error = kqueue_register(kq, kevp, td, 1);
913 if (error || (kevp->flags & EV_RECEIPT)) {
915 kevp->flags = EV_ERROR;
917 (void) k_ops->k_copyout(k_ops->arg,
929 td->td_retval[0] = nerrors;
934 error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
936 kqueue_release(kq, 0);
943 kqueue_add_filteropts(int filt, struct filterops *filtops)
948 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
950 "trying to add a filterop that is out of range: %d is beyond %d\n",
951 ~filt, EVFILT_SYSCOUNT);
954 mtx_lock(&filterops_lock);
955 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
956 sysfilt_ops[~filt].for_fop != NULL)
959 sysfilt_ops[~filt].for_fop = filtops;
960 sysfilt_ops[~filt].for_refcnt = 0;
962 mtx_unlock(&filterops_lock);
968 kqueue_del_filteropts(int filt)
973 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
976 mtx_lock(&filterops_lock);
977 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
978 sysfilt_ops[~filt].for_fop == NULL)
980 else if (sysfilt_ops[~filt].for_refcnt != 0)
983 sysfilt_ops[~filt].for_fop = &null_filtops;
984 sysfilt_ops[~filt].for_refcnt = 0;
986 mtx_unlock(&filterops_lock);
991 static struct filterops *
992 kqueue_fo_find(int filt)
995 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
998 mtx_lock(&filterops_lock);
999 sysfilt_ops[~filt].for_refcnt++;
1000 if (sysfilt_ops[~filt].for_fop == NULL)
1001 sysfilt_ops[~filt].for_fop = &null_filtops;
1002 mtx_unlock(&filterops_lock);
1004 return sysfilt_ops[~filt].for_fop;
1008 kqueue_fo_release(int filt)
1011 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1014 mtx_lock(&filterops_lock);
1015 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1016 ("filter object refcount not valid on release"));
1017 sysfilt_ops[~filt].for_refcnt--;
1018 mtx_unlock(&filterops_lock);
1022 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1023 * influence if memory allocation should wait. Make sure it is 0 if you
1027 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1029 struct filterops *fops;
1031 struct knote *kn, *tkn;
1032 cap_rights_t rights;
1033 int error, filt, event;
1034 int haskqglobal, filedesc_unlock;
1040 filedesc_unlock = 0;
1043 fops = kqueue_fo_find(filt);
1047 tkn = knote_alloc(waitok); /* prevent waiting with locks */
1051 KASSERT(td != NULL, ("td is NULL"));
1052 error = fget(td, kev->ident,
1053 cap_rights_init(&rights, CAP_EVENT), &fp);
1057 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1058 kev->ident, 0) != 0) {
1062 error = kqueue_expand(kq, fops, kev->ident, waitok);
1068 if (fp->f_type == DTYPE_KQUEUE) {
1070 * if we add some inteligence about what we are doing,
1071 * we should be able to support events on ourselves.
1072 * We need to know when we are doing this to prevent
1073 * getting both the knlist lock and the kq lock since
1074 * they are the same thing.
1076 if (fp->f_data == kq) {
1082 * Pre-lock the filedesc before the global
1083 * lock mutex, see the comment in
1086 FILEDESC_XLOCK(td->td_proc->p_fd);
1087 filedesc_unlock = 1;
1088 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1092 if (kev->ident < kq->kq_knlistsize) {
1093 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1094 if (kev->filter == kn->kn_filter)
1098 if ((kev->flags & EV_ADD) == EV_ADD)
1099 kqueue_expand(kq, fops, kev->ident, waitok);
1102 if (kq->kq_knhashmask != 0) {
1105 list = &kq->kq_knhash[
1106 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1107 SLIST_FOREACH(kn, list, kn_link)
1108 if (kev->ident == kn->kn_id &&
1109 kev->filter == kn->kn_filter)
1114 /* knote is in the process of changing, wait for it to stablize. */
1115 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1116 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1117 if (filedesc_unlock) {
1118 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1119 filedesc_unlock = 0;
1121 kq->kq_state |= KQ_FLUXWAIT;
1122 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1131 * kn now contains the matching knote, or NULL if no match
1134 if (kev->flags & EV_ADD) {
1146 * apply reference counts to knote structure, and
1147 * do not release it at the end of this routine.
1152 kn->kn_sfflags = kev->fflags;
1153 kn->kn_sdata = kev->data;
1156 kn->kn_kevent = *kev;
1157 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1158 EV_ENABLE | EV_DISABLE);
1159 kn->kn_status = KN_INFLUX|KN_DETACHED;
1161 error = knote_attach(kn, kq);
1168 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1175 /* No matching knote and the EV_ADD flag is not set. */
1182 if (kev->flags & EV_DELETE) {
1183 kn->kn_status |= KN_INFLUX;
1185 if (!(kn->kn_status & KN_DETACHED))
1186 kn->kn_fop->f_detach(kn);
1192 * The user may change some filter values after the initial EV_ADD,
1193 * but doing so will not reset any filter which has already been
1196 kn->kn_status |= KN_INFLUX | KN_SCAN;
1199 kn->kn_kevent.udata = kev->udata;
1200 if (!fops->f_isfd && fops->f_touch != NULL) {
1201 fops->f_touch(kn, kev, EVENT_REGISTER);
1203 kn->kn_sfflags = kev->fflags;
1204 kn->kn_sdata = kev->data;
1208 * We can get here with kn->kn_knlist == NULL. This can happen when
1209 * the initial attach event decides that the event is "completed"
1210 * already. i.e. filt_procattach is called on a zombie process. It
1211 * will call filt_proc which will remove it from the list, and NULL
1215 event = kn->kn_fop->f_event(kn, 0);
1218 KNOTE_ACTIVATE(kn, 1);
1219 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1222 if ((kev->flags & EV_DISABLE) &&
1223 ((kn->kn_status & KN_DISABLED) == 0)) {
1224 kn->kn_status |= KN_DISABLED;
1227 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1228 kn->kn_status &= ~KN_DISABLED;
1229 if ((kn->kn_status & KN_ACTIVE) &&
1230 ((kn->kn_status & KN_QUEUED) == 0))
1236 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1237 if (filedesc_unlock)
1238 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1244 kqueue_fo_release(filt);
1249 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1257 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1261 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1272 kqueue_release(struct kqueue *kq, int locked)
1279 if (kq->kq_refcnt == 1)
1280 wakeup(&kq->kq_refcnt);
1286 kqueue_schedtask(struct kqueue *kq)
1290 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1291 ("scheduling kqueue task while draining"));
1293 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1294 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1295 kq->kq_state |= KQ_TASKSCHED;
1300 * Expand the kq to make sure we have storage for fops/ident pair.
1302 * Return 0 on success (or no work necessary), return errno on failure.
1304 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1305 * If kqueue_register is called from a non-fd context, there usually/should
1309 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1312 struct klist *list, *tmp_knhash, *to_free;
1313 u_long tmp_knhashmask;
1316 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1323 if (kq->kq_knlistsize <= fd) {
1324 size = kq->kq_knlistsize;
1327 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1331 if (kq->kq_knlistsize > fd) {
1335 if (kq->kq_knlist != NULL) {
1336 bcopy(kq->kq_knlist, list,
1337 kq->kq_knlistsize * sizeof(*list));
1338 to_free = kq->kq_knlist;
1339 kq->kq_knlist = NULL;
1341 bzero((caddr_t)list +
1342 kq->kq_knlistsize * sizeof(*list),
1343 (size - kq->kq_knlistsize) * sizeof(*list));
1344 kq->kq_knlistsize = size;
1345 kq->kq_knlist = list;
1350 if (kq->kq_knhashmask == 0) {
1351 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1353 if (tmp_knhash == NULL)
1356 if (kq->kq_knhashmask == 0) {
1357 kq->kq_knhash = tmp_knhash;
1358 kq->kq_knhashmask = tmp_knhashmask;
1360 to_free = tmp_knhash;
1365 free(to_free, M_KQUEUE);
1372 kqueue_task(void *arg, int pending)
1380 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1383 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1385 kq->kq_state &= ~KQ_TASKSCHED;
1386 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1387 wakeup(&kq->kq_state);
1390 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1394 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1395 * We treat KN_MARKER knotes as if they are INFLUX.
1398 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1399 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1401 struct kevent *kevp;
1402 struct knote *kn, *marker;
1403 sbintime_t asbt, rsbt;
1404 int count, error, haskqglobal, influx, nkev, touch;
1416 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1417 tsp->tv_nsec >= 1000000000) {
1421 if (timespecisset(tsp)) {
1422 if (tsp->tv_sec <= INT32_MAX) {
1423 rsbt = tstosbt(*tsp);
1424 if (TIMESEL(&asbt, rsbt))
1425 asbt += tc_tick_sbt;
1426 if (asbt <= SBT_MAX - rsbt)
1430 rsbt >>= tc_precexp;
1437 marker = knote_alloc(1);
1438 if (marker == NULL) {
1442 marker->kn_status = KN_MARKER;
1447 if (kq->kq_count == 0) {
1449 error = EWOULDBLOCK;
1451 kq->kq_state |= KQ_SLEEP;
1452 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1453 "kqread", asbt, rsbt, C_ABSOLUTE);
1457 /* don't restart after signals... */
1458 if (error == ERESTART)
1460 else if (error == EWOULDBLOCK)
1465 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1469 kn = TAILQ_FIRST(&kq->kq_head);
1471 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1472 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1477 kq->kq_state |= KQ_FLUXWAIT;
1478 error = msleep(kq, &kq->kq_lock, PSOCK,
1483 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1484 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1485 kn->kn_status &= ~KN_QUEUED;
1491 if (count == maxevents)
1495 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1496 ("KN_INFLUX set when not suppose to be"));
1498 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1499 kn->kn_status &= ~KN_QUEUED;
1500 kn->kn_status |= KN_INFLUX;
1504 * We don't need to lock the list since we've marked
1507 if (!(kn->kn_status & KN_DETACHED))
1508 kn->kn_fop->f_detach(kn);
1512 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1513 kn->kn_status &= ~KN_QUEUED;
1514 kn->kn_status |= KN_INFLUX;
1518 * We don't need to lock the list since we've marked
1521 *kevp = kn->kn_kevent;
1522 if (!(kn->kn_status & KN_DETACHED))
1523 kn->kn_fop->f_detach(kn);
1528 kn->kn_status |= KN_INFLUX | KN_SCAN;
1530 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1531 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1533 if (kn->kn_fop->f_event(kn, 0) == 0) {
1535 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1537 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1544 touch = (!kn->kn_fop->f_isfd &&
1545 kn->kn_fop->f_touch != NULL);
1547 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1549 *kevp = kn->kn_kevent;
1551 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1552 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1554 * Manually clear knotes who weren't
1557 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1561 if (kn->kn_flags & EV_DISPATCH)
1562 kn->kn_status |= KN_DISABLED;
1563 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1566 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1568 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1573 /* we are returning a copy to the user */
1578 if (nkev == KQ_NEVENTS) {
1581 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1589 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1597 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1598 td->td_retval[0] = maxevents - count;
1604 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1605 struct ucred *active_cred, struct thread *td)
1608 * Enabling sigio causes two major problems:
1609 * 1) infinite recursion:
1610 * Synopsys: kevent is being used to track signals and have FIOASYNC
1611 * set. On receipt of a signal this will cause a kqueue to recurse
1612 * into itself over and over. Sending the sigio causes the kqueue
1613 * to become ready, which in turn posts sigio again, forever.
1614 * Solution: this can be solved by setting a flag in the kqueue that
1615 * we have a SIGIO in progress.
1616 * 2) locking problems:
1617 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1618 * us above the proc and pgrp locks.
1619 * Solution: Post a signal using an async mechanism, being sure to
1620 * record a generation count in the delivery so that we do not deliver
1621 * a signal to the wrong process.
1623 * Note, these two mechanisms are somewhat mutually exclusive!
1632 kq->kq_state |= KQ_ASYNC;
1634 kq->kq_state &= ~KQ_ASYNC;
1639 return (fsetown(*(int *)data, &kq->kq_sigio));
1642 *(int *)data = fgetown(&kq->kq_sigio);
1652 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1659 if ((error = kqueue_acquire(fp, &kq)))
1663 if (events & (POLLIN | POLLRDNORM)) {
1665 revents |= events & (POLLIN | POLLRDNORM);
1667 selrecord(td, &kq->kq_sel);
1668 if (SEL_WAITING(&kq->kq_sel))
1669 kq->kq_state |= KQ_SEL;
1672 kqueue_release(kq, 1);
1679 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1683 bzero((void *)st, sizeof *st);
1685 * We no longer return kq_count because the unlocked value is useless.
1686 * If you spent all this time getting the count, why not spend your
1687 * syscall better by calling kevent?
1689 * XXX - This is needed for libc_r.
1691 st->st_mode = S_IFIFO;
1697 kqueue_close(struct file *fp, struct thread *td)
1699 struct kqueue *kq = fp->f_data;
1700 struct filedesc *fdp;
1704 int filedesc_unlock;
1706 if ((error = kqueue_acquire(fp, &kq)))
1709 filedesc_unlock = 0;
1712 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1713 ("kqueue already closing"));
1714 kq->kq_state |= KQ_CLOSING;
1715 if (kq->kq_refcnt > 1)
1716 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1718 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1721 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1722 ("kqueue's knlist not empty"));
1724 for (i = 0; i < kq->kq_knlistsize; i++) {
1725 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1726 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1727 kq->kq_state |= KQ_FLUXWAIT;
1728 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1731 kn->kn_status |= KN_INFLUX;
1733 if (!(kn->kn_status & KN_DETACHED))
1734 kn->kn_fop->f_detach(kn);
1739 if (kq->kq_knhashmask != 0) {
1740 for (i = 0; i <= kq->kq_knhashmask; i++) {
1741 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1742 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1743 kq->kq_state |= KQ_FLUXWAIT;
1744 msleep(kq, &kq->kq_lock, PSOCK,
1748 kn->kn_status |= KN_INFLUX;
1750 if (!(kn->kn_status & KN_DETACHED))
1751 kn->kn_fop->f_detach(kn);
1758 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1759 kq->kq_state |= KQ_TASKDRAIN;
1760 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1763 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1764 selwakeuppri(&kq->kq_sel, PSOCK);
1765 if (!SEL_WAITING(&kq->kq_sel))
1766 kq->kq_state &= ~KQ_SEL;
1772 * We could be called due to the knote_drop() doing fdrop(),
1773 * called from kqueue_register(). In this case the global
1774 * lock is owned, and filedesc sx is locked before, to not
1775 * take the sleepable lock after non-sleepable.
1777 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1778 FILEDESC_XLOCK(fdp);
1779 filedesc_unlock = 1;
1781 filedesc_unlock = 0;
1782 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1783 if (filedesc_unlock)
1784 FILEDESC_XUNLOCK(fdp);
1786 seldrain(&kq->kq_sel);
1787 knlist_destroy(&kq->kq_sel.si_note);
1788 mtx_destroy(&kq->kq_lock);
1791 if (kq->kq_knhash != NULL)
1792 free(kq->kq_knhash, M_KQUEUE);
1793 if (kq->kq_knlist != NULL)
1794 free(kq->kq_knlist, M_KQUEUE);
1796 funsetown(&kq->kq_sigio);
1797 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1798 crfree(kq->kq_cred);
1806 kqueue_wakeup(struct kqueue *kq)
1810 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1811 kq->kq_state &= ~KQ_SLEEP;
1814 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1815 selwakeuppri(&kq->kq_sel, PSOCK);
1816 if (!SEL_WAITING(&kq->kq_sel))
1817 kq->kq_state &= ~KQ_SEL;
1819 if (!knlist_empty(&kq->kq_sel.si_note))
1820 kqueue_schedtask(kq);
1821 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1822 pgsigio(&kq->kq_sigio, SIGIO, 0);
1827 * Walk down a list of knotes, activating them if their event has triggered.
1829 * There is a possibility to optimize in the case of one kq watching another.
1830 * Instead of scheduling a task to wake it up, you could pass enough state
1831 * down the chain to make up the parent kqueue. Make this code functional
1835 knote(struct knlist *list, long hint, int lockflags)
1844 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1846 if ((lockflags & KNF_LISTLOCKED) == 0)
1847 list->kl_lock(list->kl_lockarg);
1850 * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1851 * the kqueue scheduling, but this will introduce four
1852 * lock/unlock's for each knote to test. If we do, continue to use
1853 * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1854 * only safe if you want to remove the current item, which we are
1857 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1860 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1862 * Do not process the influx notes, except for
1863 * the influx coming from the kq unlock in the
1864 * kqueue_scan(). In the later case, we do
1865 * not interfere with the scan, since the code
1866 * fragment in kqueue_scan() locks the knlist,
1867 * and cannot proceed until we finished.
1870 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1871 kn->kn_status |= KN_INFLUX;
1873 error = kn->kn_fop->f_event(kn, hint);
1875 kn->kn_status &= ~KN_INFLUX;
1877 KNOTE_ACTIVATE(kn, 1);
1880 kn->kn_status |= KN_HASKQLOCK;
1881 if (kn->kn_fop->f_event(kn, hint))
1882 KNOTE_ACTIVATE(kn, 1);
1883 kn->kn_status &= ~KN_HASKQLOCK;
1887 if ((lockflags & KNF_LISTLOCKED) == 0)
1888 list->kl_unlock(list->kl_lockarg);
1892 * add a knote to a knlist
1895 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1897 KNL_ASSERT_LOCK(knl, islocked);
1898 KQ_NOTOWNED(kn->kn_kq);
1899 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1900 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1902 knl->kl_lock(knl->kl_lockarg);
1903 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1905 knl->kl_unlock(knl->kl_lockarg);
1907 kn->kn_knlist = knl;
1908 kn->kn_status &= ~KN_DETACHED;
1909 KQ_UNLOCK(kn->kn_kq);
1913 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1915 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1916 KNL_ASSERT_LOCK(knl, knlislocked);
1917 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1919 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1920 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1922 knl->kl_lock(knl->kl_lockarg);
1923 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1924 kn->kn_knlist = NULL;
1926 knl->kl_unlock(knl->kl_lockarg);
1929 kn->kn_status |= KN_DETACHED;
1931 KQ_UNLOCK(kn->kn_kq);
1935 * remove knote from the specified knlist
1938 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1941 knlist_remove_kq(knl, kn, islocked, 0);
1945 * remove knote from the specified knlist while in f_event handler.
1948 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1951 knlist_remove_kq(knl, kn, 1,
1952 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1956 knlist_empty(struct knlist *knl)
1959 KNL_ASSERT_LOCKED(knl);
1960 return SLIST_EMPTY(&knl->kl_list);
1963 static struct mtx knlist_lock;
1964 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1966 static void knlist_mtx_lock(void *arg);
1967 static void knlist_mtx_unlock(void *arg);
1970 knlist_mtx_lock(void *arg)
1973 mtx_lock((struct mtx *)arg);
1977 knlist_mtx_unlock(void *arg)
1980 mtx_unlock((struct mtx *)arg);
1984 knlist_mtx_assert_locked(void *arg)
1987 mtx_assert((struct mtx *)arg, MA_OWNED);
1991 knlist_mtx_assert_unlocked(void *arg)
1994 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
1998 knlist_rw_rlock(void *arg)
2001 rw_rlock((struct rwlock *)arg);
2005 knlist_rw_runlock(void *arg)
2008 rw_runlock((struct rwlock *)arg);
2012 knlist_rw_assert_locked(void *arg)
2015 rw_assert((struct rwlock *)arg, RA_LOCKED);
2019 knlist_rw_assert_unlocked(void *arg)
2022 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2026 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2027 void (*kl_unlock)(void *),
2028 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2032 knl->kl_lockarg = &knlist_lock;
2034 knl->kl_lockarg = lock;
2036 if (kl_lock == NULL)
2037 knl->kl_lock = knlist_mtx_lock;
2039 knl->kl_lock = kl_lock;
2040 if (kl_unlock == NULL)
2041 knl->kl_unlock = knlist_mtx_unlock;
2043 knl->kl_unlock = kl_unlock;
2044 if (kl_assert_locked == NULL)
2045 knl->kl_assert_locked = knlist_mtx_assert_locked;
2047 knl->kl_assert_locked = kl_assert_locked;
2048 if (kl_assert_unlocked == NULL)
2049 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2051 knl->kl_assert_unlocked = kl_assert_unlocked;
2053 SLIST_INIT(&knl->kl_list);
2057 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2060 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2064 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2067 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2068 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2072 knlist_destroy(struct knlist *knl)
2077 * if we run across this error, we need to find the offending
2078 * driver and have it call knlist_clear or knlist_delete.
2080 if (!SLIST_EMPTY(&knl->kl_list))
2081 printf("WARNING: destroying knlist w/ knotes on it!\n");
2084 knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2085 SLIST_INIT(&knl->kl_list);
2089 * Even if we are locked, we may need to drop the lock to allow any influx
2090 * knotes time to "settle".
2093 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2095 struct knote *kn, *kn2;
2099 KNL_ASSERT_LOCKED(knl);
2101 KNL_ASSERT_UNLOCKED(knl);
2102 again: /* need to reacquire lock since we have dropped it */
2103 knl->kl_lock(knl->kl_lockarg);
2106 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2109 if ((kn->kn_status & KN_INFLUX)) {
2113 knlist_remove_kq(knl, kn, 1, 1);
2115 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2119 /* Make sure cleared knotes disappear soon */
2120 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2126 if (!SLIST_EMPTY(&knl->kl_list)) {
2127 /* there are still KN_INFLUX remaining */
2128 kn = SLIST_FIRST(&knl->kl_list);
2131 KASSERT(kn->kn_status & KN_INFLUX,
2132 ("knote removed w/o list lock"));
2133 knl->kl_unlock(knl->kl_lockarg);
2134 kq->kq_state |= KQ_FLUXWAIT;
2135 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2141 KNL_ASSERT_LOCKED(knl);
2143 knl->kl_unlock(knl->kl_lockarg);
2144 KNL_ASSERT_UNLOCKED(knl);
2149 * Remove all knotes referencing a specified fd must be called with FILEDESC
2150 * lock. This prevents a race where a new fd comes along and occupies the
2151 * entry and we attach a knote to the fd.
2154 knote_fdclose(struct thread *td, int fd)
2156 struct filedesc *fdp = td->td_proc->p_fd;
2161 FILEDESC_XLOCK_ASSERT(fdp);
2164 * We shouldn't have to worry about new kevents appearing on fd
2165 * since filedesc is locked.
2167 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2172 while (kq->kq_knlistsize > fd &&
2173 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2174 if (kn->kn_status & KN_INFLUX) {
2175 /* someone else might be waiting on our knote */
2178 kq->kq_state |= KQ_FLUXWAIT;
2179 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2182 kn->kn_status |= KN_INFLUX;
2184 if (!(kn->kn_status & KN_DETACHED))
2185 kn->kn_fop->f_detach(kn);
2195 knote_attach(struct knote *kn, struct kqueue *kq)
2199 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2202 if (kn->kn_fop->f_isfd) {
2203 if (kn->kn_id >= kq->kq_knlistsize)
2205 list = &kq->kq_knlist[kn->kn_id];
2207 if (kq->kq_knhash == NULL)
2209 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2212 SLIST_INSERT_HEAD(list, kn, kn_link);
2218 * knote must already have been detached using the f_detach method.
2219 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2220 * to prevent other removal.
2223 knote_drop(struct knote *kn, struct thread *td)
2231 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2232 ("knote_drop called without KN_INFLUX set in kn_status"));
2235 if (kn->kn_fop->f_isfd)
2236 list = &kq->kq_knlist[kn->kn_id];
2238 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2240 if (!SLIST_EMPTY(list))
2241 SLIST_REMOVE(list, kn, knote, kn_link);
2242 if (kn->kn_status & KN_QUEUED)
2246 if (kn->kn_fop->f_isfd) {
2247 fdrop(kn->kn_fp, td);
2250 kqueue_fo_release(kn->kn_kevent.filter);
2256 knote_enqueue(struct knote *kn)
2258 struct kqueue *kq = kn->kn_kq;
2260 KQ_OWNED(kn->kn_kq);
2261 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2263 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2264 kn->kn_status |= KN_QUEUED;
2270 knote_dequeue(struct knote *kn)
2272 struct kqueue *kq = kn->kn_kq;
2274 KQ_OWNED(kn->kn_kq);
2275 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2277 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2278 kn->kn_status &= ~KN_QUEUED;
2286 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2287 NULL, NULL, UMA_ALIGN_PTR, 0);
2289 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2291 static struct knote *
2292 knote_alloc(int waitok)
2294 return ((struct knote *)uma_zalloc(knote_zone,
2295 (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2299 knote_free(struct knote *kn)
2302 uma_zfree(knote_zone, kn);
2306 * Register the kev w/ the kq specified by fd.
2309 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2313 cap_rights_t rights;
2316 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2319 if ((error = kqueue_acquire(fp, &kq)) != 0)
2322 error = kqueue_register(kq, kev, td, waitok);
2324 kqueue_release(kq, 0);