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"
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/capability.h>
37 #include <sys/kernel.h>
39 #include <sys/mutex.h>
40 #include <sys/rwlock.h>
42 #include <sys/malloc.h>
43 #include <sys/unistd.h>
45 #include <sys/filedesc.h>
46 #include <sys/filio.h>
47 #include <sys/fcntl.h>
48 #include <sys/kthread.h>
49 #include <sys/selinfo.h>
50 #include <sys/stdatomic.h>
51 #include <sys/queue.h>
52 #include <sys/event.h>
53 #include <sys/eventvar.h>
55 #include <sys/protosw.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sigio.h>
58 #include <sys/signalvar.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
62 #include <sys/sysctl.h>
63 #include <sys/sysproto.h>
64 #include <sys/syscallsubr.h>
65 #include <sys/taskqueue.h>
68 #include <sys/ktrace.h>
73 static MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
76 * This lock is used if multiple kq locks are required. This possibly
77 * should be made into a per proc lock.
79 static struct mtx kq_global;
80 MTX_SYSINIT(kq_global, &kq_global, "kqueue order", MTX_DEF);
81 #define KQ_GLOBAL_LOCK(lck, haslck) do { \
86 #define KQ_GLOBAL_UNLOCK(lck, haslck) do { \
92 TASKQUEUE_DEFINE_THREAD(kqueue);
94 static int kevent_copyout(void *arg, struct kevent *kevp, int count);
95 static int kevent_copyin(void *arg, struct kevent *kevp, int count);
96 static int kqueue_register(struct kqueue *kq, struct kevent *kev,
97 struct thread *td, int waitok);
98 static int kqueue_acquire(struct file *fp, struct kqueue **kqp);
99 static void kqueue_release(struct kqueue *kq, int locked);
100 static int kqueue_expand(struct kqueue *kq, struct filterops *fops,
101 uintptr_t ident, int waitok);
102 static void kqueue_task(void *arg, int pending);
103 static int kqueue_scan(struct kqueue *kq, int maxevents,
104 struct kevent_copyops *k_ops,
105 const struct timespec *timeout,
106 struct kevent *keva, struct thread *td);
107 static void kqueue_wakeup(struct kqueue *kq);
108 static struct filterops *kqueue_fo_find(int filt);
109 static void kqueue_fo_release(int filt);
111 static fo_rdwr_t kqueue_read;
112 static fo_rdwr_t kqueue_write;
113 static fo_truncate_t kqueue_truncate;
114 static fo_ioctl_t kqueue_ioctl;
115 static fo_poll_t kqueue_poll;
116 static fo_kqfilter_t kqueue_kqfilter;
117 static fo_stat_t kqueue_stat;
118 static fo_close_t kqueue_close;
120 static struct fileops kqueueops = {
121 .fo_read = kqueue_read,
122 .fo_write = kqueue_write,
123 .fo_truncate = kqueue_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,
134 static int knote_attach(struct knote *kn, struct kqueue *kq);
135 static void knote_drop(struct knote *kn, struct thread *td);
136 static void knote_enqueue(struct knote *kn);
137 static void knote_dequeue(struct knote *kn);
138 static void knote_init(void);
139 static struct knote *knote_alloc(int waitok);
140 static void knote_free(struct knote *kn);
142 static void filt_kqdetach(struct knote *kn);
143 static int filt_kqueue(struct knote *kn, long hint);
144 static int filt_procattach(struct knote *kn);
145 static void filt_procdetach(struct knote *kn);
146 static int filt_proc(struct knote *kn, long hint);
147 static int filt_fileattach(struct knote *kn);
148 static void filt_timerexpire(void *knx);
149 static int filt_timerattach(struct knote *kn);
150 static void filt_timerdetach(struct knote *kn);
151 static int filt_timer(struct knote *kn, long hint);
152 static int filt_userattach(struct knote *kn);
153 static void filt_userdetach(struct knote *kn);
154 static int filt_user(struct knote *kn, long hint);
155 static void filt_usertouch(struct knote *kn, struct kevent *kev,
158 static struct filterops file_filtops = {
160 .f_attach = filt_fileattach,
162 static struct filterops kqread_filtops = {
164 .f_detach = filt_kqdetach,
165 .f_event = filt_kqueue,
167 /* XXX - move to kern_proc.c? */
168 static struct filterops proc_filtops = {
170 .f_attach = filt_procattach,
171 .f_detach = filt_procdetach,
172 .f_event = filt_proc,
174 static struct filterops timer_filtops = {
176 .f_attach = filt_timerattach,
177 .f_detach = filt_timerdetach,
178 .f_event = filt_timer,
180 static struct filterops user_filtops = {
181 .f_attach = filt_userattach,
182 .f_detach = filt_userdetach,
183 .f_event = filt_user,
184 .f_touch = filt_usertouch,
187 static uma_zone_t knote_zone;
188 static atomic_uint kq_ncallouts = ATOMIC_VAR_INIT(0);
189 static unsigned int kq_calloutmax = 4 * 1024;
190 SYSCTL_UINT(_kern, OID_AUTO, kq_calloutmax, CTLFLAG_RW,
191 &kq_calloutmax, 0, "Maximum number of callouts allocated for kqueue");
193 /* XXX - ensure not KN_INFLUX?? */
194 #define KNOTE_ACTIVATE(kn, islock) do { \
196 mtx_assert(&(kn)->kn_kq->kq_lock, MA_OWNED); \
198 KQ_LOCK((kn)->kn_kq); \
199 (kn)->kn_status |= KN_ACTIVE; \
200 if (((kn)->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
201 knote_enqueue((kn)); \
203 KQ_UNLOCK((kn)->kn_kq); \
205 #define KQ_LOCK(kq) do { \
206 mtx_lock(&(kq)->kq_lock); \
208 #define KQ_FLUX_WAKEUP(kq) do { \
209 if (((kq)->kq_state & KQ_FLUXWAIT) == KQ_FLUXWAIT) { \
210 (kq)->kq_state &= ~KQ_FLUXWAIT; \
214 #define KQ_UNLOCK_FLUX(kq) do { \
215 KQ_FLUX_WAKEUP(kq); \
216 mtx_unlock(&(kq)->kq_lock); \
218 #define KQ_UNLOCK(kq) do { \
219 mtx_unlock(&(kq)->kq_lock); \
221 #define KQ_OWNED(kq) do { \
222 mtx_assert(&(kq)->kq_lock, MA_OWNED); \
224 #define KQ_NOTOWNED(kq) do { \
225 mtx_assert(&(kq)->kq_lock, MA_NOTOWNED); \
227 #define KN_LIST_LOCK(kn) do { \
228 if (kn->kn_knlist != NULL) \
229 kn->kn_knlist->kl_lock(kn->kn_knlist->kl_lockarg); \
231 #define KN_LIST_UNLOCK(kn) do { \
232 if (kn->kn_knlist != NULL) \
233 kn->kn_knlist->kl_unlock(kn->kn_knlist->kl_lockarg); \
235 #define KNL_ASSERT_LOCK(knl, islocked) do { \
237 KNL_ASSERT_LOCKED(knl); \
239 KNL_ASSERT_UNLOCKED(knl); \
242 #define KNL_ASSERT_LOCKED(knl) do { \
243 knl->kl_assert_locked((knl)->kl_lockarg); \
245 #define KNL_ASSERT_UNLOCKED(knl) do { \
246 knl->kl_assert_unlocked((knl)->kl_lockarg); \
248 #else /* !INVARIANTS */
249 #define KNL_ASSERT_LOCKED(knl) do {} while(0)
250 #define KNL_ASSERT_UNLOCKED(knl) do {} while (0)
251 #endif /* INVARIANTS */
253 #define KN_HASHSIZE 64 /* XXX should be tunable */
254 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
257 filt_nullattach(struct knote *kn)
263 struct filterops null_filtops = {
265 .f_attach = filt_nullattach,
268 /* XXX - make SYSINIT to add these, and move into respective modules. */
269 extern struct filterops sig_filtops;
270 extern struct filterops fs_filtops;
273 * Table for for all system-defined filters.
275 static struct mtx filterops_lock;
276 MTX_SYSINIT(kqueue_filterops, &filterops_lock, "protect sysfilt_ops",
279 struct filterops *for_fop;
281 } sysfilt_ops[EVFILT_SYSCOUNT] = {
282 { &file_filtops }, /* EVFILT_READ */
283 { &file_filtops }, /* EVFILT_WRITE */
284 { &null_filtops }, /* EVFILT_AIO */
285 { &file_filtops }, /* EVFILT_VNODE */
286 { &proc_filtops }, /* EVFILT_PROC */
287 { &sig_filtops }, /* EVFILT_SIGNAL */
288 { &timer_filtops }, /* EVFILT_TIMER */
289 { &null_filtops }, /* former EVFILT_NETDEV */
290 { &fs_filtops }, /* EVFILT_FS */
291 { &null_filtops }, /* EVFILT_LIO */
292 { &user_filtops }, /* EVFILT_USER */
296 * Simple redirection for all cdevsw style objects to call their fo_kqfilter
300 filt_fileattach(struct knote *kn)
303 return (fo_kqfilter(kn->kn_fp, kn));
308 kqueue_kqfilter(struct file *fp, struct knote *kn)
310 struct kqueue *kq = kn->kn_fp->f_data;
312 if (kn->kn_filter != EVFILT_READ)
315 kn->kn_status |= KN_KQUEUE;
316 kn->kn_fop = &kqread_filtops;
317 knlist_add(&kq->kq_sel.si_note, kn, 0);
323 filt_kqdetach(struct knote *kn)
325 struct kqueue *kq = kn->kn_fp->f_data;
327 knlist_remove(&kq->kq_sel.si_note, kn, 0);
332 filt_kqueue(struct knote *kn, long hint)
334 struct kqueue *kq = kn->kn_fp->f_data;
336 kn->kn_data = kq->kq_count;
337 return (kn->kn_data > 0);
340 /* XXX - move to kern_proc.c? */
342 filt_procattach(struct knote *kn)
349 p = pfind(kn->kn_id);
350 if (p == NULL && (kn->kn_sfflags & NOTE_EXIT)) {
351 p = zpfind(kn->kn_id);
353 } else if (p != NULL && (p->p_flag & P_WEXIT)) {
359 if ((error = p_cansee(curthread, p))) {
364 kn->kn_ptr.p_proc = p;
365 kn->kn_flags |= EV_CLEAR; /* automatically set */
368 * internal flag indicating registration done by kernel
370 if (kn->kn_flags & EV_FLAG1) {
371 kn->kn_data = kn->kn_sdata; /* ppid */
372 kn->kn_fflags = NOTE_CHILD;
373 kn->kn_flags &= ~EV_FLAG1;
377 knlist_add(&p->p_klist, kn, 1);
380 * Immediately activate any exit notes if the target process is a
381 * zombie. This is necessary to handle the case where the target
382 * process, e.g. a child, dies before the kevent is registered.
384 if (immediate && filt_proc(kn, NOTE_EXIT))
385 KNOTE_ACTIVATE(kn, 0);
393 * The knote may be attached to a different process, which may exit,
394 * leaving nothing for the knote to be attached to. So when the process
395 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
396 * it will be deleted when read out. However, as part of the knote deletion,
397 * this routine is called, so a check is needed to avoid actually performing
398 * a detach, because the original process does not exist any more.
400 /* XXX - move to kern_proc.c? */
402 filt_procdetach(struct knote *kn)
406 p = kn->kn_ptr.p_proc;
407 knlist_remove(&p->p_klist, kn, 0);
408 kn->kn_ptr.p_proc = NULL;
411 /* XXX - move to kern_proc.c? */
413 filt_proc(struct knote *kn, long hint)
415 struct proc *p = kn->kn_ptr.p_proc;
419 * mask off extra data
421 event = (u_int)hint & NOTE_PCTRLMASK;
424 * if the user is interested in this event, record it.
426 if (kn->kn_sfflags & event)
427 kn->kn_fflags |= event;
430 * 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_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.
526 static __inline sbintime_t
527 timer2sbintime(intptr_t data)
530 return (SBT_1MS * data);
534 filt_timerexpire(void *knx)
536 struct callout *calloutp;
541 KNOTE_ACTIVATE(kn, 0); /* XXX - handle locking */
543 if ((kn->kn_flags & EV_ONESHOT) != EV_ONESHOT) {
544 calloutp = (struct callout *)kn->kn_hook;
545 callout_reset_sbt_on(calloutp,
546 timer2sbintime(kn->kn_sdata), 0 /* 1ms? */,
547 filt_timerexpire, kn, PCPU_GET(cpuid), 0);
552 * data contains amount of time to sleep, in milliseconds
555 filt_timerattach(struct knote *kn)
557 struct callout *calloutp;
559 unsigned int ncallouts;
561 if ((intptr_t)kn->kn_sdata < 0)
563 if ((intptr_t)kn->kn_sdata == 0 && (kn->kn_flags & EV_ONESHOT) == 0)
565 to = timer2sbintime(kn->kn_sdata);
569 ncallouts = atomic_load_explicit(&kq_ncallouts, memory_order_relaxed);
571 if (ncallouts >= kq_calloutmax)
573 } while (!atomic_compare_exchange_weak_explicit(&kq_ncallouts,
574 &ncallouts, ncallouts + 1, memory_order_relaxed,
575 memory_order_relaxed));
577 kn->kn_flags |= EV_CLEAR; /* automatically set */
578 kn->kn_status &= ~KN_DETACHED; /* knlist_add clears it */
579 calloutp = malloc(sizeof(*calloutp), M_KQUEUE, M_WAITOK);
580 callout_init(calloutp, CALLOUT_MPSAFE);
581 kn->kn_hook = calloutp;
582 callout_reset_sbt_on(calloutp, to, 0 /* 1ms? */,
583 filt_timerexpire, kn, PCPU_GET(cpuid), 0);
589 filt_timerdetach(struct knote *kn)
591 struct callout *calloutp;
594 calloutp = (struct callout *)kn->kn_hook;
595 callout_drain(calloutp);
596 free(calloutp, M_KQUEUE);
597 old = atomic_fetch_sub_explicit(&kq_ncallouts, 1, memory_order_relaxed);
598 KASSERT(old > 0, ("Number of callouts cannot become negative"));
599 kn->kn_status |= KN_DETACHED; /* knlist_remove sets it */
603 filt_timer(struct knote *kn, long hint)
606 return (kn->kn_data != 0);
610 filt_userattach(struct knote *kn)
614 * EVFILT_USER knotes are not attached to anything in the kernel.
617 if (kn->kn_fflags & NOTE_TRIGGER)
625 filt_userdetach(__unused struct knote *kn)
629 * EVFILT_USER knotes are not attached to anything in the kernel.
634 filt_user(struct knote *kn, __unused long hint)
637 return (kn->kn_hookid);
641 filt_usertouch(struct knote *kn, struct kevent *kev, u_long type)
647 if (kev->fflags & NOTE_TRIGGER)
650 ffctrl = kev->fflags & NOTE_FFCTRLMASK;
651 kev->fflags &= NOTE_FFLAGSMASK;
657 kn->kn_sfflags &= kev->fflags;
661 kn->kn_sfflags |= kev->fflags;
665 kn->kn_sfflags = kev->fflags;
669 /* XXX Return error? */
672 kn->kn_sdata = kev->data;
673 if (kev->flags & EV_CLEAR) {
681 *kev = kn->kn_kevent;
682 kev->fflags = kn->kn_sfflags;
683 kev->data = kn->kn_sdata;
684 if (kn->kn_flags & EV_CLEAR) {
692 panic("filt_usertouch() - invalid type (%ld)", type);
698 sys_kqueue(struct thread *td, struct kqueue_args *uap)
700 struct filedesc *fdp;
711 if (!chgkqcnt(cred->cr_ruidinfo, 1, lim_cur(td->td_proc,
720 error = falloc(td, &fp, &fd, 0);
724 /* An extra reference on `fp' has been held for us by falloc(). */
725 kq = malloc(sizeof *kq, M_KQUEUE, M_WAITOK | M_ZERO);
726 mtx_init(&kq->kq_lock, "kqueue", NULL, MTX_DEF|MTX_DUPOK);
727 TAILQ_INIT(&kq->kq_head);
730 knlist_init_mtx(&kq->kq_sel.si_note, &kq->kq_lock);
731 TASK_INIT(&kq->kq_task, 0, kqueue_task, kq);
734 TAILQ_INSERT_HEAD(&fdp->fd_kqlist, kq, kq_list);
735 FILEDESC_XUNLOCK(fdp);
737 finit(fp, FREAD | FWRITE, DTYPE_KQUEUE, kq, &kqueueops);
740 td->td_retval[0] = fd;
743 chgkqcnt(cred->cr_ruidinfo, -1, 0);
749 #ifndef _SYS_SYSPROTO_H_
752 const struct kevent *changelist;
754 struct kevent *eventlist;
756 const struct timespec *timeout;
760 sys_kevent(struct thread *td, struct kevent_args *uap)
762 struct timespec ts, *tsp;
763 struct kevent_copyops k_ops = { uap,
770 struct uio *ktruioin = NULL;
771 struct uio *ktruioout = NULL;
774 if (uap->timeout != NULL) {
775 error = copyin(uap->timeout, &ts, sizeof(ts));
783 if (KTRPOINT(td, KTR_GENIO)) {
784 ktriov.iov_base = uap->changelist;
785 ktriov.iov_len = uap->nchanges * sizeof(struct kevent);
786 ktruio = (struct uio){ .uio_iov = &ktriov, .uio_iovcnt = 1,
787 .uio_segflg = UIO_USERSPACE, .uio_rw = UIO_READ,
789 ktruioin = cloneuio(&ktruio);
790 ktriov.iov_base = uap->eventlist;
791 ktriov.iov_len = uap->nevents * sizeof(struct kevent);
792 ktruioout = cloneuio(&ktruio);
796 error = kern_kevent(td, uap->fd, uap->nchanges, uap->nevents,
800 if (ktruioin != NULL) {
801 ktruioin->uio_resid = uap->nchanges * sizeof(struct kevent);
802 ktrgenio(uap->fd, UIO_WRITE, ktruioin, 0);
803 ktruioout->uio_resid = td->td_retval[0] * sizeof(struct kevent);
804 ktrgenio(uap->fd, UIO_READ, ktruioout, error);
812 * Copy 'count' items into the destination list pointed to by uap->eventlist.
815 kevent_copyout(void *arg, struct kevent *kevp, int count)
817 struct kevent_args *uap;
820 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
821 uap = (struct kevent_args *)arg;
823 error = copyout(kevp, uap->eventlist, count * sizeof *kevp);
825 uap->eventlist += count;
830 * Copy 'count' items from the list pointed to by uap->changelist.
833 kevent_copyin(void *arg, struct kevent *kevp, int count)
835 struct kevent_args *uap;
838 KASSERT(count <= KQ_NEVENTS, ("count (%d) > KQ_NEVENTS", count));
839 uap = (struct kevent_args *)arg;
841 error = copyin(uap->changelist, kevp, count * sizeof *kevp);
843 uap->changelist += count;
848 kern_kevent(struct thread *td, int fd, int nchanges, int nevents,
849 struct kevent_copyops *k_ops, const struct timespec *timeout)
851 struct kevent keva[KQ_NEVENTS];
852 struct kevent *kevp, *changes;
856 int i, n, nerrors, error;
858 cap_rights_init(&rights);
860 cap_rights_set(&rights, CAP_KQUEUE_CHANGE);
862 cap_rights_set(&rights, CAP_KQUEUE_EVENT);
863 error = fget(td, fd, &rights, &fp);
867 error = kqueue_acquire(fp, &kq);
873 while (nchanges > 0) {
874 n = nchanges > KQ_NEVENTS ? KQ_NEVENTS : nchanges;
875 error = k_ops->k_copyin(k_ops->arg, keva, n);
879 for (i = 0; i < n; i++) {
883 kevp->flags &= ~EV_SYSFLAGS;
884 error = kqueue_register(kq, kevp, td, 1);
885 if (error || (kevp->flags & EV_RECEIPT)) {
887 kevp->flags = EV_ERROR;
889 (void) k_ops->k_copyout(k_ops->arg,
901 td->td_retval[0] = nerrors;
906 error = kqueue_scan(kq, nevents, k_ops, timeout, keva, td);
908 kqueue_release(kq, 0);
915 kqueue_add_filteropts(int filt, struct filterops *filtops)
920 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0) {
922 "trying to add a filterop that is out of range: %d is beyond %d\n",
923 ~filt, EVFILT_SYSCOUNT);
926 mtx_lock(&filterops_lock);
927 if (sysfilt_ops[~filt].for_fop != &null_filtops &&
928 sysfilt_ops[~filt].for_fop != NULL)
931 sysfilt_ops[~filt].for_fop = filtops;
932 sysfilt_ops[~filt].for_refcnt = 0;
934 mtx_unlock(&filterops_lock);
940 kqueue_del_filteropts(int filt)
945 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
948 mtx_lock(&filterops_lock);
949 if (sysfilt_ops[~filt].for_fop == &null_filtops ||
950 sysfilt_ops[~filt].for_fop == NULL)
952 else if (sysfilt_ops[~filt].for_refcnt != 0)
955 sysfilt_ops[~filt].for_fop = &null_filtops;
956 sysfilt_ops[~filt].for_refcnt = 0;
958 mtx_unlock(&filterops_lock);
963 static struct filterops *
964 kqueue_fo_find(int filt)
967 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
970 mtx_lock(&filterops_lock);
971 sysfilt_ops[~filt].for_refcnt++;
972 if (sysfilt_ops[~filt].for_fop == NULL)
973 sysfilt_ops[~filt].for_fop = &null_filtops;
974 mtx_unlock(&filterops_lock);
976 return sysfilt_ops[~filt].for_fop;
980 kqueue_fo_release(int filt)
983 if (filt > 0 || filt + EVFILT_SYSCOUNT < 0)
986 mtx_lock(&filterops_lock);
987 KASSERT(sysfilt_ops[~filt].for_refcnt > 0,
988 ("filter object refcount not valid on release"));
989 sysfilt_ops[~filt].for_refcnt--;
990 mtx_unlock(&filterops_lock);
994 * A ref to kq (obtained via kqueue_acquire) must be held. waitok will
995 * influence if memory allocation should wait. Make sure it is 0 if you
999 kqueue_register(struct kqueue *kq, struct kevent *kev, struct thread *td, int waitok)
1001 struct filterops *fops;
1003 struct knote *kn, *tkn;
1004 cap_rights_t rights;
1005 int error, filt, event;
1006 int haskqglobal, filedesc_unlock;
1012 filedesc_unlock = 0;
1015 fops = kqueue_fo_find(filt);
1019 tkn = knote_alloc(waitok); /* prevent waiting with locks */
1023 KASSERT(td != NULL, ("td is NULL"));
1024 error = fget(td, kev->ident,
1025 cap_rights_init(&rights, CAP_EVENT), &fp);
1029 if ((kev->flags & EV_ADD) == EV_ADD && kqueue_expand(kq, fops,
1030 kev->ident, 0) != 0) {
1034 error = kqueue_expand(kq, fops, kev->ident, waitok);
1040 if (fp->f_type == DTYPE_KQUEUE) {
1042 * if we add some inteligence about what we are doing,
1043 * we should be able to support events on ourselves.
1044 * We need to know when we are doing this to prevent
1045 * getting both the knlist lock and the kq lock since
1046 * they are the same thing.
1048 if (fp->f_data == kq) {
1054 * Pre-lock the filedesc before the global
1055 * lock mutex, see the comment in
1058 FILEDESC_XLOCK(td->td_proc->p_fd);
1059 filedesc_unlock = 1;
1060 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1064 if (kev->ident < kq->kq_knlistsize) {
1065 SLIST_FOREACH(kn, &kq->kq_knlist[kev->ident], kn_link)
1066 if (kev->filter == kn->kn_filter)
1070 if ((kev->flags & EV_ADD) == EV_ADD)
1071 kqueue_expand(kq, fops, kev->ident, waitok);
1074 if (kq->kq_knhashmask != 0) {
1077 list = &kq->kq_knhash[
1078 KN_HASH((u_long)kev->ident, kq->kq_knhashmask)];
1079 SLIST_FOREACH(kn, list, kn_link)
1080 if (kev->ident == kn->kn_id &&
1081 kev->filter == kn->kn_filter)
1086 /* knote is in the process of changing, wait for it to stablize. */
1087 if (kn != NULL && (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1088 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1089 if (filedesc_unlock) {
1090 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1091 filedesc_unlock = 0;
1093 kq->kq_state |= KQ_FLUXWAIT;
1094 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqflxwt", 0);
1103 * kn now contains the matching knote, or NULL if no match
1106 if (kev->flags & EV_ADD) {
1118 * apply reference counts to knote structure, and
1119 * do not release it at the end of this routine.
1124 kn->kn_sfflags = kev->fflags;
1125 kn->kn_sdata = kev->data;
1128 kn->kn_kevent = *kev;
1129 kn->kn_kevent.flags &= ~(EV_ADD | EV_DELETE |
1130 EV_ENABLE | EV_DISABLE);
1131 kn->kn_status = KN_INFLUX|KN_DETACHED;
1133 error = knote_attach(kn, kq);
1140 if ((error = kn->kn_fop->f_attach(kn)) != 0) {
1147 /* No matching knote and the EV_ADD flag is not set. */
1154 if (kev->flags & EV_DELETE) {
1155 kn->kn_status |= KN_INFLUX;
1157 if (!(kn->kn_status & KN_DETACHED))
1158 kn->kn_fop->f_detach(kn);
1164 * The user may change some filter values after the initial EV_ADD,
1165 * but doing so will not reset any filter which has already been
1168 kn->kn_status |= KN_INFLUX;
1171 kn->kn_kevent.udata = kev->udata;
1172 if (!fops->f_isfd && fops->f_touch != NULL) {
1173 fops->f_touch(kn, kev, EVENT_REGISTER);
1175 kn->kn_sfflags = kev->fflags;
1176 kn->kn_sdata = kev->data;
1180 * We can get here with kn->kn_knlist == NULL. This can happen when
1181 * the initial attach event decides that the event is "completed"
1182 * already. i.e. filt_procattach is called on a zombie process. It
1183 * will call filt_proc which will remove it from the list, and NULL
1187 event = kn->kn_fop->f_event(kn, 0);
1190 KNOTE_ACTIVATE(kn, 1);
1191 kn->kn_status &= ~KN_INFLUX;
1194 if ((kev->flags & EV_DISABLE) &&
1195 ((kn->kn_status & KN_DISABLED) == 0)) {
1196 kn->kn_status |= KN_DISABLED;
1199 if ((kev->flags & EV_ENABLE) && (kn->kn_status & KN_DISABLED)) {
1200 kn->kn_status &= ~KN_DISABLED;
1201 if ((kn->kn_status & KN_ACTIVE) &&
1202 ((kn->kn_status & KN_QUEUED) == 0))
1208 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1209 if (filedesc_unlock)
1210 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1216 kqueue_fo_release(filt);
1221 kqueue_acquire(struct file *fp, struct kqueue **kqp)
1229 if (fp->f_type != DTYPE_KQUEUE || kq == NULL)
1233 if ((kq->kq_state & KQ_CLOSING) == KQ_CLOSING) {
1244 kqueue_release(struct kqueue *kq, int locked)
1251 if (kq->kq_refcnt == 1)
1252 wakeup(&kq->kq_refcnt);
1258 kqueue_schedtask(struct kqueue *kq)
1262 KASSERT(((kq->kq_state & KQ_TASKDRAIN) != KQ_TASKDRAIN),
1263 ("scheduling kqueue task while draining"));
1265 if ((kq->kq_state & KQ_TASKSCHED) != KQ_TASKSCHED) {
1266 taskqueue_enqueue(taskqueue_kqueue, &kq->kq_task);
1267 kq->kq_state |= KQ_TASKSCHED;
1272 * Expand the kq to make sure we have storage for fops/ident pair.
1274 * Return 0 on success (or no work necessary), return errno on failure.
1276 * Not calling hashinit w/ waitok (proper malloc flag) should be safe.
1277 * If kqueue_register is called from a non-fd context, there usually/should
1281 kqueue_expand(struct kqueue *kq, struct filterops *fops, uintptr_t ident,
1284 struct klist *list, *tmp_knhash, *to_free;
1285 u_long tmp_knhashmask;
1288 int mflag = waitok ? M_WAITOK : M_NOWAIT;
1295 if (kq->kq_knlistsize <= fd) {
1296 size = kq->kq_knlistsize;
1299 list = malloc(size * sizeof(*list), M_KQUEUE, mflag);
1303 if (kq->kq_knlistsize > fd) {
1307 if (kq->kq_knlist != NULL) {
1308 bcopy(kq->kq_knlist, list,
1309 kq->kq_knlistsize * sizeof(*list));
1310 to_free = kq->kq_knlist;
1311 kq->kq_knlist = NULL;
1313 bzero((caddr_t)list +
1314 kq->kq_knlistsize * sizeof(*list),
1315 (size - kq->kq_knlistsize) * sizeof(*list));
1316 kq->kq_knlistsize = size;
1317 kq->kq_knlist = list;
1322 if (kq->kq_knhashmask == 0) {
1323 tmp_knhash = hashinit(KN_HASHSIZE, M_KQUEUE,
1325 if (tmp_knhash == NULL)
1328 if (kq->kq_knhashmask == 0) {
1329 kq->kq_knhash = tmp_knhash;
1330 kq->kq_knhashmask = tmp_knhashmask;
1332 to_free = tmp_knhash;
1337 free(to_free, M_KQUEUE);
1344 kqueue_task(void *arg, int pending)
1352 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1355 KNOTE_LOCKED(&kq->kq_sel.si_note, 0);
1357 kq->kq_state &= ~KQ_TASKSCHED;
1358 if ((kq->kq_state & KQ_TASKDRAIN) == KQ_TASKDRAIN) {
1359 wakeup(&kq->kq_state);
1362 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1366 * Scan, update kn_data (if not ONESHOT), and copyout triggered events.
1367 * We treat KN_MARKER knotes as if they are INFLUX.
1370 kqueue_scan(struct kqueue *kq, int maxevents, struct kevent_copyops *k_ops,
1371 const struct timespec *tsp, struct kevent *keva, struct thread *td)
1373 struct kevent *kevp;
1374 struct knote *kn, *marker;
1375 sbintime_t asbt, rsbt;
1376 int count, error, haskqglobal, influx, nkev, touch;
1388 if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
1389 tsp->tv_nsec >= 1000000000) {
1393 if (timespecisset(tsp)) {
1394 if (tsp->tv_sec <= INT32_MAX) {
1395 rsbt = tstosbt(*tsp);
1396 if (TIMESEL(&asbt, rsbt))
1397 asbt += tc_tick_sbt;
1398 if (asbt <= INT64_MAX - rsbt)
1402 rsbt >>= tc_precexp;
1409 marker = knote_alloc(1);
1410 if (marker == NULL) {
1414 marker->kn_status = KN_MARKER;
1419 if (kq->kq_count == 0) {
1421 error = EWOULDBLOCK;
1423 kq->kq_state |= KQ_SLEEP;
1424 error = msleep_sbt(kq, &kq->kq_lock, PSOCK | PCATCH,
1425 "kqread", asbt, rsbt, C_ABSOLUTE);
1429 /* don't restart after signals... */
1430 if (error == ERESTART)
1432 else if (error == EWOULDBLOCK)
1437 TAILQ_INSERT_TAIL(&kq->kq_head, marker, kn_tqe);
1441 kn = TAILQ_FIRST(&kq->kq_head);
1443 if ((kn->kn_status == KN_MARKER && kn != marker) ||
1444 (kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1449 kq->kq_state |= KQ_FLUXWAIT;
1450 error = msleep(kq, &kq->kq_lock, PSOCK,
1455 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
1456 if ((kn->kn_status & KN_DISABLED) == KN_DISABLED) {
1457 kn->kn_status &= ~KN_QUEUED;
1463 if (count == maxevents)
1467 KASSERT((kn->kn_status & KN_INFLUX) == 0,
1468 ("KN_INFLUX set when not suppose to be"));
1470 if ((kn->kn_flags & EV_DROP) == EV_DROP) {
1471 kn->kn_status &= ~KN_QUEUED;
1472 kn->kn_status |= KN_INFLUX;
1476 * We don't need to lock the list since we've marked
1479 if (!(kn->kn_status & KN_DETACHED))
1480 kn->kn_fop->f_detach(kn);
1484 } else if ((kn->kn_flags & EV_ONESHOT) == EV_ONESHOT) {
1485 kn->kn_status &= ~KN_QUEUED;
1486 kn->kn_status |= KN_INFLUX;
1490 * We don't need to lock the list since we've marked
1493 *kevp = kn->kn_kevent;
1494 if (!(kn->kn_status & KN_DETACHED))
1495 kn->kn_fop->f_detach(kn);
1500 kn->kn_status |= KN_INFLUX;
1502 if ((kn->kn_status & KN_KQUEUE) == KN_KQUEUE)
1503 KQ_GLOBAL_LOCK(&kq_global, haskqglobal);
1505 if (kn->kn_fop->f_event(kn, 0) == 0) {
1507 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1509 ~(KN_QUEUED | KN_ACTIVE | KN_INFLUX);
1515 touch = (!kn->kn_fop->f_isfd &&
1516 kn->kn_fop->f_touch != NULL);
1518 kn->kn_fop->f_touch(kn, kevp, EVENT_PROCESS);
1520 *kevp = kn->kn_kevent;
1522 KQ_GLOBAL_UNLOCK(&kq_global, haskqglobal);
1523 if (kn->kn_flags & (EV_CLEAR | EV_DISPATCH)) {
1525 * Manually clear knotes who weren't
1528 if (touch == 0 && kn->kn_flags & EV_CLEAR) {
1532 if (kn->kn_flags & EV_DISPATCH)
1533 kn->kn_status |= KN_DISABLED;
1534 kn->kn_status &= ~(KN_QUEUED | KN_ACTIVE);
1537 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
1539 kn->kn_status &= ~(KN_INFLUX);
1544 /* we are returning a copy to the user */
1549 if (nkev == KQ_NEVENTS) {
1552 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1560 TAILQ_REMOVE(&kq->kq_head, marker, kn_tqe);
1568 error = k_ops->k_copyout(k_ops->arg, keva, nkev);
1569 td->td_retval[0] = maxevents - count;
1575 * This could be expanded to call kqueue_scan, if desired.
1579 kqueue_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
1580 int flags, struct thread *td)
1587 kqueue_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
1588 int flags, struct thread *td)
1595 kqueue_truncate(struct file *fp, off_t length, struct ucred *active_cred,
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) {
1859 if ((kn->kn_status & KN_INFLUX) != KN_INFLUX) {
1861 if ((kn->kn_status & KN_INFLUX) == KN_INFLUX) {
1863 } else if ((lockflags & KNF_NOKQLOCK) != 0) {
1864 kn->kn_status |= KN_INFLUX;
1866 error = kn->kn_fop->f_event(kn, hint);
1868 kn->kn_status &= ~KN_INFLUX;
1870 KNOTE_ACTIVATE(kn, 1);
1873 kn->kn_status |= KN_HASKQLOCK;
1874 if (kn->kn_fop->f_event(kn, hint))
1875 KNOTE_ACTIVATE(kn, 1);
1876 kn->kn_status &= ~KN_HASKQLOCK;
1882 if ((lockflags & KNF_LISTLOCKED) == 0)
1883 list->kl_unlock(list->kl_lockarg);
1887 * add a knote to a knlist
1890 knlist_add(struct knlist *knl, struct knote *kn, int islocked)
1892 KNL_ASSERT_LOCK(knl, islocked);
1893 KQ_NOTOWNED(kn->kn_kq);
1894 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) ==
1895 (KN_INFLUX|KN_DETACHED), ("knote not KN_INFLUX and KN_DETACHED"));
1897 knl->kl_lock(knl->kl_lockarg);
1898 SLIST_INSERT_HEAD(&knl->kl_list, kn, kn_selnext);
1900 knl->kl_unlock(knl->kl_lockarg);
1902 kn->kn_knlist = knl;
1903 kn->kn_status &= ~KN_DETACHED;
1904 KQ_UNLOCK(kn->kn_kq);
1908 knlist_remove_kq(struct knlist *knl, struct knote *kn, int knlislocked, int kqislocked)
1910 KASSERT(!(!!kqislocked && !knlislocked), ("kq locked w/o knl locked"));
1911 KNL_ASSERT_LOCK(knl, knlislocked);
1912 mtx_assert(&kn->kn_kq->kq_lock, kqislocked ? MA_OWNED : MA_NOTOWNED);
1914 KASSERT((kn->kn_status & (KN_INFLUX|KN_DETACHED)) == KN_INFLUX,
1915 ("knlist_remove called w/o knote being KN_INFLUX or already removed"));
1917 knl->kl_lock(knl->kl_lockarg);
1918 SLIST_REMOVE(&knl->kl_list, kn, knote, kn_selnext);
1919 kn->kn_knlist = NULL;
1921 knl->kl_unlock(knl->kl_lockarg);
1924 kn->kn_status |= KN_DETACHED;
1926 KQ_UNLOCK(kn->kn_kq);
1930 * remove knote from the specified knlist
1933 knlist_remove(struct knlist *knl, struct knote *kn, int islocked)
1936 knlist_remove_kq(knl, kn, islocked, 0);
1940 * remove knote from the specified knlist while in f_event handler.
1943 knlist_remove_inevent(struct knlist *knl, struct knote *kn)
1946 knlist_remove_kq(knl, kn, 1,
1947 (kn->kn_status & KN_HASKQLOCK) == KN_HASKQLOCK);
1951 knlist_empty(struct knlist *knl)
1954 KNL_ASSERT_LOCKED(knl);
1955 return SLIST_EMPTY(&knl->kl_list);
1958 static struct mtx knlist_lock;
1959 MTX_SYSINIT(knlist_lock, &knlist_lock, "knlist lock for lockless objects",
1961 static void knlist_mtx_lock(void *arg);
1962 static void knlist_mtx_unlock(void *arg);
1965 knlist_mtx_lock(void *arg)
1968 mtx_lock((struct mtx *)arg);
1972 knlist_mtx_unlock(void *arg)
1975 mtx_unlock((struct mtx *)arg);
1979 knlist_mtx_assert_locked(void *arg)
1982 mtx_assert((struct mtx *)arg, MA_OWNED);
1986 knlist_mtx_assert_unlocked(void *arg)
1989 mtx_assert((struct mtx *)arg, MA_NOTOWNED);
1993 knlist_rw_rlock(void *arg)
1996 rw_rlock((struct rwlock *)arg);
2000 knlist_rw_runlock(void *arg)
2003 rw_runlock((struct rwlock *)arg);
2007 knlist_rw_assert_locked(void *arg)
2010 rw_assert((struct rwlock *)arg, RA_LOCKED);
2014 knlist_rw_assert_unlocked(void *arg)
2017 rw_assert((struct rwlock *)arg, RA_UNLOCKED);
2021 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
2022 void (*kl_unlock)(void *),
2023 void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *))
2027 knl->kl_lockarg = &knlist_lock;
2029 knl->kl_lockarg = lock;
2031 if (kl_lock == NULL)
2032 knl->kl_lock = knlist_mtx_lock;
2034 knl->kl_lock = kl_lock;
2035 if (kl_unlock == NULL)
2036 knl->kl_unlock = knlist_mtx_unlock;
2038 knl->kl_unlock = kl_unlock;
2039 if (kl_assert_locked == NULL)
2040 knl->kl_assert_locked = knlist_mtx_assert_locked;
2042 knl->kl_assert_locked = kl_assert_locked;
2043 if (kl_assert_unlocked == NULL)
2044 knl->kl_assert_unlocked = knlist_mtx_assert_unlocked;
2046 knl->kl_assert_unlocked = kl_assert_unlocked;
2048 SLIST_INIT(&knl->kl_list);
2052 knlist_init_mtx(struct knlist *knl, struct mtx *lock)
2055 knlist_init(knl, lock, NULL, NULL, NULL, NULL);
2059 knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
2062 knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
2063 knlist_rw_assert_locked, knlist_rw_assert_unlocked);
2067 knlist_destroy(struct knlist *knl)
2072 * if we run across this error, we need to find the offending
2073 * driver and have it call knlist_clear or knlist_delete.
2075 if (!SLIST_EMPTY(&knl->kl_list))
2076 printf("WARNING: destroying knlist w/ knotes on it!\n");
2079 knl->kl_lockarg = knl->kl_lock = knl->kl_unlock = NULL;
2080 SLIST_INIT(&knl->kl_list);
2084 * Even if we are locked, we may need to drop the lock to allow any influx
2085 * knotes time to "settle".
2088 knlist_cleardel(struct knlist *knl, struct thread *td, int islocked, int killkn)
2090 struct knote *kn, *kn2;
2094 KNL_ASSERT_LOCKED(knl);
2096 KNL_ASSERT_UNLOCKED(knl);
2097 again: /* need to reacquire lock since we have dropped it */
2098 knl->kl_lock(knl->kl_lockarg);
2101 SLIST_FOREACH_SAFE(kn, &knl->kl_list, kn_selnext, kn2) {
2104 if ((kn->kn_status & KN_INFLUX)) {
2108 knlist_remove_kq(knl, kn, 1, 1);
2110 kn->kn_status |= KN_INFLUX | KN_DETACHED;
2114 /* Make sure cleared knotes disappear soon */
2115 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2121 if (!SLIST_EMPTY(&knl->kl_list)) {
2122 /* there are still KN_INFLUX remaining */
2123 kn = SLIST_FIRST(&knl->kl_list);
2126 KASSERT(kn->kn_status & KN_INFLUX,
2127 ("knote removed w/o list lock"));
2128 knl->kl_unlock(knl->kl_lockarg);
2129 kq->kq_state |= KQ_FLUXWAIT;
2130 msleep(kq, &kq->kq_lock, PSOCK | PDROP, "kqkclr", 0);
2136 KNL_ASSERT_LOCKED(knl);
2138 knl->kl_unlock(knl->kl_lockarg);
2139 KNL_ASSERT_UNLOCKED(knl);
2144 * Remove all knotes referencing a specified fd must be called with FILEDESC
2145 * lock. This prevents a race where a new fd comes along and occupies the
2146 * entry and we attach a knote to the fd.
2149 knote_fdclose(struct thread *td, int fd)
2151 struct filedesc *fdp = td->td_proc->p_fd;
2156 FILEDESC_XLOCK_ASSERT(fdp);
2159 * We shouldn't have to worry about new kevents appearing on fd
2160 * since filedesc is locked.
2162 TAILQ_FOREACH(kq, &fdp->fd_kqlist, kq_list) {
2167 while (kq->kq_knlistsize > fd &&
2168 (kn = SLIST_FIRST(&kq->kq_knlist[fd])) != NULL) {
2169 if (kn->kn_status & KN_INFLUX) {
2170 /* someone else might be waiting on our knote */
2173 kq->kq_state |= KQ_FLUXWAIT;
2174 msleep(kq, &kq->kq_lock, PSOCK, "kqflxwt", 0);
2177 kn->kn_status |= KN_INFLUX;
2179 if (!(kn->kn_status & KN_DETACHED))
2180 kn->kn_fop->f_detach(kn);
2190 knote_attach(struct knote *kn, struct kqueue *kq)
2194 KASSERT(kn->kn_status & KN_INFLUX, ("knote not marked INFLUX"));
2197 if (kn->kn_fop->f_isfd) {
2198 if (kn->kn_id >= kq->kq_knlistsize)
2200 list = &kq->kq_knlist[kn->kn_id];
2202 if (kq->kq_knhash == NULL)
2204 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2207 SLIST_INSERT_HEAD(list, kn, kn_link);
2213 * knote must already have been detached using the f_detach method.
2214 * no lock need to be held, it is assumed that the KN_INFLUX flag is set
2215 * to prevent other removal.
2218 knote_drop(struct knote *kn, struct thread *td)
2226 KASSERT((kn->kn_status & KN_INFLUX) == KN_INFLUX,
2227 ("knote_drop called without KN_INFLUX set in kn_status"));
2230 if (kn->kn_fop->f_isfd)
2231 list = &kq->kq_knlist[kn->kn_id];
2233 list = &kq->kq_knhash[KN_HASH(kn->kn_id, kq->kq_knhashmask)];
2235 if (!SLIST_EMPTY(list))
2236 SLIST_REMOVE(list, kn, knote, kn_link);
2237 if (kn->kn_status & KN_QUEUED)
2241 if (kn->kn_fop->f_isfd) {
2242 fdrop(kn->kn_fp, td);
2245 kqueue_fo_release(kn->kn_kevent.filter);
2251 knote_enqueue(struct knote *kn)
2253 struct kqueue *kq = kn->kn_kq;
2255 KQ_OWNED(kn->kn_kq);
2256 KASSERT((kn->kn_status & KN_QUEUED) == 0, ("knote already queued"));
2258 TAILQ_INSERT_TAIL(&kq->kq_head, kn, kn_tqe);
2259 kn->kn_status |= KN_QUEUED;
2265 knote_dequeue(struct knote *kn)
2267 struct kqueue *kq = kn->kn_kq;
2269 KQ_OWNED(kn->kn_kq);
2270 KASSERT(kn->kn_status & KN_QUEUED, ("knote not queued"));
2272 TAILQ_REMOVE(&kq->kq_head, kn, kn_tqe);
2273 kn->kn_status &= ~KN_QUEUED;
2281 knote_zone = uma_zcreate("KNOTE", sizeof(struct knote), NULL, NULL,
2282 NULL, NULL, UMA_ALIGN_PTR, 0);
2284 SYSINIT(knote, SI_SUB_PSEUDO, SI_ORDER_ANY, knote_init, NULL);
2286 static struct knote *
2287 knote_alloc(int waitok)
2289 return ((struct knote *)uma_zalloc(knote_zone,
2290 (waitok ? M_WAITOK : M_NOWAIT)|M_ZERO));
2294 knote_free(struct knote *kn)
2297 uma_zfree(knote_zone, kn);
2301 * Register the kev w/ the kq specified by fd.
2304 kqfd_register(int fd, struct kevent *kev, struct thread *td, int waitok)
2308 cap_rights_t rights;
2311 error = fget(td, fd, cap_rights_init(&rights, CAP_KQUEUE_CHANGE), &fp);
2314 if ((error = kqueue_acquire(fp, &kq)) != 0)
2317 error = kqueue_register(kq, kev, td, waitok);
2319 kqueue_release(kq, 0);