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_rdwr_t kqueue_read;
113 static fo_rdwr_t kqueue_write;
114 static fo_truncate_t kqueue_truncate;
115 static fo_ioctl_t kqueue_ioctl;
116 static fo_poll_t kqueue_poll;
117 static fo_kqfilter_t kqueue_kqfilter;
118 static fo_stat_t kqueue_stat;
119 static fo_close_t kqueue_close;
121 static struct fileops kqueueops = {
122 .fo_read = kqueue_read,
123 .fo_write = kqueue_write,
124 .fo_truncate = kqueue_truncate,
125 .fo_ioctl = kqueue_ioctl,
126 .fo_poll = kqueue_poll,
127 .fo_kqfilter = kqueue_kqfilter,
128 .fo_stat = kqueue_stat,
129 .fo_close = kqueue_close,
130 .fo_chmod = invfo_chmod,
131 .fo_chown = invfo_chown,
132 .fo_sendfile = invfo_sendfile,
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 { &null_filtops }, /* former EVFILT_NETDEV */
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)
420 struct proc *p = kn->kn_ptr.p_proc;
424 * mask off extra data
426 event = (u_int)hint & NOTE_PCTRLMASK;
429 * if the user is interested in this event, record it.
431 if (kn->kn_sfflags & event)
432 kn->kn_fflags |= event;
435 * process is gone, so flag the event as finished.
437 if (event == NOTE_EXIT) {
438 if (!(kn->kn_status & KN_DETACHED))
439 knlist_remove_inevent(&p->p_klist, kn);
440 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
441 kn->kn_ptr.p_proc = NULL;
442 if (kn->kn_fflags & NOTE_EXIT)
443 kn->kn_data = p->p_xstat;
444 if (kn->kn_fflags == 0)
445 kn->kn_flags |= EV_DROP;
449 return (kn->kn_fflags != 0);
453 * Called when the process forked. It mostly does the same as the
454 * knote(), activating all knotes registered to be activated when the
455 * process forked. Additionally, for each knote attached to the
456 * parent, check whether user wants to track the new process. If so
457 * attach a new knote to it, and immediately report an event with the
461 knote_fork(struct knlist *list, int pid)
470 list->kl_lock(list->kl_lockarg);
472 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
473 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX)
477 if ((kn->kn_status & KN_INFLUX) == 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.
531 static __inline sbintime_t
532 timer2sbintime(intptr_t data)
536 if (data > INT64_MAX / SBT_1MS)
539 return (SBT_1MS * data);
543 filt_timerexpire(void *knx)
545 struct callout *calloutp;
550 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
552 if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
553 calloutp = (struct callout *)kn->kn_hook;
554 callout_reset_sbt_on(calloutp,
555 timer2sbintime(kn->kn_sdata), 0 /* 1ms? */,
556 filt_timerexpire, kn, PCPU_GET(cpuid), 0);
561 * data contains amount of time to sleep, in milliseconds
564 filt_timerattach(struct knote *kn)
566 struct callout *calloutp;
568 unsigned int ncallouts;
570 if ((intptr_t)kn->kn_sdata < 0)
572 if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
574 to = timer2sbintime(kn->kn_sdata);
578 ncallouts = atomic_load_explicit(&kq_ncallouts, memory_order_relaxed);
580 if (ncallouts >= kq_calloutmax)
582 } while (!atomic_compare_exchange_weak_explicit(&kq_ncallouts,
583 &ncallouts, ncallouts + 1, memory_order_relaxed,
584 memory_order_relaxed));
586 kn->kn_flags |= EV_CLEAR; /* automatically set */
587 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
588 calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
589 callout_init(calloutp, CALLOUT_MPSAFE);
590 kn->kn_hook = calloutp;
591 callout_reset_sbt_on(calloutp, to, 0 /* 1ms? */,
592 filt_timerexpire, kn, PCPU_GET(cpuid), 0);
598 filt_timerdetach(struct knote *kn)
600 struct callout *calloutp;
603 calloutp = (struct callout *)kn->kn_hook;
604 callout_drain(calloutp);
605 free(calloutp, M_KQUEUE);
606 old = atomic_fetch_sub_explicit(&kq_ncallouts, 1, memory_order_relaxed);
607 KASSERT(old > 0, ("Number of callouts cannot become negative"));
608 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
612 filt_timer(struct knote *kn, long hint)
615 return (kn->kn_data != 0);
619 filt_userattach(struct knote *kn)
623 * EVFILT_USER knotes are not attached to anything in the kernel.
626 if (kn->kn_fflags & NOTE_TRIGGER)
634 filt_userdetach(__unused struct knote *kn)
638 * EVFILT_USER knotes are not attached to anything in the kernel.
643 filt_user(struct knote *kn, __unused long hint)
646 return (kn->kn_hookid);
650 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
656 if (kev->fflags & NOTE_TRIGGER)
659 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
660 kev->fflags &= NOTE_FFLAGSMASK;
666 kn->kn_sfflags &= kev->fflags;
670 kn->kn_sfflags |= kev->fflags;
674 kn->kn_sfflags = kev->fflags;
678 /* XXX Return error? */
681 kn->kn_sdata = kev->data;
682 if (kev->flags & EV_CLEAR) {
690 *kev = kn->kn_kevent;
691 kev->fflags = kn->kn_sfflags;
692 kev->data = kn->kn_sdata;
693 if (kn->kn_flags & EV_CLEAR) {
701 panic("filt_usertouch() - invalid type (%ld)", type);
707 sys_kqueue(struct thread *td, struct kqueue_args *uap)
709 struct filedesc *fdp;
720 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td->td_proc,
729 error = falloc(td, &fp, &fd, 0);
733 /* An extra reference on `fp' has been held for us by falloc(). */
734 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
735 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
736 TAILQ_INIT(&kq->kq_head);
739 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
740 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
743 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
744 FILEDESC_XUNLOCK(fdp);
746 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
749 td->td_retval[0] = fd;
752 chgkqcnt(cred->cr_ruidinfo, -1, 0);
758 #ifndef _SYS_SYSPROTO_H_
761 const struct kevent *changelist;
763 struct kevent *eventlist;
765 const struct timespec *timeout;
769 sys_kevent(struct thread *td, struct kevent_args *uap)
771 struct timespec ts, *tsp;
772 struct kevent_copyops k_ops = { uap,
779 struct uio *ktruioin = NULL;
780 struct uio *ktruioout = NULL;
783 if (uap->timeout != NULL) {
784 error = copyin(uap->timeout, &ts, sizeof(ts));
792 if (KTRPOINT(td, KTR_GENIO)) {
793 ktriov.iov_base = uap->changelist;
794 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
795 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
796 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
798 ktruioin = cloneuio(&ktruio);
799 ktriov.iov_base = uap->eventlist;
800 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
801 ktruioout = cloneuio(&ktruio);
805 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
809 if (ktruioin != NULL) {
810 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
811 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
812 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
813 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
821 * Copy 'count' items into the destination list pointed to by uap->eventlist.
824 kevent_copyout(void *arg, struct kevent *kevp, int count)
826 struct kevent_args *uap;
829 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
830 uap = (struct kevent_args *)arg;
832 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
834 uap->eventlist += count;
839 * Copy 'count' items from the list pointed to by uap->changelist.
842 kevent_copyin(void *arg, struct kevent *kevp, int count)
844 struct kevent_args *uap;
847 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
848 uap = (struct kevent_args *)arg;
850 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
852 uap->changelist += count;
857 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
858 struct kevent_copyops *k_ops, const struct timespec *timeout)
860 struct kevent keva[KQ_NEVENTS];
861 struct kevent *kevp, *changes;
865 int i, n, nerrors, error;
867 cap_rights_init(&rights);
869 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
871 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
872 error = fget(td, fd, &rights, &fp);
876 error = kqueue_acquire(fp, &kq);
882 while (nchanges > 0) {
883 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
884 error = k_ops->k_copyin(k_ops->arg, keva, n);
888 for (i = 0; i < n; i++) {
892 kevp->flags &= ~EV_SYSFLAGS;
893 error = kqueue_register(kq, kevp, td, 1);
894 if (error || (kevp->flags & EV_RECEIPT)) {
896 kevp->flags = EV_ERROR;
898 (void) k_ops->k_copyout(k_ops->arg,
910 td->td_retval[0] = nerrors;
915 error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
917 kqueue_release(kq, 0);
924 kqueue_add_filteropts(int filt, struct filterops *filtops)
929 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
931 "trying to add a filterop that is out of range: %d is beyond %d\n",
932 ~filt, EVFILT_SYSCOUNT);
935 mtx_lock(&filterops_lock);
936 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
937 sysfilt_ops[~filt].for_fop != NULL)
940 sysfilt_ops[~filt].for_fop = filtops;
941 sysfilt_ops[~filt].for_refcnt = 0;
943 mtx_unlock(&filterops_lock);
949 kqueue_del_filteropts(int filt)
954 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
957 mtx_lock(&filterops_lock);
958 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
959 sysfilt_ops[~filt].for_fop == NULL)
961 else if (sysfilt_ops[~filt].for_refcnt != 0)
964 sysfilt_ops[~filt].for_fop = &null_filtops;
965 sysfilt_ops[~filt].for_refcnt = 0;
967 mtx_unlock(&filterops_lock);
972 static struct filterops *
973 kqueue_fo_find(int filt)
976 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
979 mtx_lock(&filterops_lock);
980 sysfilt_ops[~filt].for_refcnt++;
981 if (sysfilt_ops[~filt].for_fop == NULL)
982 sysfilt_ops[~filt].for_fop = &null_filtops;
983 mtx_unlock(&filterops_lock);
985 return sysfilt_ops[~filt].for_fop;
989 kqueue_fo_release(int filt)
992 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
995 mtx_lock(&filterops_lock);
996 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
997 ("filter object refcount not valid on release"));
998 sysfilt_ops[~filt].for_refcnt--;
999 mtx_unlock(&filterops_lock);
1003 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
1004 * influence if memory allocation should wait. Make sure it is 0 if you
1008 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1010 struct filterops *fops;
1012 struct knote *kn, *tkn;
1013 cap_rights_t rights;
1014 int error, filt, event;
1015 int haskqglobal, filedesc_unlock;
1021 filedesc_unlock = 0;
1024 fops = kqueue_fo_find(filt);
1028 tkn = knote_alloc(waitok); /* prevent waiting with locks */
1032 KASSERT(td != NULL, ("td is NULL"));
1033 error = fget(td, kev->ident,
1034 cap_rights_init(&rights, CAP_EVENT), &fp);
1038 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1039 kev->ident, 0) != 0) {
1043 error = kqueue_expand(kq, fops, kev->ident, waitok);
1049 if (fp->f_type == DTYPE_KQUEUE) {
1051 * if we add some inteligence about what we are doing,
1052 * we should be able to support events on ourselves.
1053 * We need to know when we are doing this to prevent
1054 * getting both the knlist lock and the kq lock since
1055 * they are the same thing.
1057 if (fp->f_data == kq) {
1063 * Pre-lock the filedesc before the global
1064 * lock mutex, see the comment in
1067 FILEDESC_XLOCK(td->td_proc->p_fd);
1068 filedesc_unlock = 1;
1069 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1073 if (kev->ident < kq->kq_knlistsize) {
1074 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1075 if (kev->filter == kn->kn_filter)
1079 if ((kev->flags & EV_ADD) == EV_ADD)
1080 kqueue_expand(kq, fops, kev->ident, waitok);
1083 if (kq->kq_knhashmask != 0) {
1086 list = &kq->kq_knhash[
1087 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1088 SLIST_FOREACH(kn, list, kn_link)
1089 if (kev->ident == kn->kn_id &&
1090 kev->filter == kn->kn_filter)
1095 /* knote is in the process of changing, wait for it to stablize. */
1096 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1097 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1098 if (filedesc_unlock) {
1099 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1100 filedesc_unlock = 0;
1102 kq->kq_state |= KQ_FLUXWAIT;
1103 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1112 * kn now contains the matching knote, or NULL if no match
1115 if (kev->flags & EV_ADD) {
1127 * apply reference counts to knote structure, and
1128 * do not release it at the end of this routine.
1133 kn->kn_sfflags = kev->fflags;
1134 kn->kn_sdata = kev->data;
1137 kn->kn_kevent = *kev;
1138 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1139 EV_ENABLE | EV_DISABLE);
1140 kn->kn_status = KN_INFLUX|KN_DETACHED;
1142 error = knote_attach(kn, kq);
1149 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1156 /* No matching knote and the EV_ADD flag is not set. */
1163 if (kev->flags & EV_DELETE) {
1164 kn->kn_status |= KN_INFLUX;
1166 if (!(kn->kn_status & KN_DETACHED))
1167 kn->kn_fop->f_detach(kn);
1173 * The user may change some filter values after the initial EV_ADD,
1174 * but doing so will not reset any filter which has already been
1177 kn->kn_status |= KN_INFLUX;
1180 kn->kn_kevent.udata = kev->udata;
1181 if (!fops->f_isfd && fops->f_touch != NULL) {
1182 fops->f_touch(kn, kev, EVENT_REGISTER);
1184 kn->kn_sfflags = kev->fflags;
1185 kn->kn_sdata = kev->data;
1189 * We can get here with kn->kn_knlist == NULL. This can happen when
1190 * the initial attach event decides that the event is "completed"
1191 * already. i.e. filt_procattach is called on a zombie process. It
1192 * will call filt_proc which will remove it from the list, and NULL
1196 event = kn->kn_fop->f_event(kn, 0);
1199 KNOTE_ACTIVATE(kn, 1);
1200 kn->kn_status &= ~KN_INFLUX;
1203 if ((kev->flags & EV_DISABLE) &&
1204 ((kn->kn_status & KN_DISABLED) == 0)) {
1205 kn->kn_status |= KN_DISABLED;
1208 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1209 kn->kn_status &= ~KN_DISABLED;
1210 if ((kn->kn_status & KN_ACTIVE) &&
1211 ((kn->kn_status & KN_QUEUED) == 0))
1217 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1218 if (filedesc_unlock)
1219 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1225 kqueue_fo_release(filt);
1230 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1238 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1242 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1253 kqueue_release(struct kqueue *kq, int locked)
1260 if (kq->kq_refcnt == 1)
1261 wakeup(&kq->kq_refcnt);
1267 kqueue_schedtask(struct kqueue *kq)
1271 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1272 ("scheduling kqueue task while draining"));
1274 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1275 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1276 kq->kq_state |= KQ_TASKSCHED;
1281 * Expand the kq to make sure we have storage for fops/ident pair.
1283 * Return 0 on success (or no work necessary), return errno on failure.
1285 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1286 * If kqueue_register is called from a non-fd context, there usually/should
1290 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1293 struct klist *list, *tmp_knhash, *to_free;
1294 u_long tmp_knhashmask;
1297 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1304 if (kq->kq_knlistsize <= fd) {
1305 size = kq->kq_knlistsize;
1308 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1312 if (kq->kq_knlistsize > fd) {
1316 if (kq->kq_knlist != NULL) {
1317 bcopy(kq->kq_knlist, list,
1318 kq->kq_knlistsize * sizeof(*list));
1319 to_free = kq->kq_knlist;
1320 kq->kq_knlist = NULL;
1322 bzero((caddr_t)list +
1323 kq->kq_knlistsize * sizeof(*list),
1324 (size - kq->kq_knlistsize) * sizeof(*list));
1325 kq->kq_knlistsize = size;
1326 kq->kq_knlist = list;
1331 if (kq->kq_knhashmask == 0) {
1332 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1334 if (tmp_knhash == NULL)
1337 if (kq->kq_knhashmask == 0) {
1338 kq->kq_knhash = tmp_knhash;
1339 kq->kq_knhashmask = tmp_knhashmask;
1341 to_free = tmp_knhash;
1346 free(to_free, M_KQUEUE);
1353 kqueue_task(void *arg, int pending)
1361 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1364 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1366 kq->kq_state &= ~KQ_TASKSCHED;
1367 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1368 wakeup(&kq->kq_state);
1371 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1375 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1376 * We treat KN_MARKER knotes as if they are INFLUX.
1379 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1380 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1382 struct kevent *kevp;
1383 struct knote *kn, *marker;
1384 sbintime_t asbt, rsbt;
1385 int count, error, haskqglobal, influx, nkev, touch;
1397 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1398 tsp->tv_nsec >= 1000000000) {
1402 if (timespecisset(tsp)) {
1403 if (tsp->tv_sec <= INT32_MAX) {
1404 rsbt = tstosbt(*tsp);
1405 if (TIMESEL(&asbt, rsbt))
1406 asbt += tc_tick_sbt;
1407 if (asbt <= INT64_MAX - rsbt)
1411 rsbt >>= tc_precexp;
1418 marker = knote_alloc(1);
1419 if (marker == NULL) {
1423 marker->kn_status = KN_MARKER;
1428 if (kq->kq_count == 0) {
1430 error = EWOULDBLOCK;
1432 kq->kq_state |= KQ_SLEEP;
1433 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1434 "kqread", asbt, rsbt, C_ABSOLUTE);
1438 /* don't restart after signals... */
1439 if (error == ERESTART)
1441 else if (error == EWOULDBLOCK)
1446 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1450 kn = TAILQ_FIRST(&kq->kq_head);
1452 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1453 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1458 kq->kq_state |= KQ_FLUXWAIT;
1459 error = msleep(kq, &kq->kq_lock, PSOCK,
1464 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1465 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1466 kn->kn_status &= ~KN_QUEUED;
1472 if (count == maxevents)
1476 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1477 ("KN_INFLUX set when not suppose to be"));
1479 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1480 kn->kn_status &= ~KN_QUEUED;
1481 kn->kn_status |= KN_INFLUX;
1485 * We don't need to lock the list since we've marked
1488 if (!(kn->kn_status & KN_DETACHED))
1489 kn->kn_fop->f_detach(kn);
1493 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1494 kn->kn_status &= ~KN_QUEUED;
1495 kn->kn_status |= KN_INFLUX;
1499 * We don't need to lock the list since we've marked
1502 *kevp = kn->kn_kevent;
1503 if (!(kn->kn_status & KN_DETACHED))
1504 kn->kn_fop->f_detach(kn);
1509 kn->kn_status |= KN_INFLUX;
1511 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1512 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1514 if (kn->kn_fop->f_event(kn, 0) == 0) {
1516 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1518 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX);
1524 touch = (!kn->kn_fop->f_isfd &&
1525 kn->kn_fop->f_touch != NULL);
1527 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1529 *kevp = kn->kn_kevent;
1531 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1532 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1534 * Manually clear knotes who weren't
1537 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1541 if (kn->kn_flags & EV_DISPATCH)
1542 kn->kn_status |= KN_DISABLED;
1543 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1546 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1548 kn->kn_status &= ~(KN_INFLUX);
1553 /* we are returning a copy to the user */
1558 if (nkev == KQ_NEVENTS) {
1561 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1569 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1577 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1578 td->td_retval[0] = maxevents - count;
1584 * This could be expanded to call kqueue_scan, if desired.
1588 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1589 int flags, struct thread *td)
1596 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1597 int flags, struct thread *td)
1604 kqueue_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1613 kqueue_ioctl(struct file *fp, u_long cmd, void *data,
1614 struct ucred *active_cred, struct thread *td)
1617 * Enabling sigio causes two major problems:
1618 * 1) infinite recursion:
1619 * Synopsys: kevent is being used to track signals and have FIOASYNC
1620 * set. On receipt of a signal this will cause a kqueue to recurse
1621 * into itself over and over. Sending the sigio causes the kqueue
1622 * to become ready, which in turn posts sigio again, forever.
1623 * Solution: this can be solved by setting a flag in the kqueue that
1624 * we have a SIGIO in progress.
1625 * 2) locking problems:
1626 * Synopsys: Kqueue is a leaf subsystem, but adding signalling puts
1627 * us above the proc and pgrp locks.
1628 * Solution: Post a signal using an async mechanism, being sure to
1629 * record a generation count in the delivery so that we do not deliver
1630 * a signal to the wrong process.
1632 * Note, these two mechanisms are somewhat mutually exclusive!
1641 kq->kq_state |= KQ_ASYNC;
1643 kq->kq_state &= ~KQ_ASYNC;
1648 return (fsetown(*(int *)data, &kq->kq_sigio));
1651 *(int *)data = fgetown(&kq->kq_sigio);
1661 kqueue_poll(struct file *fp, int events, struct ucred *active_cred,
1668 if ((error = kqueue_acquire(fp, &kq)))
1672 if (events & (POLLIN | POLLRDNORM)) {
1674 revents |= events & (POLLIN | POLLRDNORM);
1676 selrecord(td, &kq->kq_sel);
1677 if (SEL_WAITING(&kq->kq_sel))
1678 kq->kq_state |= KQ_SEL;
1681 kqueue_release(kq, 1);
1688 kqueue_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
1692 bzero((void *)st, sizeof *st);
1694 * We no longer return kq_count because the unlocked value is useless.
1695 * If you spent all this time getting the count, why not spend your
1696 * syscall better by calling kevent?
1698 * XXX - This is needed for libc_r.
1700 st->st_mode = S_IFIFO;
1706 kqueue_close(struct file *fp, struct thread *td)
1708 struct kqueue *kq = fp->f_data;
1709 struct filedesc *fdp;
1713 int filedesc_unlock;
1715 if ((error = kqueue_acquire(fp, &kq)))
1718 filedesc_unlock = 0;
1721 KASSERT((kq->kq_state & KQ_CLOSING) != KQ_CLOSING,
1722 ("kqueue already closing"));
1723 kq->kq_state |= KQ_CLOSING;
1724 if (kq->kq_refcnt > 1)
1725 msleep(&kq->kq_refcnt, &kq->kq_lock, PSOCK, "kqclose", 0);
1727 KASSERT(kq->kq_refcnt == 1, ("other refs are out there!"));
1730 KASSERT(knlist_empty(&kq->kq_sel.si_note),
1731 ("kqueue's knlist not empty"));
1733 for (i = 0; i < kq->kq_knlistsize; i++) {
1734 while ((kn = SLIST_FIRST(&kq->kq_knlist[i])) != NULL) {
1735 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1736 kq->kq_state |= KQ_FLUXWAIT;
1737 msleep(kq, &kq->kq_lock, PSOCK, "kqclo1", 0);
1740 kn->kn_status |= KN_INFLUX;
1742 if (!(kn->kn_status & KN_DETACHED))
1743 kn->kn_fop->f_detach(kn);
1748 if (kq->kq_knhashmask != 0) {
1749 for (i = 0; i <= kq->kq_knhashmask; i++) {
1750 while ((kn = SLIST_FIRST(&kq->kq_knhash[i])) != NULL) {
1751 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1752 kq->kq_state |= KQ_FLUXWAIT;
1753 msleep(kq, &kq->kq_lock, PSOCK,
1757 kn->kn_status |= KN_INFLUX;
1759 if (!(kn->kn_status & KN_DETACHED))
1760 kn->kn_fop->f_detach(kn);
1767 if ((kq->kq_state & KQ_TASKSCHED) == KQ_TASKSCHED) {
1768 kq->kq_state |= KQ_TASKDRAIN;
1769 msleep(&kq->kq_state, &kq->kq_lock, PSOCK, "kqtqdr", 0);
1772 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1773 selwakeuppri(&kq->kq_sel, PSOCK);
1774 if (!SEL_WAITING(&kq->kq_sel))
1775 kq->kq_state &= ~KQ_SEL;
1781 * We could be called due to the knote_drop() doing fdrop(),
1782 * called from kqueue_register(). In this case the global
1783 * lock is owned, and filedesc sx is locked before, to not
1784 * take the sleepable lock after non-sleepable.
1786 if (!sx_xlocked(FILEDESC_LOCK(fdp))) {
1787 FILEDESC_XLOCK(fdp);
1788 filedesc_unlock = 1;
1790 filedesc_unlock = 0;
1791 TAILQ_REMOVE(&fdp->fd_kqlist, kq, kq_list);
1792 if (filedesc_unlock)
1793 FILEDESC_XUNLOCK(fdp);
1795 seldrain(&kq->kq_sel);
1796 knlist_destroy(&kq->kq_sel.si_note);
1797 mtx_destroy(&kq->kq_lock);
1800 if (kq->kq_knhash != NULL)
1801 free(kq->kq_knhash, M_KQUEUE);
1802 if (kq->kq_knlist != NULL)
1803 free(kq->kq_knlist, M_KQUEUE);
1805 funsetown(&kq->kq_sigio);
1806 chgkqcnt(kq->kq_cred->cr_ruidinfo, -1, 0);
1807 crfree(kq->kq_cred);
1815 kqueue_wakeup(struct kqueue *kq)
1819 if ((kq->kq_state & KQ_SLEEP) == KQ_SLEEP) {
1820 kq->kq_state &= ~KQ_SLEEP;
1823 if ((kq->kq_state & KQ_SEL) == KQ_SEL) {
1824 selwakeuppri(&kq->kq_sel, PSOCK);
1825 if (!SEL_WAITING(&kq->kq_sel))
1826 kq->kq_state &= ~KQ_SEL;
1828 if (!knlist_empty(&kq->kq_sel.si_note))
1829 kqueue_schedtask(kq);
1830 if ((kq->kq_state & KQ_ASYNC) == KQ_ASYNC) {
1831 pgsigio(&kq->kq_sigio, SIGIO, 0);
1836 * Walk down a list of knotes, activating them if their event has triggered.
1838 * There is a possibility to optimize in the case of one kq watching another.
1839 * Instead of scheduling a task to wake it up, you could pass enough state
1840 * down the chain to make up the parent kqueue. Make this code functional
1844 knote(struct knlist *list, long hint, int lockflags)
1853 KNL_ASSERT_LOCK(list, lockflags & KNF_LISTLOCKED);
1855 if ((lockflags & KNF_LISTLOCKED) == 0)
1856 list->kl_lock(list->kl_lockarg);
1859 * If we unlock the list lock (and set KN_INFLUX), we can eliminate
1860 * the kqueue scheduling, but this will introduce four
1861 * lock/unlock's for each knote to test. If we do, continue to use
1862 * SLIST_FOREACH, SLIST_FOREACH_SAFE is not safe in our case, it is
1863 * only safe if you want to remove the current item, which we are
1866 SLIST_FOREACH(kn, &list->kl_list, kn_selnext) {
1868 if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1870 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1872 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1873 kn->kn_status |= KN_INFLUX;
1875 error = kn->kn_fop->f_event(kn, hint);
1877 kn->kn_status &= ~KN_INFLUX;
1879 KNOTE_ACTIVATE(kn, 1);
1882 kn->kn_status |= KN_HASKQLOCK;
1883 if (kn->kn_fop->f_event(kn, hint))
1884 KNOTE_ACTIVATE(kn, 1);
1885 kn->kn_status &= ~KN_HASKQLOCK;
1891 if ((lockflags & KNF_LISTLOCKED) == 0)
1892 list->kl_unlock(list->kl_lockarg);
1896 * add a knote to a knlist
1899 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1901 KNL_ASSERT_LOCK(knl, islocked);
1902 KQ_NOTOWNED(kn->kn_kq);
1903 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1904 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1906 knl->kl_lock(knl->kl_lockarg);
1907 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1909 knl->kl_unlock(knl->kl_lockarg);
1911 kn->kn_knlist = knl;
1912 kn->kn_status &= ~KN_DETACHED;
1913 KQ_UNLOCK(kn->kn_kq);
1917 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1919 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1920 KNL_ASSERT_LOCK(knl, knlislocked);
1921 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1923 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1924 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1926 knl->kl_lock(knl->kl_lockarg);
1927 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1928 kn->kn_knlist = NULL;
1930 knl->kl_unlock(knl->kl_lockarg);
1933 kn->kn_status |= KN_DETACHED;
1935 KQ_UNLOCK(kn->kn_kq);
1939 * remove knote from the specified knlist
1942 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1945 knlist_remove_kq(knl, kn, islocked, 0);
1949 * remove knote from the specified knlist while in f_event handler.
1952 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1955 knlist_remove_kq(knl, kn, 1,
1956 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1960 knlist_empty(struct knlist *knl)
1963 KNL_ASSERT_LOCKED(knl);
1964 return SLIST_EMPTY(&knl->kl_list);
1967 static struct mtx knlist_lock;
1968 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1970 static void knlist_mtx_lock(void *arg);
1971 static void knlist_mtx_unlock(void *arg);
1974 knlist_mtx_lock(void *arg)
1977 mtx_lock((struct mtx *)arg);
1981 knlist_mtx_unlock(void *arg)
1984 mtx_unlock((struct mtx *)arg);
1988 knlist_mtx_assert_locked(void *arg)
1991 mtx_assert((struct mtx *)arg, MA_OWNED);
1995 knlist_mtx_assert_unlocked(void *arg)
1998 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
2002 knlist_rw_rlock(void *arg)
2005 rw_rlock((struct rwlock *)arg);
2009 knlist_rw_runlock(void *arg)
2012 rw_runlock((struct rwlock *)arg);
2016 knlist_rw_assert_locked(void *arg)
2019 rw_assert((struct rwlock *)arg, RA_LOCKED);
2023 knlist_rw_assert_unlocked(void *arg)
2026 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2030 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2031 void (*kl_unlock)(void *),
2032 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2036 knl->kl_lockarg = &knlist_lock;
2038 knl->kl_lockarg = lock;
2040 if (kl_lock == NULL)
2041 knl->kl_lock = knlist_mtx_lock;
2043 knl->kl_lock = kl_lock;
2044 if (kl_unlock == NULL)
2045 knl->kl_unlock = knlist_mtx_unlock;
2047 knl->kl_unlock = kl_unlock;
2048 if (kl_assert_locked == NULL)
2049 knl->kl_assert_locked = knlist_mtx_assert_locked;
2051 knl->kl_assert_locked = kl_assert_locked;
2052 if (kl_assert_unlocked == NULL)
2053 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2055 knl->kl_assert_unlocked = kl_assert_unlocked;
2057 SLIST_INIT(&knl->kl_list);
2061 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2064 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2068 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2071 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2072 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2076 knlist_destroy(struct knlist *knl)
2081 * if we run across this error, we need to find the offending
2082 * driver and have it call knlist_clear or knlist_delete.
2084 if (!SLIST_EMPTY(&knl->kl_list))
2085 printf("WARNING: destroying knlist w/ knotes on it!\n");
2088 knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2089 SLIST_INIT(&knl->kl_list);
2093 * Even if we are locked, we may need to drop the lock to allow any influx
2094 * knotes time to "settle".
2097 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2099 struct knote *kn, *kn2;
2103 KNL_ASSERT_LOCKED(knl);
2105 KNL_ASSERT_UNLOCKED(knl);
2106 again: /* need to reacquire lock since we have dropped it */
2107 knl->kl_lock(knl->kl_lockarg);
2110 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2113 if ((kn->kn_status & KN_INFLUX)) {
2117 knlist_remove_kq(knl, kn, 1, 1);
2119 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2123 /* Make sure cleared knotes disappear soon */
2124 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2130 if (!SLIST_EMPTY(&knl->kl_list)) {
2131 /* there are still KN_INFLUX remaining */
2132 kn = SLIST_FIRST(&knl->kl_list);
2135 KASSERT(kn->kn_status & KN_INFLUX,
2136 ("knote removed w/o list lock"));
2137 knl->kl_unlock(knl->kl_lockarg);
2138 kq->kq_state |= KQ_FLUXWAIT;
2139 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2145 KNL_ASSERT_LOCKED(knl);
2147 knl->kl_unlock(knl->kl_lockarg);
2148 KNL_ASSERT_UNLOCKED(knl);
2153 * Remove all knotes referencing a specified fd must be called with FILEDESC
2154 * lock. This prevents a race where a new fd comes along and occupies the
2155 * entry and we attach a knote to the fd.
2158 knote_fdclose(struct thread *td, int fd)
2160 struct filedesc *fdp = td->td_proc->p_fd;
2165 FILEDESC_XLOCK_ASSERT(fdp);
2168 * We shouldn't have to worry about new kevents appearing on fd
2169 * since filedesc is locked.
2171 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2176 while (kq->kq_knlistsize > fd &&
2177 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2178 if (kn->kn_status & KN_INFLUX) {
2179 /* someone else might be waiting on our knote */
2182 kq->kq_state |= KQ_FLUXWAIT;
2183 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2186 kn->kn_status |= KN_INFLUX;
2188 if (!(kn->kn_status & KN_DETACHED))
2189 kn->kn_fop->f_detach(kn);
2199 knote_attach(struct knote *kn, struct kqueue *kq)
2203 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2206 if (kn->kn_fop->f_isfd) {
2207 if (kn->kn_id >= kq->kq_knlistsize)
2209 list = &kq->kq_knlist[kn->kn_id];
2211 if (kq->kq_knhash == NULL)
2213 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2216 SLIST_INSERT_HEAD(list, kn, kn_link);
2222 * knote must already have been detached using the f_detach method.
2223 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2224 * to prevent other removal.
2227 knote_drop(struct knote *kn, struct thread *td)
2235 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2236 ("knote_drop called without KN_INFLUX set in kn_status"));
2239 if (kn->kn_fop->f_isfd)
2240 list = &kq->kq_knlist[kn->kn_id];
2242 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2244 if (!SLIST_EMPTY(list))
2245 SLIST_REMOVE(list, kn, knote, kn_link);
2246 if (kn->kn_status & KN_QUEUED)
2250 if (kn->kn_fop->f_isfd) {
2251 fdrop(kn->kn_fp, td);
2254 kqueue_fo_release(kn->kn_kevent.filter);
2260 knote_enqueue(struct knote *kn)
2262 struct kqueue *kq = kn->kn_kq;
2264 KQ_OWNED(kn->kn_kq);
2265 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2267 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2268 kn->kn_status |= KN_QUEUED;
2274 knote_dequeue(struct knote *kn)
2276 struct kqueue *kq = kn->kn_kq;
2278 KQ_OWNED(kn->kn_kq);
2279 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2281 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2282 kn->kn_status &= ~KN_QUEUED;
2290 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2291 NULL, NULL, UMA_ALIGN_PTR, 0);
2293 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2295 static struct knote *
2296 knote_alloc(int waitok)
2298 return ((struct knote *)uma_zalloc(knote_zone,
2299 (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2303 knote_free(struct knote *kn)
2306 uma_zfree(knote_zone, kn);
2310 * Register the kev w/ the kq specified by fd.
2313 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2317 cap_rights_t rights;
2320 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2323 if ((error = kqueue_acquire(fp, &kq)) != 0)
2326 error = kqueue_register(kq, kev, td, waitok);
2328 kqueue_release(kq, 0);