2 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * $FreeBSD: src/sys/kern/kern_event.c,v 1.2.2.10 2004/04/04 07:03:14 cperciva Exp $
27 * $DragonFly: src/sys/kern/kern_event.c,v 1.33 2007/02/03 17:05:57 corecode Exp $
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
34 #include <sys/malloc.h>
35 #include <sys/unistd.h>
38 #include <sys/fcntl.h>
39 #include <sys/queue.h>
40 #include <sys/event.h>
41 #include <sys/eventvar.h>
42 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #include <sys/socketvar.h>
46 #include <sys/sysctl.h>
47 #include <sys/sysproto.h>
48 #include <sys/thread.h>
50 #include <sys/signalvar.h>
51 #include <sys/filio.h>
54 #include <sys/thread2.h>
55 #include <sys/file2.h>
56 #include <sys/mplock2.h>
58 #include <vm/vm_zone.h>
61 * Global token for kqueue subsystem
63 struct lwkt_token kq_token
= LWKT_TOKEN_UP_INITIALIZER(kq_token
);
64 SYSCTL_INT(_lwkt
, OID_AUTO
, kq_mpsafe
,
65 CTLFLAG_RW
, &kq_token
.t_flags
, 0, "");
66 SYSCTL_LONG(_lwkt
, OID_AUTO
, kq_collisions
,
67 CTLFLAG_RW
, &kq_token
.t_collisions
, 0, "");
69 MALLOC_DEFINE(M_KQUEUE
, "kqueue", "memory for kqueue system");
71 struct kevent_copyin_args
{
72 struct kevent_args
*ka
;
76 static int kqueue_sleep(struct kqueue
*kq
, struct timespec
*tsp
);
77 static int kqueue_scan(struct kqueue
*kq
, struct kevent
*kevp
, int count
,
78 struct knote
*marker
);
79 static int kqueue_read(struct file
*fp
, struct uio
*uio
,
80 struct ucred
*cred
, int flags
);
81 static int kqueue_write(struct file
*fp
, struct uio
*uio
,
82 struct ucred
*cred
, int flags
);
83 static int kqueue_ioctl(struct file
*fp
, u_long com
, caddr_t data
,
84 struct ucred
*cred
, struct sysmsg
*msg
);
85 static int kqueue_kqfilter(struct file
*fp
, struct knote
*kn
);
86 static int kqueue_stat(struct file
*fp
, struct stat
*st
,
88 static int kqueue_close(struct file
*fp
);
89 static void kqueue_wakeup(struct kqueue
*kq
);
90 static int filter_attach(struct knote
*kn
);
91 static int filter_event(struct knote
*kn
, long hint
);
96 static struct fileops kqueueops
= {
97 .fo_read
= kqueue_read
,
98 .fo_write
= kqueue_write
,
99 .fo_ioctl
= kqueue_ioctl
,
100 .fo_kqfilter
= kqueue_kqfilter
,
101 .fo_stat
= kqueue_stat
,
102 .fo_close
= kqueue_close
,
103 .fo_shutdown
= nofo_shutdown
106 static void knote_attach(struct knote
*kn
);
107 static void knote_drop(struct knote
*kn
);
108 static void knote_detach_and_drop(struct knote
*kn
);
109 static void knote_enqueue(struct knote
*kn
);
110 static void knote_dequeue(struct knote
*kn
);
111 static void knote_init(void);
112 static struct knote
*knote_alloc(void);
113 static void knote_free(struct knote
*kn
);
115 static void filt_kqdetach(struct knote
*kn
);
116 static int filt_kqueue(struct knote
*kn
, long hint
);
117 static int filt_procattach(struct knote
*kn
);
118 static void filt_procdetach(struct knote
*kn
);
119 static int filt_proc(struct knote
*kn
, long hint
);
120 static int filt_fileattach(struct knote
*kn
);
121 static void filt_timerexpire(void *knx
);
122 static int filt_timerattach(struct knote
*kn
);
123 static void filt_timerdetach(struct knote
*kn
);
124 static int filt_timer(struct knote
*kn
, long hint
);
126 static struct filterops file_filtops
=
127 { FILTEROP_ISFD
, filt_fileattach
, NULL
, NULL
};
128 static struct filterops kqread_filtops
=
129 { FILTEROP_ISFD
, NULL
, filt_kqdetach
, filt_kqueue
};
130 static struct filterops proc_filtops
=
131 { 0, filt_procattach
, filt_procdetach
, filt_proc
};
132 static struct filterops timer_filtops
=
133 { 0, filt_timerattach
, filt_timerdetach
, filt_timer
};
135 static vm_zone_t knote_zone
;
136 static int kq_ncallouts
= 0;
137 static int kq_calloutmax
= (4 * 1024);
138 SYSCTL_INT(_kern
, OID_AUTO
, kq_calloutmax
, CTLFLAG_RW
,
139 &kq_calloutmax
, 0, "Maximum number of callouts allocated for kqueue");
140 static int kq_checkloop
= 1000000;
141 SYSCTL_INT(_kern
, OID_AUTO
, kq_checkloop
, CTLFLAG_RW
,
142 &kq_checkloop
, 0, "Maximum number of callouts allocated for kqueue");
144 #define KNOTE_ACTIVATE(kn) do { \
145 kn->kn_status |= KN_ACTIVE; \
146 if ((kn->kn_status & (KN_QUEUED | KN_DISABLED)) == 0) \
150 #define KN_HASHSIZE 64 /* XXX should be tunable */
151 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
153 extern struct filterops aio_filtops
;
154 extern struct filterops sig_filtops
;
157 * Table for for all system-defined filters.
159 static struct filterops
*sysfilt_ops
[] = {
160 &file_filtops
, /* EVFILT_READ */
161 &file_filtops
, /* EVFILT_WRITE */
162 &aio_filtops
, /* EVFILT_AIO */
163 &file_filtops
, /* EVFILT_VNODE */
164 &proc_filtops
, /* EVFILT_PROC */
165 &sig_filtops
, /* EVFILT_SIGNAL */
166 &timer_filtops
, /* EVFILT_TIMER */
167 &file_filtops
, /* EVFILT_EXCEPT */
171 filt_fileattach(struct knote
*kn
)
173 return (fo_kqfilter(kn
->kn_fp
, kn
));
180 kqueue_kqfilter(struct file
*fp
, struct knote
*kn
)
182 struct kqueue
*kq
= (struct kqueue
*)kn
->kn_fp
->f_data
;
184 if (kn
->kn_filter
!= EVFILT_READ
)
187 kn
->kn_fop
= &kqread_filtops
;
188 knote_insert(&kq
->kq_kqinfo
.ki_note
, kn
);
193 filt_kqdetach(struct knote
*kn
)
195 struct kqueue
*kq
= (struct kqueue
*)kn
->kn_fp
->f_data
;
197 knote_remove(&kq
->kq_kqinfo
.ki_note
, kn
);
202 filt_kqueue(struct knote
*kn
, long hint
)
204 struct kqueue
*kq
= (struct kqueue
*)kn
->kn_fp
->f_data
;
206 kn
->kn_data
= kq
->kq_count
;
207 return (kn
->kn_data
> 0);
211 filt_procattach(struct knote
*kn
)
217 lwkt_gettoken(&proc_token
);
218 p
= pfind(kn
->kn_id
);
219 if (p
== NULL
&& (kn
->kn_sfflags
& NOTE_EXIT
)) {
220 p
= zpfind(kn
->kn_id
);
224 lwkt_reltoken(&proc_token
);
227 if (!PRISON_CHECK(curthread
->td_ucred
, p
->p_ucred
)) {
228 lwkt_reltoken(&proc_token
);
232 kn
->kn_ptr
.p_proc
= p
;
233 kn
->kn_flags
|= EV_CLEAR
; /* automatically set */
236 * internal flag indicating registration done by kernel
238 if (kn
->kn_flags
& EV_FLAG1
) {
239 kn
->kn_data
= kn
->kn_sdata
; /* ppid */
240 kn
->kn_fflags
= NOTE_CHILD
;
241 kn
->kn_flags
&= ~EV_FLAG1
;
244 knote_insert(&p
->p_klist
, kn
);
247 * Immediately activate any exit notes if the target process is a
248 * zombie. This is necessary to handle the case where the target
249 * process, e.g. a child, dies before the kevent is negistered.
251 if (immediate
&& filt_proc(kn
, NOTE_EXIT
))
253 lwkt_reltoken(&proc_token
);
259 * The knote may be attached to a different process, which may exit,
260 * leaving nothing for the knote to be attached to. So when the process
261 * exits, the knote is marked as DETACHED and also flagged as ONESHOT so
262 * it will be deleted when read out. However, as part of the knote deletion,
263 * this routine is called, so a check is needed to avoid actually performing
264 * a detach, because the original process does not exist any more.
267 filt_procdetach(struct knote
*kn
)
271 if (kn
->kn_status
& KN_DETACHED
)
273 /* XXX locking? take proc_token here? */
274 p
= kn
->kn_ptr
.p_proc
;
275 knote_remove(&p
->p_klist
, kn
);
279 filt_proc(struct knote
*kn
, long hint
)
284 * mask off extra data
286 event
= (u_int
)hint
& NOTE_PCTRLMASK
;
289 * if the user is interested in this event, record it.
291 if (kn
->kn_sfflags
& event
)
292 kn
->kn_fflags
|= event
;
295 * Process is gone, so flag the event as finished. Detach the
296 * knote from the process now because the process will be poof,
299 if (event
== NOTE_EXIT
) {
300 struct proc
*p
= kn
->kn_ptr
.p_proc
;
301 if ((kn
->kn_status
& KN_DETACHED
) == 0) {
302 knote_remove(&p
->p_klist
, kn
);
303 kn
->kn_status
|= KN_DETACHED
;
304 kn
->kn_data
= p
->p_xstat
;
305 kn
->kn_ptr
.p_proc
= NULL
;
307 kn
->kn_flags
|= (EV_EOF
| EV_ONESHOT
);
312 * process forked, and user wants to track the new process,
313 * so attach a new knote to it, and immediately report an
314 * event with the parent's pid.
316 if ((event
== NOTE_FORK
) && (kn
->kn_sfflags
& NOTE_TRACK
)) {
321 * register knote with new process.
323 kev
.ident
= hint
& NOTE_PDATAMASK
; /* pid */
324 kev
.filter
= kn
->kn_filter
;
325 kev
.flags
= kn
->kn_flags
| EV_ADD
| EV_ENABLE
| EV_FLAG1
;
326 kev
.fflags
= kn
->kn_sfflags
;
327 kev
.data
= kn
->kn_id
; /* parent */
328 kev
.udata
= kn
->kn_kevent
.udata
; /* preserve udata */
329 error
= kqueue_register(kn
->kn_kq
, &kev
);
331 kn
->kn_fflags
|= NOTE_TRACKERR
;
334 return (kn
->kn_fflags
!= 0);
338 * The callout interlocks with callout_stop() (or should), so the
339 * knote should still be a valid structure. However the timeout
340 * can race a deletion so if KN_DELETING is set we just don't touch
344 filt_timerexpire(void *knx
)
346 struct knote
*kn
= knx
;
347 struct callout
*calloutp
;
351 lwkt_gettoken(&kq_token
);
352 if ((kn
->kn_status
& KN_DELETING
) == 0) {
356 if ((kn
->kn_flags
& EV_ONESHOT
) == 0) {
357 tv
.tv_sec
= kn
->kn_sdata
/ 1000;
358 tv
.tv_usec
= (kn
->kn_sdata
% 1000) * 1000;
359 tticks
= tvtohz_high(&tv
);
360 calloutp
= (struct callout
*)kn
->kn_hook
;
361 callout_reset(calloutp
, tticks
, filt_timerexpire
, kn
);
364 lwkt_reltoken(&kq_token
);
368 * data contains amount of time to sleep, in milliseconds
371 filt_timerattach(struct knote
*kn
)
373 struct callout
*calloutp
;
377 if (kq_ncallouts
>= kq_calloutmax
)
381 tv
.tv_sec
= kn
->kn_sdata
/ 1000;
382 tv
.tv_usec
= (kn
->kn_sdata
% 1000) * 1000;
383 tticks
= tvtohz_high(&tv
);
385 kn
->kn_flags
|= EV_CLEAR
; /* automatically set */
386 MALLOC(calloutp
, struct callout
*, sizeof(*calloutp
),
388 callout_init(calloutp
);
389 kn
->kn_hook
= (caddr_t
)calloutp
;
390 callout_reset(calloutp
, tticks
, filt_timerexpire
, kn
);
396 filt_timerdetach(struct knote
*kn
)
398 struct callout
*calloutp
;
400 calloutp
= (struct callout
*)kn
->kn_hook
;
401 callout_stop(calloutp
);
402 FREE(calloutp
, M_KQUEUE
);
407 filt_timer(struct knote
*kn
, long hint
)
410 return (kn
->kn_data
!= 0);
414 * Acquire a knote, return non-zero on success, 0 on failure.
416 * If we cannot acquire the knote we sleep and return 0. The knote
417 * may be stale on return in this case and the caller must restart
418 * whatever loop they are in.
422 knote_acquire(struct knote
*kn
)
424 if (kn
->kn_status
& KN_PROCESSING
) {
425 kn
->kn_status
|= KN_WAITING
| KN_REPROCESS
;
426 tsleep(kn
, 0, "kqepts", hz
);
427 /* knote may be stale now */
430 kn
->kn_status
|= KN_PROCESSING
;
435 * Release an acquired knote, clearing KN_PROCESSING and handling any
436 * KN_REPROCESS events.
438 * Non-zero is returned if the knote is destroyed.
442 knote_release(struct knote
*kn
)
444 while (kn
->kn_status
& KN_REPROCESS
) {
445 kn
->kn_status
&= ~KN_REPROCESS
;
446 if (kn
->kn_status
& KN_WAITING
) {
447 kn
->kn_status
&= ~KN_WAITING
;
450 if (kn
->kn_status
& KN_DELETING
) {
451 knote_detach_and_drop(kn
);
455 if (filter_event(kn
, 0))
458 kn
->kn_status
&= ~KN_PROCESSING
;
463 * Initialize a kqueue.
465 * NOTE: The lwp/proc code initializes a kqueue for select/poll ops.
470 kqueue_init(struct kqueue
*kq
, struct filedesc
*fdp
)
472 TAILQ_INIT(&kq
->kq_knpend
);
473 TAILQ_INIT(&kq
->kq_knlist
);
476 SLIST_INIT(&kq
->kq_kqinfo
.ki_note
);
480 * Terminate a kqueue. Freeing the actual kq itself is left up to the
481 * caller (it might be embedded in a lwp so we don't do it here).
483 * The kq's knlist must be completely eradicated so block on any
487 kqueue_terminate(struct kqueue
*kq
)
491 lwkt_gettoken(&kq_token
);
492 while ((kn
= TAILQ_FIRST(&kq
->kq_knlist
)) != NULL
) {
493 if (knote_acquire(kn
))
494 knote_detach_and_drop(kn
);
497 kfree(kq
->kq_knhash
, M_KQUEUE
);
498 kq
->kq_knhash
= NULL
;
499 kq
->kq_knhashmask
= 0;
501 lwkt_reltoken(&kq_token
);
508 sys_kqueue(struct kqueue_args
*uap
)
510 struct thread
*td
= curthread
;
515 error
= falloc(td
->td_lwp
, &fp
, &fd
);
518 fp
->f_flag
= FREAD
| FWRITE
;
519 fp
->f_type
= DTYPE_KQUEUE
;
520 fp
->f_ops
= &kqueueops
;
522 kq
= kmalloc(sizeof(struct kqueue
), M_KQUEUE
, M_WAITOK
| M_ZERO
);
523 kqueue_init(kq
, td
->td_proc
->p_fd
);
526 fsetfd(kq
->kq_fdp
, fp
, fd
);
527 uap
->sysmsg_result
= fd
;
533 * Copy 'count' items into the destination list pointed to by uap->eventlist.
536 kevent_copyout(void *arg
, struct kevent
*kevp
, int count
, int *res
)
538 struct kevent_copyin_args
*kap
;
541 kap
= (struct kevent_copyin_args
*)arg
;
543 error
= copyout(kevp
, kap
->ka
->eventlist
, count
* sizeof(*kevp
));
545 kap
->ka
->eventlist
+= count
;
555 * Copy at most 'max' items from the list pointed to by kap->changelist,
556 * return number of items in 'events'.
559 kevent_copyin(void *arg
, struct kevent
*kevp
, int max
, int *events
)
561 struct kevent_copyin_args
*kap
;
564 kap
= (struct kevent_copyin_args
*)arg
;
566 count
= min(kap
->ka
->nchanges
- kap
->pchanges
, max
);
567 error
= copyin(kap
->ka
->changelist
, kevp
, count
* sizeof *kevp
);
569 kap
->ka
->changelist
+= count
;
570 kap
->pchanges
+= count
;
581 kern_kevent(struct kqueue
*kq
, int nevents
, int *res
, void *uap
,
582 k_copyin_fn kevent_copyinfn
, k_copyout_fn kevent_copyoutfn
,
583 struct timespec
*tsp_in
)
586 struct timespec
*tsp
;
587 int i
, n
, total
, error
, nerrors
= 0;
589 int limit
= kq_checkloop
;
590 struct kevent kev
[KQ_NEVENTS
];
596 lwkt_gettoken(&kq_token
);
599 error
= kevent_copyinfn(uap
, kev
, KQ_NEVENTS
, &n
);
604 for (i
= 0; i
< n
; i
++) {
606 kevp
->flags
&= ~EV_SYSFLAGS
;
607 error
= kqueue_register(kq
, kevp
);
610 * If a registration returns an error we
611 * immediately post the error. The kevent()
612 * call itself will fail with the error if
613 * no space is available for posting.
615 * Such errors normally bypass the timeout/blocking
616 * code. However, if the copyoutfn function refuses
617 * to post the error (see sys_poll()), then we
621 kevp
->flags
= EV_ERROR
;
624 kevent_copyoutfn(uap
, kevp
, 1, res
);
638 * Acquire/wait for events - setup timeout
643 if (tsp
->tv_sec
|| tsp
->tv_nsec
) {
645 timespecadd(tsp
, &ats
); /* tsp = target time */
652 * Collect as many events as we can. Sleeping on successive
653 * loops is disabled if copyoutfn has incremented (*res).
655 * The loop stops if an error occurs, all events have been
656 * scanned (the marker has been reached), or fewer than the
657 * maximum number of events is found.
659 * The copyoutfn function does not have to increment (*res) in
660 * order for the loop to continue.
662 * NOTE: doselect() usually passes 0x7FFFFFFF for nevents.
666 marker
.kn_filter
= EVFILT_MARKER
;
667 marker
.kn_status
= KN_PROCESSING
;
668 TAILQ_INSERT_TAIL(&kq
->kq_knpend
, &marker
, kn_tqe
);
669 while ((n
= nevents
- total
) > 0) {
674 * If no events are pending sleep until timeout (if any)
675 * or an event occurs.
677 * After the sleep completes the marker is moved to the
678 * end of the list, making any received events available
681 if (kq
->kq_count
== 0 && *res
== 0) {
682 error
= kqueue_sleep(kq
, tsp
);
686 TAILQ_REMOVE(&kq
->kq_knpend
, &marker
, kn_tqe
);
687 TAILQ_INSERT_TAIL(&kq
->kq_knpend
, &marker
, kn_tqe
);
691 * Process all received events
692 * Account for all non-spurious events in our total
694 i
= kqueue_scan(kq
, kev
, n
, &marker
);
697 error
= kevent_copyoutfn(uap
, kev
, i
, res
);
698 total
+= *res
- lres
;
702 if (limit
&& --limit
== 0)
703 panic("kqueue: checkloop failed i=%d", i
);
706 * Normally when fewer events are returned than requested
707 * we can stop. However, if only spurious events were
708 * collected the copyout will not bump (*res) and we have
715 * Deal with an edge case where spurious events can cause
716 * a loop to occur without moving the marker. This can
717 * prevent kqueue_scan() from picking up new events which
718 * race us. We must be sure to move the marker for this
721 * NOTE: We do not want to move the marker if events
722 * were scanned because normal kqueue operations
723 * may reactivate events. Moving the marker in
724 * that case could result in duplicates for the
728 TAILQ_REMOVE(&kq
->kq_knpend
, &marker
, kn_tqe
);
729 TAILQ_INSERT_TAIL(&kq
->kq_knpend
, &marker
, kn_tqe
);
732 TAILQ_REMOVE(&kq
->kq_knpend
, &marker
, kn_tqe
);
734 /* Timeouts do not return EWOULDBLOCK. */
735 if (error
== EWOULDBLOCK
)
739 lwkt_reltoken(&kq_token
);
747 sys_kevent(struct kevent_args
*uap
)
749 struct thread
*td
= curthread
;
750 struct proc
*p
= td
->td_proc
;
751 struct timespec ts
, *tsp
;
753 struct file
*fp
= NULL
;
754 struct kevent_copyin_args
*kap
, ka
;
758 error
= copyin(uap
->timeout
, &ts
, sizeof(ts
));
766 fp
= holdfp(p
->p_fd
, uap
->fd
, -1);
769 if (fp
->f_type
!= DTYPE_KQUEUE
) {
774 kq
= (struct kqueue
*)fp
->f_data
;
780 error
= kern_kevent(kq
, uap
->nevents
, &uap
->sysmsg_result
, kap
,
781 kevent_copyin
, kevent_copyout
, tsp
);
789 kqueue_register(struct kqueue
*kq
, struct kevent
*kev
)
791 struct filedesc
*fdp
= kq
->kq_fdp
;
792 struct filterops
*fops
;
793 struct file
*fp
= NULL
;
794 struct knote
*kn
= NULL
;
797 if (kev
->filter
< 0) {
798 if (kev
->filter
+ EVFILT_SYSCOUNT
< 0)
800 fops
= sysfilt_ops
[~kev
->filter
]; /* to 0-base index */
804 * filter attach routine is responsible for insuring that
805 * the identifier can be attached to it.
807 kprintf("unknown filter: %d\n", kev
->filter
);
811 lwkt_gettoken(&kq_token
);
812 if (fops
->f_flags
& FILTEROP_ISFD
) {
813 /* validate descriptor */
814 fp
= holdfp(fdp
, kev
->ident
, -1);
816 lwkt_reltoken(&kq_token
);
821 SLIST_FOREACH(kn
, &fp
->f_klist
, kn_link
) {
822 if (kn
->kn_kq
== kq
&&
823 kn
->kn_filter
== kev
->filter
&&
824 kn
->kn_id
== kev
->ident
) {
825 if (knote_acquire(kn
) == 0)
831 if (kq
->kq_knhashmask
) {
834 list
= &kq
->kq_knhash
[
835 KN_HASH((u_long
)kev
->ident
, kq
->kq_knhashmask
)];
837 SLIST_FOREACH(kn
, list
, kn_link
) {
838 if (kn
->kn_id
== kev
->ident
&&
839 kn
->kn_filter
== kev
->filter
) {
840 if (knote_acquire(kn
) == 0)
849 * NOTE: At this point if kn is non-NULL we will have acquired
850 * it and set KN_PROCESSING.
852 if (kn
== NULL
&& ((kev
->flags
& EV_ADD
) == 0)) {
858 * kn now contains the matching knote, or NULL if no match
860 if (kev
->flags
& EV_ADD
) {
872 * apply reference count to knote structure, and
873 * do not release it at the end of this routine.
877 kn
->kn_sfflags
= kev
->fflags
;
878 kn
->kn_sdata
= kev
->data
;
881 kn
->kn_kevent
= *kev
;
884 * KN_PROCESSING prevents the knote from getting
885 * ripped out from under us while we are trying
886 * to attach it, in case the attach blocks.
888 kn
->kn_status
= KN_PROCESSING
;
890 if ((error
= filter_attach(kn
)) != 0) {
891 kn
->kn_status
|= KN_DELETING
| KN_REPROCESS
;
897 * Interlock against close races which either tried
898 * to remove our knote while we were blocked or missed
899 * it entirely prior to our attachment. We do not
900 * want to end up with a knote on a closed descriptor.
902 if ((fops
->f_flags
& FILTEROP_ISFD
) &&
903 checkfdclosed(fdp
, kev
->ident
, kn
->kn_fp
)) {
904 kn
->kn_status
|= KN_DELETING
| KN_REPROCESS
;
908 * The user may change some filter values after the
909 * initial EV_ADD, but doing so will not reset any
910 * filter which have already been triggered.
912 KKASSERT(kn
->kn_status
& KN_PROCESSING
);
913 kn
->kn_sfflags
= kev
->fflags
;
914 kn
->kn_sdata
= kev
->data
;
915 kn
->kn_kevent
.udata
= kev
->udata
;
919 * Execute the filter event to immediately activate the
920 * knote if necessary. If reprocessing events are pending
921 * due to blocking above we do not run the filter here
922 * but instead let knote_release() do it. Otherwise we
923 * might run the filter on a deleted event.
925 if ((kn
->kn_status
& KN_REPROCESS
) == 0) {
926 if (filter_event(kn
, 0))
929 } else if (kev
->flags
& EV_DELETE
) {
931 * Delete the existing knote
933 knote_detach_and_drop(kn
);
938 * Disablement does not deactivate a knote here.
940 if ((kev
->flags
& EV_DISABLE
) &&
941 ((kn
->kn_status
& KN_DISABLED
) == 0)) {
942 kn
->kn_status
|= KN_DISABLED
;
946 * Re-enablement may have to immediately enqueue an active knote.
948 if ((kev
->flags
& EV_ENABLE
) && (kn
->kn_status
& KN_DISABLED
)) {
949 kn
->kn_status
&= ~KN_DISABLED
;
950 if ((kn
->kn_status
& KN_ACTIVE
) &&
951 ((kn
->kn_status
& KN_QUEUED
) == 0)) {
957 * Handle any required reprocessing
960 /* kn may be invalid now */
963 lwkt_reltoken(&kq_token
);
970 * Block as necessary until the target time is reached.
971 * If tsp is NULL we block indefinitely. If tsp->ts_secs/nsecs are both
972 * 0 we do not block at all.
975 kqueue_sleep(struct kqueue
*kq
, struct timespec
*tsp
)
980 kq
->kq_state
|= KQ_SLEEP
;
981 error
= tsleep(kq
, PCATCH
, "kqread", 0);
982 } else if (tsp
->tv_sec
== 0 && tsp
->tv_nsec
== 0) {
986 struct timespec atx
= *tsp
;
990 timespecsub(&atx
, &ats
);
991 if (ats
.tv_sec
< 0) {
994 timeout
= atx
.tv_sec
> 24 * 60 * 60 ?
995 24 * 60 * 60 * hz
: tstohz_high(&atx
);
996 kq
->kq_state
|= KQ_SLEEP
;
997 error
= tsleep(kq
, PCATCH
, "kqread", timeout
);
1001 /* don't restart after signals... */
1002 if (error
== ERESTART
)
1009 * Scan the kqueue, return the number of active events placed in kevp up
1012 * Continuous mode events may get recycled, do not continue scanning past
1013 * marker unless no events have been collected.
1016 kqueue_scan(struct kqueue
*kq
, struct kevent
*kevp
, int count
,
1017 struct knote
*marker
)
1019 struct knote
*kn
, local_marker
;
1023 local_marker
.kn_filter
= EVFILT_MARKER
;
1024 local_marker
.kn_status
= KN_PROCESSING
;
1029 TAILQ_INSERT_HEAD(&kq
->kq_knpend
, &local_marker
, kn_tqe
);
1031 kn
= TAILQ_NEXT(&local_marker
, kn_tqe
);
1032 if (kn
->kn_filter
== EVFILT_MARKER
) {
1033 /* Marker reached, we are done */
1037 /* Move local marker past some other threads marker */
1038 kn
= TAILQ_NEXT(kn
, kn_tqe
);
1039 TAILQ_REMOVE(&kq
->kq_knpend
, &local_marker
, kn_tqe
);
1040 TAILQ_INSERT_BEFORE(kn
, &local_marker
, kn_tqe
);
1045 * We can't skip a knote undergoing processing, otherwise
1046 * we risk not returning it when the user process expects
1047 * it should be returned. Sleep and retry.
1049 if (knote_acquire(kn
) == 0)
1053 * Remove the event for processing.
1055 * WARNING! We must leave KN_QUEUED set to prevent the
1056 * event from being KNOTE_ACTIVATE()d while
1057 * the queue state is in limbo, in case we
1060 * WARNING! We must set KN_PROCESSING to avoid races
1061 * against deletion or another thread's
1064 TAILQ_REMOVE(&kq
->kq_knpend
, kn
, kn_tqe
);
1068 * We have to deal with an extremely important race against
1069 * file descriptor close()s here. The file descriptor can
1070 * disappear MPSAFE, and there is a small window of
1071 * opportunity between that and the call to knote_fdclose().
1073 * If we hit that window here while doselect or dopoll is
1074 * trying to delete a spurious event they will not be able
1075 * to match up the event against a knote and will go haywire.
1077 if ((kn
->kn_fop
->f_flags
& FILTEROP_ISFD
) &&
1078 checkfdclosed(kq
->kq_fdp
, kn
->kn_kevent
.ident
, kn
->kn_fp
)) {
1079 kn
->kn_status
|= KN_DELETING
| KN_REPROCESS
;
1082 if (kn
->kn_status
& KN_DISABLED
) {
1084 * If disabled we ensure the event is not queued
1085 * but leave its active bit set. On re-enablement
1086 * the event may be immediately triggered.
1088 kn
->kn_status
&= ~KN_QUEUED
;
1089 } else if ((kn
->kn_flags
& EV_ONESHOT
) == 0 &&
1090 (kn
->kn_status
& KN_DELETING
) == 0 &&
1091 filter_event(kn
, 0) == 0) {
1093 * If not running in one-shot mode and the event
1094 * is no longer present we ensure it is removed
1095 * from the queue and ignore it.
1097 kn
->kn_status
&= ~(KN_QUEUED
| KN_ACTIVE
);
1102 *kevp
++ = kn
->kn_kevent
;
1106 if (kn
->kn_flags
& EV_ONESHOT
) {
1107 kn
->kn_status
&= ~KN_QUEUED
;
1108 kn
->kn_status
|= KN_DELETING
| KN_REPROCESS
;
1109 } else if (kn
->kn_flags
& EV_CLEAR
) {
1112 kn
->kn_status
&= ~(KN_QUEUED
| KN_ACTIVE
);
1114 TAILQ_INSERT_TAIL(&kq
->kq_knpend
, kn
, kn_tqe
);
1120 * Handle any post-processing states
1124 TAILQ_REMOVE(&kq
->kq_knpend
, &local_marker
, kn_tqe
);
1131 * This could be expanded to call kqueue_scan, if desired.
1136 kqueue_read(struct file
*fp
, struct uio
*uio
, struct ucred
*cred
, int flags
)
1145 kqueue_write(struct file
*fp
, struct uio
*uio
, struct ucred
*cred
, int flags
)
1154 kqueue_ioctl(struct file
*fp
, u_long com
, caddr_t data
,
1155 struct ucred
*cred
, struct sysmsg
*msg
)
1160 lwkt_gettoken(&kq_token
);
1161 kq
= (struct kqueue
*)fp
->f_data
;
1166 kq
->kq_state
|= KQ_ASYNC
;
1168 kq
->kq_state
&= ~KQ_ASYNC
;
1172 error
= fsetown(*(int *)data
, &kq
->kq_sigio
);
1178 lwkt_reltoken(&kq_token
);
1186 kqueue_stat(struct file
*fp
, struct stat
*st
, struct ucred
*cred
)
1188 struct kqueue
*kq
= (struct kqueue
*)fp
->f_data
;
1190 bzero((void *)st
, sizeof(*st
));
1191 st
->st_size
= kq
->kq_count
;
1192 st
->st_blksize
= sizeof(struct kevent
);
1193 st
->st_mode
= S_IFIFO
;
1201 kqueue_close(struct file
*fp
)
1203 struct kqueue
*kq
= (struct kqueue
*)fp
->f_data
;
1205 kqueue_terminate(kq
);
1208 funsetown(kq
->kq_sigio
);
1210 kfree(kq
, M_KQUEUE
);
1215 kqueue_wakeup(struct kqueue
*kq
)
1217 if (kq
->kq_state
& KQ_SLEEP
) {
1218 kq
->kq_state
&= ~KQ_SLEEP
;
1221 KNOTE(&kq
->kq_kqinfo
.ki_note
, 0);
1225 * Calls filterops f_attach function, acquiring mplock if filter is not
1226 * marked as FILTEROP_MPSAFE.
1229 filter_attach(struct knote
*kn
)
1233 if (!(kn
->kn_fop
->f_flags
& FILTEROP_MPSAFE
)) {
1235 ret
= kn
->kn_fop
->f_attach(kn
);
1238 ret
= kn
->kn_fop
->f_attach(kn
);
1245 * Detach the knote and drop it, destroying the knote.
1247 * Calls filterops f_detach function, acquiring mplock if filter is not
1248 * marked as FILTEROP_MPSAFE.
1251 knote_detach_and_drop(struct knote
*kn
)
1253 kn
->kn_status
|= KN_DELETING
| KN_REPROCESS
;
1254 if (kn
->kn_fop
->f_flags
& FILTEROP_MPSAFE
) {
1255 kn
->kn_fop
->f_detach(kn
);
1258 kn
->kn_fop
->f_detach(kn
);
1265 * Calls filterops f_event function, acquiring mplock if filter is not
1266 * marked as FILTEROP_MPSAFE.
1268 * If the knote is in the middle of being created or deleted we cannot
1269 * safely call the filter op.
1272 filter_event(struct knote
*kn
, long hint
)
1276 if (kn
->kn_fop
->f_flags
& FILTEROP_MPSAFE
) {
1277 ret
= kn
->kn_fop
->f_event(kn
, hint
);
1280 ret
= kn
->kn_fop
->f_event(kn
, hint
);
1287 * Walk down a list of knotes, activating them if their event has triggered.
1289 * If we encounter any knotes which are undergoing processing we just mark
1290 * them for reprocessing and do not try to [re]activate the knote. However,
1291 * if a hint is being passed we have to wait and that makes things a bit
1295 knote(struct klist
*list
, long hint
)
1299 lwkt_gettoken(&kq_token
);
1301 SLIST_FOREACH(kn
, list
, kn_next
) {
1302 if (kn
->kn_status
& KN_PROCESSING
) {
1304 * Someone else is processing the knote, ask the
1305 * other thread to reprocess it and don't mess
1306 * with it otherwise.
1309 kn
->kn_status
|= KN_REPROCESS
;
1314 * If the hint is non-zero we have to wait or risk
1315 * losing the state the caller is trying to update.
1317 * XXX This is a real problem, certain process
1318 * and signal filters will bump kn_data for
1319 * already-processed notes more than once if
1320 * we restart the list scan. FIXME.
1322 kn
->kn_status
|= KN_WAITING
| KN_REPROCESS
;
1323 tsleep(kn
, 0, "knotec", hz
);
1328 * Become the reprocessing master ourselves.
1330 * If hint is non-zer running the event is mandatory
1331 * when not deleting so do it whether reprocessing is
1334 kn
->kn_status
|= KN_PROCESSING
;
1335 if ((kn
->kn_status
& KN_DELETING
) == 0) {
1336 if (filter_event(kn
, hint
))
1339 if (knote_release(kn
))
1342 lwkt_reltoken(&kq_token
);
1346 * Insert knote at head of klist.
1348 * This function may only be called via a filter function and thus
1349 * kq_token should already be held and marked for processing.
1352 knote_insert(struct klist
*klist
, struct knote
*kn
)
1354 KKASSERT(kn
->kn_status
& KN_PROCESSING
);
1355 ASSERT_LWKT_TOKEN_HELD(&kq_token
);
1356 SLIST_INSERT_HEAD(klist
, kn
, kn_next
);
1360 * Remove knote from a klist
1362 * This function may only be called via a filter function and thus
1363 * kq_token should already be held and marked for processing.
1366 knote_remove(struct klist
*klist
, struct knote
*kn
)
1368 KKASSERT(kn
->kn_status
& KN_PROCESSING
);
1369 ASSERT_LWKT_TOKEN_HELD(&kq_token
);
1370 SLIST_REMOVE(klist
, kn
, knote
, kn_next
);
1374 * Remove all knotes from a specified klist
1376 * Only called from aio.
1379 knote_empty(struct klist
*list
)
1383 lwkt_gettoken(&kq_token
);
1384 while ((kn
= SLIST_FIRST(list
)) != NULL
) {
1385 if (knote_acquire(kn
))
1386 knote_detach_and_drop(kn
);
1388 lwkt_reltoken(&kq_token
);
1392 knote_assume_knotes(struct kqinfo
*src
, struct kqinfo
*dst
,
1393 struct filterops
*ops
, void *hook
)
1397 lwkt_gettoken(&kq_token
);
1398 while ((kn
= SLIST_FIRST(&src
->ki_note
)) != NULL
) {
1399 if (knote_acquire(kn
)) {
1400 knote_remove(&src
->ki_note
, kn
);
1403 knote_insert(&dst
->ki_note
, kn
);
1405 /* kn may be invalid now */
1408 lwkt_reltoken(&kq_token
);
1412 * Remove all knotes referencing a specified fd
1415 knote_fdclose(struct file
*fp
, struct filedesc
*fdp
, int fd
)
1419 lwkt_gettoken(&kq_token
);
1421 SLIST_FOREACH(kn
, &fp
->f_klist
, kn_link
) {
1422 if (kn
->kn_kq
->kq_fdp
== fdp
&& kn
->kn_id
== fd
) {
1423 if (knote_acquire(kn
))
1424 knote_detach_and_drop(kn
);
1428 lwkt_reltoken(&kq_token
);
1432 * Low level attach function.
1434 * The knote should already be marked for processing.
1437 knote_attach(struct knote
*kn
)
1440 struct kqueue
*kq
= kn
->kn_kq
;
1442 if (kn
->kn_fop
->f_flags
& FILTEROP_ISFD
) {
1443 KKASSERT(kn
->kn_fp
);
1444 list
= &kn
->kn_fp
->f_klist
;
1446 if (kq
->kq_knhashmask
== 0)
1447 kq
->kq_knhash
= hashinit(KN_HASHSIZE
, M_KQUEUE
,
1448 &kq
->kq_knhashmask
);
1449 list
= &kq
->kq_knhash
[KN_HASH(kn
->kn_id
, kq
->kq_knhashmask
)];
1451 SLIST_INSERT_HEAD(list
, kn
, kn_link
);
1452 TAILQ_INSERT_HEAD(&kq
->kq_knlist
, kn
, kn_kqlink
);
1456 * Low level drop function.
1458 * The knote should already be marked for processing.
1461 knote_drop(struct knote
*kn
)
1468 if (kn
->kn_fop
->f_flags
& FILTEROP_ISFD
)
1469 list
= &kn
->kn_fp
->f_klist
;
1471 list
= &kq
->kq_knhash
[KN_HASH(kn
->kn_id
, kq
->kq_knhashmask
)];
1473 SLIST_REMOVE(list
, kn
, knote
, kn_link
);
1474 TAILQ_REMOVE(&kq
->kq_knlist
, kn
, kn_kqlink
);
1475 if (kn
->kn_status
& KN_QUEUED
)
1477 if (kn
->kn_fop
->f_flags
& FILTEROP_ISFD
) {
1485 * Low level enqueue function.
1487 * The knote should already be marked for processing.
1490 knote_enqueue(struct knote
*kn
)
1492 struct kqueue
*kq
= kn
->kn_kq
;
1494 KASSERT((kn
->kn_status
& KN_QUEUED
) == 0, ("knote already queued"));
1495 TAILQ_INSERT_TAIL(&kq
->kq_knpend
, kn
, kn_tqe
);
1496 kn
->kn_status
|= KN_QUEUED
;
1500 * Send SIGIO on request (typically set up as a mailbox signal)
1502 if (kq
->kq_sigio
&& (kq
->kq_state
& KQ_ASYNC
) && kq
->kq_count
== 1)
1503 pgsigio(kq
->kq_sigio
, SIGIO
, 0);
1509 * Low level dequeue function.
1511 * The knote should already be marked for processing.
1514 knote_dequeue(struct knote
*kn
)
1516 struct kqueue
*kq
= kn
->kn_kq
;
1518 KASSERT(kn
->kn_status
& KN_QUEUED
, ("knote not queued"));
1519 TAILQ_REMOVE(&kq
->kq_knpend
, kn
, kn_tqe
);
1520 kn
->kn_status
&= ~KN_QUEUED
;
1527 knote_zone
= zinit("KNOTE", sizeof(struct knote
), 0, 0, 1);
1529 SYSINIT(knote
, SI_SUB_PSEUDO
, SI_ORDER_ANY
, knote_init
, NULL
)
1531 static struct knote
*
1534 return ((struct knote
*)zalloc(knote_zone
));
1538 knote_free(struct knote
*kn
)
1540 zfree(knote_zone
, kn
);