2 * Copyright (c) 2000-2005 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_OSREFERENCE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the
10 * License may not be used to create, or enable the creation or
11 * redistribution of, unlawful or unlicensed copies of an Apple operating
12 * system, or to circumvent, violate, or enable the circumvention or
13 * violation of, any terms of an Apple operating system software license
16 * Please obtain a copy of the License at
17 * http://www.opensource.apple.com/apsl/ and read it before using this
20 * The Original Code and all software distributed under the License are
21 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
22 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
23 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
25 * Please see the License for the specific language governing rights and
26 * limitations under the License.
28 * @APPLE_LICENSE_OSREFERENCE_HEADER_END@
32 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
33 * All rights reserved.
35 * Redistribution and use in source and binary forms, with or without
36 * modification, are permitted provided that the following conditions
38 * 1. Redistributions of source code must retain the above copyright
39 * notice, this list of conditions and the following disclaimer.
40 * 2. Redistributions in binary form must reproduce the above copyright
41 * notice, this list of conditions and the following disclaimer in the
42 * documentation and/or other materials provided with the distribution.
44 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
45 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
47 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
48 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
49 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
50 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
52 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
53 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57 * @(#)kern_event.c 1.0 (3/31/2000)
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/filedesc.h>
64 #include <sys/kernel.h>
65 #include <sys/proc_internal.h>
66 #include <sys/kauth.h>
67 #include <sys/malloc.h>
68 #include <sys/unistd.h>
69 #include <sys/file_internal.h>
70 #include <sys/fcntl.h>
71 #include <sys/select.h>
72 #include <sys/queue.h>
73 #include <sys/event.h>
74 #include <sys/eventvar.h>
75 #include <sys/protosw.h>
76 #include <sys/socket.h>
77 #include <sys/socketvar.h>
79 #include <sys/sysctl.h>
81 #include <sys/sysproto.h>
84 #include <sys/proc_info.h>
86 #include <kern/lock.h>
87 #include <kern/clock.h>
88 #include <kern/thread_call.h>
89 #include <kern/sched_prim.h>
90 #include <kern/zalloc.h>
91 #include <kern/assert.h>
93 #include <libkern/libkern.h>
95 extern void unix_syscall_return(int);
97 MALLOC_DEFINE(M_KQUEUE
, "kqueue", "memory for kqueue system");
99 static inline void kqlock(struct kqueue
*kq
);
100 static inline void kqunlock(struct kqueue
*kq
);
102 static int kqlock2knoteuse(struct kqueue
*kq
, struct knote
*kn
);
103 static int kqlock2knoteusewait(struct kqueue
*kq
, struct knote
*kn
);
104 static int kqlock2knotedrop(struct kqueue
*kq
, struct knote
*kn
);
105 static int knoteuse2kqlock(struct kqueue
*kq
, struct knote
*kn
);
107 static void kqueue_wakeup(struct kqueue
*kq
);
108 static int kqueue_read(struct fileproc
*fp
, struct uio
*uio
,
109 kauth_cred_t cred
, int flags
, struct proc
*p
);
110 static int kqueue_write(struct fileproc
*fp
, struct uio
*uio
,
111 kauth_cred_t cred
, int flags
, struct proc
*p
);
112 static int kqueue_ioctl(struct fileproc
*fp
, u_long com
, caddr_t data
,
114 static int kqueue_select(struct fileproc
*fp
, int which
, void *wql
,
116 static int kqueue_close(struct fileglob
*fp
, struct proc
*p
);
117 static int kqueue_kqfilter(struct fileproc
*fp
, struct knote
*kn
, struct proc
*p
);
118 extern int kqueue_stat(struct fileproc
*fp
, struct stat
*st
, struct proc
*p
);
120 static struct fileops kqueueops
= {
130 static int kevent_copyin(user_addr_t
*addrp
, struct kevent
*kevp
, struct proc
*p
);
131 static int kevent_copyout(struct kevent
*kevp
, user_addr_t
*addrp
, struct proc
*p
);
133 static int kevent_callback(struct kqueue
*kq
, struct kevent
*kevp
, void *data
);
134 static void kevent_continue(struct kqueue
*kq
, void *data
, int error
);
135 static void kevent_scan_continue(void *contp
, wait_result_t wait_result
);
136 static int kevent_process(struct kqueue
*kq
, kevent_callback_t callback
,
137 void *data
, int *countp
, struct proc
*p
);
138 static void knote_put(struct knote
*kn
);
139 static int knote_fdpattach(struct knote
*kn
, struct filedesc
*fdp
, struct proc
*p
);
140 static void knote_drop(struct knote
*kn
, struct proc
*p
);
141 static void knote_activate(struct knote
*kn
);
142 static void knote_deactivate(struct knote
*kn
);
143 static void knote_enqueue(struct knote
*kn
);
144 static void knote_dequeue(struct knote
*kn
);
145 static struct knote
*knote_alloc(void);
146 static void knote_free(struct knote
*kn
);
147 extern void knote_init(void);
149 static int filt_fileattach(struct knote
*kn
);
150 static struct filterops file_filtops
=
151 { 1, filt_fileattach
, NULL
, NULL
};
153 static void filt_kqdetach(struct knote
*kn
);
154 static int filt_kqueue(struct knote
*kn
, long hint
);
155 static struct filterops kqread_filtops
=
156 { 1, NULL
, filt_kqdetach
, filt_kqueue
};
159 * placeholder for not-yet-implemented filters
161 static int filt_badattach(struct knote
*kn
);
162 static struct filterops bad_filtops
=
163 { 0, filt_badattach
, 0 , 0 };
165 static int filt_procattach(struct knote
*kn
);
166 static void filt_procdetach(struct knote
*kn
);
167 static int filt_proc(struct knote
*kn
, long hint
);
169 static struct filterops proc_filtops
=
170 { 0, filt_procattach
, filt_procdetach
, filt_proc
};
172 extern struct filterops fs_filtops
;
174 extern struct filterops sig_filtops
;
178 static int filt_timercompute(struct knote
*kn
, uint64_t *abs_time
);
179 static void filt_timerexpire(void *knx
, void *param1
);
180 static int filt_timerattach(struct knote
*kn
);
181 static void filt_timerdetach(struct knote
*kn
);
182 static int filt_timer(struct knote
*kn
, long hint
);
184 static struct filterops timer_filtops
=
185 { 0, filt_timerattach
, filt_timerdetach
, filt_timer
};
187 /* to avoid arming timers that fire quicker than we can handle */
188 static uint64_t filt_timerfloor
= 0;
190 static lck_mtx_t _filt_timerlock
;
191 static void filt_timerlock(void);
192 static void filt_timerunlock(void);
195 * Sentinel marker for a thread scanning through the list of
198 static struct filterops threadmarker_filtops
=
199 { 0, filt_badattach
, 0, 0 };
201 static zone_t knote_zone
;
203 #define KN_HASHSIZE 64 /* XXX should be tunable */
204 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
207 extern struct filterops aio_filtops
;
211 * Table for for all system-defined filters.
213 static struct filterops
*sysfilt_ops
[] = {
214 &file_filtops
, /* EVFILT_READ */
215 &file_filtops
, /* EVFILT_WRITE */
217 &aio_filtops
, /* EVFILT_AIO */
219 &bad_filtops
, /* EVFILT_AIO */
221 &file_filtops
, /* EVFILT_VNODE */
222 &proc_filtops
, /* EVFILT_PROC */
223 &sig_filtops
, /* EVFILT_SIGNAL */
224 &timer_filtops
, /* EVFILT_TIMER */
225 &bad_filtops
, /* EVFILT_MACHPORT */
226 &fs_filtops
/* EVFILT_FS */
230 * kqueue/note lock attributes and implementations
232 * kqueues have locks, while knotes have use counts
233 * Most of the knote state is guarded by the object lock.
234 * the knote "inuse" count and status use the kqueue lock.
236 lck_grp_attr_t
* kq_lck_grp_attr
;
237 lck_grp_t
* kq_lck_grp
;
238 lck_attr_t
* kq_lck_attr
;
241 kqlock(struct kqueue
*kq
)
243 lck_spin_lock(&kq
->kq_lock
);
247 kqunlock(struct kqueue
*kq
)
249 lck_spin_unlock(&kq
->kq_lock
);
253 * Convert a kq lock to a knote use referece.
255 * If the knote is being dropped, we can't get
256 * a use reference, so just return with it
259 * - kq locked at entry
260 * - unlock on exit if we get the use reference
263 kqlock2knoteuse(struct kqueue
*kq
, struct knote
*kn
)
265 if (kn
->kn_status
& KN_DROPPING
)
273 * Convert a kq lock to a knote use referece.
275 * If the knote is being dropped, we can't get
276 * a use reference, so just return with it
279 * - kq locked at entry
280 * - kq always unlocked on exit
283 kqlock2knoteusewait(struct kqueue
*kq
, struct knote
*kn
)
285 if (!kqlock2knoteuse(kq
, kn
)) {
286 kn
->kn_status
|= KN_DROPWAIT
;
287 assert_wait(&kn
->kn_status
, THREAD_UNINT
);
289 thread_block(THREAD_CONTINUE_NULL
);
296 * Convert from a knote use reference back to kq lock.
298 * Drop a use reference and wake any waiters if
299 * this is the last one.
301 * The exit return indicates if the knote is
302 * still alive - but the kqueue lock is taken
306 knoteuse2kqlock(struct kqueue
*kq
, struct knote
*kn
)
309 if ((--kn
->kn_inuse
== 0) &&
310 (kn
->kn_status
& KN_USEWAIT
)) {
311 kn
->kn_status
&= ~KN_USEWAIT
;
312 thread_wakeup(&kn
->kn_inuse
);
314 return ((kn
->kn_status
& KN_DROPPING
) == 0);
318 * Convert a kq lock to a knote drop referece.
320 * If the knote is in use, wait for the use count
321 * to subside. We first mark our intention to drop
322 * it - keeping other users from "piling on."
323 * If we are too late, we have to wait for the
324 * other drop to complete.
326 * - kq locked at entry
327 * - always unlocked on exit.
328 * - caller can't hold any locks that would prevent
329 * the other dropper from completing.
332 kqlock2knotedrop(struct kqueue
*kq
, struct knote
*kn
)
335 if ((kn
->kn_status
& KN_DROPPING
) == 0) {
336 kn
->kn_status
|= KN_DROPPING
;
337 if (kn
->kn_inuse
> 0) {
338 kn
->kn_status
|= KN_USEWAIT
;
339 assert_wait(&kn
->kn_inuse
, THREAD_UNINT
);
341 thread_block(THREAD_CONTINUE_NULL
);
346 kn
->kn_status
|= KN_DROPWAIT
;
347 assert_wait(&kn
->kn_status
, THREAD_UNINT
);
349 thread_block(THREAD_CONTINUE_NULL
);
355 * Release a knote use count reference.
358 knote_put(struct knote
*kn
)
360 struct kqueue
*kq
= kn
->kn_kq
;
363 if ((--kn
->kn_inuse
== 0) &&
364 (kn
->kn_status
& KN_USEWAIT
)) {
365 kn
->kn_status
&= ~KN_USEWAIT
;
366 thread_wakeup(&kn
->kn_inuse
);
374 filt_fileattach(struct knote
*kn
)
377 return (fo_kqfilter(kn
->kn_fp
, kn
, current_proc()));
380 #define f_flag f_fglob->fg_flag
381 #define f_type f_fglob->fg_type
382 #define f_msgcount f_fglob->fg_msgcount
383 #define f_cred f_fglob->fg_cred
384 #define f_ops f_fglob->fg_ops
385 #define f_offset f_fglob->fg_offset
386 #define f_data f_fglob->fg_data
389 filt_kqdetach(struct knote
*kn
)
391 struct kqueue
*kq
= (struct kqueue
*)kn
->kn_fp
->f_data
;
394 KNOTE_DETACH(&kq
->kq_sel
.si_note
, kn
);
400 filt_kqueue(struct knote
*kn
, __unused
long hint
)
402 struct kqueue
*kq
= (struct kqueue
*)kn
->kn_fp
->f_data
;
404 kn
->kn_data
= kq
->kq_count
;
405 return (kn
->kn_data
> 0);
409 filt_procattach(struct knote
*kn
)
414 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
416 p
= pfind(kn
->kn_id
);
418 thread_funnel_set(kernel_flock
, funnel_state
);
422 kn
->kn_flags
|= EV_CLEAR
; /* automatically set */
423 kn
->kn_hookid
= 1; /* mark exit not seen */
426 * internal flag indicating registration done by kernel
428 if (kn
->kn_flags
& EV_FLAG1
) {
429 kn
->kn_data
= (int)kn
->kn_sdata
; /* ppid */
430 kn
->kn_fflags
= NOTE_CHILD
;
431 kn
->kn_flags
&= ~EV_FLAG1
;
434 /* XXX lock the proc here while adding to the list? */
435 KNOTE_ATTACH(&p
->p_klist
, kn
);
437 thread_funnel_set(kernel_flock
, funnel_state
);
443 * The knote may be attached to a different process, which may exit,
444 * leaving nothing for the knote to be attached to. In that case,
445 * we wont be able to find the process from its pid. But the exit
446 * code may still be processing the knote list for the target process.
447 * We may have to wait for that processing to complete before we can
448 * return (and presumably free the knote) without actually removing
449 * it from the dead process' knote list.
452 filt_procdetach(struct knote
*kn
)
457 funnel_state
= thread_funnel_set(kernel_flock
, TRUE
);
458 p
= pfind(kn
->kn_id
);
460 if (p
!= (struct proc
*)NULL
) {
461 KNOTE_DETACH(&p
->p_klist
, kn
);
462 } else if (kn
->kn_hookid
!= 0) { /* if not NOTE_EXIT yet */
463 kn
->kn_hookid
= -1; /* we are detaching but... */
464 assert_wait(&kn
->kn_hook
, THREAD_UNINT
); /* have to wait */
465 thread_block(THREAD_CONTINUE_NULL
);
467 thread_funnel_set(kernel_flock
, funnel_state
);
471 filt_proc(struct knote
*kn
, long hint
)
477 /* must hold the funnel when coming from below */
478 assert(thread_funnel_get() != (funnel_t
)0);
481 * mask off extra data
483 event
= (u_int
)hint
& NOTE_PCTRLMASK
;
486 * if the user is interested in this event, record it.
488 if (kn
->kn_sfflags
& event
)
489 kn
->kn_fflags
|= event
;
492 * process is gone, so flag the event as finished.
494 * If someone was trying to detach, but couldn't
495 * find the proc to complete the detach, wake them
496 * up (nothing will ever need to walk the per-proc
497 * knote list again - so its safe for them to dump
500 if (event
== NOTE_EXIT
) {
501 boolean_t detaching
= (kn
->kn_hookid
== -1);
504 kn
->kn_flags
|= (EV_EOF
| EV_ONESHOT
);
506 thread_wakeup(&kn
->kn_hookid
);
511 * process forked, and user wants to track the new process,
512 * so attach a new knote to it, and immediately report an
513 * event with the parent's pid.
515 if ((event
== NOTE_FORK
) && (kn
->kn_sfflags
& NOTE_TRACK
)) {
520 * register knote with new process.
522 kev
.ident
= hint
& NOTE_PDATAMASK
; /* pid */
523 kev
.filter
= kn
->kn_filter
;
524 kev
.flags
= kn
->kn_flags
| EV_ADD
| EV_ENABLE
| EV_FLAG1
;
525 kev
.fflags
= kn
->kn_sfflags
;
526 kev
.data
= kn
->kn_id
; /* parent */
527 kev
.udata
= kn
->kn_kevent
.udata
; /* preserve udata */
528 error
= kevent_register(kn
->kn_kq
, &kev
, NULL
);
530 kn
->kn_fflags
|= NOTE_TRACKERR
;
534 return (kn
->kn_fflags
!= 0); /* atomic check - no funnel needed from above */
538 * filt_timercompute - compute absolute timeout
540 * The saved-data field in the knote contains the
541 * time value. The saved filter-flags indicates
542 * the unit of measurement.
544 * If the timeout is not absolute, adjust it for
548 filt_timercompute(struct knote
*kn
, uint64_t *abs_time
)
553 switch (kn
->kn_sfflags
& (NOTE_SECONDS
|NOTE_USECONDS
|NOTE_NSECONDS
)) {
555 multiplier
= NSEC_PER_SEC
;
558 multiplier
= NSEC_PER_USEC
;
563 case 0: /* milliseconds (default) */
564 multiplier
= NSEC_PER_SEC
/ 1000;
569 nanoseconds_to_absolutetime((uint64_t)kn
->kn_sdata
* multiplier
, &raw
);
570 if (raw
<= filt_timerfloor
) {
574 if ((kn
->kn_sfflags
& NOTE_ABSOLUTE
) == NOTE_ABSOLUTE
) {
575 uint32_t seconds
, nanoseconds
;
578 clock_get_calendar_nanotime(&seconds
, &nanoseconds
);
579 nanoseconds_to_absolutetime((uint64_t)seconds
* NSEC_PER_SEC
+ nanoseconds
,
581 if (now
>= raw
+ filt_timerfloor
) {
587 clock_absolutetime_interval_to_deadline(raw
, abs_time
);
592 * filt_timerexpire - the timer callout routine
594 * Just propagate the timer event into the knote
595 * filter routine (by going through the knote
596 * synchronization point). Pass a hint to
597 * indicate this is a real event, not just a
601 filt_timerexpire(void *knx
, __unused
void *spare
)
603 struct klist timer_list
;
604 struct knote
*kn
= knx
;
606 /* no "object" for timers, so fake a list */
607 SLIST_INIT(&timer_list
);
608 SLIST_INSERT_HEAD(&timer_list
, kn
, kn_selnext
);
609 KNOTE(&timer_list
, 1);
613 * data contains amount of time to sleep, in milliseconds,
614 * or a pointer to a timespec structure.
617 filt_timerattach(struct knote
*kn
)
619 thread_call_t callout
;
623 error
= filt_timercompute(kn
, &deadline
);
628 callout
= thread_call_allocate(filt_timerexpire
, kn
);
632 /* handle as immediate */
638 kn
->kn_hook
= (caddr_t
)callout
;
640 /* absolute=EV_ONESHOT */
641 if (kn
->kn_sfflags
& NOTE_ABSOLUTE
)
642 kn
->kn_flags
|= EV_ONESHOT
;
645 /* all others - if not faking immediate */
646 kn
->kn_flags
|= EV_CLEAR
;
647 thread_call_enter_delayed(callout
, deadline
);
658 filt_timerdetach(struct knote
*kn
)
660 thread_call_t callout
;
663 callout
= (thread_call_t
)kn
->kn_hook
;
664 if (callout
!= NULL
) {
667 /* cancel the callout if we can */
668 cancelled
= thread_call_cancel(callout
);
670 /* got it, just free it */
673 thread_call_free(callout
);
676 /* we have to wait for the expire routine. */
677 kn
->kn_hookid
= -1; /* we are detaching */
678 assert_wait(&kn
->kn_hook
, THREAD_UNINT
);
680 thread_block(THREAD_CONTINUE_NULL
);
681 assert(kn
->kn_hook
== NULL
);
691 filt_timer(struct knote
*kn
, __unused
long hint
)
697 thread_call_t callout
;
704 detaching
= (kn
->kn_hookid
< 0);
705 callout
= (thread_call_t
)kn
->kn_hook
;
707 if (!detaching
&& (kn
->kn_flags
& EV_ONESHOT
) == 0) {
711 /* user input data may have changed - deal */
712 error
= filt_timercompute(kn
, &deadline
);
714 kn
->kn_flags
|= EV_ERROR
;
716 } else if (deadline
== 0) {
717 /* revert to fake immediate */
718 kn
->kn_flags
&= ~EV_CLEAR
;
722 /* keep the callout and re-arm */
723 thread_call_enter_delayed(callout
, deadline
);
730 thread_call_free(callout
);
732 /* if someone is waiting for timer to pop */
734 thread_wakeup(&kn
->kn_hook
);
742 /* change fake timer to real if needed */
743 while (kn
->kn_hookid
> 0 && kn
->kn_sdata
> 0) {
746 /* update the fake timer (make real) */
750 error
= filt_timerattach(kn
);
753 kn
->kn_flags
|= EV_ERROR
;
760 /* if still fake, pretend it fired */
761 if (kn
->kn_hookid
> 0)
764 result
= (kn
->kn_data
!= 0);
772 lck_mtx_lock(&_filt_timerlock
);
776 filt_timerunlock(void)
778 lck_mtx_unlock(&_filt_timerlock
);
782 * JMM - placeholder for not-yet-implemented filters
785 filt_badattach(__unused
struct knote
*kn
)
792 kqueue_alloc(struct proc
*p
)
794 struct filedesc
*fdp
= p
->p_fd
;
797 MALLOC_ZONE(kq
, struct kqueue
*, sizeof(struct kqueue
), M_KQUEUE
, M_WAITOK
);
799 bzero(kq
, sizeof(struct kqueue
));
800 lck_spin_init(&kq
->kq_lock
, kq_lck_grp
, kq_lck_attr
);
801 TAILQ_INIT(&kq
->kq_head
);
802 TAILQ_INIT(&kq
->kq_inprocess
);
806 if (fdp
->fd_knlistsize
< 0) {
808 if (fdp
->fd_knlistsize
< 0)
809 fdp
->fd_knlistsize
= 0; /* this process has had a kq */
818 * kqueue_dealloc - detach all knotes from a kqueue and free it
820 * We walk each list looking for knotes referencing this
821 * this kqueue. If we find one, we try to drop it. But
822 * if we fail to get a drop reference, that will wait
823 * until it is dropped. So, we can just restart again
824 * safe in the assumption that the list will eventually
825 * not contain any more references to this kqueue (either
826 * we dropped them all, or someone else did).
828 * Assumes no new events are being added to the kqueue.
829 * Nothing locked on entry or exit.
832 kqueue_dealloc(struct kqueue
*kq
, struct proc
*p
)
834 struct filedesc
*fdp
= p
->p_fd
;
839 for (i
= 0; i
< fdp
->fd_knlistsize
; i
++) {
840 kn
= SLIST_FIRST(&fdp
->fd_knlist
[i
]);
842 if (kq
== kn
->kn_kq
) {
845 /* drop it ourselves or wait */
846 if (kqlock2knotedrop(kq
, kn
)) {
847 kn
->kn_fop
->f_detach(kn
);
851 /* start over at beginning of list */
852 kn
= SLIST_FIRST(&fdp
->fd_knlist
[i
]);
855 kn
= SLIST_NEXT(kn
, kn_link
);
858 if (fdp
->fd_knhashmask
!= 0) {
859 for (i
= 0; i
< (int)fdp
->fd_knhashmask
+ 1; i
++) {
860 kn
= SLIST_FIRST(&fdp
->fd_knhash
[i
]);
862 if (kq
== kn
->kn_kq
) {
865 /* drop it ourselves or wait */
866 if (kqlock2knotedrop(kq
, kn
)) {
867 kn
->kn_fop
->f_detach(kn
);
871 /* start over at beginning of list */
872 kn
= SLIST_FIRST(&fdp
->fd_knhash
[i
]);
875 kn
= SLIST_NEXT(kn
, kn_link
);
880 lck_spin_destroy(&kq
->kq_lock
, kq_lck_grp
);
881 FREE_ZONE(kq
, sizeof(struct kqueue
), M_KQUEUE
);
885 kqueue(struct proc
*p
, __unused
struct kqueue_args
*uap
, register_t
*retval
)
891 error
= falloc(p
, &fp
, &fd
);
896 kq
= kqueue_alloc(p
);
902 fp
->f_flag
= FREAD
| FWRITE
;
903 fp
->f_type
= DTYPE_KQUEUE
;
904 fp
->f_ops
= &kqueueops
;
905 fp
->f_data
= (caddr_t
)kq
;
908 *fdflags(p
, fd
) &= ~UF_RESERVED
;
909 fp_drop(p
, fd
, fp
, 1);
917 kqueue_portset_np(__unused
struct proc
*p
,
918 __unused
struct kqueue_portset_np_args
*uap
,
919 __unused register_t
*retval
)
921 /* JMM - Placeholder for now */
926 kqueue_from_portset_np(__unused
struct proc
*p
,
927 __unused
struct kqueue_from_portset_np_args
*uap
,
928 __unused register_t
*retval
)
930 /* JMM - Placeholder for now */
935 kevent_copyin(user_addr_t
*addrp
, struct kevent
*kevp
, struct proc
*p
)
940 if (IS_64BIT_PROCESS(p
)) {
941 struct user_kevent kev64
;
943 advance
= sizeof(kev64
);
944 error
= copyin(*addrp
, (caddr_t
)&kev64
, advance
);
947 kevp
->ident
= CAST_DOWN(uintptr_t, kev64
.ident
);
948 kevp
->filter
= kev64
.filter
;
949 kevp
->flags
= kev64
.flags
;
950 kevp
->fflags
= kev64
.fflags
;
951 kevp
->data
= CAST_DOWN(intptr_t, kev64
.data
);
952 kevp
->udata
= kev64
.udata
;
955 * compensate for legacy in-kernel kevent layout
956 * where the udata field is alredy 64-bit.
958 advance
= sizeof(*kevp
) + sizeof(void *) - sizeof(user_addr_t
);
959 error
= copyin(*addrp
, (caddr_t
)kevp
, advance
);
967 kevent_copyout(struct kevent
*kevp
, user_addr_t
*addrp
, struct proc
*p
)
972 if (IS_64BIT_PROCESS(p
)) {
973 struct user_kevent kev64
;
975 kev64
.ident
= (uint64_t) kevp
->ident
;
976 kev64
.filter
= kevp
->filter
;
977 kev64
.flags
= kevp
->flags
;
978 kev64
.fflags
= kevp
->fflags
;
979 kev64
.data
= (int64_t) kevp
->data
;
980 kev64
.udata
= kevp
->udata
;
981 advance
= sizeof(kev64
);
982 error
= copyout((caddr_t
)&kev64
, *addrp
, advance
);
985 * compensate for legacy in-kernel kevent layout
986 * where the udata field is alredy 64-bit.
988 advance
= sizeof(*kevp
) + sizeof(void *) - sizeof(user_addr_t
);
989 error
= copyout((caddr_t
)kevp
, *addrp
, advance
);
997 * kevent_continue - continue a kevent syscall after blocking
999 * assume we inherit a use count on the kq fileglob.
1003 kevent_continue(__unused
struct kqueue
*kq
, void *data
, int error
)
1005 struct _kevent
*cont_args
;
1006 struct fileproc
*fp
;
1010 struct proc
*p
= current_proc();
1012 cont_args
= (struct _kevent
*)data
;
1013 noutputs
= cont_args
->eventout
;
1014 retval
= cont_args
->retval
;
1018 fp_drop(p
, fd
, fp
, 0);
1020 /* don't restart after signals... */
1021 if (error
== ERESTART
)
1023 else if (error
== EWOULDBLOCK
)
1027 unix_syscall_return(error
);
1031 * kevent - [syscall] register and wait for kernel events
1036 kevent(struct proc
*p
, struct kevent_args
*uap
, register_t
*retval
)
1038 user_addr_t changelist
= uap
->changelist
;
1039 user_addr_t ueventlist
= uap
->eventlist
;
1040 int nchanges
= uap
->nchanges
;
1041 int nevents
= uap
->nevents
;
1044 struct _kevent
*cont_args
;
1047 struct fileproc
*fp
;
1049 int error
, noutputs
;
1052 /* convert timeout to absolute - if we have one */
1053 if (uap
->timeout
!= USER_ADDR_NULL
) {
1055 if ( IS_64BIT_PROCESS(p
) ) {
1056 struct user_timespec ts
;
1057 error
= copyin( uap
->timeout
, &ts
, sizeof(ts
) );
1058 if ((ts
.tv_sec
& 0xFFFFFFFF00000000ull
) != 0)
1061 TIMESPEC_TO_TIMEVAL(&rtv
, &ts
);
1064 error
= copyin( uap
->timeout
, &ts
, sizeof(ts
) );
1065 TIMESPEC_TO_TIMEVAL(&rtv
, &ts
);
1069 if (itimerfix(&rtv
))
1071 getmicrouptime(&atv
);
1072 timevaladd(&atv
, &rtv
);
1078 /* get a usecount for the kq itself */
1079 if ((error
= fp_getfkq(p
, fd
, &fp
, &kq
)) != 0)
1082 /* register all the change requests the user provided... */
1084 while (nchanges
> 0 && error
== 0) {
1085 error
= kevent_copyin(&changelist
, &kev
, p
);
1089 kev
.flags
&= ~EV_SYSFLAGS
;
1090 error
= kevent_register(kq
, &kev
, p
);
1091 if (error
&& nevents
> 0) {
1092 kev
.flags
= EV_ERROR
;
1094 error
= kevent_copyout(&kev
, &ueventlist
, p
);
1103 /* store the continuation/completion data in the uthread */
1104 ut
= (uthread_t
)get_bsdthread_info(current_thread());
1105 cont_args
= (struct _kevent
*)&ut
->uu_state
.ss_kevent
;
1108 cont_args
->retval
= retval
;
1109 cont_args
->eventlist
= ueventlist
;
1110 cont_args
->eventcount
= nevents
;
1111 cont_args
->eventout
= noutputs
;
1113 if (nevents
> 0 && noutputs
== 0 && error
== 0)
1114 error
= kevent_scan(kq
, kevent_callback
,
1115 kevent_continue
, cont_args
,
1117 kevent_continue(kq
, cont_args
, error
);
1124 * kevent_callback - callback for each individual event
1126 * called with nothing locked
1127 * caller holds a reference on the kqueue
1131 kevent_callback(__unused
struct kqueue
*kq
, struct kevent
*kevp
, void *data
)
1133 struct _kevent
*cont_args
;
1136 cont_args
= (struct _kevent
*)data
;
1137 assert(cont_args
->eventout
< cont_arg
->eventcount
);
1140 * Copy out the appropriate amount of event data for this user.
1142 error
= kevent_copyout(kevp
, &cont_args
->eventlist
, current_proc());
1145 * If there isn't space for additional events, return
1146 * a harmless error to stop the processing here
1148 if (error
== 0 && ++cont_args
->eventout
== cont_args
->eventcount
)
1149 error
= EWOULDBLOCK
;
1154 * kevent_register - add a new event to a kqueue
1156 * Creates a mapping between the event source and
1157 * the kqueue via a knote data structure.
1159 * Because many/most the event sources are file
1160 * descriptor related, the knote is linked off
1161 * the filedescriptor table for quick access.
1163 * called with nothing locked
1164 * caller holds a reference on the kqueue
1168 kevent_register(struct kqueue
*kq
, struct kevent
*kev
, struct proc
*p
)
1170 struct filedesc
*fdp
= kq
->kq_fdp
;
1171 struct filterops
*fops
;
1172 struct fileproc
*fp
= NULL
;
1173 struct knote
*kn
= NULL
;
1176 if (kev
->filter
< 0) {
1177 if (kev
->filter
+ EVFILT_SYSCOUNT
< 0)
1179 fops
= sysfilt_ops
[~kev
->filter
]; /* to 0-base index */
1183 * filter attach routine is responsible for insuring that
1184 * the identifier can be attached to it.
1186 printf("unknown filter: %d\n", kev
->filter
);
1190 /* this iocount needs to be dropped if it is not registered */
1191 if (fops
->f_isfd
&& (error
= fp_lookup(p
, kev
->ident
, &fp
, 0)) != 0)
1197 /* fd-based knotes are linked off the fd table */
1198 if (kev
->ident
< (u_int
)fdp
->fd_knlistsize
) {
1199 SLIST_FOREACH(kn
, &fdp
->fd_knlist
[kev
->ident
], kn_link
)
1200 if (kq
== kn
->kn_kq
&&
1201 kev
->filter
== kn
->kn_filter
)
1205 /* hash non-fd knotes here too */
1206 if (fdp
->fd_knhashmask
!= 0) {
1209 list
= &fdp
->fd_knhash
[
1210 KN_HASH((u_long
)kev
->ident
, fdp
->fd_knhashmask
)];
1211 SLIST_FOREACH(kn
, list
, kn_link
)
1212 if (kev
->ident
== kn
->kn_id
&&
1214 kev
->filter
== kn
->kn_filter
)
1220 * kn now contains the matching knote, or NULL if no match
1223 if ((kev
->flags
& (EV_ADD
|EV_DELETE
)) == EV_ADD
) {
1232 kn
->kn_tq
= &kq
->kq_head
;
1234 kn
->kn_sfflags
= kev
->fflags
;
1235 kn
->kn_sdata
= kev
->data
;
1238 kn
->kn_kevent
= *kev
;
1239 kn
->kn_inuse
= 1; /* for f_attach() */
1242 /* before anyone can find it */
1243 if (kev
->flags
& EV_DISABLE
)
1244 kn
->kn_status
|= KN_DISABLED
;
1246 error
= knote_fdpattach(kn
, fdp
, p
);
1255 * apply reference count to knote structure, and
1256 * do not release it at the end of this routine.
1261 * If the attach fails here, we can drop it knowing
1262 * that nobody else has a reference to the knote.
1264 if ((error
= fops
->f_attach(kn
)) != 0) {
1274 /* existing knote - get kqueue lock */
1278 if (kev
->flags
& EV_DELETE
) {
1280 kn
->kn_status
|= KN_DISABLED
;
1281 if (kqlock2knotedrop(kq
, kn
)) {
1282 kn
->kn_fop
->f_detach(kn
);
1288 /* update status flags for existing knote */
1289 if (kev
->flags
& EV_DISABLE
) {
1291 kn
->kn_status
|= KN_DISABLED
;
1292 } else if (kev
->flags
& EV_ENABLE
) {
1293 kn
->kn_status
&= ~KN_DISABLED
;
1294 if (kn
->kn_status
& KN_ACTIVE
)
1299 * If somebody is in the middle of dropping this
1300 * knote - go find/insert a new one. But we have
1301 * wait for this one to go away first.
1303 if (!kqlock2knoteusewait(kq
, kn
))
1304 /* kqueue unlocked */
1308 * The user may change some filter values after the
1309 * initial EV_ADD, but doing so will not reset any
1310 * filter which have already been triggered.
1312 kn
->kn_sfflags
= kev
->fflags
;
1313 kn
->kn_sdata
= kev
->data
;
1314 kn
->kn_kevent
.udata
= kev
->udata
;
1317 /* still have use ref on knote */
1318 if (kn
->kn_fop
->f_event(kn
, 0)) {
1319 if (knoteuse2kqlock(kq
, kn
))
1328 fp_drop(p
, kev
->ident
, fp
, 0);
1333 * kevent_process - process the triggered events in a kqueue
1335 * Walk the queued knotes and validate that they are
1336 * really still triggered events by calling the filter
1337 * routines (if necessary). Hold a use reference on
1338 * the knote to avoid it being detached. For each event
1339 * that is still considered triggered, invoke the
1340 * callback routine provided.
1342 * caller holds a reference on the kqueue.
1343 * kqueue locked on entry and exit - but may be dropped
1347 kevent_process(struct kqueue
*kq
,
1348 kevent_callback_t callback
,
1359 if (kq
->kq_count
== 0) {
1364 /* if someone else is processing the queue, wait */
1365 if (!TAILQ_EMPTY(&kq
->kq_inprocess
)) {
1366 assert_wait(&kq
->kq_inprocess
, THREAD_UNINT
);
1367 kq
->kq_state
|= KQ_PROCWAIT
;
1369 thread_block(THREAD_CONTINUE_NULL
);
1376 while (error
== 0 &&
1377 (kn
= TAILQ_FIRST(&kq
->kq_head
)) != NULL
) {
1380 * move knote to the processed queue.
1381 * this is also protected by the kq lock.
1383 assert(kn
->kn_tq
== &kq
->kq_head
);
1384 TAILQ_REMOVE(&kq
->kq_head
, kn
, kn_tqe
);
1385 kn
->kn_tq
= &kq
->kq_inprocess
;
1386 TAILQ_INSERT_TAIL(&kq
->kq_inprocess
, kn
, kn_tqe
);
1389 * Non-EV_ONESHOT events must be re-validated.
1391 * Convert our lock to a use-count and call the event's
1392 * filter routine to update.
1394 * If the event is dropping (or no longer valid), we
1395 * already have it off the active queue, so just
1396 * finish the job of deactivating it.
1398 if ((kn
->kn_flags
& EV_ONESHOT
) == 0) {
1401 if (kqlock2knoteuse(kq
, kn
)) {
1403 /* call the filter with just a ref */
1404 result
= kn
->kn_fop
->f_event(kn
, 0);
1406 if (!knoteuse2kqlock(kq
, kn
) || result
== 0) {
1407 knote_deactivate(kn
);
1411 knote_deactivate(kn
);
1417 * Got a valid triggered knote with the kqueue
1418 * still locked. Snapshot the data, and determine
1419 * how to dispatch the knote for future events.
1421 kev
= kn
->kn_kevent
;
1423 /* now what happens to it? */
1424 if (kn
->kn_flags
& EV_ONESHOT
) {
1425 knote_deactivate(kn
);
1426 if (kqlock2knotedrop(kq
, kn
)) {
1427 kn
->kn_fop
->f_detach(kn
);
1430 } else if (kn
->kn_flags
& EV_CLEAR
) {
1431 knote_deactivate(kn
);
1437 * leave on in-process queue. We'll
1438 * move all the remaining ones back
1439 * the kq queue and wakeup any
1440 * waiters when we are done.
1445 /* callback to handle each event as we find it */
1446 error
= (callback
)(kq
, &kev
, data
);
1453 * With the kqueue still locked, move any knotes
1454 * remaining on the in-process queue back to the
1455 * kq's queue and wake up any waiters.
1457 while ((kn
= TAILQ_FIRST(&kq
->kq_inprocess
)) != NULL
) {
1458 assert(kn
->kn_tq
== &kq
->kq_inprocess
);
1459 TAILQ_REMOVE(&kq
->kq_inprocess
, kn
, kn_tqe
);
1460 kn
->kn_tq
= &kq
->kq_head
;
1461 TAILQ_INSERT_TAIL(&kq
->kq_head
, kn
, kn_tqe
);
1463 if (kq
->kq_state
& KQ_PROCWAIT
) {
1464 kq
->kq_state
&= ~KQ_PROCWAIT
;
1465 thread_wakeup(&kq
->kq_inprocess
);
1474 kevent_scan_continue(void *data
, wait_result_t wait_result
)
1476 uthread_t ut
= (uthread_t
)get_bsdthread_info(current_thread());
1477 struct _kevent_scan
* cont_args
= &ut
->uu_state
.ss_kevent_scan
;
1478 struct kqueue
*kq
= (struct kqueue
*)data
;
1482 /* convert the (previous) wait_result to a proper error */
1483 switch (wait_result
) {
1484 case THREAD_AWAKENED
:
1486 error
= kevent_process(kq
, cont_args
->call
, cont_args
, &count
, current_proc());
1487 if (error
== 0 && count
== 0) {
1488 assert_wait_deadline(kq
, THREAD_ABORTSAFE
, cont_args
->deadline
);
1489 kq
->kq_state
|= KQ_SLEEP
;
1491 thread_block_parameter(kevent_scan_continue
, kq
);
1496 case THREAD_TIMED_OUT
:
1497 error
= EWOULDBLOCK
;
1499 case THREAD_INTERRUPTED
:
1503 panic("kevent_scan_cont() - invalid wait_result (%d)", wait_result
);
1507 /* call the continuation with the results */
1508 assert(cont_args
->cont
!= NULL
);
1509 (cont_args
->cont
)(kq
, cont_args
->data
, error
);
1514 * kevent_scan - scan and wait for events in a kqueue
1516 * Process the triggered events in a kqueue.
1518 * If there are no events triggered arrange to
1519 * wait for them. If the caller provided a
1520 * continuation routine, then kevent_scan will
1523 * The callback routine must be valid.
1524 * The caller must hold a use-count reference on the kq.
1528 kevent_scan(struct kqueue
*kq
,
1529 kevent_callback_t callback
,
1530 kevent_continue_t continuation
,
1532 struct timeval
*atvp
,
1535 thread_continue_t cont
= THREAD_CONTINUE_NULL
;
1540 assert(callback
!= NULL
);
1544 wait_result_t wait_result
;
1548 * Make a pass through the kq to find events already
1552 error
= kevent_process(kq
, callback
, data
, &count
, p
);
1554 break; /* lock still held */
1556 /* looks like we have to consider blocking */
1559 /* convert the timeout to a deadline once */
1560 if (atvp
->tv_sec
|| atvp
->tv_usec
) {
1561 uint32_t seconds
, nanoseconds
;
1564 clock_get_uptime(&now
);
1565 nanoseconds_to_absolutetime((uint64_t)atvp
->tv_sec
* NSEC_PER_SEC
+
1566 atvp
->tv_usec
* NSEC_PER_USEC
,
1568 if (now
>= deadline
) {
1569 /* non-blocking call */
1570 error
= EWOULDBLOCK
;
1571 break; /* lock still held */
1574 clock_absolutetime_interval_to_deadline(deadline
, &deadline
);
1576 deadline
= 0; /* block forever */
1580 uthread_t ut
= (uthread_t
)get_bsdthread_info(current_thread());
1581 struct _kevent_scan
*cont_args
= &ut
->uu_state
.ss_kevent_scan
;
1583 cont_args
->call
= callback
;
1584 cont_args
->cont
= continuation
;
1585 cont_args
->deadline
= deadline
;
1586 cont_args
->data
= data
;
1587 cont
= kevent_scan_continue
;
1591 /* go ahead and wait */
1592 assert_wait_deadline(kq
, THREAD_ABORTSAFE
, deadline
);
1593 kq
->kq_state
|= KQ_SLEEP
;
1595 wait_result
= thread_block_parameter(cont
, kq
);
1596 /* NOTREACHED if (continuation != NULL) */
1598 switch (wait_result
) {
1599 case THREAD_AWAKENED
:
1601 case THREAD_TIMED_OUT
:
1603 case THREAD_INTERRUPTED
:
1606 panic("kevent_scan - bad wait_result (%d)",
1618 * This could be expanded to call kqueue_scan, if desired.
1622 kqueue_read(__unused
struct fileproc
*fp
,
1623 __unused
struct uio
*uio
,
1624 __unused kauth_cred_t cred
,
1626 __unused
struct proc
*p
)
1633 kqueue_write(__unused
struct fileproc
*fp
,
1634 __unused
struct uio
*uio
,
1635 __unused kauth_cred_t cred
,
1637 __unused
struct proc
*p
)
1644 kqueue_ioctl(__unused
struct fileproc
*fp
,
1645 __unused u_long com
,
1646 __unused caddr_t data
,
1647 __unused
struct proc
*p
)
1654 kqueue_select(struct fileproc
*fp
, int which
, void *wql
, struct proc
*p
)
1656 struct kqueue
*kq
= (struct kqueue
*)fp
->f_data
;
1659 if (which
== FREAD
) {
1664 selrecord(p
, &kq
->kq_sel
, wql
);
1665 kq
->kq_state
|= KQ_SEL
;
1677 kqueue_close(struct fileglob
*fg
, struct proc
*p
)
1679 struct kqueue
*kq
= (struct kqueue
*)fg
->fg_data
;
1681 kqueue_dealloc(kq
, p
);
1688 * The callers has taken a use-count reference on this kqueue and will donate it
1689 * to the kqueue we are being added to. This keeps the kqueue from closing until
1690 * that relationship is torn down.
1693 kqueue_kqfilter(__unused
struct fileproc
*fp
, struct knote
*kn
, __unused
struct proc
*p
)
1695 struct kqueue
*kq
= (struct kqueue
*)kn
->kn_fp
->f_data
;
1697 if (kn
->kn_filter
!= EVFILT_READ
)
1700 kn
->kn_fop
= &kqread_filtops
;
1702 KNOTE_ATTACH(&kq
->kq_sel
.si_note
, kn
);
1709 kqueue_stat(struct fileproc
*fp
, struct stat
*st
, __unused
struct proc
*p
)
1711 struct kqueue
*kq
= (struct kqueue
*)fp
->f_data
;
1713 bzero((void *)st
, sizeof(*st
));
1714 st
->st_size
= kq
->kq_count
;
1715 st
->st_blksize
= sizeof(struct kevent
);
1716 st
->st_mode
= S_IFIFO
;
1721 * Called with the kqueue locked
1724 kqueue_wakeup(struct kqueue
*kq
)
1727 if (kq
->kq_state
& KQ_SLEEP
) {
1728 kq
->kq_state
&= ~KQ_SLEEP
;
1731 if (kq
->kq_state
& KQ_SEL
) {
1732 kq
->kq_state
&= ~KQ_SEL
;
1733 selwakeup(&kq
->kq_sel
);
1735 KNOTE(&kq
->kq_sel
.si_note
, 0);
1739 klist_init(struct klist
*list
)
1746 * Query/Post each knote in the object's list
1748 * The object lock protects the list. It is assumed
1749 * that the filter/event routine for the object can
1750 * determine that the object is already locked (via
1751 * the hind) and not deadlock itself.
1753 * The object lock should also hold off pending
1754 * detach/drop operations. But we'll prevent it here
1755 * too - just in case.
1758 knote(struct klist
*list
, long hint
)
1762 SLIST_FOREACH(kn
, list
, kn_selnext
) {
1763 struct kqueue
*kq
= kn
->kn_kq
;
1766 if (kqlock2knoteuse(kq
, kn
)) {
1769 /* call the event with only a use count */
1770 result
= kn
->kn_fop
->f_event(kn
, hint
);
1772 /* if its not going away and triggered */
1773 if (knoteuse2kqlock(kq
, kn
) && result
)
1775 /* lock held again */
1782 * attach a knote to the specified list. Return true if this is the first entry.
1783 * The list is protected by whatever lock the object it is associated with uses.
1786 knote_attach(struct klist
*list
, struct knote
*kn
)
1788 int ret
= SLIST_EMPTY(list
);
1789 SLIST_INSERT_HEAD(list
, kn
, kn_selnext
);
1794 * detach a knote from the specified list. Return true if that was the last entry.
1795 * The list is protected by whatever lock the object it is associated with uses.
1798 knote_detach(struct klist
*list
, struct knote
*kn
)
1800 SLIST_REMOVE(list
, kn
, knote
, kn_selnext
);
1801 return SLIST_EMPTY(list
);
1805 * remove all knotes referencing a specified fd
1807 * Essentially an inlined knote_remove & knote_drop
1808 * when we know for sure that the thing is a file
1810 * Entered with the proc_fd lock already held.
1811 * It returns the same way, but may drop it temporarily.
1814 knote_fdclose(struct proc
*p
, int fd
)
1816 struct filedesc
*fdp
= p
->p_fd
;
1820 list
= &fdp
->fd_knlist
[fd
];
1821 while ((kn
= SLIST_FIRST(list
)) != NULL
) {
1822 struct kqueue
*kq
= kn
->kn_kq
;
1828 * Convert the lock to a drop ref.
1829 * If we get it, go ahead and drop it.
1830 * Otherwise, we waited for it to
1831 * be dropped by the other guy, so
1832 * it is safe to move on in the list.
1834 if (kqlock2knotedrop(kq
, kn
)) {
1835 kn
->kn_fop
->f_detach(kn
);
1841 /* the fd tables may have changed - start over */
1842 list
= &fdp
->fd_knlist
[fd
];
1846 /* proc_fdlock held on entry (and exit) */
1848 knote_fdpattach(struct knote
*kn
, struct filedesc
*fdp
, __unused
struct proc
*p
)
1850 struct klist
*list
= NULL
;
1852 if (! kn
->kn_fop
->f_isfd
) {
1853 if (fdp
->fd_knhashmask
== 0)
1854 fdp
->fd_knhash
= hashinit(KN_HASHSIZE
, M_KQUEUE
,
1855 &fdp
->fd_knhashmask
);
1856 list
= &fdp
->fd_knhash
[KN_HASH(kn
->kn_id
, fdp
->fd_knhashmask
)];
1858 if ((u_int
)fdp
->fd_knlistsize
<= kn
->kn_id
) {
1861 /* have to grow the fd_knlist */
1862 size
= fdp
->fd_knlistsize
;
1863 while (size
<= kn
->kn_id
)
1865 MALLOC(list
, struct klist
*,
1866 size
* sizeof(struct klist
*), M_KQUEUE
, M_WAITOK
);
1870 bcopy((caddr_t
)fdp
->fd_knlist
, (caddr_t
)list
,
1871 fdp
->fd_knlistsize
* sizeof(struct klist
*));
1872 bzero((caddr_t
)list
+
1873 fdp
->fd_knlistsize
* sizeof(struct klist
*),
1874 (size
- fdp
->fd_knlistsize
) * sizeof(struct klist
*));
1875 FREE(fdp
->fd_knlist
, M_KQUEUE
);
1876 fdp
->fd_knlist
= list
;
1877 fdp
->fd_knlistsize
= size
;
1879 list
= &fdp
->fd_knlist
[kn
->kn_id
];
1881 SLIST_INSERT_HEAD(list
, kn
, kn_link
);
1888 * should be called at spl == 0, since we don't want to hold spl
1889 * while calling fdrop and free.
1892 knote_drop(struct knote
*kn
, struct proc
*p
)
1894 struct filedesc
*fdp
= p
->p_fd
;
1895 struct kqueue
*kq
= kn
->kn_kq
;
1899 if (kn
->kn_fop
->f_isfd
)
1900 list
= &fdp
->fd_knlist
[kn
->kn_id
];
1902 list
= &fdp
->fd_knhash
[KN_HASH(kn
->kn_id
, fdp
->fd_knhashmask
)];
1904 SLIST_REMOVE(list
, kn
, knote
, kn_link
);
1907 if (kn
->kn_status
& KN_DROPWAIT
)
1908 thread_wakeup(&kn
->kn_status
);
1912 if (kn
->kn_fop
->f_isfd
)
1913 fp_drop(p
, kn
->kn_id
, kn
->kn_fp
, 0);
1918 /* called with kqueue lock held */
1920 knote_activate(struct knote
*kn
)
1922 struct kqueue
*kq
= kn
->kn_kq
;
1924 kn
->kn_status
|= KN_ACTIVE
;
1929 /* called with kqueue lock held */
1931 knote_deactivate(struct knote
*kn
)
1933 kn
->kn_status
&= ~KN_ACTIVE
;
1937 /* called with kqueue lock held */
1939 knote_enqueue(struct knote
*kn
)
1941 struct kqueue
*kq
= kn
->kn_kq
;
1943 if ((kn
->kn_status
& (KN_QUEUED
| KN_DISABLED
)) == 0) {
1944 struct kqtailq
*tq
= kn
->kn_tq
;
1946 TAILQ_INSERT_TAIL(tq
, kn
, kn_tqe
);
1947 kn
->kn_status
|= KN_QUEUED
;
1952 /* called with kqueue lock held */
1954 knote_dequeue(struct knote
*kn
)
1956 struct kqueue
*kq
= kn
->kn_kq
;
1958 assert((kn
->kn_status
& KN_DISABLED
) == 0);
1959 if ((kn
->kn_status
& KN_QUEUED
) == KN_QUEUED
) {
1960 struct kqtailq
*tq
= kn
->kn_tq
;
1962 TAILQ_REMOVE(tq
, kn
, kn_tqe
);
1963 kn
->kn_tq
= &kq
->kq_head
;
1964 kn
->kn_status
&= ~KN_QUEUED
;
1972 knote_zone
= zinit(sizeof(struct knote
), 8192*sizeof(struct knote
), 8192, "knote zone");
1974 /* allocate kq lock group attribute and group */
1975 kq_lck_grp_attr
= lck_grp_attr_alloc_init();
1977 kq_lck_grp
= lck_grp_alloc_init("kqueue", kq_lck_grp_attr
);
1979 /* Allocate kq lock attribute */
1980 kq_lck_attr
= lck_attr_alloc_init();
1982 /* Initialize the timer filter lock */
1983 lck_mtx_init(&_filt_timerlock
, kq_lck_grp
, kq_lck_attr
);
1985 SYSINIT(knote
, SI_SUB_PSEUDO
, SI_ORDER_ANY
, knote_init
, NULL
)
1987 static struct knote
*
1990 return ((struct knote
*)zalloc(knote_zone
));
1994 knote_free(struct knote
*kn
)
1996 zfree(knote_zone
, kn
);
1999 #include <sys/param.h>
2000 #include <sys/socket.h>
2001 #include <sys/protosw.h>
2002 #include <sys/domain.h>
2003 #include <sys/mbuf.h>
2004 #include <sys/kern_event.h>
2005 #include <sys/malloc.h>
2006 #include <sys/sys_domain.h>
2007 #include <sys/syslog.h>
2010 static int kev_attach(struct socket
*so
, int proto
, struct proc
*p
);
2011 static int kev_detach(struct socket
*so
);
2012 static int kev_control(struct socket
*so
, u_long cmd
, caddr_t data
, struct ifnet
*ifp
, struct proc
*p
);
2014 struct pr_usrreqs event_usrreqs
= {
2015 pru_abort_notsupp
, pru_accept_notsupp
, kev_attach
, pru_bind_notsupp
, pru_connect_notsupp
,
2016 pru_connect2_notsupp
, kev_control
, kev_detach
, pru_disconnect_notsupp
,
2017 pru_listen_notsupp
, pru_peeraddr_notsupp
, pru_rcvd_notsupp
, pru_rcvoob_notsupp
,
2018 pru_send_notsupp
, pru_sense_null
, pru_shutdown_notsupp
, pru_sockaddr_notsupp
,
2019 pru_sosend_notsupp
, soreceive
, pru_sopoll_notsupp
2022 struct protosw eventsw
[] = {
2024 SOCK_RAW
, &systemdomain
, SYSPROTO_EVENT
, PR_ATOMIC
,
2040 struct kern_event_head kern_event_head
;
2042 static u_long static_event_id
= 0;
2043 struct domain
*sysdom
= &systemdomain
;
2045 static lck_grp_t
*evt_mtx_grp
;
2046 static lck_attr_t
*evt_mtx_attr
;
2047 static lck_grp_attr_t
*evt_mtx_grp_attr
;
2048 lck_mtx_t
*evt_mutex
;
2050 * Install the protosw's for the NKE manager. Invoked at
2051 * extension load time
2054 kern_event_init(void)
2058 if ((retval
= net_add_proto(eventsw
, &systemdomain
)) != 0) {
2059 log(LOG_WARNING
, "Can't install kernel events protocol (%d)\n", retval
);
2064 * allocate lock group attribute and group for kern event
2066 evt_mtx_grp_attr
= lck_grp_attr_alloc_init();
2068 evt_mtx_grp
= lck_grp_alloc_init("eventlist", evt_mtx_grp_attr
);
2071 * allocate the lock attribute for mutexes
2073 evt_mtx_attr
= lck_attr_alloc_init();
2074 evt_mutex
= lck_mtx_alloc_init(evt_mtx_grp
, evt_mtx_attr
);
2075 if (evt_mutex
== NULL
)
2078 return(KERN_SUCCESS
);
2082 kev_attach(struct socket
*so
, __unused
int proto
, __unused
struct proc
*p
)
2085 struct kern_event_pcb
*ev_pcb
;
2087 error
= soreserve(so
, KEV_SNDSPACE
, KEV_RECVSPACE
);
2091 MALLOC(ev_pcb
, struct kern_event_pcb
*, sizeof(struct kern_event_pcb
), M_PCB
, M_WAITOK
);
2095 ev_pcb
->ev_socket
= so
;
2096 ev_pcb
->vendor_code_filter
= 0xffffffff;
2098 so
->so_pcb
= (caddr_t
) ev_pcb
;
2099 lck_mtx_lock(evt_mutex
);
2100 LIST_INSERT_HEAD(&kern_event_head
, ev_pcb
, ev_link
);
2101 lck_mtx_unlock(evt_mutex
);
2108 kev_detach(struct socket
*so
)
2110 struct kern_event_pcb
*ev_pcb
= (struct kern_event_pcb
*) so
->so_pcb
;
2113 lck_mtx_lock(evt_mutex
);
2114 LIST_REMOVE(ev_pcb
, ev_link
);
2115 lck_mtx_unlock(evt_mutex
);
2116 FREE(ev_pcb
, M_PCB
);
2118 so
->so_flags
|= SOF_PCBCLEARING
;
2125 * For now, kev_vender_code and mbuf_tags use the same
2128 extern errno_t
mbuf_tag_id_find_internal(const char *string
, u_long
*out_id
,
2131 errno_t
kev_vendor_code_find(
2133 u_long
*out_vender_code
)
2135 if (strlen(string
) >= KEV_VENDOR_CODE_MAX_STR_LEN
) {
2138 return mbuf_tag_id_find_internal(string
, out_vender_code
, 1);
2141 extern void mbuf_tag_id_first_last(u_long
*first
, u_long
*last
);
2143 errno_t
kev_msg_post(struct kev_msg
*event_msg
)
2145 u_long min_vendor
, max_vendor
;
2147 mbuf_tag_id_first_last(&min_vendor
, &max_vendor
);
2149 if (event_msg
== NULL
)
2152 /* Limit third parties to posting events for registered vendor codes only */
2153 if (event_msg
->vendor_code
< min_vendor
||
2154 event_msg
->vendor_code
> max_vendor
)
2159 return kev_post_msg(event_msg
);
2163 int kev_post_msg(struct kev_msg
*event_msg
)
2165 struct mbuf
*m
, *m2
;
2166 struct kern_event_pcb
*ev_pcb
;
2167 struct kern_event_msg
*ev
;
2169 unsigned long total_size
;
2172 /* Verify the message is small enough to fit in one mbuf w/o cluster */
2173 total_size
= KEV_MSG_HEADER_SIZE
;
2175 for (i
= 0; i
< 5; i
++) {
2176 if (event_msg
->dv
[i
].data_length
== 0)
2178 total_size
+= event_msg
->dv
[i
].data_length
;
2181 if (total_size
> MLEN
) {
2185 m
= m_get(M_DONTWAIT
, MT_DATA
);
2189 ev
= mtod(m
, struct kern_event_msg
*);
2190 total_size
= KEV_MSG_HEADER_SIZE
;
2192 tmp
= (char *) &ev
->event_data
[0];
2193 for (i
= 0; i
< 5; i
++) {
2194 if (event_msg
->dv
[i
].data_length
== 0)
2197 total_size
+= event_msg
->dv
[i
].data_length
;
2198 bcopy(event_msg
->dv
[i
].data_ptr
, tmp
,
2199 event_msg
->dv
[i
].data_length
);
2200 tmp
+= event_msg
->dv
[i
].data_length
;
2203 ev
->id
= ++static_event_id
;
2204 ev
->total_size
= total_size
;
2205 ev
->vendor_code
= event_msg
->vendor_code
;
2206 ev
->kev_class
= event_msg
->kev_class
;
2207 ev
->kev_subclass
= event_msg
->kev_subclass
;
2208 ev
->event_code
= event_msg
->event_code
;
2210 m
->m_len
= total_size
;
2211 lck_mtx_lock(evt_mutex
);
2212 for (ev_pcb
= LIST_FIRST(&kern_event_head
);
2214 ev_pcb
= LIST_NEXT(ev_pcb
, ev_link
)) {
2216 if (ev_pcb
->vendor_code_filter
!= KEV_ANY_VENDOR
) {
2217 if (ev_pcb
->vendor_code_filter
!= ev
->vendor_code
)
2220 if (ev_pcb
->class_filter
!= KEV_ANY_CLASS
) {
2221 if (ev_pcb
->class_filter
!= ev
->kev_class
)
2224 if ((ev_pcb
->subclass_filter
!= KEV_ANY_SUBCLASS
) &&
2225 (ev_pcb
->subclass_filter
!= ev
->kev_subclass
))
2230 m2
= m_copym(m
, 0, m
->m_len
, M_NOWAIT
);
2233 lck_mtx_unlock(evt_mutex
);
2236 socket_lock(ev_pcb
->ev_socket
, 1);
2237 if (sbappendrecord(&ev_pcb
->ev_socket
->so_rcv
, m2
))
2238 sorwakeup(ev_pcb
->ev_socket
);
2239 socket_unlock(ev_pcb
->ev_socket
, 1);
2243 lck_mtx_unlock(evt_mutex
);
2248 kev_control(struct socket
*so
,
2251 __unused
struct ifnet
*ifp
,
2252 __unused
struct proc
*p
)
2254 struct kev_request
*kev_req
= (struct kev_request
*) data
;
2255 struct kern_event_pcb
*ev_pcb
;
2256 struct kev_vendor_code
*kev_vendor
;
2257 u_long
*id_value
= (u_long
*) data
;
2263 *id_value
= static_event_id
;
2267 ev_pcb
= (struct kern_event_pcb
*) so
->so_pcb
;
2268 ev_pcb
->vendor_code_filter
= kev_req
->vendor_code
;
2269 ev_pcb
->class_filter
= kev_req
->kev_class
;
2270 ev_pcb
->subclass_filter
= kev_req
->kev_subclass
;
2274 ev_pcb
= (struct kern_event_pcb
*) so
->so_pcb
;
2275 kev_req
->vendor_code
= ev_pcb
->vendor_code_filter
;
2276 kev_req
->kev_class
= ev_pcb
->class_filter
;
2277 kev_req
->kev_subclass
= ev_pcb
->subclass_filter
;
2280 case SIOCGKEVVENDOR
:
2281 kev_vendor
= (struct kev_vendor_code
*)data
;
2283 /* Make sure string is NULL terminated */
2284 kev_vendor
->vendor_string
[KEV_VENDOR_CODE_MAX_STR_LEN
-1] = 0;
2286 return mbuf_tag_id_find_internal(kev_vendor
->vendor_string
,
2287 &kev_vendor
->vendor_code
, 0);
2299 fill_kqueueinfo(struct kqueue
*kq
, struct kqueue_info
* kinfo
)
2303 /* No need for the funnel as fd is kept alive */
2305 st
= &kinfo
->kq_stat
;
2307 st
->st_size
= kq
->kq_count
;
2308 st
->st_blksize
= sizeof(struct kevent
);
2309 st
->st_mode
= S_IFIFO
;
2310 if (kq
->kq_state
& KQ_SEL
)
2311 kinfo
->kq_state
|= PROC_KQUEUE_SELECT
;
2312 if (kq
->kq_state
& KQ_SLEEP
)
2313 kinfo
->kq_state
|= PROC_KQUEUE_SLEEP
;