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;
285 } sysfilt_ops[EVFILT_SYSCOUNT] = {
286 { &file_filtops }, /* EVFILT_READ */
287 { &file_filtops }, /* EVFILT_WRITE */
288 { &null_filtops }, /* EVFILT_AIO */
289 { &file_filtops }, /* EVFILT_VNODE */
290 { &proc_filtops }, /* EVFILT_PROC */
291 { &sig_filtops }, /* EVFILT_SIGNAL */
292 { &timer_filtops }, /* EVFILT_TIMER */
293 { &file_filtops }, /* EVFILT_PROCDESC */
294 { &fs_filtops }, /* EVFILT_FS */
295 { &null_filtops }, /* EVFILT_LIO */
296 { &user_filtops }, /* EVFILT_USER */
297 { &null_filtops }, /* EVFILT_SENDFILE */
301 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
305 filt_fileattach(struct knote *kn)
308 return (fo_kqfilter(kn->kn_fp, kn));
313 kqueue_kqfilter(struct file *fp, struct knote *kn)
315 struct kqueue *kq = kn->kn_fp->f_data;
317 if (kn->kn_filter != EVFILT_READ)
320 kn->kn_status |= KN_KQUEUE;
321 kn->kn_fop = &kqread_filtops;
322 knlist_add(&kq->kq_sel.si_note, kn, 0);
328 filt_kqdetach(struct knote *kn)
330 struct kqueue *kq = kn->kn_fp->f_data;
332 knlist_remove(&kq->kq_sel.si_note, kn, 0);
337 filt_kqueue(struct knote *kn, long hint)
339 struct kqueue *kq = kn->kn_fp->f_data;
341 kn->kn_data = kq->kq_count;
342 return (kn->kn_data > 0);
345 /* XXX - move to kern_proc.c? */
347 filt_procattach(struct knote *kn)
354 p = pfind(kn->kn_id);
355 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
356 p = zpfind(kn->kn_id);
358 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
364 if ((error = p_cansee(curthread, p))) {
369 kn->kn_ptr.p_proc = p;
370 kn->kn_flags |= EV_CLEAR; /* automatically set */
373 * internal flag indicating registration done by kernel
375 if (kn->kn_flags & EV_FLAG1) {
376 kn->kn_data = kn->kn_sdata; /* ppid */
377 kn->kn_fflags = NOTE_CHILD;
378 kn->kn_flags &= ~EV_FLAG1;
382 knlist_add(&p->p_klist, kn, 1);
385 * Immediately activate any exit notes if the target process is a
386 * zombie. This is necessary to handle the case where the target
387 * process, e.g. a child, dies before the kevent is registered.
389 if (immediate && filt_proc(kn, NOTE_EXIT))
390 KNOTE_ACTIVATE(kn, 0);
398 * The knote may be attached to a different process, which may exit,
399 * leaving nothing for the knote to be attached to. So when the process
400 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
401 * it will be deleted when read out. However, as part of the knote deletion,
402 * this routine is called, so a check is needed to avoid actually performing
403 * a detach, because the original process does not exist any more.
405 /* XXX - move to kern_proc.c? */
407 filt_procdetach(struct knote *kn)
411 p = kn->kn_ptr.p_proc;
412 knlist_remove(&p->p_klist, kn, 0);
413 kn->kn_ptr.p_proc = NULL;
416 /* XXX - move to kern_proc.c? */
418 filt_proc(struct knote *kn, long hint)
423 p = kn->kn_ptr.p_proc;
424 /* Mask off extra data. */
425 event = (u_int)hint & NOTE_PCTRLMASK;
427 /* If the user is interested in this event, record it. */
428 if (kn->kn_sfflags & event)
429 kn->kn_fflags |= event;
431 /* Process is gone, so flag the event as finished. */
432 if (event == NOTE_EXIT) {
433 if (!(kn->kn_status & KN_DETACHED))
434 knlist_remove_inevent(&p->p_klist, kn);
435 kn->kn_flags |= EV_EOF | EV_ONESHOT;
436 kn->kn_ptr.p_proc = NULL;
437 if (kn->kn_fflags & NOTE_EXIT)
438 kn->kn_data = p->p_xstat;
439 if (kn->kn_fflags == 0)
440 kn->kn_flags |= EV_DROP;
444 return (kn->kn_fflags != 0);
448 * Called when the process forked. It mostly does the same as the
449 * knote(), activating all knotes registered to be activated when the
450 * process forked. Additionally, for each knote attached to the
451 * parent, check whether user wants to track the new process. If so
452 * attach a new knote to it, and immediately report an event with the
456 knote_fork(struct knlist *list, int pid)
465 list->kl_lock(list->kl_lockarg);
467 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
468 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX)
472 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
478 * The same as knote(), activate the event.
480 if ((kn->kn_sfflags & NOTE_TRACK) == 0) {
481 kn->kn_status |= KN_HASKQLOCK;
482 if (kn->kn_fop->f_event(kn, NOTE_FORK))
483 KNOTE_ACTIVATE(kn, 1);
484 kn->kn_status &= ~KN_HASKQLOCK;
490 * The NOTE_TRACK case. In addition to the activation
491 * of the event, we need to register new event to
492 * track the child. Drop the locks in preparation for
493 * the call to kqueue_register().
495 kn->kn_status |= KN_INFLUX;
497 list->kl_unlock(list->kl_lockarg);
500 * Activate existing knote and register a knote with
504 kev.filter = kn->kn_filter;
505 kev.flags = kn->kn_flags | EV_ADD | EV_ENABLE | EV_FLAG1;
506 kev.fflags = kn->kn_sfflags;
507 kev.data = kn->kn_id; /* parent */
508 kev.udata = kn->kn_kevent.udata;/* preserve udata */
509 error = kqueue_register(kq, &kev, NULL, 0);
511 kn->kn_fflags |= NOTE_TRACKERR;
512 if (kn->kn_fop->f_event(kn, NOTE_FORK))
513 KNOTE_ACTIVATE(kn, 0);
515 kn->kn_status &= ~KN_INFLUX;
517 list->kl_lock(list->kl_lockarg);
519 list->kl_unlock(list->kl_lockarg);
523 * XXX: EVFILT_TIMER should perhaps live in kern_time.c beside the
524 * interval timer support code.
527 #define NOTE_TIMER_PRECMASK (NOTE_SECONDS|NOTE_MSECONDS|NOTE_USECONDS| \
530 static __inline sbintime_t
531 timer2sbintime(intptr_t data, int flags)
535 switch (flags & NOTE_TIMER_PRECMASK) {
539 case NOTE_MSECONDS: /* FALLTHROUGH */
554 if (data > SBT_MAX / modifier)
557 return (modifier * data);
561 filt_timerexpire(void *knx)
563 struct callout *calloutp;
568 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
570 if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
571 calloutp = (struct callout *)kn->kn_hook;
572 *kn->kn_ptr.p_nexttime += timer2sbintime(kn->kn_sdata,
574 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
575 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
580 * data contains amount of time to sleep
583 filt_timerattach(struct knote *kn)
585 struct callout *calloutp;
587 unsigned int ncallouts;
589 if ((intptr_t)kn->kn_sdata < 0)
591 if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
593 /* Only precision unit are supported in flags so far */
594 if (kn->kn_sfflags & ~NOTE_TIMER_PRECMASK)
597 to = timer2sbintime(kn->kn_sdata, kn->kn_sfflags);
601 ncallouts = atomic_load_explicit(&kq_ncallouts, memory_order_relaxed);
603 if (ncallouts >= kq_calloutmax)
605 } while (!atomic_compare_exchange_weak_explicit(&kq_ncallouts,
606 &ncallouts, ncallouts + 1, memory_order_relaxed,
607 memory_order_relaxed));
609 kn->kn_flags |= EV_CLEAR; /* automatically set */
610 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
611 kn->kn_ptr.p_nexttime = malloc(sizeof(sbintime_t), M_KQUEUE, M_WAITOK);
612 calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
613 callout_init(calloutp, CALLOUT_MPSAFE);
614 kn->kn_hook = calloutp;
615 *kn->kn_ptr.p_nexttime = to + sbinuptime();
616 callout_reset_sbt_on(calloutp, *kn->kn_ptr.p_nexttime, 0,
617 filt_timerexpire, kn, PCPU_GET(cpuid), C_ABSOLUTE);
623 filt_timerdetach(struct knote *kn)
625 struct callout *calloutp;
628 calloutp = (struct callout *)kn->kn_hook;
629 callout_drain(calloutp);
630 free(calloutp, M_KQUEUE);
631 free(kn->kn_ptr.p_nexttime, M_KQUEUE);
632 old = atomic_fetch_sub_explicit(&kq_ncallouts, 1, memory_order_relaxed);
633 KASSERT(old > 0, ("Number of callouts cannot become negative"));
634 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
638 filt_timer(struct knote *kn, long hint)
641 return (kn->kn_data != 0);
645 filt_userattach(struct knote *kn)
649 * EVFILT_USER knotes are not attached to anything in the kernel.
652 if (kn->kn_fflags & NOTE_TRIGGER)
660 filt_userdetach(__unused struct knote *kn)
664 * EVFILT_USER knotes are not attached to anything in the kernel.
669 filt_user(struct knote *kn, __unused long hint)
672 return (kn->kn_hookid);
676 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
682 if (kev->fflags & NOTE_TRIGGER)
685 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
686 kev->fflags &= NOTE_FFLAGSMASK;
692 kn->kn_sfflags &= kev->fflags;
696 kn->kn_sfflags |= kev->fflags;
700 kn->kn_sfflags = kev->fflags;
704 /* XXX Return error? */
707 kn->kn_sdata = kev->data;
708 if (kev->flags & EV_CLEAR) {
716 *kev = kn->kn_kevent;
717 kev->fflags = kn->kn_sfflags;
718 kev->data = kn->kn_sdata;
719 if (kn->kn_flags & EV_CLEAR) {
727 panic("filt_usertouch() - invalid type (%ld)", type);
733 sys_kqueue(struct thread *td, struct kqueue_args *uap)
735 struct filedesc *fdp;
746 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td->td_proc,
755 error = falloc(td, &fp, &fd, 0);
759 /* An extra reference on `fp' has been held for us by falloc(). */
760 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
761 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
762 TAILQ_INIT(&kq->kq_head);
765 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
766 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
769 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
770 FILEDESC_XUNLOCK(fdp);
772 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
775 td->td_retval[0] = fd;
778 chgkqcnt(cred->cr_ruidinfo, -1, 0);
784 #ifndef _SYS_SYSPROTO_H_
787 const struct kevent *changelist;
789 struct kevent *eventlist;
791 const struct timespec *timeout;
795 sys_kevent(struct thread *td, struct kevent_args *uap)
797 struct timespec ts, *tsp;
798 struct kevent_copyops k_ops = { uap,
805 struct uio *ktruioin = NULL;
806 struct uio *ktruioout = NULL;
809 if (uap->timeout != NULL) {
810 error = copyin(uap->timeout, &ts, sizeof(ts));
818 if (KTRPOINT(td, KTR_GENIO)) {
819 ktriov.iov_base = uap->changelist;
820 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
821 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
822 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
824 ktruioin = cloneuio(&ktruio);
825 ktriov.iov_base = uap->eventlist;
826 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
827 ktruioout = cloneuio(&ktruio);
831 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
835 if (ktruioin != NULL) {
836 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
837 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
838 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
839 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
847 * Copy 'count' items into the destination list pointed to by uap->eventlist.
850 kevent_copyout(void *arg, struct kevent *kevp, int count)
852 struct kevent_args *uap;
855 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
856 uap = (struct kevent_args *)arg;
858 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
860 uap->eventlist += count;
865 * Copy 'count' items from the list pointed to by uap->changelist.
868 kevent_copyin(void *arg, struct kevent *kevp, int count)
870 struct kevent_args *uap;
873 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
874 uap = (struct kevent_args *)arg;
876 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
878 uap->changelist += count;
883 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
884 struct kevent_copyops *k_ops, const struct timespec *timeout)
886 struct kevent keva[KQ_NEVENTS];
887 struct kevent *kevp, *changes;
891 int i, n, nerrors, error;
893 cap_rights_init(&rights);
895 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
897 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
898 error = fget(td, fd, &rights, &fp);
902 error = kqueue_acquire(fp, &kq);
908 while (nchanges > 0) {
909 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
910 error = k_ops->k_copyin(k_ops->arg, keva, n);
914 for (i = 0; i < n; i++) {
918 kevp->flags &= ~EV_SYSFLAGS;
919 error = kqueue_register(kq, kevp, td, 1);
920 if (error || (kevp->flags & EV_RECEIPT)) {
922 kevp->flags = EV_ERROR;
924 (void) k_ops->k_copyout(k_ops->arg,
936 td->td_retval[0] = nerrors;
941 error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
943 kqueue_release(kq, 0);
950 kqueue_add_filteropts(int filt, struct filterops *filtops)
955 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
957 "trying to add a filterop that is out of range: %d is beyond %d\n",
958 ~filt, EVFILT_SYSCOUNT);
961 mtx_lock(&filterops_lock);
962 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
963 sysfilt_ops[~filt].for_fop != NULL)
966 sysfilt_ops[~filt].for_fop = filtops;
967 sysfilt_ops[~filt].for_refcnt = 0;
969 mtx_unlock(&filterops_lock);
975 kqueue_del_filteropts(int filt)
980 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
983 mtx_lock(&filterops_lock);
984 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
985 sysfilt_ops[~filt].for_fop == NULL)
987 else if (sysfilt_ops[~filt].for_refcnt != 0)
990 sysfilt_ops[~filt].for_fop = &null_filtops;
991 sysfilt_ops[~filt].for_refcnt = 0;
993 mtx_unlock(&filterops_lock);
998 static struct filterops *
999 kqueue_fo_find(int filt)
1002 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1005 mtx_lock(&filterops_lock);
1006 sysfilt_ops[~filt].for_refcnt++;
1007 if (sysfilt_ops[~filt].for_fop == NULL)
1008 sysfilt_ops[~filt].for_fop = &null_filtops;
1009 mtx_unlock(&filterops_lock);
1011 return sysfilt_ops[~filt].for_fop;
1015 kqueue_fo_release(int filt)
1018 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
1021 mtx_lock(&filterops_lock);
1022 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
1023 ("filter object refcount not valid on release"));
1024 sysfilt_ops[~filt].for_refcnt--;
1025 mtx_unlock(&filterops_lock);
1029 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1030 * influence if memory allocation should wait. Make sure it is 0 if you
1034 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1036 struct filterops *fops;
1038 struct knote *kn, *tkn;
1039 cap_rights_t rights;
1040 int error, filt, event;
1041 int haskqglobal, filedesc_unlock;
1047 filedesc_unlock = 0;
1050 fops = kqueue_fo_find(filt);
1054 tkn = knote_alloc(waitok); /* prevent waiting with locks */
1058 KASSERT(td != NULL, ("td is NULL"));
1059 error = fget(td, kev->ident,
1060 cap_rights_init(&rights, CAP_EVENT), &fp);
1064 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1065 kev->ident, 0) != 0) {
1069 error = kqueue_expand(kq, fops, kev->ident, waitok);
1075 if (fp->f_type == DTYPE_KQUEUE) {
1077 * if we add some inteligence about what we are doing,
1078 * we should be able to support events on ourselves.
1079 * We need to know when we are doing this to prevent
1080 * getting both the knlist lock and the kq lock since
1081 * they are the same thing.
1083 if (fp->f_data == kq) {
1089 * Pre-lock the filedesc before the global
1090 * lock mutex, see the comment in
1093 FILEDESC_XLOCK(td->td_proc->p_fd);
1094 filedesc_unlock = 1;
1095 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1099 if (kev->ident < kq->kq_knlistsize) {
1100 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1101 if (kev->filter == kn->kn_filter)
1105 if ((kev->flags & EV_ADD) == EV_ADD)
1106 kqueue_expand(kq, fops, kev->ident, waitok);
1109 if (kq->kq_knhashmask != 0) {
1112 list = &kq->kq_knhash[
1113 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1114 SLIST_FOREACH(kn, list, kn_link)
1115 if (kev->ident == kn->kn_id &&
1116 kev->filter == kn->kn_filter)
1121 /* knote is in the process of changing, wait for it to stablize. */
1122 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1123 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1124 if (filedesc_unlock) {
1125 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1126 filedesc_unlock = 0;
1128 kq->kq_state |= KQ_FLUXWAIT;
1129 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1138 * kn now contains the matching knote, or NULL if no match
1141 if (kev->flags & EV_ADD) {
1153 * apply reference counts to knote structure, and
1154 * do not release it at the end of this routine.
1159 kn->kn_sfflags = kev->fflags;
1160 kn->kn_sdata = kev->data;
1163 kn->kn_kevent = *kev;
1164 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1165 EV_ENABLE | EV_DISABLE);
1166 kn->kn_status = KN_INFLUX|KN_DETACHED;
1168 error = knote_attach(kn, kq);
1175 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1182 /* No matching knote and the EV_ADD flag is not set. */
1189 if (kev->flags & EV_DELETE) {
1190 kn->kn_status |= KN_INFLUX;
1192 if (!(kn->kn_status & KN_DETACHED))
1193 kn->kn_fop->f_detach(kn);
1199 * The user may change some filter values after the initial EV_ADD,
1200 * but doing so will not reset any filter which has already been
1203 kn->kn_status |= KN_INFLUX | KN_SCAN;
1206 kn->kn_kevent.udata = kev->udata;
1207 if (!fops->f_isfd && fops->f_touch != NULL) {
1208 fops->f_touch(kn, kev, EVENT_REGISTER);
1210 kn->kn_sfflags = kev->fflags;
1211 kn->kn_sdata = kev->data;
1215 * We can get here with kn->kn_knlist == NULL. This can happen when
1216 * the initial attach event decides that the event is "completed"
1217 * already. i.e. filt_procattach is called on a zombie process. It
1218 * will call filt_proc which will remove it from the list, and NULL
1222 event = kn->kn_fop->f_event(kn, 0);
1225 KNOTE_ACTIVATE(kn, 1);
1226 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1229 if ((kev->flags & EV_DISABLE) &&
1230 ((kn->kn_status & KN_DISABLED) == 0)) {
1231 kn->kn_status |= KN_DISABLED;
1234 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1235 kn->kn_status &= ~KN_DISABLED;
1236 if ((kn->kn_status & KN_ACTIVE) &&
1237 ((kn->kn_status & KN_QUEUED) == 0))
1243 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1244 if (filedesc_unlock)
1245 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1251 kqueue_fo_release(filt);
1256 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1264 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1268 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1279 kqueue_release(struct kqueue *kq, int locked)
1286 if (kq->kq_refcnt == 1)
1287 wakeup(&kq->kq_refcnt);
1293 kqueue_schedtask(struct kqueue *kq)
1297 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1298 ("scheduling kqueue task while draining"));
1300 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1301 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1302 kq->kq_state |= KQ_TASKSCHED;
1307 * Expand the kq to make sure we have storage for fops/ident pair.
1309 * Return 0 on success (or no work necessary), return errno on failure.
1311 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1312 * If kqueue_register is called from a non-fd context, there usually/should
1316 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1319 struct klist *list, *tmp_knhash, *to_free;
1320 u_long tmp_knhashmask;
1323 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1330 if (kq->kq_knlistsize <= fd) {
1331 size = kq->kq_knlistsize;
1334 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1338 if (kq->kq_knlistsize > fd) {
1342 if (kq->kq_knlist != NULL) {
1343 bcopy(kq->kq_knlist, list,
1344 kq->kq_knlistsize * sizeof(*list));
1345 to_free = kq->kq_knlist;
1346 kq->kq_knlist = NULL;
1348 bzero((caddr_t)list +
1349 kq->kq_knlistsize * sizeof(*list),
1350 (size - kq->kq_knlistsize) * sizeof(*list));
1351 kq->kq_knlistsize = size;
1352 kq->kq_knlist = list;
1357 if (kq->kq_knhashmask == 0) {
1358 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1360 if (tmp_knhash == NULL)
1363 if (kq->kq_knhashmask == 0) {
1364 kq->kq_knhash = tmp_knhash;
1365 kq->kq_knhashmask = tmp_knhashmask;
1367 to_free = tmp_knhash;
1372 free(to_free, M_KQUEUE);
1379 kqueue_task(void *arg, int pending)
1387 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1390 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1392 kq->kq_state &= ~KQ_TASKSCHED;
1393 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1394 wakeup(&kq->kq_state);
1397 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1401 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1402 * We treat KN_MARKER knotes as if they are INFLUX.
1405 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1406 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1408 struct kevent *kevp;
1409 struct knote *kn, *marker;
1410 sbintime_t asbt, rsbt;
1411 int count, error, haskqglobal, influx, nkev, touch;
1423 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1424 tsp->tv_nsec >= 1000000000) {
1428 if (timespecisset(tsp)) {
1429 if (tsp->tv_sec <= INT32_MAX) {
1430 rsbt = tstosbt(*tsp);
1431 if (TIMESEL(&asbt, rsbt))
1432 asbt += tc_tick_sbt;
1433 if (asbt <= SBT_MAX - rsbt)
1437 rsbt >>= tc_precexp;
1444 marker = knote_alloc(1);
1445 if (marker == NULL) {
1449 marker->kn_status = KN_MARKER;
1454 if (kq->kq_count == 0) {
1456 error = EWOULDBLOCK;
1458 kq->kq_state |= KQ_SLEEP;
1459 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1460 "kqread", asbt, rsbt, C_ABSOLUTE);
1464 /* don't restart after signals... */
1465 if (error == ERESTART)
1467 else if (error == EWOULDBLOCK)
1472 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1476 kn = TAILQ_FIRST(&kq->kq_head);
1478 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1479 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1484 kq->kq_state |= KQ_FLUXWAIT;
1485 error = msleep(kq, &kq->kq_lock, PSOCK,
1490 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1491 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1492 kn->kn_status &= ~KN_QUEUED;
1498 if (count == maxevents)
1502 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1503 ("KN_INFLUX set when not suppose to be"));
1505 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1506 kn->kn_status &= ~KN_QUEUED;
1507 kn->kn_status |= KN_INFLUX;
1511 * We don't need to lock the list since we've marked
1514 if (!(kn->kn_status & KN_DETACHED))
1515 kn->kn_fop->f_detach(kn);
1519 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1520 kn->kn_status &= ~KN_QUEUED;
1521 kn->kn_status |= KN_INFLUX;
1525 * We don't need to lock the list since we've marked
1528 *kevp = kn->kn_kevent;
1529 if (!(kn->kn_status & KN_DETACHED))
1530 kn->kn_fop->f_detach(kn);
1535 kn->kn_status |= KN_INFLUX | KN_SCAN;
1537 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1538 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1540 if (kn->kn_fop->f_event(kn, 0) == 0) {
1542 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1544 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX |
1551 touch = (!kn->kn_fop->f_isfd &&
1552 kn->kn_fop->f_touch != NULL);
1554 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1556 *kevp = kn->kn_kevent;
1558 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1559 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1561 * Manually clear knotes who weren't
1564 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1568 if (kn->kn_flags & EV_DISPATCH)
1569 kn->kn_status |= KN_DISABLED;
1570 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1573 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1575 kn->kn_status &= ~(KN_INFLUX | KN_SCAN);
1580 /* we are returning a copy to the user */
1585 if (nkev == KQ_NEVENTS) {
1588 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1596 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1604 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1605 td->td_retval[0] = maxevents - count;
1611 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1612 struct ucred *active_cred, struct thread *td)
1615 * Enabling sigio causes two major problems:
1616 * 1) infinite recursion:
1617 * Synopsys: kevent is being used to track signals and have FIOASYNC
1618 * set. On receipt of a signal this will cause a kqueue to recurse
1619 * into itself over and over. Sending the sigio causes the kqueue
1620 * to become ready, which in turn posts sigio again, forever.
1621 * Solution: this can be solved by setting a flag in the kqueue that
1622 * we have a SIGIO in progress.
1623 * 2) locking problems:
1624 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1625 * us above the proc and pgrp locks.
1626 * Solution: Post a signal using an async mechanism, being sure to
1627 * record a generation count in the delivery so that we do not deliver
1628 * a signal to the wrong process.
1630 * Note, these two mechanisms are somewhat mutually exclusive!
1639 kq->kq_state |= KQ_ASYNC;
1641 kq->kq_state &= ~KQ_ASYNC;
1646 return (fsetown(*(int *)data, &kq->kq_sigio));
1649 *(int *)data = fgetown(&kq->kq_sigio);
1659 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1666 if ((error = kqueue_acquire(fp, &kq)))
1670 if (events & (POLLIN | POLLRDNORM)) {
1672 revents |= events & (POLLIN | POLLRDNORM);
1674 selrecord(td, &kq->kq_sel);
1675 if (SEL_WAITING(&kq->kq_sel))
1676 kq->kq_state |= KQ_SEL;
1679 kqueue_release(kq, 1);
1686 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1690 bzero((void *)st, sizeof *st);
1692 * We no longer return kq_count because the unlocked value is useless.
1693 * If you spent all this time getting the count, why not spend your
1694 * syscall better by calling kevent?
1696 * XXX - This is needed for libc_r.
1698 st->st_mode = S_IFIFO;
1704 kqueue_close(struct file *fp, struct thread *td)
1706 struct kqueue *kq = fp->f_data;
1707 struct filedesc *fdp;
1711 int filedesc_unlock;
1713 if ((error = kqueue_acquire(fp, &kq)))
1716 filedesc_unlock = 0;
1719 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1720 ("kqueue already closing"));
1721 kq->kq_state |= KQ_CLOSING;
1722 if (kq->kq_refcnt > 1)
1723 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1725 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1728 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1729 ("kqueue's knlist not empty"));
1731 for (i = 0; i < kq->kq_knlistsize; i++) {
1732 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1733 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1734 kq->kq_state |= KQ_FLUXWAIT;
1735 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1738 kn->kn_status |= KN_INFLUX;
1740 if (!(kn->kn_status & KN_DETACHED))
1741 kn->kn_fop->f_detach(kn);
1746 if (kq->kq_knhashmask != 0) {
1747 for (i = 0; i <= kq->kq_knhashmask; i++) {
1748 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1749 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1750 kq->kq_state |= KQ_FLUXWAIT;
1751 msleep(kq, &kq->kq_lock, PSOCK,
1755 kn->kn_status |= KN_INFLUX;
1757 if (!(kn->kn_status & KN_DETACHED))
1758 kn->kn_fop->f_detach(kn);
1765 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1766 kq->kq_state |= KQ_TASKDRAIN;
1767 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1770 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1771 selwakeuppri(&kq->kq_sel, PSOCK);
1772 if (!SEL_WAITING(&kq->kq_sel))
1773 kq->kq_state &= ~KQ_SEL;
1779 * We could be called due to the knote_drop() doing fdrop(),
1780 * called from kqueue_register(). In this case the global
1781 * lock is owned, and filedesc sx is locked before, to not
1782 * take the sleepable lock after non-sleepable.
1784 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1785 FILEDESC_XLOCK(fdp);
1786 filedesc_unlock = 1;
1788 filedesc_unlock = 0;
1789 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1790 if (filedesc_unlock)
1791 FILEDESC_XUNLOCK(fdp);
1793 seldrain(&kq->kq_sel);
1794 knlist_destroy(&kq->kq_sel.si_note);
1795 mtx_destroy(&kq->kq_lock);
1798 if (kq->kq_knhash != NULL)
1799 free(kq->kq_knhash, M_KQUEUE);
1800 if (kq->kq_knlist != NULL)
1801 free(kq->kq_knlist, M_KQUEUE);
1803 funsetown(&kq->kq_sigio);
1804 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1805 crfree(kq->kq_cred);
1813 kqueue_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
1816 kif->kf_type = KF_TYPE_KQUEUE;
1821 kqueue_wakeup(struct kqueue *kq)
1825 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1826 kq->kq_state &= ~KQ_SLEEP;
1829 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1830 selwakeuppri(&kq->kq_sel, PSOCK);
1831 if (!SEL_WAITING(&kq->kq_sel))
1832 kq->kq_state &= ~KQ_SEL;
1834 if (!knlist_empty(&kq->kq_sel.si_note))
1835 kqueue_schedtask(kq);
1836 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1837 pgsigio(&kq->kq_sigio, SIGIO, 0);
1842 * Walk down a list of knotes, activating them if their event has triggered.
1844 * There is a possibility to optimize in the case of one kq watching another.
1845 * Instead of scheduling a task to wake it up, you could pass enough state
1846 * down the chain to make up the parent kqueue. Make this code functional
1850 knote(struct knlist *list, long hint, int lockflags)
1859 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1861 if ((lockflags & KNF_LISTLOCKED) == 0)
1862 list->kl_lock(list->kl_lockarg);
1865 * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1866 * the kqueue scheduling, but this will introduce four
1867 * lock/unlock's for each knote to test. If we do, continue to use
1868 * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1869 * only safe if you want to remove the current item, which we are
1872 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1875 if ((kn->kn_status & (KN_INFLUX | KN_SCAN)) == KN_INFLUX) {
1877 * Do not process the influx notes, except for
1878 * the influx coming from the kq unlock in the
1879 * kqueue_scan(). In the later case, we do
1880 * not interfere with the scan, since the code
1881 * fragment in kqueue_scan() locks the knlist,
1882 * and cannot proceed until we finished.
1885 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1886 kn->kn_status |= KN_INFLUX;
1888 error = kn->kn_fop->f_event(kn, hint);
1890 kn->kn_status &= ~KN_INFLUX;
1892 KNOTE_ACTIVATE(kn, 1);
1895 kn->kn_status |= KN_HASKQLOCK;
1896 if (kn->kn_fop->f_event(kn, hint))
1897 KNOTE_ACTIVATE(kn, 1);
1898 kn->kn_status &= ~KN_HASKQLOCK;
1902 if ((lockflags & KNF_LISTLOCKED) == 0)
1903 list->kl_unlock(list->kl_lockarg);
1907 * add a knote to a knlist
1910 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1912 KNL_ASSERT_LOCK(knl, islocked);
1913 KQ_NOTOWNED(kn->kn_kq);
1914 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1915 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1917 knl->kl_lock(knl->kl_lockarg);
1918 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1920 knl->kl_unlock(knl->kl_lockarg);
1922 kn->kn_knlist = knl;
1923 kn->kn_status &= ~KN_DETACHED;
1924 KQ_UNLOCK(kn->kn_kq);
1928 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1930 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1931 KNL_ASSERT_LOCK(knl, knlislocked);
1932 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1934 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1935 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1937 knl->kl_lock(knl->kl_lockarg);
1938 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1939 kn->kn_knlist = NULL;
1941 knl->kl_unlock(knl->kl_lockarg);
1944 kn->kn_status |= KN_DETACHED;
1946 KQ_UNLOCK(kn->kn_kq);
1950 * remove knote from the specified knlist
1953 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1956 knlist_remove_kq(knl, kn, islocked, 0);
1960 * remove knote from the specified knlist while in f_event handler.
1963 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1966 knlist_remove_kq(knl, kn, 1,
1967 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1971 knlist_empty(struct knlist *knl)
1974 KNL_ASSERT_LOCKED(knl);
1975 return SLIST_EMPTY(&knl->kl_list);
1978 static struct mtx knlist_lock;
1979 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1981 static void knlist_mtx_lock(void *arg);
1982 static void knlist_mtx_unlock(void *arg);
1985 knlist_mtx_lock(void *arg)
1988 mtx_lock((struct mtx *)arg);
1992 knlist_mtx_unlock(void *arg)
1995 mtx_unlock((struct mtx *)arg);
1999 knlist_mtx_assert_locked(void *arg)
2002 mtx_assert((struct mtx *)arg, MA_OWNED);
2006 knlist_mtx_assert_unlocked(void *arg)
2009 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2013 knlist_rw_rlock(void *arg)
2016 rw_rlock((struct rwlock *)arg);
2020 knlist_rw_runlock(void *arg)
2023 rw_runlock((struct rwlock *)arg);
2027 knlist_rw_assert_locked(void *arg)
2030 rw_assert((struct rwlock *)arg, RA_LOCKED);
2034 knlist_rw_assert_unlocked(void *arg)
2037 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2041 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2042 void (*kl_unlock)(void *),
2043 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2047 knl->kl_lockarg = &knlist_lock;
2049 knl->kl_lockarg = lock;
2051 if (kl_lock == NULL)
2052 knl->kl_lock = knlist_mtx_lock;
2054 knl->kl_lock = kl_lock;
2055 if (kl_unlock == NULL)
2056 knl->kl_unlock = knlist_mtx_unlock;
2058 knl->kl_unlock = kl_unlock;
2059 if (kl_assert_locked == NULL)
2060 knl->kl_assert_locked = knlist_mtx_assert_locked;
2062 knl->kl_assert_locked = kl_assert_locked;
2063 if (kl_assert_unlocked == NULL)
2064 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2066 knl->kl_assert_unlocked = kl_assert_unlocked;
2068 SLIST_INIT(&knl->kl_list);
2072 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2075 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2079 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2082 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2083 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2087 knlist_destroy(struct knlist *knl)
2092 * if we run across this error, we need to find the offending
2093 * driver and have it call knlist_clear or knlist_delete.
2095 if (!SLIST_EMPTY(&knl->kl_list))
2096 printf("WARNING: destroying knlist w/ knotes on it!\n");
2099 knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2100 SLIST_INIT(&knl->kl_list);
2104 * Even if we are locked, we may need to drop the lock to allow any influx
2105 * knotes time to "settle".
2108 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2110 struct knote *kn, *kn2;
2114 KNL_ASSERT_LOCKED(knl);
2116 KNL_ASSERT_UNLOCKED(knl);
2117 again: /* need to reacquire lock since we have dropped it */
2118 knl->kl_lock(knl->kl_lockarg);
2121 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2124 if ((kn->kn_status & KN_INFLUX)) {
2128 knlist_remove_kq(knl, kn, 1, 1);
2130 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2134 /* Make sure cleared knotes disappear soon */
2135 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2141 if (!SLIST_EMPTY(&knl->kl_list)) {
2142 /* there are still KN_INFLUX remaining */
2143 kn = SLIST_FIRST(&knl->kl_list);
2146 KASSERT(kn->kn_status & KN_INFLUX,
2147 ("knote removed w/o list lock"));
2148 knl->kl_unlock(knl->kl_lockarg);
2149 kq->kq_state |= KQ_FLUXWAIT;
2150 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2156 KNL_ASSERT_LOCKED(knl);
2158 knl->kl_unlock(knl->kl_lockarg);
2159 KNL_ASSERT_UNLOCKED(knl);
2164 * Remove all knotes referencing a specified fd must be called with FILEDESC
2165 * lock. This prevents a race where a new fd comes along and occupies the
2166 * entry and we attach a knote to the fd.
2169 knote_fdclose(struct thread *td, int fd)
2171 struct filedesc *fdp = td->td_proc->p_fd;
2176 FILEDESC_XLOCK_ASSERT(fdp);
2179 * We shouldn't have to worry about new kevents appearing on fd
2180 * since filedesc is locked.
2182 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2187 while (kq->kq_knlistsize > fd &&
2188 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2189 if (kn->kn_status & KN_INFLUX) {
2190 /* someone else might be waiting on our knote */
2193 kq->kq_state |= KQ_FLUXWAIT;
2194 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2197 kn->kn_status |= KN_INFLUX;
2199 if (!(kn->kn_status & KN_DETACHED))
2200 kn->kn_fop->f_detach(kn);
2210 knote_attach(struct knote *kn, struct kqueue *kq)
2214 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2217 if (kn->kn_fop->f_isfd) {
2218 if (kn->kn_id >= kq->kq_knlistsize)
2220 list = &kq->kq_knlist[kn->kn_id];
2222 if (kq->kq_knhash == NULL)
2224 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2227 SLIST_INSERT_HEAD(list, kn, kn_link);
2233 * knote must already have been detached using the f_detach method.
2234 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2235 * to prevent other removal.
2238 knote_drop(struct knote *kn, struct thread *td)
2246 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2247 ("knote_drop called without KN_INFLUX set in kn_status"));
2250 if (kn->kn_fop->f_isfd)
2251 list = &kq->kq_knlist[kn->kn_id];
2253 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2255 if (!SLIST_EMPTY(list))
2256 SLIST_REMOVE(list, kn, knote, kn_link);
2257 if (kn->kn_status & KN_QUEUED)
2261 if (kn->kn_fop->f_isfd) {
2262 fdrop(kn->kn_fp, td);
2265 kqueue_fo_release(kn->kn_kevent.filter);
2271 knote_enqueue(struct knote *kn)
2273 struct kqueue *kq = kn->kn_kq;
2275 KQ_OWNED(kn->kn_kq);
2276 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2278 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2279 kn->kn_status |= KN_QUEUED;
2285 knote_dequeue(struct knote *kn)
2287 struct kqueue *kq = kn->kn_kq;
2289 KQ_OWNED(kn->kn_kq);
2290 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2292 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2293 kn->kn_status &= ~KN_QUEUED;
2301 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2302 NULL, NULL, UMA_ALIGN_PTR, 0);
2304 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2306 static struct knote *
2307 knote_alloc(int waitok)
2309 return ((struct knote *)uma_zalloc(knote_zone,
2310 (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2314 knote_free(struct knote *kn)
2317 uma_zfree(knote_zone, kn);
2321 * Register the kev w/ the kq specified by fd.
2324 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2328 cap_rights_t rights;
2331 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2334 if ((error = kqueue_acquire(fp, &kq)) != 0)
2337 error = kqueue_register(kq, kev, td, waitok);
2339 kqueue_release(kq, 0);