2 * Copyright (c) 2000-2015 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_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 License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
30 * Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
31 * All rights reserved.
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
42 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * @(#)kern_event.c 1.0 (3/31/2000)
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/filedesc.h>
62 #include <sys/kernel.h>
63 #include <sys/proc_internal.h>
64 #include <sys/kauth.h>
65 #include <sys/malloc.h>
66 #include <sys/unistd.h>
67 #include <sys/file_internal.h>
68 #include <sys/fcntl.h>
69 #include <sys/select.h>
70 #include <sys/queue.h>
71 #include <sys/event.h>
72 #include <sys/eventvar.h>
73 #include <sys/protosw.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
77 #include <sys/sysctl.h>
79 #include <sys/sysproto.h>
81 #include <sys/vnode_internal.h>
83 #include <sys/proc_info.h>
84 #include <sys/codesign.h>
85 #include <sys/pthread_shims.h>
87 #include <kern/locks.h>
88 #include <kern/clock.h>
89 #include <kern/thread_call.h>
90 #include <kern/sched_prim.h>
91 #include <kern/waitq.h>
92 #include <kern/zalloc.h>
93 #include <kern/kalloc.h>
94 #include <kern/assert.h>
96 #include <libkern/libkern.h>
97 #include "net/net_str_id.h"
99 #include <mach/task.h>
101 #if VM_PRESSURE_EVENTS
102 #include <kern/vm_pressure.h>
105 #if CONFIG_MEMORYSTATUS
106 #include <sys/kern_memorystatus.h>
109 MALLOC_DEFINE(M_KQUEUE
, "kqueue", "memory for kqueue system");
111 #define KQ_EVENT NO_EVENT64
113 static inline void kqlock(struct kqueue
*kq
);
114 static inline void kqunlock(struct kqueue
*kq
);
116 static int kqlock2knoteuse(struct kqueue
*kq
, struct knote
*kn
);
117 static int kqlock2knoteusewait(struct kqueue
*kq
, struct knote
*kn
);
118 static int kqlock2knotedrop(struct kqueue
*kq
, struct knote
*kn
);
119 static int knoteuse2kqlock(struct kqueue
*kq
, struct knote
*kn
);
121 static void kqueue_wakeup(struct kqueue
*kq
, int closed
);
122 static int kqueue_read(struct fileproc
*fp
, struct uio
*uio
,
123 int flags
, vfs_context_t ctx
);
124 static int kqueue_write(struct fileproc
*fp
, struct uio
*uio
,
125 int flags
, vfs_context_t ctx
);
126 static int kqueue_ioctl(struct fileproc
*fp
, u_long com
, caddr_t data
,
128 static int kqueue_select(struct fileproc
*fp
, int which
, void *wq_link_id
,
130 static int kqueue_close(struct fileglob
*fg
, vfs_context_t ctx
);
131 static int kqueue_kqfilter(struct fileproc
*fp
, struct knote
*kn
,
133 static int kqueue_drain(struct fileproc
*fp
, vfs_context_t ctx
);
135 static const struct fileops kqueueops
= {
136 .fo_type
= DTYPE_KQUEUE
,
137 .fo_read
= kqueue_read
,
138 .fo_write
= kqueue_write
,
139 .fo_ioctl
= kqueue_ioctl
,
140 .fo_select
= kqueue_select
,
141 .fo_close
= kqueue_close
,
142 .fo_kqfilter
= kqueue_kqfilter
,
143 .fo_drain
= kqueue_drain
,
146 static int kevent_internal(struct proc
*p
, int fd
,
147 user_addr_t changelist
, int nchanges
,
148 user_addr_t eventlist
, int nevents
,
149 user_addr_t data_out
, user_size_t
*data_available
,
150 unsigned int flags
, user_addr_t utimeout
,
151 kqueue_continue_t continuation
,
153 static int kevent_copyin(user_addr_t
*addrp
, struct kevent_internal_s
*kevp
,
154 struct proc
*p
, unsigned int flags
);
155 static int kevent_copyout(struct kevent_internal_s
*kevp
, user_addr_t
*addrp
,
156 struct proc
*p
, unsigned int flags
);
157 char * kevent_description(struct kevent_internal_s
*kevp
, char *s
, size_t n
);
159 static int kevent_callback(struct kqueue
*kq
, struct kevent_internal_s
*kevp
,
161 static void kevent_continue(struct kqueue
*kq
, void *data
, int error
);
162 static void kqueue_scan_continue(void *contp
, wait_result_t wait_result
);
163 static int kqueue_process(struct kqueue
*kq
, kevent_callback_t callback
,
164 void *data
, int *countp
, struct proc
*p
);
165 static int kqueue_begin_processing(struct kqueue
*kq
);
166 static void kqueue_end_processing(struct kqueue
*kq
);
167 static int knote_process(struct knote
*kn
, kevent_callback_t callback
,
168 void *data
, struct kqtailq
*inprocessp
, struct proc
*p
);
169 static void knote_put(struct knote
*kn
);
170 static int knote_fdpattach(struct knote
*kn
, struct filedesc
*fdp
,
172 static void knote_drop(struct knote
*kn
, struct proc
*p
);
173 static void knote_activate(struct knote
*kn
, int);
174 static void knote_deactivate(struct knote
*kn
);
175 static void knote_enqueue(struct knote
*kn
);
176 static void knote_dequeue(struct knote
*kn
);
177 static struct knote
*knote_alloc(void);
178 static void knote_free(struct knote
*kn
);
180 static int filt_fileattach(struct knote
*kn
);
181 static struct filterops file_filtops
= {
183 .f_attach
= filt_fileattach
,
186 static void filt_kqdetach(struct knote
*kn
);
187 static int filt_kqueue(struct knote
*kn
, long hint
);
188 static struct filterops kqread_filtops
= {
190 .f_detach
= filt_kqdetach
,
191 .f_event
= filt_kqueue
,
194 /* placeholder for not-yet-implemented filters */
195 static int filt_badattach(struct knote
*kn
);
196 static struct filterops bad_filtops
= {
197 .f_attach
= filt_badattach
,
200 static int filt_procattach(struct knote
*kn
);
201 static void filt_procdetach(struct knote
*kn
);
202 static int filt_proc(struct knote
*kn
, long hint
);
203 static struct filterops proc_filtops
= {
204 .f_attach
= filt_procattach
,
205 .f_detach
= filt_procdetach
,
206 .f_event
= filt_proc
,
209 #if VM_PRESSURE_EVENTS
210 static int filt_vmattach(struct knote
*kn
);
211 static void filt_vmdetach(struct knote
*kn
);
212 static int filt_vm(struct knote
*kn
, long hint
);
213 static struct filterops vm_filtops
= {
214 .f_attach
= filt_vmattach
,
215 .f_detach
= filt_vmdetach
,
218 #endif /* VM_PRESSURE_EVENTS */
220 #if CONFIG_MEMORYSTATUS
221 extern struct filterops memorystatus_filtops
;
222 #endif /* CONFIG_MEMORYSTATUS */
224 extern struct filterops fs_filtops
;
226 extern struct filterops sig_filtops
;
229 static int filt_timerattach(struct knote
*kn
);
230 static void filt_timerdetach(struct knote
*kn
);
231 static int filt_timer(struct knote
*kn
, long hint
);
232 static void filt_timertouch(struct knote
*kn
, struct kevent_internal_s
*kev
,
234 static struct filterops timer_filtops
= {
235 .f_attach
= filt_timerattach
,
236 .f_detach
= filt_timerdetach
,
237 .f_event
= filt_timer
,
238 .f_touch
= filt_timertouch
,
242 static void filt_timerexpire(void *knx
, void *param1
);
243 static int filt_timervalidate(struct knote
*kn
);
244 static void filt_timerupdate(struct knote
*kn
);
245 static void filt_timercancel(struct knote
*kn
);
247 #define TIMER_RUNNING 0x1
248 #define TIMER_CANCELWAIT 0x2
250 static lck_mtx_t _filt_timerlock
;
251 static void filt_timerlock(void);
252 static void filt_timerunlock(void);
254 static zone_t knote_zone
;
256 #define KN_HASH(val, mask) (((val) ^ (val >> 8)) & (mask))
259 extern struct filterops aio_filtops
;
262 /* Mach portset filter */
263 extern struct filterops machport_filtops
;
266 static int filt_userattach(struct knote
*kn
);
267 static void filt_userdetach(struct knote
*kn
);
268 static int filt_user(struct knote
*kn
, long hint
);
269 static void filt_usertouch(struct knote
*kn
, struct kevent_internal_s
*kev
,
271 static struct filterops user_filtops
= {
272 .f_attach
= filt_userattach
,
273 .f_detach
= filt_userdetach
,
274 .f_event
= filt_user
,
275 .f_touch
= filt_usertouch
,
279 * Table for all system-defined filters.
281 static struct filterops
*sysfilt_ops
[] = {
282 &file_filtops
, /* EVFILT_READ */
283 &file_filtops
, /* EVFILT_WRITE */
285 &aio_filtops
, /* EVFILT_AIO */
287 &bad_filtops
, /* EVFILT_AIO */
289 &file_filtops
, /* EVFILT_VNODE */
290 &proc_filtops
, /* EVFILT_PROC */
291 &sig_filtops
, /* EVFILT_SIGNAL */
292 &timer_filtops
, /* EVFILT_TIMER */
293 &machport_filtops
, /* EVFILT_MACHPORT */
294 &fs_filtops
, /* EVFILT_FS */
295 &user_filtops
, /* EVFILT_USER */
296 &bad_filtops
, /* unused */
297 #if VM_PRESSURE_EVENTS
298 &vm_filtops
, /* EVFILT_VM */
300 &bad_filtops
, /* EVFILT_VM */
302 &file_filtops
, /* EVFILT_SOCK */
303 #if CONFIG_MEMORYSTATUS
304 &memorystatus_filtops
, /* EVFILT_MEMORYSTATUS */
306 &bad_filtops
, /* EVFILT_MEMORYSTATUS */
311 * kqueue/note lock attributes and implementations
313 * kqueues have locks, while knotes have use counts
314 * Most of the knote state is guarded by the object lock.
315 * the knote "inuse" count and status use the kqueue lock.
317 lck_grp_attr_t
* kq_lck_grp_attr
;
318 lck_grp_t
* kq_lck_grp
;
319 lck_attr_t
* kq_lck_attr
;
322 kqlock(struct kqueue
*kq
)
324 lck_spin_lock(&kq
->kq_lock
);
328 kqunlock(struct kqueue
*kq
)
330 lck_spin_unlock(&kq
->kq_lock
);
334 * Convert a kq lock to a knote use referece.
336 * If the knote is being dropped, we can't get
337 * a use reference, so just return with it
339 * - kq locked at entry
340 * - unlock on exit if we get the use reference
343 kqlock2knoteuse(struct kqueue
*kq
, struct knote
*kn
)
345 if (kn
->kn_status
& KN_DROPPING
)
353 * Convert a kq lock to a knote use referece,
354 * but wait for attach and drop events to complete.
356 * If the knote is being dropped, we can't get
357 * a use reference, so just return with it
359 * - kq locked at entry
360 * - kq always unlocked on exit
363 kqlock2knoteusewait(struct kqueue
*kq
, struct knote
*kn
)
365 if ((kn
->kn_status
& (KN_DROPPING
| KN_ATTACHING
)) != 0) {
366 kn
->kn_status
|= KN_USEWAIT
;
367 waitq_assert_wait64((struct waitq
*)kq
->kq_wqs
,
368 CAST_EVENT64_T(&kn
->kn_status
),
369 THREAD_UNINT
, TIMEOUT_WAIT_FOREVER
);
371 thread_block(THREAD_CONTINUE_NULL
);
380 * Convert from a knote use reference back to kq lock.
382 * Drop a use reference and wake any waiters if
383 * this is the last one.
385 * The exit return indicates if the knote is
386 * still alive - but the kqueue lock is taken
390 knoteuse2kqlock(struct kqueue
*kq
, struct knote
*kn
)
393 if (--kn
->kn_inuse
== 0) {
394 if ((kn
->kn_status
& KN_ATTACHING
) != 0) {
395 kn
->kn_status
&= ~KN_ATTACHING
;
397 if ((kn
->kn_status
& KN_USEWAIT
) != 0) {
398 kn
->kn_status
&= ~KN_USEWAIT
;
399 waitq_wakeup64_all((struct waitq
*)kq
->kq_wqs
,
400 CAST_EVENT64_T(&kn
->kn_status
),
402 WAITQ_ALL_PRIORITIES
);
405 return ((kn
->kn_status
& KN_DROPPING
) == 0);
409 * Convert a kq lock to a knote drop reference.
411 * If the knote is in use, wait for the use count
412 * to subside. We first mark our intention to drop
413 * it - keeping other users from "piling on."
414 * If we are too late, we have to wait for the
415 * other drop to complete.
417 * - kq locked at entry
418 * - always unlocked on exit.
419 * - caller can't hold any locks that would prevent
420 * the other dropper from completing.
423 kqlock2knotedrop(struct kqueue
*kq
, struct knote
*kn
)
427 oktodrop
= ((kn
->kn_status
& (KN_DROPPING
| KN_ATTACHING
)) == 0);
428 kn
->kn_status
&= ~KN_STAYQUEUED
;
429 kn
->kn_status
|= KN_DROPPING
;
431 if (kn
->kn_inuse
== 0) {
436 kn
->kn_status
|= KN_USEWAIT
;
437 waitq_assert_wait64((struct waitq
*)kq
->kq_wqs
,
438 CAST_EVENT64_T(&kn
->kn_status
),
439 THREAD_UNINT
, TIMEOUT_WAIT_FOREVER
);
441 thread_block(THREAD_CONTINUE_NULL
);
446 * Release a knote use count reference.
449 knote_put(struct knote
*kn
)
451 struct kqueue
*kq
= kn
->kn_kq
;
454 if (--kn
->kn_inuse
== 0) {
455 if ((kn
->kn_status
& KN_USEWAIT
) != 0) {
456 kn
->kn_status
&= ~KN_USEWAIT
;
457 waitq_wakeup64_all((struct waitq
*)kq
->kq_wqs
,
458 CAST_EVENT64_T(&kn
->kn_status
),
460 WAITQ_ALL_PRIORITIES
);
467 filt_fileattach(struct knote
*kn
)
469 return (fo_kqfilter(kn
->kn_fp
, kn
, vfs_context_current()));
472 #define f_flag f_fglob->fg_flag
473 #define f_msgcount f_fglob->fg_msgcount
474 #define f_cred f_fglob->fg_cred
475 #define f_ops f_fglob->fg_ops
476 #define f_offset f_fglob->fg_offset
477 #define f_data f_fglob->fg_data
480 filt_kqdetach(struct knote
*kn
)
482 struct kqueue
*kq
= (struct kqueue
*)kn
->kn_fp
->f_data
;
485 KNOTE_DETACH(&kq
->kq_sel
.si_note
, kn
);
491 filt_kqueue(struct knote
*kn
, __unused
long hint
)
493 struct kqueue
*kq
= (struct kqueue
*)kn
->kn_fp
->f_data
;
495 kn
->kn_data
= kq
->kq_count
;
496 return (kn
->kn_data
> 0);
500 filt_procattach(struct knote
*kn
)
504 assert(PID_MAX
< NOTE_PDATAMASK
);
506 if ((kn
->kn_sfflags
& (NOTE_TRACK
| NOTE_TRACKERR
| NOTE_CHILD
)) != 0)
509 p
= proc_find(kn
->kn_id
);
514 const int NoteExitStatusBits
= NOTE_EXIT
| NOTE_EXITSTATUS
;
516 if ((kn
->kn_sfflags
& NoteExitStatusBits
) == NoteExitStatusBits
)
518 pid_t selfpid
= proc_selfpid();
520 if (p
->p_ppid
== selfpid
)
521 break; /* parent => ok */
523 if ((p
->p_lflag
& P_LTRACED
) != 0 &&
524 (p
->p_oppid
== selfpid
))
525 break; /* parent-in-waiting => ok */
533 kn
->kn_flags
|= EV_CLEAR
; /* automatically set */
534 kn
->kn_ptr
.p_proc
= p
; /* store the proc handle */
536 KNOTE_ATTACH(&p
->p_klist
, kn
);
546 * The knote may be attached to a different process, which may exit,
547 * leaving nothing for the knote to be attached to. In that case,
548 * the pointer to the process will have already been nulled out.
551 filt_procdetach(struct knote
*kn
)
557 p
= kn
->kn_ptr
.p_proc
;
558 if (p
!= PROC_NULL
) {
559 kn
->kn_ptr
.p_proc
= PROC_NULL
;
560 KNOTE_DETACH(&p
->p_klist
, kn
);
567 filt_proc(struct knote
*kn
, long hint
)
570 * Note: a lot of bits in hint may be obtained from the knote
571 * To free some of those bits, see <rdar://problem/12592988> Freeing up
572 * bits in hint for filt_proc
574 /* hint is 0 when called from above */
578 /* ALWAYS CALLED WITH proc_klist_lock when (hint != 0) */
581 * mask off extra data
583 event
= (u_int
)hint
& NOTE_PCTRLMASK
;
586 * termination lifecycle events can happen while a debugger
587 * has reparented a process, in which case notifications
588 * should be quashed except to the tracing parent. When
589 * the debugger reaps the child (either via wait4(2) or
590 * process exit), the child will be reparented to the original
591 * parent and these knotes re-fired.
593 if (event
& NOTE_EXIT
) {
594 if ((kn
->kn_ptr
.p_proc
->p_oppid
!= 0)
595 && (kn
->kn_kq
->kq_p
->p_pid
!= kn
->kn_ptr
.p_proc
->p_ppid
)) {
597 * This knote is not for the current ptrace(2) parent, ignore.
604 * if the user is interested in this event, record it.
606 if (kn
->kn_sfflags
& event
)
607 kn
->kn_fflags
|= event
;
609 #pragma clang diagnostic push
610 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
611 if ((event
== NOTE_REAP
) || ((event
== NOTE_EXIT
) && !(kn
->kn_sfflags
& NOTE_REAP
))) {
612 kn
->kn_flags
|= (EV_EOF
| EV_ONESHOT
);
614 #pragma clang diagnostic pop
618 * The kernel has a wrapper in place that returns the same data
619 * as is collected here, in kn_data. Any changes to how
620 * NOTE_EXITSTATUS and NOTE_EXIT_DETAIL are collected
621 * should also be reflected in the proc_pidnoteexit() wrapper.
623 if (event
== NOTE_EXIT
) {
625 if ((kn
->kn_sfflags
& NOTE_EXITSTATUS
) != 0) {
626 kn
->kn_fflags
|= NOTE_EXITSTATUS
;
627 kn
->kn_data
|= (hint
& NOTE_PDATAMASK
);
629 if ((kn
->kn_sfflags
& NOTE_EXIT_DETAIL
) != 0) {
630 kn
->kn_fflags
|= NOTE_EXIT_DETAIL
;
631 if ((kn
->kn_ptr
.p_proc
->p_lflag
&
632 P_LTERM_DECRYPTFAIL
) != 0) {
633 kn
->kn_data
|= NOTE_EXIT_DECRYPTFAIL
;
635 if ((kn
->kn_ptr
.p_proc
->p_lflag
&
636 P_LTERM_JETSAM
) != 0) {
637 kn
->kn_data
|= NOTE_EXIT_MEMORY
;
638 switch (kn
->kn_ptr
.p_proc
->p_lflag
&
640 case P_JETSAM_VMPAGESHORTAGE
:
641 kn
->kn_data
|= NOTE_EXIT_MEMORY_VMPAGESHORTAGE
;
643 case P_JETSAM_VMTHRASHING
:
644 kn
->kn_data
|= NOTE_EXIT_MEMORY_VMTHRASHING
;
646 case P_JETSAM_FCTHRASHING
:
647 kn
->kn_data
|= NOTE_EXIT_MEMORY_FCTHRASHING
;
650 kn
->kn_data
|= NOTE_EXIT_MEMORY_VNODE
;
653 kn
->kn_data
|= NOTE_EXIT_MEMORY_HIWAT
;
656 kn
->kn_data
|= NOTE_EXIT_MEMORY_PID
;
658 case P_JETSAM_IDLEEXIT
:
659 kn
->kn_data
|= NOTE_EXIT_MEMORY_IDLE
;
663 if ((kn
->kn_ptr
.p_proc
->p_csflags
&
665 kn
->kn_data
|= NOTE_EXIT_CSERROR
;
671 /* atomic check, no locking need when called from above */
672 return (kn
->kn_fflags
!= 0);
675 #if VM_PRESSURE_EVENTS
677 * Virtual memory kevents
679 * author: Matt Jacobson [matthew_jacobson@apple.com]
683 filt_vmattach(struct knote
*kn
)
686 * The note will be cleared once the information has been flushed to
687 * the client. If there is still pressure, we will be re-alerted.
689 kn
->kn_flags
|= EV_CLEAR
;
690 return (vm_knote_register(kn
));
694 filt_vmdetach(struct knote
*kn
)
696 vm_knote_unregister(kn
);
700 filt_vm(struct knote
*kn
, long hint
)
702 /* hint == 0 means this is just an alive? check (always true) */
704 const pid_t pid
= (pid_t
)hint
;
705 if ((kn
->kn_sfflags
& NOTE_VM_PRESSURE
) &&
706 (kn
->kn_kq
->kq_p
->p_pid
== pid
)) {
707 kn
->kn_fflags
|= NOTE_VM_PRESSURE
;
711 return (kn
->kn_fflags
!= 0);
713 #endif /* VM_PRESSURE_EVENTS */
716 * filt_timervalidate - process data from user
718 * Converts to either interval or deadline format.
720 * The saved-data field in the knote contains the
721 * time value. The saved filter-flags indicates
722 * the unit of measurement.
724 * After validation, either the saved-data field
725 * contains the interval in absolute time, or ext[0]
726 * contains the expected deadline. If that deadline
727 * is in the past, ext[0] is 0.
729 * Returns EINVAL for unrecognized units of time.
731 * Timer filter lock is held.
735 filt_timervalidate(struct knote
*kn
)
740 switch (kn
->kn_sfflags
& (NOTE_SECONDS
|NOTE_USECONDS
|NOTE_NSECONDS
)) {
742 multiplier
= NSEC_PER_SEC
;
745 multiplier
= NSEC_PER_USEC
;
750 case 0: /* milliseconds (default) */
751 multiplier
= NSEC_PER_SEC
/ 1000;
757 /* transform the slop delta(leeway) in kn_ext[1] if passed to same time scale */
758 if(kn
->kn_sfflags
& NOTE_LEEWAY
){
759 nanoseconds_to_absolutetime((uint64_t)kn
->kn_ext
[1] * multiplier
, &raw
);
763 nanoseconds_to_absolutetime((uint64_t)kn
->kn_sdata
* multiplier
, &raw
);
768 if (kn
->kn_sfflags
& NOTE_ABSOLUTE
) {
770 clock_nsec_t nanoseconds
;
773 clock_get_calendar_nanotime(&seconds
, &nanoseconds
);
774 nanoseconds_to_absolutetime((uint64_t)seconds
* NSEC_PER_SEC
+
778 /* time has already passed */
782 clock_absolutetime_interval_to_deadline(raw
,
793 * filt_timerupdate - compute the next deadline
795 * Repeating timers store their interval in kn_sdata. Absolute
796 * timers have already calculated the deadline, stored in ext[0].
798 * On return, the next deadline (or zero if no deadline is needed)
799 * is stored in kn_ext[0].
801 * Timer filter lock is held.
804 filt_timerupdate(struct knote
*kn
)
806 /* if there's no interval, deadline is just in kn_ext[0] */
807 if (kn
->kn_sdata
== 0)
810 /* if timer hasn't fired before, fire in interval nsecs */
811 if (kn
->kn_ext
[0] == 0) {
812 clock_absolutetime_interval_to_deadline(kn
->kn_sdata
,
816 * If timer has fired before, schedule the next pop
817 * relative to the last intended deadline.
819 * We could check for whether the deadline has expired,
820 * but the thread call layer can handle that.
822 kn
->kn_ext
[0] += kn
->kn_sdata
;
827 * filt_timerexpire - the timer callout routine
829 * Just propagate the timer event into the knote
830 * filter routine (by going through the knote
831 * synchronization point). Pass a hint to
832 * indicate this is a real event, not just a
836 filt_timerexpire(void *knx
, __unused
void *spare
)
838 struct klist timer_list
;
839 struct knote
*kn
= knx
;
843 kn
->kn_hookid
&= ~TIMER_RUNNING
;
845 /* no "object" for timers, so fake a list */
846 SLIST_INIT(&timer_list
);
847 SLIST_INSERT_HEAD(&timer_list
, kn
, kn_selnext
);
848 KNOTE(&timer_list
, 1);
850 /* if someone is waiting for timer to pop */
851 if (kn
->kn_hookid
& TIMER_CANCELWAIT
) {
852 struct kqueue
*kq
= kn
->kn_kq
;
853 waitq_wakeup64_all((struct waitq
*)kq
->kq_wqs
,
854 CAST_EVENT64_T(&kn
->kn_hook
),
856 WAITQ_ALL_PRIORITIES
);
863 * Cancel a running timer (or wait for the pop).
864 * Timer filter lock is held.
867 filt_timercancel(struct knote
*kn
)
869 struct kqueue
*kq
= kn
->kn_kq
;
870 thread_call_t callout
= kn
->kn_hook
;
873 if (kn
->kn_hookid
& TIMER_RUNNING
) {
874 /* cancel the callout if we can */
875 cancelled
= thread_call_cancel(callout
);
877 kn
->kn_hookid
&= ~TIMER_RUNNING
;
879 /* we have to wait for the expire routine. */
880 kn
->kn_hookid
|= TIMER_CANCELWAIT
;
881 waitq_assert_wait64((struct waitq
*)kq
->kq_wqs
,
882 CAST_EVENT64_T(&kn
->kn_hook
),
883 THREAD_UNINT
, TIMEOUT_WAIT_FOREVER
);
885 thread_block(THREAD_CONTINUE_NULL
);
887 assert((kn
->kn_hookid
& TIMER_RUNNING
) == 0);
893 * Allocate a thread call for the knote's lifetime, and kick off the timer.
896 filt_timerattach(struct knote
*kn
)
898 thread_call_t callout
;
901 callout
= thread_call_allocate(filt_timerexpire
, kn
);
906 error
= filt_timervalidate(kn
);
909 thread_call_free(callout
);
913 kn
->kn_hook
= (void*)callout
;
916 /* absolute=EV_ONESHOT */
917 if (kn
->kn_sfflags
& NOTE_ABSOLUTE
)
918 kn
->kn_flags
|= EV_ONESHOT
;
920 filt_timerupdate(kn
);
922 kn
->kn_flags
|= EV_CLEAR
;
923 unsigned int timer_flags
= 0;
924 if (kn
->kn_sfflags
& NOTE_CRITICAL
)
925 timer_flags
|= THREAD_CALL_DELAY_USER_CRITICAL
;
926 else if (kn
->kn_sfflags
& NOTE_BACKGROUND
)
927 timer_flags
|= THREAD_CALL_DELAY_USER_BACKGROUND
;
929 timer_flags
|= THREAD_CALL_DELAY_USER_NORMAL
;
931 if (kn
->kn_sfflags
& NOTE_LEEWAY
)
932 timer_flags
|= THREAD_CALL_DELAY_LEEWAY
;
934 thread_call_enter_delayed_with_leeway(callout
, NULL
,
935 kn
->kn_ext
[0], kn
->kn_ext
[1], timer_flags
);
937 kn
->kn_hookid
|= TIMER_RUNNING
;
948 * Shut down the timer if it's running, and free the callout.
951 filt_timerdetach(struct knote
*kn
)
953 thread_call_t callout
;
957 callout
= (thread_call_t
)kn
->kn_hook
;
958 filt_timercancel(kn
);
962 thread_call_free(callout
);
968 filt_timer(struct knote
*kn
, long hint
)
973 /* real timer pop -- timer lock held by filt_timerexpire */
976 if (((kn
->kn_hookid
& TIMER_CANCELWAIT
) == 0) &&
977 ((kn
->kn_flags
& EV_ONESHOT
) == 0)) {
979 /* evaluate next time to fire */
980 filt_timerupdate(kn
);
983 unsigned int timer_flags
= 0;
985 /* keep the callout and re-arm */
986 if (kn
->kn_sfflags
& NOTE_CRITICAL
)
987 timer_flags
|= THREAD_CALL_DELAY_USER_CRITICAL
;
988 else if (kn
->kn_sfflags
& NOTE_BACKGROUND
)
989 timer_flags
|= THREAD_CALL_DELAY_USER_BACKGROUND
;
991 timer_flags
|= THREAD_CALL_DELAY_USER_NORMAL
;
993 if (kn
->kn_sfflags
& NOTE_LEEWAY
)
994 timer_flags
|= THREAD_CALL_DELAY_LEEWAY
;
996 thread_call_enter_delayed_with_leeway(kn
->kn_hook
, NULL
,
997 kn
->kn_ext
[0], kn
->kn_ext
[1], timer_flags
);
999 kn
->kn_hookid
|= TIMER_RUNNING
;
1009 result
= (kn
->kn_data
!= 0);
1018 * filt_timertouch - update knote with new user input
1020 * Cancel and restart the timer based on new user data. When
1021 * the user picks up a knote, clear the count of how many timer
1022 * pops have gone off (in kn_data).
1025 filt_timertouch(struct knote
*kn
, struct kevent_internal_s
*kev
, long type
)
1031 case EVENT_REGISTER
:
1032 /* cancel current call */
1033 filt_timercancel(kn
);
1035 /* recalculate deadline */
1036 kn
->kn_sdata
= kev
->data
;
1037 kn
->kn_sfflags
= kev
->fflags
;
1038 kn
->kn_ext
[0] = kev
->ext
[0];
1039 kn
->kn_ext
[1] = kev
->ext
[1];
1041 error
= filt_timervalidate(kn
);
1043 /* no way to report error, so mark it in the knote */
1044 kn
->kn_flags
|= EV_ERROR
;
1045 kn
->kn_data
= error
;
1049 /* start timer if necessary */
1050 filt_timerupdate(kn
);
1052 if (kn
->kn_ext
[0]) {
1053 unsigned int timer_flags
= 0;
1054 if (kn
->kn_sfflags
& NOTE_CRITICAL
)
1055 timer_flags
|= THREAD_CALL_DELAY_USER_CRITICAL
;
1056 else if (kn
->kn_sfflags
& NOTE_BACKGROUND
)
1057 timer_flags
|= THREAD_CALL_DELAY_USER_BACKGROUND
;
1059 timer_flags
|= THREAD_CALL_DELAY_USER_NORMAL
;
1061 if (kn
->kn_sfflags
& NOTE_LEEWAY
)
1062 timer_flags
|= THREAD_CALL_DELAY_LEEWAY
;
1064 thread_call_enter_delayed_with_leeway(kn
->kn_hook
, NULL
,
1065 kn
->kn_ext
[0], kn
->kn_ext
[1], timer_flags
);
1067 kn
->kn_hookid
|= TIMER_RUNNING
;
1069 /* pretend the timer has fired */
1076 /* reset the timer pop count in kn_data */
1077 *kev
= kn
->kn_kevent
;
1080 if (kn
->kn_flags
& EV_CLEAR
)
1084 panic("%s: - invalid type (%ld)", __func__
, type
);
1092 filt_timerlock(void)
1094 lck_mtx_lock(&_filt_timerlock
);
1098 filt_timerunlock(void)
1100 lck_mtx_unlock(&_filt_timerlock
);
1104 filt_userattach(struct knote
*kn
)
1106 /* EVFILT_USER knotes are not attached to anything in the kernel */
1108 if (kn
->kn_fflags
& NOTE_TRIGGER
) {
1117 filt_userdetach(__unused
struct knote
*kn
)
1119 /* EVFILT_USER knotes are not attached to anything in the kernel */
1123 filt_user(struct knote
*kn
, __unused
long hint
)
1125 return (kn
->kn_hookid
);
1129 filt_usertouch(struct knote
*kn
, struct kevent_internal_s
*kev
, long type
)
1133 case EVENT_REGISTER
:
1134 if (kev
->fflags
& NOTE_TRIGGER
) {
1138 ffctrl
= kev
->fflags
& NOTE_FFCTRLMASK
;
1139 kev
->fflags
&= NOTE_FFLAGSMASK
;
1144 OSBitAndAtomic(kev
->fflags
, &kn
->kn_sfflags
);
1147 OSBitOrAtomic(kev
->fflags
, &kn
->kn_sfflags
);
1150 kn
->kn_sfflags
= kev
->fflags
;
1153 kn
->kn_sdata
= kev
->data
;
1156 *kev
= kn
->kn_kevent
;
1157 kev
->fflags
= (volatile UInt32
)kn
->kn_sfflags
;
1158 kev
->data
= kn
->kn_sdata
;
1159 if (kn
->kn_flags
& EV_CLEAR
) {
1166 panic("%s: - invalid type (%ld)", __func__
, type
);
1172 * JMM - placeholder for not-yet-implemented filters
1175 filt_badattach(__unused
struct knote
*kn
)
1181 kqueue_alloc(struct proc
*p
)
1183 struct filedesc
*fdp
= p
->p_fd
;
1186 MALLOC_ZONE(kq
, struct kqueue
*, sizeof (struct kqueue
), M_KQUEUE
,
1189 struct waitq_set
*wqs
;
1191 wqs
= waitq_set_alloc(SYNC_POLICY_FIFO
| SYNC_POLICY_PREPOST
| SYNC_POLICY_DISABLE_IRQ
);
1193 bzero(kq
, sizeof (struct kqueue
));
1194 lck_spin_init(&kq
->kq_lock
, kq_lck_grp
, kq_lck_attr
);
1195 TAILQ_INIT(&kq
->kq_head
);
1199 FREE_ZONE(kq
, sizeof (struct kqueue
), M_KQUEUE
);
1204 if (fdp
->fd_knlistsize
< 0) {
1206 if (fdp
->fd_knlistsize
< 0)
1207 fdp
->fd_knlistsize
= 0; /* this process has had a kq */
1215 * kqueue_dealloc - detach all knotes from a kqueue and free it
1217 * We walk each list looking for knotes referencing this
1218 * this kqueue. If we find one, we try to drop it. But
1219 * if we fail to get a drop reference, that will wait
1220 * until it is dropped. So, we can just restart again
1221 * safe in the assumption that the list will eventually
1222 * not contain any more references to this kqueue (either
1223 * we dropped them all, or someone else did).
1225 * Assumes no new events are being added to the kqueue.
1226 * Nothing locked on entry or exit.
1229 kqueue_dealloc(struct kqueue
*kq
)
1232 struct filedesc
*fdp
;
1243 for (i
= 0; i
< fdp
->fd_knlistsize
; i
++) {
1244 kn
= SLIST_FIRST(&fdp
->fd_knlist
[i
]);
1245 while (kn
!= NULL
) {
1246 if (kq
== kn
->kn_kq
) {
1249 /* drop it ourselves or wait */
1250 if (kqlock2knotedrop(kq
, kn
)) {
1251 kn
->kn_fop
->f_detach(kn
);
1255 /* start over at beginning of list */
1256 kn
= SLIST_FIRST(&fdp
->fd_knlist
[i
]);
1259 kn
= SLIST_NEXT(kn
, kn_link
);
1262 if (fdp
->fd_knhashmask
!= 0) {
1263 for (i
= 0; i
< (int)fdp
->fd_knhashmask
+ 1; i
++) {
1264 kn
= SLIST_FIRST(&fdp
->fd_knhash
[i
]);
1265 while (kn
!= NULL
) {
1266 if (kq
== kn
->kn_kq
) {
1269 /* drop it ourselves or wait */
1270 if (kqlock2knotedrop(kq
, kn
)) {
1271 kn
->kn_fop
->f_detach(kn
);
1275 /* start over at beginning of list */
1276 kn
= SLIST_FIRST(&fdp
->fd_knhash
[i
]);
1279 kn
= SLIST_NEXT(kn
, kn_link
);
1286 * waitq_set_free() clears all preposts and also remove the KQ's
1287 * waitq set from any select sets to which it may belong.
1289 waitq_set_free(kq
->kq_wqs
);
1291 lck_spin_destroy(&kq
->kq_lock
, kq_lck_grp
);
1292 FREE_ZONE(kq
, sizeof (struct kqueue
), M_KQUEUE
);
1296 kqueue_body(struct proc
*p
, fp_allocfn_t fp_zalloc
, void *cra
, int32_t *retval
)
1299 struct fileproc
*fp
;
1302 error
= falloc_withalloc(p
,
1303 &fp
, &fd
, vfs_context_current(), fp_zalloc
, cra
);
1308 kq
= kqueue_alloc(p
);
1314 fp
->f_flag
= FREAD
| FWRITE
;
1315 fp
->f_ops
= &kqueueops
;
1319 *fdflags(p
, fd
) |= UF_EXCLOSE
;
1320 procfdtbl_releasefd(p
, fd
, NULL
);
1321 fp_drop(p
, fd
, fp
, 1);
1329 kqueue(struct proc
*p
, __unused
struct kqueue_args
*uap
, int32_t *retval
)
1331 return (kqueue_body(p
, fileproc_alloc_init
, NULL
, retval
));
1335 kevent_copyin(user_addr_t
*addrp
, struct kevent_internal_s
*kevp
, struct proc
*p
,
1341 if (flags
& KEVENT_FLAG_LEGACY32
) {
1342 bzero(kevp
, sizeof (*kevp
));
1344 if (IS_64BIT_PROCESS(p
)) {
1345 struct user64_kevent kev64
;
1347 advance
= sizeof (kev64
);
1348 error
= copyin(*addrp
, (caddr_t
)&kev64
, advance
);
1351 kevp
->ident
= kev64
.ident
;
1352 kevp
->filter
= kev64
.filter
;
1353 kevp
->flags
= kev64
.flags
;
1354 kevp
->udata
= kev64
.udata
;
1355 kevp
->fflags
= kev64
.fflags
;
1356 kevp
->data
= kev64
.data
;
1358 struct user32_kevent kev32
;
1360 advance
= sizeof (kev32
);
1361 error
= copyin(*addrp
, (caddr_t
)&kev32
, advance
);
1364 kevp
->ident
= (uintptr_t)kev32
.ident
;
1365 kevp
->filter
= kev32
.filter
;
1366 kevp
->flags
= kev32
.flags
;
1367 kevp
->udata
= CAST_USER_ADDR_T(kev32
.udata
);
1368 kevp
->fflags
= kev32
.fflags
;
1369 kevp
->data
= (intptr_t)kev32
.data
;
1371 } else if (flags
& KEVENT_FLAG_LEGACY64
) {
1372 struct kevent64_s kev64
;
1374 bzero(kevp
, sizeof (*kevp
));
1376 advance
= sizeof (struct kevent64_s
);
1377 error
= copyin(*addrp
, (caddr_t
)&kev64
, advance
);
1380 kevp
->ident
= kev64
.ident
;
1381 kevp
->filter
= kev64
.filter
;
1382 kevp
->flags
= kev64
.flags
;
1383 kevp
->udata
= kev64
.udata
;
1384 kevp
->fflags
= kev64
.fflags
;
1385 kevp
->data
= kev64
.data
;
1386 kevp
->ext
[0] = kev64
.ext
[0];
1387 kevp
->ext
[1] = kev64
.ext
[1];
1390 struct kevent_qos_s kevqos
;
1392 bzero(kevp
, sizeof (*kevp
));
1394 advance
= sizeof (struct kevent_qos_s
);
1395 error
= copyin(*addrp
, (caddr_t
)&kevqos
, advance
);
1398 kevp
->ident
= kevqos
.ident
;
1399 kevp
->filter
= kevqos
.filter
;
1400 kevp
->flags
= kevqos
.flags
;
1401 kevp
->udata
= kevqos
.udata
;
1402 kevp
->fflags
= kevqos
.fflags
;
1403 kevp
->data
= kevqos
.data
;
1404 kevp
->ext
[0] = kevqos
.ext
[0];
1405 kevp
->ext
[1] = kevqos
.ext
[1];
1413 kevent_copyout(struct kevent_internal_s
*kevp
, user_addr_t
*addrp
, struct proc
*p
,
1416 user_addr_t addr
= *addrp
;
1420 if (flags
& KEVENT_FLAG_LEGACY32
) {
1421 assert((flags
& KEVENT_FLAG_STACK_EVENTS
) == 0);
1423 if (IS_64BIT_PROCESS(p
)) {
1424 struct user64_kevent kev64
;
1427 * deal with the special case of a user-supplied
1428 * value of (uintptr_t)-1.
1430 kev64
.ident
= (kevp
->ident
== (uintptr_t)-1) ?
1431 (uint64_t)-1LL : (uint64_t)kevp
->ident
;
1433 kev64
.filter
= kevp
->filter
;
1434 kev64
.flags
= kevp
->flags
;
1435 kev64
.fflags
= kevp
->fflags
;
1436 kev64
.data
= (int64_t) kevp
->data
;
1437 kev64
.udata
= kevp
->udata
;
1438 advance
= sizeof (kev64
);
1439 error
= copyout((caddr_t
)&kev64
, addr
, advance
);
1441 struct user32_kevent kev32
;
1443 kev32
.ident
= (uint32_t)kevp
->ident
;
1444 kev32
.filter
= kevp
->filter
;
1445 kev32
.flags
= kevp
->flags
;
1446 kev32
.fflags
= kevp
->fflags
;
1447 kev32
.data
= (int32_t)kevp
->data
;
1448 kev32
.udata
= kevp
->udata
;
1449 advance
= sizeof (kev32
);
1450 error
= copyout((caddr_t
)&kev32
, addr
, advance
);
1452 } else if (flags
& KEVENT_FLAG_LEGACY64
) {
1453 struct kevent64_s kev64
;
1455 advance
= sizeof (struct kevent64_s
);
1456 if (flags
& KEVENT_FLAG_STACK_EVENTS
) {
1459 kev64
.ident
= kevp
->ident
;
1460 kev64
.filter
= kevp
->filter
;
1461 kev64
.flags
= kevp
->flags
;
1462 kev64
.fflags
= kevp
->fflags
;
1463 kev64
.data
= (int64_t) kevp
->data
;
1464 kev64
.udata
= kevp
->udata
;
1465 kev64
.ext
[0] = kevp
->ext
[0];
1466 kev64
.ext
[1] = kevp
->ext
[1];
1467 error
= copyout((caddr_t
)&kev64
, addr
, advance
);
1469 struct kevent_qos_s kevqos
;
1471 bzero(&kevqos
, sizeof (struct kevent_qos_s
));
1472 advance
= sizeof (struct kevent_qos_s
);
1473 if (flags
& KEVENT_FLAG_STACK_EVENTS
) {
1476 kevqos
.ident
= kevp
->ident
;
1477 kevqos
.filter
= kevp
->filter
;
1478 kevqos
.flags
= kevp
->flags
;
1479 kevqos
.fflags
= kevp
->fflags
;
1480 kevqos
.data
= (int64_t) kevp
->data
;
1481 kevqos
.udata
= kevp
->udata
;
1482 kevqos
.ext
[0] = kevp
->ext
[0];
1483 kevqos
.ext
[1] = kevp
->ext
[1];
1484 error
= copyout((caddr_t
)&kevqos
, addr
, advance
);
1487 if (flags
& KEVENT_FLAG_STACK_EVENTS
)
1490 *addrp
= addr
+ advance
;
1496 * kevent_continue - continue a kevent syscall after blocking
1498 * assume we inherit a use count on the kq fileglob.
1502 kevent_continue(__unused
struct kqueue
*kq
, void *data
, int error
)
1504 struct _kevent
*cont_args
;
1505 struct fileproc
*fp
;
1509 struct proc
*p
= current_proc();
1511 cont_args
= (struct _kevent
*)data
;
1512 noutputs
= cont_args
->eventout
;
1513 retval
= cont_args
->retval
;
1518 fp_drop(p
, fd
, fp
, 0);
1520 /* don't restart after signals... */
1521 if (error
== ERESTART
)
1523 else if (error
== EWOULDBLOCK
)
1527 unix_syscall_return(error
);
1531 * kevent - [syscall] register and wait for kernel events
1535 kevent(struct proc
*p
, struct kevent_args
*uap
, int32_t *retval
)
1537 unsigned int flags
= KEVENT_FLAG_LEGACY32
;
1539 return kevent_internal(p
,
1541 uap
->changelist
, uap
->nchanges
,
1542 uap
->eventlist
, uap
->nevents
,
1551 kevent64(struct proc
*p
, struct kevent64_args
*uap
, int32_t *retval
)
1555 /* restrict to user flags and set legacy64 */
1556 flags
= uap
->flags
& KEVENT_FLAG_USER
;
1557 flags
|= KEVENT_FLAG_LEGACY64
;
1559 return kevent_internal(p
,
1561 uap
->changelist
, uap
->nchanges
,
1562 uap
->eventlist
, uap
->nevents
,
1571 kevent_qos(struct proc
*p
, struct kevent_qos_args
*uap
, int32_t *retval
)
1573 user_size_t usize
= 0;
1577 /* restrict to user flags */
1578 uap
->flags
&= KEVENT_FLAG_USER
;
1580 if (uap
->data_available
) {
1581 if (!IS_64BIT_PROCESS(p
)) {
1584 error
= copyin(uap
->data_available
, (caddr_t
)&csize
, sizeof(csize
));
1590 error
= copyin(uap
->data_available
, (caddr_t
)&csize
, sizeof(csize
));
1598 error
= kevent_internal(p
,
1600 uap
->changelist
, uap
->nchanges
,
1601 uap
->eventlist
, uap
->nevents
,
1602 uap
->data_out
, &usize
,
1608 if (error
== 0 && uap
->data_available
&& usize
!= ssize
) {
1609 if (!IS_64BIT_PROCESS(p
)) {
1610 uint32_t csize
= (uint32_t)usize
;
1612 error
= copyout((caddr_t
)&csize
, uap
->data_available
, sizeof(csize
));
1614 error
= copyout((caddr_t
)&usize
, uap
->data_available
, sizeof(usize
));
1621 kevent_qos_internal(struct proc
*p
, int fd
,
1622 user_addr_t changelist
, int nchanges
,
1623 user_addr_t eventlist
, int nevents
,
1624 user_addr_t data_out
, user_size_t
*data_available
,
1628 return kevent_internal(p
,
1630 changelist
, nchanges
,
1632 data_out
, data_available
,
1640 kevent_internal(struct proc
*p
,
1642 user_addr_t changelist
, int nchanges
,
1643 user_addr_t ueventlist
, int nevents
,
1644 user_addr_t data_out
, user_size_t
*data_available
,
1646 user_addr_t utimeout
,
1647 kqueue_continue_t continuation
,
1650 struct _kevent
*cont_args
;
1653 struct fileproc
*fp
= NULL
;
1654 struct kevent_internal_s kev
;
1655 int error
= 0, noutputs
;
1659 /* temporarily ignore these fields */
1661 (void)data_available
;
1664 /* prepare to deal with stack-wise allocation of out events */
1665 if (flags
& KEVENT_FLAG_STACK_EVENTS
) {
1666 int scale
= ((flags
& KEVENT_FLAG_LEGACY32
) ?
1667 (IS_64BIT_PROCESS(p
) ? sizeof(struct user64_kevent
) :
1668 sizeof(struct user32_kevent
)) :
1669 ((flags
& KEVENT_FLAG_LEGACY64
) ? sizeof(struct kevent64_s
) :
1670 sizeof(struct kevent_qos_s
)));
1671 ueventlist
+= nevents
* scale
;
1674 /* convert timeout to absolute - if we have one (and not immediate) */
1675 if (flags
& KEVENT_FLAG_IMMEDIATE
) {
1676 getmicrouptime(&atv
);
1677 } else if (utimeout
!= USER_ADDR_NULL
) {
1679 if (IS_64BIT_PROCESS(p
)) {
1680 struct user64_timespec ts
;
1681 error
= copyin(utimeout
, &ts
, sizeof(ts
));
1682 if ((ts
.tv_sec
& 0xFFFFFFFF00000000ull
) != 0)
1685 TIMESPEC_TO_TIMEVAL(&rtv
, &ts
);
1687 struct user32_timespec ts
;
1688 error
= copyin(utimeout
, &ts
, sizeof(ts
));
1689 TIMESPEC_TO_TIMEVAL(&rtv
, &ts
);
1693 if (itimerfix(&rtv
))
1695 getmicrouptime(&atv
);
1696 timevaladd(&atv
, &rtv
);
1698 /* wait forever value */
1703 if (flags
& KEVENT_FLAG_WORKQ
) {
1705 * use the private kq associated with the proc workq.
1706 * Just being a thread within the process (and not
1707 * being the exit/exec thread) is enough to hold a
1708 * reference on this special kq.
1712 struct kqueue
*alloc_kq
= kqueue_alloc(p
);
1713 if (alloc_kq
== NULL
)
1717 if (p
->p_wqkqueue
== NULL
) {
1719 * The kq is marked as special -
1720 * with unique interactions with
1721 * the workq for this process.
1723 alloc_kq
->kq_state
|= KQ_WORKQ
;
1724 kq
= p
->p_wqkqueue
= alloc_kq
;
1729 kqueue_dealloc(alloc_kq
);
1733 /* get a usecount for the kq itself */
1734 if ((error
= fp_getfkq(p
, fd
, &fp
, &kq
)) != 0)
1738 /* each kq should only be used for events of one type */
1740 if (kq
->kq_state
& (KQ_KEV32
| KQ_KEV64
| KQ_KEV_QOS
)) {
1741 if (flags
& KEVENT_FLAG_LEGACY32
) {
1742 if ((kq
->kq_state
& KQ_KEV32
) == 0) {
1747 } else if (kq
->kq_state
& KQ_KEV32
) {
1752 } else if (flags
& KEVENT_FLAG_LEGACY32
) {
1753 kq
->kq_state
|= KQ_KEV32
;
1755 /* JMM - set KQ_KEVQOS when we are ready for exclusive */
1756 kq
->kq_state
|= KQ_KEV64
;
1760 /* register all the change requests the user provided... */
1762 while (nchanges
> 0 && error
== 0) {
1763 error
= kevent_copyin(&changelist
, &kev
, p
, flags
);
1767 kev
.flags
&= ~EV_SYSFLAGS
;
1768 error
= kevent_register(kq
, &kev
, p
);
1769 if ((error
|| (kev
.flags
& EV_RECEIPT
)) && nevents
> 0) {
1770 kev
.flags
= EV_ERROR
;
1772 error
= kevent_copyout(&kev
, &ueventlist
, p
, flags
);
1781 /* short-circuit the scan if we only want error events */
1782 if (flags
& KEVENT_FLAG_ERROR_EVENTS
)
1785 if (nevents
> 0 && noutputs
== 0 && error
== 0) {
1787 /* store the continuation/completion data in the uthread */
1788 ut
= (uthread_t
)get_bsdthread_info(current_thread());
1789 cont_args
= &ut
->uu_kevent
.ss_kevent
;
1792 cont_args
->retval
= retval
;
1793 cont_args
->eventlist
= ueventlist
;
1794 cont_args
->eventcount
= nevents
;
1795 cont_args
->eventout
= noutputs
;
1796 cont_args
->eventflags
= flags
;
1798 error
= kqueue_scan(kq
, kevent_callback
,
1799 continuation
, cont_args
,
1802 noutputs
= cont_args
->eventout
;
1805 /* don't restart after signals... */
1806 if (error
== ERESTART
)
1808 else if (error
== EWOULDBLOCK
)
1814 fp_drop(p
, fd
, fp
, 0);
1820 * kevent_callback - callback for each individual event
1822 * called with nothing locked
1823 * caller holds a reference on the kqueue
1826 kevent_callback(__unused
struct kqueue
*kq
, struct kevent_internal_s
*kevp
,
1829 struct _kevent
*cont_args
;
1832 cont_args
= (struct _kevent
*)data
;
1833 assert(cont_args
->eventout
< cont_args
->eventcount
);
1836 * Copy out the appropriate amount of event data for this user.
1838 error
= kevent_copyout(kevp
, &cont_args
->eventlist
, current_proc(),
1839 cont_args
->eventflags
);
1842 * If there isn't space for additional events, return
1843 * a harmless error to stop the processing here
1845 if (error
== 0 && ++cont_args
->eventout
== cont_args
->eventcount
)
1846 error
= EWOULDBLOCK
;
1851 * kevent_description - format a description of a kevent for diagnostic output
1853 * called with a 256-byte string buffer
1857 kevent_description(struct kevent_internal_s
*kevp
, char *s
, size_t n
)
1861 "{.ident=%#llx, .filter=%d, .flags=%#x, .udata=%#llx, .fflags=%#x, .data=%#llx, .ext[0]=%#llx, .ext[1]=%#llx}",
1875 * kevent_register - add a new event to a kqueue
1877 * Creates a mapping between the event source and
1878 * the kqueue via a knote data structure.
1880 * Because many/most the event sources are file
1881 * descriptor related, the knote is linked off
1882 * the filedescriptor table for quick access.
1884 * called with nothing locked
1885 * caller holds a reference on the kqueue
1889 kevent_register(struct kqueue
*kq
, struct kevent_internal_s
*kev
,
1890 __unused
struct proc
*ctxp
)
1892 struct proc
*p
= kq
->kq_p
;
1893 struct filedesc
*fdp
= p
->p_fd
;
1894 struct filterops
*fops
;
1895 struct fileproc
*fp
= NULL
;
1896 struct knote
*kn
= NULL
;
1900 if (kev
->filter
< 0) {
1901 if (kev
->filter
+ EVFILT_SYSCOUNT
< 0)
1903 fops
= sysfilt_ops
[~kev
->filter
]; /* to 0-base index */
1909 /* this iocount needs to be dropped if it is not registered */
1914 * determine where to look for the knote
1917 if ((error
= fp_lookup(p
, kev
->ident
, &fp
, 1)) != 0) {
1921 /* fd-based knotes are linked off the fd table */
1922 if (kev
->ident
< (u_int
)fdp
->fd_knlistsize
) {
1923 list
= &fdp
->fd_knlist
[kev
->ident
];
1925 } else if (fdp
->fd_knhashmask
!= 0) {
1926 /* hash non-fd knotes here too */
1927 list
= &fdp
->fd_knhash
[KN_HASH((u_long
)kev
->ident
, fdp
->fd_knhashmask
)];
1931 * scan the selected list looking for a match
1934 SLIST_FOREACH(kn
, list
, kn_link
) {
1935 if (kq
== kn
->kn_kq
&&
1936 kev
->ident
== kn
->kn_id
&&
1937 kev
->filter
== kn
->kn_filter
) {
1938 if (kev
->flags
& EV_UDATA_SPECIFIC
) {
1939 if ((kn
->kn_flags
& EV_UDATA_SPECIFIC
) &&
1940 kev
->udata
== kn
->kn_udata
) {
1941 break; /* matching udata-specific knote */
1943 } else if ((kn
->kn_flags
& EV_UDATA_SPECIFIC
) == 0) {
1944 break; /* matching non-udata-specific knote */
1951 * kn now contains the matching knote, or NULL if no match
1954 if ((kev
->flags
& (EV_ADD
|EV_DELETE
)) == EV_ADD
) {
1963 kn
->kn_tq
= &kq
->kq_head
;
1965 kn
->kn_sfflags
= kev
->fflags
;
1966 kn
->kn_sdata
= kev
->data
;
1969 kn
->kn_kevent
= *kev
;
1970 kn
->kn_inuse
= 1; /* for f_attach() */
1971 kn
->kn_status
= KN_ATTACHING
;
1973 /* before anyone can find it */
1974 if (kev
->flags
& EV_DISABLE
)
1975 kn
->kn_status
|= KN_DISABLED
;
1977 error
= knote_fdpattach(kn
, fdp
, p
);
1986 * apply reference count to knote structure, and
1987 * do not release it at the end of this routine.
1991 error
= fops
->f_attach(kn
);
1997 * Failed to attach correctly, so drop.
1998 * All other possible users/droppers
1999 * have deferred to us.
2001 kn
->kn_status
|= KN_DROPPING
;
2005 } else if (kn
->kn_status
& KN_DROPPING
) {
2007 * Attach succeeded, but someone else
2008 * deferred their drop - now we have
2009 * to do it for them (after detaching).
2012 kn
->kn_fop
->f_detach(kn
);
2016 kn
->kn_status
&= ~KN_ATTACHING
;
2024 /* existing knote - get kqueue lock */
2028 if (kev
->flags
& EV_DELETE
) {
2029 if ((kev
->flags
& EV_ENABLE
) == 0 &&
2030 (kev
->flags
& EV_DISPATCH2
) == EV_DISPATCH2
&&
2031 (kn
->kn_status
& KN_DISABLED
) == KN_DISABLED
) {
2032 /* mark for deferred drop */
2033 kn
->kn_status
|= KN_DEFERDROP
;
2035 error
= EINPROGRESS
;
2038 kn
->kn_status
|= KN_DISABLED
;
2039 if (kqlock2knotedrop(kq
, kn
)) {
2040 kn
->kn_fop
->f_detach(kn
);
2043 /* pretend we didn't find it */
2050 /* update status flags for existing knote */
2051 if (kev
->flags
& EV_DISABLE
) {
2053 kn
->kn_status
|= KN_DISABLED
;
2055 } else if ((kev
->flags
& EV_ENABLE
) &&
2056 (kn
->kn_status
& KN_DISABLED
)) {
2057 kn
->kn_status
&= ~KN_DISABLED
;
2059 /* handle deferred drop */
2060 if (kn
->kn_status
& KN_DEFERDROP
) {
2061 kn
->kn_status
&= ~KN_DEFERDROP
;
2062 kn
->kn_flags
|= (EV_DELETE
| EV_ONESHOT
);
2063 knote_activate(kn
, 0);
2068 if (kn
->kn_status
& KN_ACTIVE
) {
2069 /* force re-activate if previously active */
2070 knote_activate(kn
, 1);
2075 * The user may change some filter values after the
2076 * initial EV_ADD, but doing so will not reset any
2077 * filter which have already been triggered.
2079 kn
->kn_kevent
.udata
= kev
->udata
;
2080 if (fops
->f_isfd
|| fops
->f_touch
== NULL
) {
2081 kn
->kn_sfflags
= kev
->fflags
;
2082 kn
->kn_sdata
= kev
->data
;
2086 * If somebody is in the middle of dropping this
2087 * knote - go find/insert a new one. But we have
2088 * wait for this one to go away first. Attaches
2089 * running in parallel may also drop/modify the
2090 * knote. Wait for those to complete as well and
2091 * then start over if we encounter one.
2093 if (!kqlock2knoteusewait(kq
, kn
)) {
2094 /* kqueue, proc_fdlock both unlocked */
2099 * Call touch routine to notify filter of changes
2102 if (!fops
->f_isfd
&& fops
->f_touch
!= NULL
)
2103 fops
->f_touch(kn
, kev
, EVENT_REGISTER
);
2105 /* still have use ref on knote */
2108 * Invoke the filter routine to see if it should be enqueued now.
2111 if (kn
->kn_fop
->f_event(kn
, 0)) {
2114 * JMM - temporary workaround until rdar://problem/19986199
2115 * This potentially results in extra wakeups for KN_STAYQUEUED event types,
2116 * but waking up only truly active ones (yet trying below to determine
2117 * active status, by invoking the filter routine, is having side-effects).
2119 if ((kn
->kn_status
& KN_STAYQUEUED
) || kn
->kn_fop
->f_event(kn
, 0)) {
2121 if (knoteuse2kqlock(kq
, kn
))
2122 knote_activate(kn
, (kn
->kn_status
& KN_STAYQUEUED
));
2130 fp_drop(p
, kev
->ident
, fp
, 0);
2136 * knote_process - process a triggered event
2138 * Validate that it is really still a triggered event
2139 * by calling the filter routines (if necessary). Hold
2140 * a use reference on the knote to avoid it being detached.
2141 * If it is still considered triggered, invoke the callback
2142 * routine provided and move it to the provided inprocess
2145 * caller holds a reference on the kqueue.
2146 * kqueue locked on entry and exit - but may be dropped
2149 knote_process(struct knote
*kn
,
2150 kevent_callback_t callback
,
2152 struct kqtailq
*inprocessp
,
2155 struct kqueue
*kq
= kn
->kn_kq
;
2156 struct kevent_internal_s kev
;
2162 * Determine the kevent state we want to return.
2164 * Some event states need to be revalidated before returning
2165 * them, others we take the snapshot at the time the event
2168 * Events with non-NULL f_touch operations must be touched.
2169 * Triggered events must fill in kev for the callback.
2171 * Convert our lock to a use-count and call the event's
2172 * filter routine(s) to update.
2174 if ((kn
->kn_status
& KN_DISABLED
) != 0) {
2181 revalidate
= ((kn
->kn_status
& KN_STAYQUEUED
) != 0 ||
2182 (kn
->kn_flags
& EV_ONESHOT
) == 0);
2183 touch
= (!kn
->kn_fop
->f_isfd
&& kn
->kn_fop
->f_touch
!= NULL
);
2185 if (revalidate
|| touch
) {
2187 knote_deactivate(kn
);
2189 /* call the filter/touch routines with just a ref */
2190 if (kqlock2knoteuse(kq
, kn
)) {
2191 /* if we have to revalidate, call the filter */
2193 result
= kn
->kn_fop
->f_event(kn
, 0);
2197 * capture the kevent data - using touch if
2200 if (result
&& touch
) {
2201 kn
->kn_fop
->f_touch(kn
, &kev
,
2204 if (result
&& (kn
->kn_status
& KN_TOUCH
))
2205 kn
->kn_fop
->f_touch(kn
, &kev
,
2209 * convert back to a kqlock - bail if the knote
2212 if (!knoteuse2kqlock(kq
, kn
)) {
2213 return (EJUSTRETURN
);
2214 } else if (result
) {
2216 * if revalidated as alive, make sure
2219 knote_activate(kn
, 0);
2222 * capture all events that occurred
2226 kev
= kn
->kn_kevent
;
2229 } else if ((kn
->kn_status
& KN_STAYQUEUED
) == 0) {
2231 * was already dequeued, so just bail on
2234 return (EJUSTRETURN
);
2237 return (EJUSTRETURN
);
2240 kev
= kn
->kn_kevent
;
2244 /* move knote onto inprocess queue */
2245 assert(kn
->kn_tq
== &kq
->kq_head
);
2246 TAILQ_REMOVE(&kq
->kq_head
, kn
, kn_tqe
);
2247 kn
->kn_tq
= inprocessp
;
2248 TAILQ_INSERT_TAIL(inprocessp
, kn
, kn_tqe
);
2251 * Determine how to dispatch the knote for future event handling.
2252 * not-fired: just return (do not callout).
2253 * One-shot: If dispatch2, enter deferred-delete mode (unless this is
2254 * is the deferred delete event delivery itself). Otherwise,
2255 * deactivate and drop it.
2256 * Clear: deactivate and clear the state.
2257 * Dispatch: don't clear state, just deactivate it and mark it disabled.
2258 * All others: just leave where they are.
2262 return (EJUSTRETURN
);
2263 } else if ((kn
->kn_flags
& EV_ONESHOT
) != 0) {
2264 knote_deactivate(kn
);
2265 if ((kn
->kn_flags
& (EV_DISPATCH2
|EV_DELETE
)) == EV_DISPATCH2
) {
2266 /* defer dropping non-delete oneshot dispatch2 events */
2267 kn
->kn_status
|= (KN_DISABLED
| KN_DEFERDROP
);
2269 } else if (kqlock2knotedrop(kq
, kn
)) {
2270 kn
->kn_fop
->f_detach(kn
);
2273 } else if ((kn
->kn_flags
& (EV_CLEAR
| EV_DISPATCH
)) != 0) {
2274 if ((kn
->kn_flags
& EV_DISPATCH
) != 0) {
2275 /* deactivate and disable all dispatch knotes */
2276 knote_deactivate(kn
);
2277 kn
->kn_status
|= KN_DISABLED
;
2278 } else if (!touch
|| kn
->kn_fflags
== 0) {
2279 /* only deactivate if nothing since the touch */
2280 knote_deactivate(kn
);
2282 if (!touch
&& (kn
->kn_flags
& EV_CLEAR
) != 0) {
2283 /* manually clear non-touch knotes */
2290 * leave on inprocess queue. We'll
2291 * move all the remaining ones back
2292 * the kq queue and wakeup any
2293 * waiters when we are done.
2298 /* callback to handle each event as we find it */
2299 error
= (callback
)(kq
, &kev
, data
);
2306 * Return 0 to indicate that processing should proceed,
2307 * -1 if there is nothing to process.
2309 * Called with kqueue locked and returns the same way,
2310 * but may drop lock temporarily.
2313 kqueue_begin_processing(struct kqueue
*kq
)
2316 if (kq
->kq_count
== 0) {
2320 /* if someone else is processing the queue, wait */
2321 if (kq
->kq_nprocess
!= 0) {
2322 waitq_assert_wait64((struct waitq
*)kq
->kq_wqs
,
2323 CAST_EVENT64_T(&kq
->kq_nprocess
),
2324 THREAD_UNINT
, TIMEOUT_WAIT_FOREVER
);
2325 kq
->kq_state
|= KQ_PROCWAIT
;
2327 thread_block(THREAD_CONTINUE_NULL
);
2330 kq
->kq_nprocess
= 1;
2337 * Called with kqueue lock held.
2340 kqueue_end_processing(struct kqueue
*kq
)
2342 kq
->kq_nprocess
= 0;
2343 if (kq
->kq_state
& KQ_PROCWAIT
) {
2344 kq
->kq_state
&= ~KQ_PROCWAIT
;
2345 waitq_wakeup64_all((struct waitq
*)kq
->kq_wqs
,
2346 CAST_EVENT64_T(&kq
->kq_nprocess
),
2348 WAITQ_ALL_PRIORITIES
);
2353 * kqueue_process - process the triggered events in a kqueue
2355 * Walk the queued knotes and validate that they are
2356 * really still triggered events by calling the filter
2357 * routines (if necessary). Hold a use reference on
2358 * the knote to avoid it being detached. For each event
2359 * that is still considered triggered, invoke the
2360 * callback routine provided.
2362 * caller holds a reference on the kqueue.
2363 * kqueue locked on entry and exit - but may be dropped
2364 * kqueue list locked (held for duration of call)
2368 kqueue_process(struct kqueue
*kq
,
2369 kevent_callback_t callback
,
2374 struct kqtailq inprocess
;
2379 TAILQ_INIT(&inprocess
);
2381 if (kqueue_begin_processing(kq
) == -1) {
2383 /* Nothing to process */
2388 * Clear any pre-posted status from previous runs, so we
2389 * only detect events that occur during this run.
2391 waitq_set_clear_preposts(kq
->kq_wqs
);
2394 * loop through the enqueued knotes, processing each one and
2395 * revalidating those that need it. As they are processed,
2396 * they get moved to the inprocess queue (so the loop can end).
2401 while (error
== 0 &&
2402 (kn
= TAILQ_FIRST(&kq
->kq_head
)) != NULL
) {
2403 error
= knote_process(kn
, callback
, data
, &inprocess
, p
);
2404 if (error
== EJUSTRETURN
)
2411 * With the kqueue still locked, move any knotes
2412 * remaining on the inprocess queue back to the
2413 * kq's queue and wake up any waiters.
2415 while ((kn
= TAILQ_FIRST(&inprocess
)) != NULL
) {
2416 assert(kn
->kn_tq
== &inprocess
);
2417 TAILQ_REMOVE(&inprocess
, kn
, kn_tqe
);
2418 kn
->kn_tq
= &kq
->kq_head
;
2419 TAILQ_INSERT_TAIL(&kq
->kq_head
, kn
, kn_tqe
);
2422 kqueue_end_processing(kq
);
2430 kqueue_scan_continue(void *data
, wait_result_t wait_result
)
2432 thread_t self
= current_thread();
2433 uthread_t ut
= (uthread_t
)get_bsdthread_info(self
);
2434 struct _kqueue_scan
* cont_args
= &ut
->uu_kevent
.ss_kqueue_scan
;
2435 struct kqueue
*kq
= (struct kqueue
*)data
;
2439 /* convert the (previous) wait_result to a proper error */
2440 switch (wait_result
) {
2441 case THREAD_AWAKENED
:
2443 error
= kqueue_process(kq
, cont_args
->call
, cont_args
, &count
,
2445 if (error
== 0 && count
== 0) {
2446 waitq_assert_wait64((struct waitq
*)kq
->kq_wqs
,
2447 KQ_EVENT
, THREAD_ABORTSAFE
,
2448 cont_args
->deadline
);
2449 kq
->kq_state
|= KQ_SLEEP
;
2451 thread_block_parameter(kqueue_scan_continue
, kq
);
2456 case THREAD_TIMED_OUT
:
2457 error
= EWOULDBLOCK
;
2459 case THREAD_INTERRUPTED
:
2463 panic("%s: - invalid wait_result (%d)", __func__
,
2468 /* call the continuation with the results */
2469 assert(cont_args
->cont
!= NULL
);
2470 (cont_args
->cont
)(kq
, cont_args
->data
, error
);
2475 * kqueue_scan - scan and wait for events in a kqueue
2477 * Process the triggered events in a kqueue.
2479 * If there are no events triggered arrange to
2480 * wait for them. If the caller provided a
2481 * continuation routine, then kevent_scan will
2484 * The callback routine must be valid.
2485 * The caller must hold a use-count reference on the kq.
2489 kqueue_scan(struct kqueue
*kq
,
2490 kevent_callback_t callback
,
2491 kqueue_continue_t continuation
,
2493 struct timeval
*atvp
,
2496 thread_continue_t cont
= THREAD_CONTINUE_NULL
;
2501 assert(callback
!= NULL
);
2505 wait_result_t wait_result
;
2509 * Make a pass through the kq to find events already
2513 error
= kqueue_process(kq
, callback
, data
, &count
, p
);
2515 break; /* lock still held */
2517 /* looks like we have to consider blocking */
2520 /* convert the timeout to a deadline once */
2521 if (atvp
->tv_sec
|| atvp
->tv_usec
) {
2524 clock_get_uptime(&now
);
2525 nanoseconds_to_absolutetime((uint64_t)atvp
->tv_sec
* NSEC_PER_SEC
+
2526 atvp
->tv_usec
* (long)NSEC_PER_USEC
,
2528 if (now
>= deadline
) {
2529 /* non-blocking call */
2530 error
= EWOULDBLOCK
;
2531 break; /* lock still held */
2534 clock_absolutetime_interval_to_deadline(deadline
, &deadline
);
2536 deadline
= 0; /* block forever */
2540 uthread_t ut
= (uthread_t
)get_bsdthread_info(current_thread());
2541 struct _kqueue_scan
*cont_args
= &ut
->uu_kevent
.ss_kqueue_scan
;
2543 cont_args
->call
= callback
;
2544 cont_args
->cont
= continuation
;
2545 cont_args
->deadline
= deadline
;
2546 cont_args
->data
= data
;
2547 cont
= kqueue_scan_continue
;
2551 /* go ahead and wait */
2552 waitq_assert_wait64_leeway((struct waitq
*)kq
->kq_wqs
,
2553 KQ_EVENT
, THREAD_ABORTSAFE
,
2554 TIMEOUT_URGENCY_USER_NORMAL
,
2555 deadline
, TIMEOUT_NO_LEEWAY
);
2556 kq
->kq_state
|= KQ_SLEEP
;
2558 wait_result
= thread_block_parameter(cont
, kq
);
2559 /* NOTREACHED if (continuation != NULL) */
2561 switch (wait_result
) {
2562 case THREAD_AWAKENED
:
2564 case THREAD_TIMED_OUT
:
2565 return (EWOULDBLOCK
);
2566 case THREAD_INTERRUPTED
:
2569 panic("%s: - bad wait_result (%d)", __func__
,
2581 * This could be expanded to call kqueue_scan, if desired.
2585 kqueue_read(__unused
struct fileproc
*fp
,
2586 __unused
struct uio
*uio
,
2588 __unused vfs_context_t ctx
)
2595 kqueue_write(__unused
struct fileproc
*fp
,
2596 __unused
struct uio
*uio
,
2598 __unused vfs_context_t ctx
)
2605 kqueue_ioctl(__unused
struct fileproc
*fp
,
2606 __unused u_long com
,
2607 __unused caddr_t data
,
2608 __unused vfs_context_t ctx
)
2615 kqueue_select(struct fileproc
*fp
, int which
, void *wq_link_id
,
2616 __unused vfs_context_t ctx
)
2618 struct kqueue
*kq
= (struct kqueue
*)fp
->f_data
;
2620 struct kqtailq inprocessq
;
2626 TAILQ_INIT(&inprocessq
);
2630 * If this is the first pass, link the wait queue associated with the
2631 * the kqueue onto the wait queue set for the select(). Normally we
2632 * use selrecord() for this, but it uses the wait queue within the
2633 * selinfo structure and we need to use the main one for the kqueue to
2634 * catch events from KN_STAYQUEUED sources. So we do the linkage manually.
2635 * (The select() call will unlink them when it ends).
2637 if (wq_link_id
!= NULL
) {
2638 thread_t cur_act
= current_thread();
2639 struct uthread
* ut
= get_bsdthread_info(cur_act
);
2641 kq
->kq_state
|= KQ_SEL
;
2642 waitq_link((struct waitq
*)kq
->kq_wqs
, ut
->uu_wqset
,
2643 WAITQ_SHOULD_LOCK
, (uint64_t *)wq_link_id
);
2645 /* always consume the reserved link object */
2646 waitq_link_release(*(uint64_t *)wq_link_id
);
2647 *(uint64_t *)wq_link_id
= 0;
2650 * selprocess() is expecting that we send it back the waitq
2651 * that was just added to the thread's waitq set. In order
2652 * to not change the selrecord() API (which is exported to
2653 * kexts), we pass this value back through the
2654 * void *wq_link_id pointer we were passed. We need to use
2655 * memcpy here because the pointer may not be properly aligned
2656 * on 32-bit systems.
2658 memcpy(wq_link_id
, (void *)&(kq
->kq_wqs
), sizeof(void *));
2661 if (kqueue_begin_processing(kq
) == -1) {
2666 if (kq
->kq_count
!= 0) {
2668 * there is something queued - but it might be a
2669 * KN_STAYQUEUED knote, which may or may not have
2670 * any events pending. So, we have to walk the
2671 * list of knotes to see, and peek at the stay-
2672 * queued ones to be really sure.
2674 while ((kn
= (struct knote
*)TAILQ_FIRST(&kq
->kq_head
)) != NULL
) {
2675 if ((kn
->kn_status
& KN_STAYQUEUED
) == 0) {
2680 TAILQ_REMOVE(&kq
->kq_head
, kn
, kn_tqe
);
2681 TAILQ_INSERT_TAIL(&inprocessq
, kn
, kn_tqe
);
2683 if (kqlock2knoteuse(kq
, kn
)) {
2686 peek
= kn
->kn_fop
->f_peek(kn
);
2687 if (knoteuse2kqlock(kq
, kn
)) {
2700 /* Return knotes to active queue */
2701 while ((kn
= TAILQ_FIRST(&inprocessq
)) != NULL
) {
2702 TAILQ_REMOVE(&inprocessq
, kn
, kn_tqe
);
2703 kn
->kn_tq
= &kq
->kq_head
;
2704 TAILQ_INSERT_TAIL(&kq
->kq_head
, kn
, kn_tqe
);
2707 kqueue_end_processing(kq
);
2717 kqueue_close(struct fileglob
*fg
, __unused vfs_context_t ctx
)
2719 struct kqueue
*kq
= (struct kqueue
*)fg
->fg_data
;
2728 * The callers has taken a use-count reference on this kqueue and will donate it
2729 * to the kqueue we are being added to. This keeps the kqueue from closing until
2730 * that relationship is torn down.
2733 kqueue_kqfilter(__unused
struct fileproc
*fp
, struct knote
*kn
, __unused vfs_context_t ctx
)
2735 struct kqueue
*kq
= (struct kqueue
*)kn
->kn_fp
->f_data
;
2736 struct kqueue
*parentkq
= kn
->kn_kq
;
2738 if (parentkq
== kq
||
2739 kn
->kn_filter
!= EVFILT_READ
)
2743 * We have to avoid creating a cycle when nesting kqueues
2744 * inside another. Rather than trying to walk the whole
2745 * potential DAG of nested kqueues, we just use a simple
2746 * ceiling protocol. When a kqueue is inserted into another,
2747 * we check that the (future) parent is not already nested
2748 * into another kqueue at a lower level than the potenial
2749 * child (because it could indicate a cycle). If that test
2750 * passes, we just mark the nesting levels accordingly.
2754 if (parentkq
->kq_level
> 0 &&
2755 parentkq
->kq_level
< kq
->kq_level
)
2760 /* set parent level appropriately */
2761 if (parentkq
->kq_level
== 0)
2762 parentkq
->kq_level
= 2;
2763 if (parentkq
->kq_level
< kq
->kq_level
+ 1)
2764 parentkq
->kq_level
= kq
->kq_level
+ 1;
2767 kn
->kn_fop
= &kqread_filtops
;
2769 KNOTE_ATTACH(&kq
->kq_sel
.si_note
, kn
);
2770 /* indicate nesting in child, if needed */
2771 if (kq
->kq_level
== 0)
2779 * kqueue_drain - called when kq is closed
2783 kqueue_drain(struct fileproc
*fp
, __unused vfs_context_t ctx
)
2785 struct kqueue
*kq
= (struct kqueue
*)fp
->f_fglob
->fg_data
;
2787 kqueue_wakeup(kq
, 1);
2794 kqueue_stat(struct kqueue
*kq
, void *ub
, int isstat64
, proc_t p
)
2797 if (isstat64
!= 0) {
2798 struct stat64
*sb64
= (struct stat64
*)ub
;
2800 bzero((void *)sb64
, sizeof(*sb64
));
2801 sb64
->st_size
= kq
->kq_count
;
2802 if (kq
->kq_state
& KQ_KEV_QOS
)
2803 sb64
->st_blksize
= sizeof(struct kevent_qos_s
);
2804 else if (kq
->kq_state
& KQ_KEV64
)
2805 sb64
->st_blksize
= sizeof(struct kevent64_s
);
2806 else if (IS_64BIT_PROCESS(p
))
2807 sb64
->st_blksize
= sizeof(struct user64_kevent
);
2809 sb64
->st_blksize
= sizeof(struct user32_kevent
);
2810 sb64
->st_mode
= S_IFIFO
;
2812 struct stat
*sb
= (struct stat
*)ub
;
2814 bzero((void *)sb
, sizeof(*sb
));
2815 sb
->st_size
= kq
->kq_count
;
2816 if (kq
->kq_state
& KQ_KEV_QOS
)
2817 sb
->st_blksize
= sizeof(struct kevent_qos_s
);
2818 else if (kq
->kq_state
& KQ_KEV64
)
2819 sb
->st_blksize
= sizeof(struct kevent64_s
);
2820 else if (IS_64BIT_PROCESS(p
))
2821 sb
->st_blksize
= sizeof(struct user64_kevent
);
2823 sb
->st_blksize
= sizeof(struct user32_kevent
);
2824 sb
->st_mode
= S_IFIFO
;
2831 * Called with the kqueue locked
2834 kqueue_wakeup(struct kqueue
*kq
, int closed
)
2836 wait_result_t res
= THREAD_NOT_WAITING
;
2838 if ((kq
->kq_state
& (KQ_SLEEP
| KQ_SEL
)) != 0 || kq
->kq_nprocess
> 0) {
2839 kq
->kq_state
&= ~(KQ_SLEEP
| KQ_SEL
);
2840 res
= waitq_wakeup64_all((struct waitq
*)kq
->kq_wqs
, KQ_EVENT
,
2841 (closed
) ? THREAD_INTERRUPTED
: THREAD_AWAKENED
,
2842 WAITQ_ALL_PRIORITIES
);
2845 /* request additional workq threads if appropriate */
2846 if (res
== THREAD_NOT_WAITING
&& (kq
->kq_state
& KQ_WORKQ
) &&
2847 pthread_functions
!= NULL
&& pthread_functions
->workq_reqthreads
!= NULL
) {
2849 * The special workq kq should be accumulating the counts of
2850 * queued sources on a pthread_priority_t basis and we should
2851 * be providing that here. For now, just hard-code a single
2852 * entry request at a fixed (default) QOS.
2854 struct workq_reqthreads_req_s request
= {
2855 .priority
= 0x020004ff, /* legacy event manager */
2856 .count
= kq
->kq_count
};
2859 wqthread
= (*pthread_functions
->workq_reqthreads
)(kq
->kq_p
, 1, &request
);
2860 assert(wqthread
== THREAD_NULL
);
2865 klist_init(struct klist
*list
)
2872 * Query/Post each knote in the object's list
2874 * The object lock protects the list. It is assumed
2875 * that the filter/event routine for the object can
2876 * determine that the object is already locked (via
2877 * the hint) and not deadlock itself.
2879 * The object lock should also hold off pending
2880 * detach/drop operations. But we'll prevent it here
2881 * too - just in case.
2884 knote(struct klist
*list
, long hint
)
2888 SLIST_FOREACH(kn
, list
, kn_selnext
) {
2889 struct kqueue
*kq
= kn
->kn_kq
;
2892 if (kqlock2knoteuse(kq
, kn
)) {
2895 /* call the event with only a use count */
2896 result
= kn
->kn_fop
->f_event(kn
, hint
);
2898 /* if its not going away and triggered */
2899 if (knoteuse2kqlock(kq
, kn
) && result
)
2900 knote_activate(kn
, 0);
2901 /* lock held again */
2908 * attach a knote to the specified list. Return true if this is the first entry.
2909 * The list is protected by whatever lock the object it is associated with uses.
2912 knote_attach(struct klist
*list
, struct knote
*kn
)
2914 int ret
= SLIST_EMPTY(list
);
2915 SLIST_INSERT_HEAD(list
, kn
, kn_selnext
);
2920 * detach a knote from the specified list. Return true if that was the last entry.
2921 * The list is protected by whatever lock the object it is associated with uses.
2924 knote_detach(struct klist
*list
, struct knote
*kn
)
2926 SLIST_REMOVE(list
, kn
, knote
, kn_selnext
);
2927 return (SLIST_EMPTY(list
));
2931 * For a given knote, link a provided wait queue directly with the kqueue.
2932 * Wakeups will happen via recursive wait queue support. But nothing will move
2933 * the knote to the active list at wakeup (nothing calls knote()). Instead,
2934 * we permanently enqueue them here.
2936 * kqueue and knote references are held by caller.
2938 * caller provides the wait queue link structure.
2941 knote_link_waitq(struct knote
*kn
, struct waitq
*wq
, uint64_t *reserved_link
)
2943 struct kqueue
*kq
= kn
->kn_kq
;
2946 kr
= waitq_link(wq
, kq
->kq_wqs
, WAITQ_SHOULD_LOCK
, reserved_link
);
2947 if (kr
== KERN_SUCCESS
) {
2948 knote_markstayqueued(kn
);
2956 * Unlink the provided wait queue from the kqueue associated with a knote.
2957 * Also remove it from the magic list of directly attached knotes.
2959 * Note that the unlink may have already happened from the other side, so
2960 * ignore any failures to unlink and just remove it from the kqueue list.
2962 * On success, caller is responsible for the link structure
2965 knote_unlink_waitq(struct knote
*kn
, struct waitq
*wq
)
2967 struct kqueue
*kq
= kn
->kn_kq
;
2970 kr
= waitq_unlink(wq
, kq
->kq_wqs
);
2971 knote_clearstayqueued(kn
);
2972 return ((kr
!= KERN_SUCCESS
) ? EINVAL
: 0);
2976 * remove all knotes referencing a specified fd
2978 * Essentially an inlined knote_remove & knote_drop
2979 * when we know for sure that the thing is a file
2981 * Entered with the proc_fd lock already held.
2982 * It returns the same way, but may drop it temporarily.
2985 knote_fdclose(struct proc
*p
, int fd
)
2987 struct filedesc
*fdp
= p
->p_fd
;
2991 list
= &fdp
->fd_knlist
[fd
];
2992 while ((kn
= SLIST_FIRST(list
)) != NULL
) {
2993 struct kqueue
*kq
= kn
->kn_kq
;
2996 panic("%s: proc mismatch (kq->kq_p=%p != p=%p)",
2997 __func__
, kq
->kq_p
, p
);
3003 * Convert the lock to a drop ref.
3004 * If we get it, go ahead and drop it.
3005 * Otherwise, we waited for it to
3006 * be dropped by the other guy, so
3007 * it is safe to move on in the list.
3009 if (kqlock2knotedrop(kq
, kn
)) {
3010 kn
->kn_fop
->f_detach(kn
);
3016 /* the fd tables may have changed - start over */
3017 list
= &fdp
->fd_knlist
[fd
];
3021 /* proc_fdlock held on entry (and exit) */
3023 knote_fdpattach(struct knote
*kn
, struct filedesc
*fdp
, struct proc
*p
)
3025 struct klist
*list
= NULL
;
3027 if (! kn
->kn_fop
->f_isfd
) {
3028 if (fdp
->fd_knhashmask
== 0)
3029 fdp
->fd_knhash
= hashinit(CONFIG_KN_HASHSIZE
, M_KQUEUE
,
3030 &fdp
->fd_knhashmask
);
3031 list
= &fdp
->fd_knhash
[KN_HASH(kn
->kn_id
, fdp
->fd_knhashmask
)];
3033 if ((u_int
)fdp
->fd_knlistsize
<= kn
->kn_id
) {
3036 if (kn
->kn_id
>= (uint64_t)p
->p_rlimit
[RLIMIT_NOFILE
].rlim_cur
3037 || kn
->kn_id
>= (uint64_t)maxfiles
)
3040 /* have to grow the fd_knlist */
3041 size
= fdp
->fd_knlistsize
;
3042 while (size
<= kn
->kn_id
)
3045 if (size
>= (UINT_MAX
/sizeof(struct klist
*)))
3048 MALLOC(list
, struct klist
*,
3049 size
* sizeof(struct klist
*), M_KQUEUE
, M_WAITOK
);
3053 bcopy((caddr_t
)fdp
->fd_knlist
, (caddr_t
)list
,
3054 fdp
->fd_knlistsize
* sizeof(struct klist
*));
3055 bzero((caddr_t
)list
+
3056 fdp
->fd_knlistsize
* sizeof(struct klist
*),
3057 (size
- fdp
->fd_knlistsize
) * sizeof(struct klist
*));
3058 FREE(fdp
->fd_knlist
, M_KQUEUE
);
3059 fdp
->fd_knlist
= list
;
3060 fdp
->fd_knlistsize
= size
;
3062 list
= &fdp
->fd_knlist
[kn
->kn_id
];
3064 SLIST_INSERT_HEAD(list
, kn
, kn_link
);
3071 * should be called at spl == 0, since we don't want to hold spl
3072 * while calling fdrop and free.
3075 knote_drop(struct knote
*kn
, __unused
struct proc
*ctxp
)
3077 struct kqueue
*kq
= kn
->kn_kq
;
3078 struct proc
*p
= kq
->kq_p
;
3079 struct filedesc
*fdp
= p
->p_fd
;
3084 if (kn
->kn_fop
->f_isfd
)
3085 list
= &fdp
->fd_knlist
[kn
->kn_id
];
3087 list
= &fdp
->fd_knhash
[KN_HASH(kn
->kn_id
, fdp
->fd_knhashmask
)];
3089 SLIST_REMOVE(list
, kn
, knote
, kn_link
);
3092 needswakeup
= (kn
->kn_status
& KN_USEWAIT
);
3097 waitq_wakeup64_all((struct waitq
*)kq
->kq_wqs
,
3098 CAST_EVENT64_T(&kn
->kn_status
),
3100 WAITQ_ALL_PRIORITIES
);
3102 if (kn
->kn_fop
->f_isfd
)
3103 fp_drop(p
, kn
->kn_id
, kn
->kn_fp
, 0);
3108 /* called with kqueue lock held */
3110 knote_activate(struct knote
*kn
, int force
)
3112 struct kqueue
*kq
= kn
->kn_kq
;
3114 if (!force
&& (kn
->kn_status
& KN_ACTIVE
))
3117 kn
->kn_status
|= KN_ACTIVE
;
3119 kqueue_wakeup(kq
, 0);
3121 /* wake up the parent kq, too */
3122 KNOTE(&kq
->kq_sel
.si_note
, 0);
3125 /* called with kqueue lock held */
3127 knote_deactivate(struct knote
*kn
)
3129 kn
->kn_status
&= ~KN_ACTIVE
;
3133 /* called with kqueue lock held */
3135 knote_enqueue(struct knote
*kn
)
3137 if ((kn
->kn_status
& (KN_QUEUED
| KN_STAYQUEUED
)) == KN_STAYQUEUED
||
3138 (kn
->kn_status
& (KN_QUEUED
| KN_STAYQUEUED
| KN_DISABLED
)) == 0) {
3139 struct kqtailq
*tq
= kn
->kn_tq
;
3140 struct kqueue
*kq
= kn
->kn_kq
;
3142 TAILQ_INSERT_TAIL(tq
, kn
, kn_tqe
);
3143 kn
->kn_status
|= KN_QUEUED
;
3148 /* called with kqueue lock held */
3150 knote_dequeue(struct knote
*kn
)
3152 struct kqueue
*kq
= kn
->kn_kq
;
3154 if ((kn
->kn_status
& (KN_QUEUED
| KN_STAYQUEUED
)) == KN_QUEUED
) {
3155 struct kqtailq
*tq
= kn
->kn_tq
;
3157 TAILQ_REMOVE(tq
, kn
, kn_tqe
);
3158 kn
->kn_tq
= &kq
->kq_head
;
3159 kn
->kn_status
&= ~KN_QUEUED
;
3167 knote_zone
= zinit(sizeof(struct knote
), 8192*sizeof(struct knote
),
3168 8192, "knote zone");
3170 /* allocate kq lock group attribute and group */
3171 kq_lck_grp_attr
= lck_grp_attr_alloc_init();
3173 kq_lck_grp
= lck_grp_alloc_init("kqueue", kq_lck_grp_attr
);
3175 /* Allocate kq lock attribute */
3176 kq_lck_attr
= lck_attr_alloc_init();
3178 /* Initialize the timer filter lock */
3179 lck_mtx_init(&_filt_timerlock
, kq_lck_grp
, kq_lck_attr
);
3181 #if VM_PRESSURE_EVENTS
3182 /* Initialize the vm pressure list lock */
3183 vm_pressure_init(kq_lck_grp
, kq_lck_attr
);
3186 #if CONFIG_MEMORYSTATUS
3187 /* Initialize the memorystatus list lock */
3188 memorystatus_kevent_init(kq_lck_grp
, kq_lck_attr
);
3191 SYSINIT(knote
, SI_SUB_PSEUDO
, SI_ORDER_ANY
, knote_init
, NULL
)
3193 static struct knote
*
3196 return ((struct knote
*)zalloc(knote_zone
));
3200 knote_free(struct knote
*kn
)
3202 zfree(knote_zone
, kn
);
3206 #include <sys/param.h>
3207 #include <sys/socket.h>
3208 #include <sys/protosw.h>
3209 #include <sys/domain.h>
3210 #include <sys/mbuf.h>
3211 #include <sys/kern_event.h>
3212 #include <sys/malloc.h>
3213 #include <sys/sys_domain.h>
3214 #include <sys/syslog.h>
3217 #define ROUNDUP64(x) P2ROUNDUP((x), sizeof (u_int64_t))
3221 #define ADVANCE64(p, n) (void*)((char *)(p) + ROUNDUP64(n))
3224 static lck_grp_attr_t
*kev_lck_grp_attr
;
3225 static lck_attr_t
*kev_lck_attr
;
3226 static lck_grp_t
*kev_lck_grp
;
3227 static decl_lck_rw_data(,kev_lck_data
);
3228 static lck_rw_t
*kev_rwlock
= &kev_lck_data
;
3230 static int kev_attach(struct socket
*so
, int proto
, struct proc
*p
);
3231 static int kev_detach(struct socket
*so
);
3232 static int kev_control(struct socket
*so
, u_long cmd
, caddr_t data
,
3233 struct ifnet
*ifp
, struct proc
*p
);
3234 static lck_mtx_t
* event_getlock(struct socket
*, int);
3235 static int event_lock(struct socket
*, int, void *);
3236 static int event_unlock(struct socket
*, int, void *);
3238 static int event_sofreelastref(struct socket
*);
3239 static void kev_delete(struct kern_event_pcb
*);
3241 static struct pr_usrreqs event_usrreqs
= {
3242 .pru_attach
= kev_attach
,
3243 .pru_control
= kev_control
,
3244 .pru_detach
= kev_detach
,
3245 .pru_soreceive
= soreceive
,
3248 static struct protosw eventsw
[] = {
3250 .pr_type
= SOCK_RAW
,
3251 .pr_protocol
= SYSPROTO_EVENT
,
3252 .pr_flags
= PR_ATOMIC
,
3253 .pr_usrreqs
= &event_usrreqs
,
3254 .pr_lock
= event_lock
,
3255 .pr_unlock
= event_unlock
,
3256 .pr_getlock
= event_getlock
,
3260 __private_extern__
int kevt_getstat SYSCTL_HANDLER_ARGS
;
3261 __private_extern__
int kevt_pcblist SYSCTL_HANDLER_ARGS
;
3263 SYSCTL_NODE(_net_systm
, OID_AUTO
, kevt
,
3264 CTLFLAG_RW
|CTLFLAG_LOCKED
, 0, "Kernel event family");
3266 struct kevtstat kevtstat
;
3267 SYSCTL_PROC(_net_systm_kevt
, OID_AUTO
, stats
,
3268 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
, 0, 0,
3269 kevt_getstat
, "S,kevtstat", "");
3271 SYSCTL_PROC(_net_systm_kevt
, OID_AUTO
, pcblist
,
3272 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
, 0, 0,
3273 kevt_pcblist
, "S,xkevtpcb", "");
3276 event_getlock(struct socket
*so
, int locktype
)
3278 #pragma unused(locktype)
3279 struct kern_event_pcb
*ev_pcb
= (struct kern_event_pcb
*)so
->so_pcb
;
3281 if (so
->so_pcb
!= NULL
) {
3282 if (so
->so_usecount
< 0)
3283 panic("%s: so=%p usecount=%d lrh= %s\n", __func__
,
3284 so
, so
->so_usecount
, solockhistory_nr(so
));
3287 panic("%s: so=%p NULL NO so_pcb %s\n", __func__
,
3288 so
, solockhistory_nr(so
));
3291 return (&ev_pcb
->evp_mtx
);
3295 event_lock(struct socket
*so
, int refcount
, void *lr
)
3300 lr_saved
= __builtin_return_address(0);
3304 if (so
->so_pcb
!= NULL
) {
3305 lck_mtx_lock(&((struct kern_event_pcb
*)so
->so_pcb
)->evp_mtx
);
3307 panic("%s: so=%p NO PCB! lr=%p lrh= %s\n", __func__
,
3308 so
, lr_saved
, solockhistory_nr(so
));
3312 if (so
->so_usecount
< 0) {
3313 panic("%s: so=%p so_pcb=%p lr=%p ref=%d lrh= %s\n", __func__
,
3314 so
, so
->so_pcb
, lr_saved
, so
->so_usecount
,
3315 solockhistory_nr(so
));
3322 so
->lock_lr
[so
->next_lock_lr
] = lr_saved
;
3323 so
->next_lock_lr
= (so
->next_lock_lr
+1) % SO_LCKDBG_MAX
;
3328 event_unlock(struct socket
*so
, int refcount
, void *lr
)
3331 lck_mtx_t
*mutex_held
;
3334 lr_saved
= __builtin_return_address(0);
3341 if (so
->so_usecount
< 0) {
3342 panic("%s: so=%p usecount=%d lrh= %s\n", __func__
,
3343 so
, so
->so_usecount
, solockhistory_nr(so
));
3346 if (so
->so_pcb
== NULL
) {
3347 panic("%s: so=%p NO PCB usecount=%d lr=%p lrh= %s\n", __func__
,
3348 so
, so
->so_usecount
, (void *)lr_saved
,
3349 solockhistory_nr(so
));
3352 mutex_held
= (&((struct kern_event_pcb
*)so
->so_pcb
)->evp_mtx
);
3354 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
3355 so
->unlock_lr
[so
->next_unlock_lr
] = lr_saved
;
3356 so
->next_unlock_lr
= (so
->next_unlock_lr
+1) % SO_LCKDBG_MAX
;
3358 if (so
->so_usecount
== 0) {
3359 VERIFY(so
->so_flags
& SOF_PCBCLEARING
);
3360 event_sofreelastref(so
);
3362 lck_mtx_unlock(mutex_held
);
3369 event_sofreelastref(struct socket
*so
)
3371 struct kern_event_pcb
*ev_pcb
= (struct kern_event_pcb
*)so
->so_pcb
;
3373 lck_mtx_assert(&(ev_pcb
->evp_mtx
), LCK_MTX_ASSERT_OWNED
);
3378 * Disable upcall in the event another thread is in kev_post_msg()
3379 * appending record to the receive socket buffer, since sbwakeup()
3380 * may release the socket lock otherwise.
3382 so
->so_rcv
.sb_flags
&= ~SB_UPCALL
;
3383 so
->so_snd
.sb_flags
&= ~SB_UPCALL
;
3384 so
->so_event
= sonullevent
;
3385 lck_mtx_unlock(&(ev_pcb
->evp_mtx
));
3387 lck_mtx_assert(&(ev_pcb
->evp_mtx
), LCK_MTX_ASSERT_NOTOWNED
);
3388 lck_rw_lock_exclusive(kev_rwlock
);
3389 LIST_REMOVE(ev_pcb
, evp_link
);
3390 kevtstat
.kes_pcbcount
--;
3391 kevtstat
.kes_gencnt
++;
3392 lck_rw_done(kev_rwlock
);
3395 sofreelastref(so
, 1);
3399 static int event_proto_count
= (sizeof (eventsw
) / sizeof (struct protosw
));
3402 struct kern_event_head kern_event_head
;
3404 static u_int32_t static_event_id
= 0;
3406 #define EVPCB_ZONE_MAX 65536
3407 #define EVPCB_ZONE_NAME "kerneventpcb"
3408 static struct zone
*ev_pcb_zone
;
3411 * Install the protosw's for the NKE manager. Invoked at extension load time
3414 kern_event_init(struct domain
*dp
)
3419 VERIFY(!(dp
->dom_flags
& DOM_INITIALIZED
));
3420 VERIFY(dp
== systemdomain
);
3422 kev_lck_grp_attr
= lck_grp_attr_alloc_init();
3423 if (kev_lck_grp_attr
== NULL
) {
3424 panic("%s: lck_grp_attr_alloc_init failed\n", __func__
);
3428 kev_lck_grp
= lck_grp_alloc_init("Kernel Event Protocol",
3430 if (kev_lck_grp
== NULL
) {
3431 panic("%s: lck_grp_alloc_init failed\n", __func__
);
3435 kev_lck_attr
= lck_attr_alloc_init();
3436 if (kev_lck_attr
== NULL
) {
3437 panic("%s: lck_attr_alloc_init failed\n", __func__
);
3441 lck_rw_init(kev_rwlock
, kev_lck_grp
, kev_lck_attr
);
3442 if (kev_rwlock
== NULL
) {
3443 panic("%s: lck_mtx_alloc_init failed\n", __func__
);
3447 for (i
= 0, pr
= &eventsw
[0]; i
< event_proto_count
; i
++, pr
++)
3448 net_add_proto(pr
, dp
, 1);
3450 ev_pcb_zone
= zinit(sizeof(struct kern_event_pcb
),
3451 EVPCB_ZONE_MAX
* sizeof(struct kern_event_pcb
), 0, EVPCB_ZONE_NAME
);
3452 if (ev_pcb_zone
== NULL
) {
3453 panic("%s: failed allocating ev_pcb_zone", __func__
);
3456 zone_change(ev_pcb_zone
, Z_EXPAND
, TRUE
);
3457 zone_change(ev_pcb_zone
, Z_CALLERACCT
, TRUE
);
3461 kev_attach(struct socket
*so
, __unused
int proto
, __unused
struct proc
*p
)
3464 struct kern_event_pcb
*ev_pcb
;
3466 error
= soreserve(so
, KEV_SNDSPACE
, KEV_RECVSPACE
);
3470 if ((ev_pcb
= (struct kern_event_pcb
*)zalloc(ev_pcb_zone
)) == NULL
) {
3473 bzero(ev_pcb
, sizeof(struct kern_event_pcb
));
3474 lck_mtx_init(&ev_pcb
->evp_mtx
, kev_lck_grp
, kev_lck_attr
);
3476 ev_pcb
->evp_socket
= so
;
3477 ev_pcb
->evp_vendor_code_filter
= 0xffffffff;
3479 so
->so_pcb
= (caddr_t
) ev_pcb
;
3480 lck_rw_lock_exclusive(kev_rwlock
);
3481 LIST_INSERT_HEAD(&kern_event_head
, ev_pcb
, evp_link
);
3482 kevtstat
.kes_pcbcount
++;
3483 kevtstat
.kes_gencnt
++;
3484 lck_rw_done(kev_rwlock
);
3490 kev_delete(struct kern_event_pcb
*ev_pcb
)
3492 VERIFY(ev_pcb
!= NULL
);
3493 lck_mtx_destroy(&ev_pcb
->evp_mtx
, kev_lck_grp
);
3494 zfree(ev_pcb_zone
, ev_pcb
);
3498 kev_detach(struct socket
*so
)
3500 struct kern_event_pcb
*ev_pcb
= (struct kern_event_pcb
*) so
->so_pcb
;
3502 if (ev_pcb
!= NULL
) {
3503 soisdisconnected(so
);
3504 so
->so_flags
|= SOF_PCBCLEARING
;
3511 * For now, kev_vendor_code and mbuf_tags use the same
3514 errno_t
kev_vendor_code_find(
3516 u_int32_t
*out_vendor_code
)
3518 if (strlen(string
) >= KEV_VENDOR_CODE_MAX_STR_LEN
) {
3521 return (net_str_id_find_internal(string
, out_vendor_code
,
3522 NSI_VENDOR_CODE
, 1));
3526 kev_msg_post(struct kev_msg
*event_msg
)
3528 mbuf_tag_id_t min_vendor
, max_vendor
;
3530 net_str_id_first_last(&min_vendor
, &max_vendor
, NSI_VENDOR_CODE
);
3532 if (event_msg
== NULL
)
3536 * Limit third parties to posting events for registered vendor codes
3539 if (event_msg
->vendor_code
< min_vendor
||
3540 event_msg
->vendor_code
> max_vendor
) {
3541 OSIncrementAtomic64((SInt64
*)&kevtstat
.kes_badvendor
);
3544 return (kev_post_msg(event_msg
));
3548 kev_post_msg(struct kev_msg
*event_msg
)
3550 struct mbuf
*m
, *m2
;
3551 struct kern_event_pcb
*ev_pcb
;
3552 struct kern_event_msg
*ev
;
3554 u_int32_t total_size
;
3557 /* Verify the message is small enough to fit in one mbuf w/o cluster */
3558 total_size
= KEV_MSG_HEADER_SIZE
;
3560 for (i
= 0; i
< 5; i
++) {
3561 if (event_msg
->dv
[i
].data_length
== 0)
3563 total_size
+= event_msg
->dv
[i
].data_length
;
3566 if (total_size
> MLEN
) {
3567 OSIncrementAtomic64((SInt64
*)&kevtstat
.kes_toobig
);
3571 m
= m_get(M_DONTWAIT
, MT_DATA
);
3573 OSIncrementAtomic64((SInt64
*)&kevtstat
.kes_nomem
);
3576 ev
= mtod(m
, struct kern_event_msg
*);
3577 total_size
= KEV_MSG_HEADER_SIZE
;
3579 tmp
= (char *) &ev
->event_data
[0];
3580 for (i
= 0; i
< 5; i
++) {
3581 if (event_msg
->dv
[i
].data_length
== 0)
3584 total_size
+= event_msg
->dv
[i
].data_length
;
3585 bcopy(event_msg
->dv
[i
].data_ptr
, tmp
,
3586 event_msg
->dv
[i
].data_length
);
3587 tmp
+= event_msg
->dv
[i
].data_length
;
3590 ev
->id
= ++static_event_id
;
3591 ev
->total_size
= total_size
;
3592 ev
->vendor_code
= event_msg
->vendor_code
;
3593 ev
->kev_class
= event_msg
->kev_class
;
3594 ev
->kev_subclass
= event_msg
->kev_subclass
;
3595 ev
->event_code
= event_msg
->event_code
;
3597 m
->m_len
= total_size
;
3598 lck_rw_lock_shared(kev_rwlock
);
3599 for (ev_pcb
= LIST_FIRST(&kern_event_head
);
3601 ev_pcb
= LIST_NEXT(ev_pcb
, evp_link
)) {
3602 lck_mtx_lock(&ev_pcb
->evp_mtx
);
3603 if (ev_pcb
->evp_socket
->so_pcb
== NULL
) {
3604 lck_mtx_unlock(&ev_pcb
->evp_mtx
);
3607 if (ev_pcb
->evp_vendor_code_filter
!= KEV_ANY_VENDOR
) {
3608 if (ev_pcb
->evp_vendor_code_filter
!= ev
->vendor_code
) {
3609 lck_mtx_unlock(&ev_pcb
->evp_mtx
);
3613 if (ev_pcb
->evp_class_filter
!= KEV_ANY_CLASS
) {
3614 if (ev_pcb
->evp_class_filter
!= ev
->kev_class
) {
3615 lck_mtx_unlock(&ev_pcb
->evp_mtx
);
3619 if ((ev_pcb
->evp_subclass_filter
!=
3620 KEV_ANY_SUBCLASS
) &&
3621 (ev_pcb
->evp_subclass_filter
!=
3622 ev
->kev_subclass
)) {
3623 lck_mtx_unlock(&ev_pcb
->evp_mtx
);
3629 m2
= m_copym(m
, 0, m
->m_len
, M_NOWAIT
);
3631 OSIncrementAtomic64((SInt64
*)&kevtstat
.kes_nomem
);
3633 lck_mtx_unlock(&ev_pcb
->evp_mtx
);
3634 lck_rw_done(kev_rwlock
);
3637 if (sbappendrecord(&ev_pcb
->evp_socket
->so_rcv
, m2
)) {
3639 * We use "m" for the socket stats as it would be
3640 * unsafe to use "m2"
3642 so_inc_recv_data_stat(ev_pcb
->evp_socket
,
3643 1, m
->m_len
, SO_TC_BE
);
3645 sorwakeup(ev_pcb
->evp_socket
);
3646 OSIncrementAtomic64((SInt64
*)&kevtstat
.kes_posted
);
3648 OSIncrementAtomic64((SInt64
*)&kevtstat
.kes_fullsock
);
3650 lck_mtx_unlock(&ev_pcb
->evp_mtx
);
3653 lck_rw_done(kev_rwlock
);
3659 kev_control(struct socket
*so
,
3662 __unused
struct ifnet
*ifp
,
3663 __unused
struct proc
*p
)
3665 struct kev_request
*kev_req
= (struct kev_request
*) data
;
3666 struct kern_event_pcb
*ev_pcb
;
3667 struct kev_vendor_code
*kev_vendor
;
3668 u_int32_t
*id_value
= (u_int32_t
*) data
;
3672 *id_value
= static_event_id
;
3675 ev_pcb
= (struct kern_event_pcb
*) so
->so_pcb
;
3676 ev_pcb
->evp_vendor_code_filter
= kev_req
->vendor_code
;
3677 ev_pcb
->evp_class_filter
= kev_req
->kev_class
;
3678 ev_pcb
->evp_subclass_filter
= kev_req
->kev_subclass
;
3681 ev_pcb
= (struct kern_event_pcb
*) so
->so_pcb
;
3682 kev_req
->vendor_code
= ev_pcb
->evp_vendor_code_filter
;
3683 kev_req
->kev_class
= ev_pcb
->evp_class_filter
;
3684 kev_req
->kev_subclass
= ev_pcb
->evp_subclass_filter
;
3686 case SIOCGKEVVENDOR
:
3687 kev_vendor
= (struct kev_vendor_code
*)data
;
3688 /* Make sure string is NULL terminated */
3689 kev_vendor
->vendor_string
[KEV_VENDOR_CODE_MAX_STR_LEN
-1] = 0;
3690 return (net_str_id_find_internal(kev_vendor
->vendor_string
,
3691 &kev_vendor
->vendor_code
, NSI_VENDOR_CODE
, 0));
3700 kevt_getstat SYSCTL_HANDLER_ARGS
3702 #pragma unused(oidp, arg1, arg2)
3705 lck_rw_lock_shared(kev_rwlock
);
3707 if (req
->newptr
!= USER_ADDR_NULL
) {
3711 if (req
->oldptr
== USER_ADDR_NULL
) {
3712 req
->oldidx
= sizeof(struct kevtstat
);
3716 error
= SYSCTL_OUT(req
, &kevtstat
,
3717 MIN(sizeof(struct kevtstat
), req
->oldlen
));
3719 lck_rw_done(kev_rwlock
);
3724 __private_extern__
int
3725 kevt_pcblist SYSCTL_HANDLER_ARGS
3727 #pragma unused(oidp, arg1, arg2)
3730 struct xsystmgen xsg
;
3732 size_t item_size
= ROUNDUP64(sizeof (struct xkevtpcb
)) +
3733 ROUNDUP64(sizeof (struct xsocket_n
)) +
3734 2 * ROUNDUP64(sizeof (struct xsockbuf_n
)) +
3735 ROUNDUP64(sizeof (struct xsockstat_n
));
3736 struct kern_event_pcb
*ev_pcb
;
3738 buf
= _MALLOC(item_size
, M_TEMP
, M_WAITOK
| M_ZERO
);
3742 lck_rw_lock_shared(kev_rwlock
);
3744 n
= kevtstat
.kes_pcbcount
;
3746 if (req
->oldptr
== USER_ADDR_NULL
) {
3747 req
->oldidx
= (n
+ n
/8) * item_size
;
3750 if (req
->newptr
!= USER_ADDR_NULL
) {
3754 bzero(&xsg
, sizeof (xsg
));
3755 xsg
.xg_len
= sizeof (xsg
);
3757 xsg
.xg_gen
= kevtstat
.kes_gencnt
;
3758 xsg
.xg_sogen
= so_gencnt
;
3759 error
= SYSCTL_OUT(req
, &xsg
, sizeof (xsg
));
3764 * We are done if there is no pcb
3771 for (i
= 0, ev_pcb
= LIST_FIRST(&kern_event_head
);
3772 i
< n
&& ev_pcb
!= NULL
;
3773 i
++, ev_pcb
= LIST_NEXT(ev_pcb
, evp_link
)) {
3774 struct xkevtpcb
*xk
= (struct xkevtpcb
*)buf
;
3775 struct xsocket_n
*xso
= (struct xsocket_n
*)
3776 ADVANCE64(xk
, sizeof (*xk
));
3777 struct xsockbuf_n
*xsbrcv
= (struct xsockbuf_n
*)
3778 ADVANCE64(xso
, sizeof (*xso
));
3779 struct xsockbuf_n
*xsbsnd
= (struct xsockbuf_n
*)
3780 ADVANCE64(xsbrcv
, sizeof (*xsbrcv
));
3781 struct xsockstat_n
*xsostats
= (struct xsockstat_n
*)
3782 ADVANCE64(xsbsnd
, sizeof (*xsbsnd
));
3784 bzero(buf
, item_size
);
3786 lck_mtx_lock(&ev_pcb
->evp_mtx
);
3788 xk
->kep_len
= sizeof(struct xkevtpcb
);
3789 xk
->kep_kind
= XSO_EVT
;
3790 xk
->kep_evtpcb
= (uint64_t)VM_KERNEL_ADDRPERM(ev_pcb
);
3791 xk
->kep_vendor_code_filter
= ev_pcb
->evp_vendor_code_filter
;
3792 xk
->kep_class_filter
= ev_pcb
->evp_class_filter
;
3793 xk
->kep_subclass_filter
= ev_pcb
->evp_subclass_filter
;
3795 sotoxsocket_n(ev_pcb
->evp_socket
, xso
);
3796 sbtoxsockbuf_n(ev_pcb
->evp_socket
?
3797 &ev_pcb
->evp_socket
->so_rcv
: NULL
, xsbrcv
);
3798 sbtoxsockbuf_n(ev_pcb
->evp_socket
?
3799 &ev_pcb
->evp_socket
->so_snd
: NULL
, xsbsnd
);
3800 sbtoxsockstat_n(ev_pcb
->evp_socket
, xsostats
);
3802 lck_mtx_unlock(&ev_pcb
->evp_mtx
);
3804 error
= SYSCTL_OUT(req
, buf
, item_size
);
3809 * Give the user an updated idea of our state.
3810 * If the generation differs from what we told
3811 * her before, she knows that something happened
3812 * while we were processing this request, and it
3813 * might be necessary to retry.
3815 bzero(&xsg
, sizeof (xsg
));
3816 xsg
.xg_len
= sizeof (xsg
);
3818 xsg
.xg_gen
= kevtstat
.kes_gencnt
;
3819 xsg
.xg_sogen
= so_gencnt
;
3820 error
= SYSCTL_OUT(req
, &xsg
, sizeof (xsg
));
3827 lck_rw_done(kev_rwlock
);
3832 #endif /* SOCKETS */
3836 fill_kqueueinfo(struct kqueue
*kq
, struct kqueue_info
* kinfo
)
3838 struct vinfo_stat
* st
;
3840 st
= &kinfo
->kq_stat
;
3842 st
->vst_size
= kq
->kq_count
;
3843 if (kq
->kq_state
& KQ_KEV_QOS
)
3844 st
->vst_blksize
= sizeof(struct kevent_qos_s
);
3845 else if (kq
->kq_state
& KQ_KEV64
)
3846 st
->vst_blksize
= sizeof(struct kevent64_s
);
3848 st
->vst_blksize
= sizeof(struct kevent
);
3849 st
->vst_mode
= S_IFIFO
;
3851 /* flags exported to libproc as PROC_KQUEUE_* (sys/proc_info.h) */
3852 #define PROC_KQUEUE_MASK (KQ_SEL|KQ_SLEEP|KQ_KEV32|KQ_KEV64|KQ_KEV_QOS)
3853 kinfo
->kq_state
= kq
->kq_state
& PROC_KQUEUE_MASK
;
3860 knote_markstayqueued(struct knote
*kn
)
3863 kn
->kn_status
|= KN_STAYQUEUED
;
3865 kqunlock(kn
->kn_kq
);
3869 knote_clearstayqueued(struct knote
*kn
)
3872 kn
->kn_status
&= ~KN_STAYQUEUED
;
3874 kqunlock(kn
->kn_kq
);
3877 static unsigned long
3878 kevent_extinfo_emit(struct kqueue
*kq
, struct knote
*kn
, struct kevent_extinfo
*buf
,
3879 unsigned long buflen
, unsigned long nknotes
)
3881 struct kevent_qos_s kevqos
;
3882 struct kevent_internal_s
*kevp
;
3883 for (; kn
; kn
= SLIST_NEXT(kn
, kn_link
)) {
3884 if (kq
== kn
->kn_kq
) {
3885 if (nknotes
< buflen
) {
3886 struct kevent_extinfo
*info
= &buf
[nknotes
];
3889 bzero(&kevqos
, sizeof(kevqos
));
3890 kevp
= &(kn
->kn_kevent
);
3892 kevqos
.ident
= kevp
->ident
;
3893 kevqos
.filter
= kevp
->filter
;
3894 kevqos
.flags
= kevp
->flags
;
3895 kevqos
.fflags
= kevp
->fflags
;
3896 kevqos
.data
= (int64_t) kevp
->data
;
3897 kevqos
.udata
= kevp
->udata
;
3898 kevqos
.ext
[0] = kevp
->ext
[0];
3899 kevqos
.ext
[1] = kevp
->ext
[1];
3901 memcpy(&info
->kqext_kev
, &kevqos
, sizeof(info
->kqext_kev
));
3902 info
->kqext_sdata
= kn
->kn_sdata
;
3904 /* status flags exported to userspace/libproc */
3905 #define KQEXT_STATUS_MASK (KN_ACTIVE|KN_QUEUED|KN_DISABLED|KN_STAYQUEUED)
3906 info
->kqext_status
= kn
->kn_status
& KQEXT_STATUS_MASK
;
3907 info
->kqext_sfflags
= kn
->kn_sfflags
;
3912 /* we return total number of knotes, which may be more than requested */
3921 pid_kqueue_extinfo(proc_t p
, struct kqueue
*kq
, user_addr_t ubuf
,
3922 uint32_t bufsize
, int32_t *retval
)
3927 struct filedesc
*fdp
= p
->p_fd
;
3928 unsigned long nknotes
= 0;
3929 unsigned long buflen
= bufsize
/ sizeof(struct kevent_extinfo
);
3930 struct kevent_extinfo
*kqext
= NULL
;
3932 kqext
= kalloc(buflen
* sizeof(struct kevent_extinfo
));
3933 if (kqext
== NULL
) {
3937 bzero(kqext
, buflen
* sizeof(struct kevent_extinfo
));
3941 for (i
= 0; i
< fdp
->fd_knlistsize
; i
++) {
3942 kn
= SLIST_FIRST(&fdp
->fd_knlist
[i
]);
3943 nknotes
= kevent_extinfo_emit(kq
, kn
, kqext
, buflen
, nknotes
);
3946 if (fdp
->fd_knhashmask
!= 0) {
3947 for (i
= 0; i
< (int)fdp
->fd_knhashmask
+ 1; i
++) {
3948 kn
= SLIST_FIRST(&fdp
->fd_knhash
[i
]);
3949 nknotes
= kevent_extinfo_emit(kq
, kn
, kqext
, buflen
, nknotes
);
3955 assert(bufsize
>= sizeof(struct kevent_extinfo
) * min(buflen
, nknotes
));
3956 err
= copyout(kqext
, ubuf
, sizeof(struct kevent_extinfo
) * min(buflen
, nknotes
));
3960 kfree(kqext
, buflen
* sizeof(struct kevent_extinfo
));