2 * Copyright (c) 2008-2016 Apple Inc. All rights reserved.
4 * @APPLE_APACHE_LICENSE_HEADER_START@
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * @APPLE_APACHE_LICENSE_HEADER_END@
22 #if DISPATCH_EVENT_BACKEND_KEVENT
25 #include "protocolServer.h"
28 #if DISPATCH_USE_KEVENT_WORKQUEUE && !DISPATCH_USE_KEVENT_QOS
29 #error unsupported configuration
32 #define DISPATCH_KEVENT_MUXED_MARKER 1ul
33 #define DISPATCH_MACH_AUDIT_TOKEN_PID (5)
35 typedef struct dispatch_muxnote_s
{
36 TAILQ_ENTRY(dispatch_muxnote_s
) dmn_list
;
37 TAILQ_HEAD(, dispatch_unote_linkage_s
) dmn_unotes_head
;
38 dispatch_wlh_t dmn_wlh
;
39 dispatch_kevent_s dmn_kev
;
40 } *dispatch_muxnote_t
;
42 static bool _dispatch_timers_force_max_leeway
;
43 static int _dispatch_kq
= -1;
46 dispatch_unfair_lock_s lock
;
48 #if !DISPATCH_USE_KEVENT_WORKQUEUE
49 #define _dispatch_muxnotes_lock() \
50 _dispatch_unfair_lock_lock(&_dispatch_muxnotes.lock)
51 #define _dispatch_muxnotes_unlock() \
52 _dispatch_unfair_lock_unlock(&_dispatch_muxnotes.lock)
54 #define _dispatch_muxnotes_lock()
55 #define _dispatch_muxnotes_unlock()
56 #endif // !DISPATCH_USE_KEVENT_WORKQUEUE
58 DISPATCH_CACHELINE_ALIGN
59 static TAILQ_HEAD(dispatch_muxnote_bucket_s
, dispatch_muxnote_s
)
60 _dispatch_sources
[DSL_HASH_SIZE
];
62 #define DISPATCH_NOTE_CLOCK_WALL NOTE_MACH_CONTINUOUS_TIME
63 #define DISPATCH_NOTE_CLOCK_MACH 0
65 static const uint32_t _dispatch_timer_index_to_fflags
[] = {
66 #define DISPATCH_TIMER_FFLAGS_INIT(kind, qos, note) \
67 [DISPATCH_TIMER_INDEX(DISPATCH_CLOCK_##kind, DISPATCH_TIMER_QOS_##qos)] = \
68 DISPATCH_NOTE_CLOCK_##kind | NOTE_ABSOLUTE | \
69 NOTE_NSECONDS | NOTE_LEEWAY | (note)
70 DISPATCH_TIMER_FFLAGS_INIT(WALL
, NORMAL
, 0),
71 DISPATCH_TIMER_FFLAGS_INIT(MACH
, NORMAL
, 0),
72 #if DISPATCH_HAVE_TIMER_QOS
73 DISPATCH_TIMER_FFLAGS_INIT(WALL
, CRITICAL
, NOTE_CRITICAL
),
74 DISPATCH_TIMER_FFLAGS_INIT(MACH
, CRITICAL
, NOTE_CRITICAL
),
75 DISPATCH_TIMER_FFLAGS_INIT(WALL
, BACKGROUND
, NOTE_BACKGROUND
),
76 DISPATCH_TIMER_FFLAGS_INIT(MACH
, BACKGROUND
, NOTE_BACKGROUND
),
78 #undef DISPATCH_TIMER_FFLAGS_INIT
81 static void _dispatch_kevent_timer_drain(dispatch_kevent_t ke
);
84 #pragma mark kevent debug
88 _evfiltstr(short filt
)
91 #define _evfilt2(f) case (f): return #f
92 _evfilt2(EVFILT_READ
);
93 _evfilt2(EVFILT_WRITE
);
94 _evfilt2(EVFILT_SIGNAL
);
95 _evfilt2(EVFILT_TIMER
);
97 #ifdef DISPATCH_EVENT_BACKEND_KEVENT
99 _evfilt2(EVFILT_VNODE
);
100 _evfilt2(EVFILT_PROC
);
102 _evfilt2(EVFILT_MACHPORT
);
103 _evfilt2(DISPATCH_EVFILT_MACH_NOTIFICATION
);
106 _evfilt2(EVFILT_USER
);
108 _evfilt2(EVFILT_SOCK
);
110 #ifdef EVFILT_MEMORYSTATUS
111 _evfilt2(EVFILT_MEMORYSTATUS
);
113 #endif // DISPATCH_EVENT_BACKEND_KEVENT
115 _evfilt2(DISPATCH_EVFILT_TIMER
);
116 _evfilt2(DISPATCH_EVFILT_CUSTOM_ADD
);
117 _evfilt2(DISPATCH_EVFILT_CUSTOM_OR
);
118 _evfilt2(DISPATCH_EVFILT_CUSTOM_REPLACE
);
120 return "EVFILT_missing";
126 _evflagstr2(uint16_t *flagsp
)
128 #define _evflag2(f) \
129 if ((*flagsp & (f)) == (f) && (f)) { \
136 _evflag2(EV_DISABLE
);
137 _evflag2(EV_ONESHOT
);
139 _evflag2(EV_RECEIPT
);
140 _evflag2(EV_DISPATCH
);
141 _evflag2(EV_UDATA_SPECIFIC
);
150 _evflag2(EV_VANISHED
);
152 return "EV_UNKNOWN ";
157 _evflagstr(uint16_t flags
, char *str
, size_t strsize
)
161 strlcat(str
, _evflagstr2(&flags
), strsize
);
163 size_t sz
= strlen(str
);
164 if (sz
) str
[sz
-1] = 0;
170 dispatch_kevent_debug(const char *verb
, const dispatch_kevent_s
*kev
,
171 int i
, int n
, const char *function
, unsigned int line
)
177 snprintf(i_n
, sizeof(i_n
), "%d/%d ", i
+ 1, n
);
182 if (kev
->flags
& EV_DELETE
) {
184 } else if (kev
->flags
& EV_ADD
) {
190 #if DISPATCH_USE_KEVENT_QOS
191 _dispatch_debug("%s kevent[%p] %s= { ident = 0x%llx, filter = %s, "
192 "flags = %s (0x%x), fflags = 0x%x, data = 0x%llx, udata = 0x%llx, "
193 "qos = 0x%x, ext[0] = 0x%llx, ext[1] = 0x%llx, ext[2] = 0x%llx, "
194 "ext[3] = 0x%llx }: %s #%u", verb
, kev
, i_n
, kev
->ident
,
195 _evfiltstr(kev
->filter
), _evflagstr(kev
->flags
, flagstr
,
196 sizeof(flagstr
)), kev
->flags
, kev
->fflags
, kev
->data
, kev
->udata
,
197 kev
->qos
, kev
->ext
[0], kev
->ext
[1], kev
->ext
[2], kev
->ext
[3],
200 _dispatch_debug("%s kevent[%p] %s= { ident = 0x%llx, filter = %s, "
201 "flags = %s (0x%x), fflags = 0x%x, data = 0x%llx, udata = 0x%llx}: "
202 "%s #%u", verb
, kev
, i_n
,
203 kev
->ident
, _evfiltstr(kev
->filter
), _evflagstr(kev
->flags
, flagstr
,
204 sizeof(flagstr
)), kev
->flags
, kev
->fflags
, kev
->data
, kev
->udata
,
210 dispatch_kevent_debug(const char *verb
, const dispatch_kevent_s
*kev
,
211 int i
, int n
, const char *function
, unsigned int line
)
213 (void)verb
; (void)kev
; (void)i
; (void)n
; (void)function
; (void)line
;
215 #endif // DISPATCH_DEBUG
216 #define _dispatch_kevent_debug_n(verb, _kev, i, n) \
217 dispatch_kevent_debug(verb, _kev, i, n, __FUNCTION__, __LINE__)
218 #define _dispatch_kevent_debug(verb, _kev) \
219 _dispatch_kevent_debug_n(verb, _kev, 0, 0)
220 #if DISPATCH_MGR_QUEUE_DEBUG
221 #define _dispatch_kevent_mgr_debug(verb, kev) _dispatch_kevent_debug(verb, kev)
223 #define _dispatch_kevent_mgr_debug(verb, kev) ((void)verb, (void)kev)
224 #endif // DISPATCH_MGR_QUEUE_DEBUG
225 #if DISPATCH_WLH_DEBUG
226 #define _dispatch_kevent_wlh_debug(verb, kev) _dispatch_kevent_debug(verb, kev)
228 #define _dispatch_kevent_wlh_debug(verb, kev) ((void)verb, (void)kev)
229 #endif // DISPATCH_WLH_DEBUG
231 #if DISPATCH_MACHPORT_DEBUG
232 #ifndef MACH_PORT_TYPE_SPREQUEST
233 #define MACH_PORT_TYPE_SPREQUEST 0x40000000
238 dispatch_debug_machport(mach_port_t name
, const char* str
)
240 mach_port_type_t type
;
241 mach_msg_bits_t ns
= 0, nr
= 0, nso
= 0, nd
= 0;
242 unsigned int dnreqs
= 0, dnrsiz
;
243 kern_return_t kr
= mach_port_type(mach_task_self(), name
, &type
);
245 _dispatch_log("machport[0x%08x] = { error(0x%x) \"%s\" }: %s", name
,
246 kr
, mach_error_string(kr
), str
);
249 if (type
& MACH_PORT_TYPE_SEND
) {
250 (void)dispatch_assume_zero(mach_port_get_refs(mach_task_self(), name
,
251 MACH_PORT_RIGHT_SEND
, &ns
));
253 if (type
& MACH_PORT_TYPE_SEND_ONCE
) {
254 (void)dispatch_assume_zero(mach_port_get_refs(mach_task_self(), name
,
255 MACH_PORT_RIGHT_SEND_ONCE
, &nso
));
257 if (type
& MACH_PORT_TYPE_DEAD_NAME
) {
258 (void)dispatch_assume_zero(mach_port_get_refs(mach_task_self(), name
,
259 MACH_PORT_RIGHT_DEAD_NAME
, &nd
));
261 if (type
& (MACH_PORT_TYPE_RECEIVE
|MACH_PORT_TYPE_SEND
)) {
262 kr
= mach_port_dnrequest_info(mach_task_self(), name
, &dnrsiz
, &dnreqs
);
263 if (kr
!= KERN_INVALID_RIGHT
) (void)dispatch_assume_zero(kr
);
265 if (type
& MACH_PORT_TYPE_RECEIVE
) {
266 mach_port_status_t status
= { .mps_pset
= 0, };
267 mach_msg_type_number_t cnt
= MACH_PORT_RECEIVE_STATUS_COUNT
;
268 (void)dispatch_assume_zero(mach_port_get_refs(mach_task_self(), name
,
269 MACH_PORT_RIGHT_RECEIVE
, &nr
));
270 (void)dispatch_assume_zero(mach_port_get_attributes(mach_task_self(),
271 name
, MACH_PORT_RECEIVE_STATUS
, (void*)&status
, &cnt
));
272 _dispatch_log("machport[0x%08x] = { R(%03u) S(%03u) SO(%03u) D(%03u) "
273 "dnreqs(%03u) spreq(%s) nsreq(%s) pdreq(%s) srights(%s) "
274 "sorights(%03u) qlim(%03u) msgcount(%03u) mkscount(%03u) "
275 "seqno(%03u) }: %s", name
, nr
, ns
, nso
, nd
, dnreqs
,
276 type
& MACH_PORT_TYPE_SPREQUEST
? "Y":"N",
277 status
.mps_nsrequest
? "Y":"N", status
.mps_pdrequest
? "Y":"N",
278 status
.mps_srights
? "Y":"N", status
.mps_sorights
,
279 status
.mps_qlimit
, status
.mps_msgcount
, status
.mps_mscount
,
280 status
.mps_seqno
, str
);
281 } else if (type
& (MACH_PORT_TYPE_SEND
|MACH_PORT_TYPE_SEND_ONCE
|
282 MACH_PORT_TYPE_DEAD_NAME
)) {
283 _dispatch_log("machport[0x%08x] = { R(%03u) S(%03u) SO(%03u) D(%03u) "
284 "dnreqs(%03u) spreq(%s) }: %s", name
, nr
, ns
, nso
, nd
, dnreqs
,
285 type
& MACH_PORT_TYPE_SPREQUEST
? "Y":"N", str
);
287 _dispatch_log("machport[0x%08x] = { type(0x%08x) }: %s", name
, type
,
293 #pragma mark dispatch_kevent_t
297 static dispatch_once_t _dispatch_mach_host_port_pred
;
298 static mach_port_t _dispatch_mach_host_port
;
301 _dispatch_kevent_mach_msg_buf(dispatch_kevent_t ke
)
303 return (void*)ke
->ext
[0];
306 static inline mach_msg_size_t
307 _dispatch_kevent_mach_msg_size(dispatch_kevent_t ke
)
309 // buffer size in the successful receive case, but message size (like
310 // msgh_size) in the MACH_RCV_TOO_LARGE case, i.e. add trailer size.
311 return (mach_msg_size_t
)ke
->ext
[1];
314 static void _dispatch_kevent_mach_msg_drain(dispatch_kevent_t ke
);
315 static inline void _dispatch_mach_host_calendar_change_register(void);
317 // DISPATCH_MACH_NOTIFICATION_ARMED are muxnotes that aren't registered with
318 // kevent for real, but with mach_port_request_notification()
320 // the kevent structure is used for bookkeeping:
321 // - ident, filter, flags and fflags have their usual meaning
322 // - data is used to monitor the actual state of the
323 // mach_port_request_notification()
324 // - ext[0] is a boolean that trackes whether the notification is armed or not
325 #define DISPATCH_MACH_NOTIFICATION_ARMED(dk) ((dk)->ext[0])
328 DISPATCH_ALWAYS_INLINE
329 static dispatch_muxnote_t
330 _dispatch_kevent_get_muxnote(dispatch_kevent_t ke
)
332 uintptr_t dmn_addr
= (uintptr_t)ke
->udata
& ~DISPATCH_KEVENT_MUXED_MARKER
;
333 return (dispatch_muxnote_t
)dmn_addr
;
336 DISPATCH_ALWAYS_INLINE
337 static dispatch_unote_t
338 _dispatch_kevent_get_unote(dispatch_kevent_t ke
)
340 dispatch_assert((ke
->udata
& DISPATCH_KEVENT_MUXED_MARKER
) == 0);
341 return (dispatch_unote_t
){ ._du
= (dispatch_unote_class_t
)ke
->udata
};
346 _dispatch_kevent_print_error(dispatch_kevent_t ke
)
348 _dispatch_debug("kevent[0x%llx]: handling error",
349 (unsigned long long)ke
->udata
);
350 if (ke
->flags
& EV_DELETE
) {
351 if (ke
->flags
& EV_UDATA_SPECIFIC
) {
352 if (ke
->data
== EINPROGRESS
) {
353 // deferred EV_DELETE
357 // for EV_DELETE if the update was deferred we may have reclaimed
358 // the udata already, and it is unsafe to dereference it now.
359 } else if (ke
->udata
& DISPATCH_KEVENT_MUXED_MARKER
) {
360 ke
->flags
|= _dispatch_kevent_get_muxnote(ke
)->dmn_kev
.flags
;
361 } else if (ke
->udata
) {
362 if (!_dispatch_unote_registered(_dispatch_kevent_get_unote(ke
))) {
368 if (ke
->filter
== EVFILT_MACHPORT
&& ke
->data
== ENOTSUP
&&
369 (ke
->flags
& EV_ADD
) && (ke
->fflags
& MACH_RCV_MSG
)) {
370 DISPATCH_INTERNAL_CRASH(ke
->ident
,
371 "Missing EVFILT_MACHPORT support for ports");
376 // log the unexpected error
377 _dispatch_bug_kevent_client("kevent", _evfiltstr(ke
->filter
),
379 ke
->flags
& EV_DELETE
? "delete" :
380 ke
->flags
& EV_ADD
? "add" :
381 ke
->flags
& EV_ENABLE
? "enable" : "monitor",
388 _dispatch_kevent_merge(dispatch_unote_t du
, dispatch_kevent_t ke
)
391 uintptr_t status
= 0;
392 pthread_priority_t pp
= 0;
393 #if DISPATCH_USE_KEVENT_QOS
394 pp
= ((pthread_priority_t
)ke
->qos
) & ~_PTHREAD_PRIORITY_FLAGS_MASK
;
396 dispatch_unote_action_t action
= du
._du
->du_data_action
;
397 if (action
== DISPATCH_UNOTE_ACTION_DATA_SET
) {
398 // ke->data is signed and "negative available data" makes no sense
399 // zero bytes happens when EV_EOF is set
400 dispatch_assert(ke
->data
>= 0l);
401 data
= ~(unsigned long)ke
->data
;
403 } else if (du
._du
->du_filter
== EVFILT_MACHPORT
) {
404 data
= DISPATCH_MACH_RECV_MESSAGE
;
406 } else if (action
== DISPATCH_UNOTE_ACTION_DATA_ADD
) {
407 data
= (unsigned long)ke
->data
;
408 } else if (action
== DISPATCH_UNOTE_ACTION_DATA_OR
) {
409 data
= ke
->fflags
& du
._du
->du_fflags
;
410 } else if (action
== DISPATCH_UNOTE_ACTION_DATA_OR_STATUS_SET
) {
411 data
= ke
->fflags
& du
._du
->du_fflags
;
412 status
= (unsigned long)ke
->data
;
414 DISPATCH_INTERNAL_CRASH(action
, "Corrupt unote action");
416 return dux_merge_evt(du
._du
, ke
->flags
, data
, status
, pp
);
421 _dispatch_kevent_merge_muxed(dispatch_kevent_t ke
)
423 dispatch_muxnote_t dmn
= _dispatch_kevent_get_muxnote(ke
);
424 dispatch_unote_linkage_t dul
, dul_next
;
426 TAILQ_FOREACH_SAFE(dul
, &dmn
->dmn_unotes_head
, du_link
, dul_next
) {
427 _dispatch_kevent_merge(_dispatch_unote_linkage_get_unote(dul
), ke
);
433 _dispatch_kevent_drain(dispatch_kevent_t ke
)
435 if (ke
->filter
== EVFILT_USER
) {
436 _dispatch_kevent_mgr_debug("received", ke
);
439 _dispatch_kevent_debug("received", ke
);
440 if (unlikely(ke
->flags
& EV_ERROR
)) {
441 if (ke
->filter
== EVFILT_PROC
&& ke
->data
== ESRCH
) {
442 // EVFILT_PROC may fail with ESRCH when the process exists but is a zombie
443 // <rdar://problem/5067725>. As a workaround, we simulate an exit event for
444 // any EVFILT_PROC with an invalid pid <rdar://problem/6626350>.
445 ke
->flags
&= ~(EV_ERROR
| EV_ADD
| EV_ENABLE
| EV_UDATA_SPECIFIC
);
446 ke
->flags
|= EV_ONESHOT
;
447 ke
->fflags
= NOTE_EXIT
;
449 _dispatch_kevent_debug("synthetic NOTE_EXIT", ke
);
451 return _dispatch_kevent_print_error(ke
);
454 if (ke
->filter
== EVFILT_TIMER
) {
455 return _dispatch_kevent_timer_drain(ke
);
459 if (ke
->filter
== EVFILT_MACHPORT
) {
460 if (_dispatch_kevent_mach_msg_size(ke
)) {
461 return _dispatch_kevent_mach_msg_drain(ke
);
466 if (ke
->udata
& DISPATCH_KEVENT_MUXED_MARKER
) {
467 return _dispatch_kevent_merge_muxed(ke
);
469 return _dispatch_kevent_merge(_dispatch_kevent_get_unote(ke
), ke
);
472 #pragma mark dispatch_kq
474 #if DISPATCH_USE_MGR_THREAD
477 _dispatch_kq_create(const void *guard_ptr
)
479 static const dispatch_kevent_s kev
= {
481 .filter
= EVFILT_USER
,
482 .flags
= EV_ADD
|EV_CLEAR
,
483 .udata
= (uintptr_t)DISPATCH_WLH_MANAGER
,
487 _dispatch_fork_becomes_unsafe();
488 #if DISPATCH_USE_GUARDED_FD
489 guardid_t guard
= (uintptr_t)guard_ptr
;
490 kqfd
= guarded_kqueue_np(&guard
, GUARD_CLOSE
| GUARD_DUP
);
499 DISPATCH_CLIENT_CRASH(err
, "kqueue() failure: "
500 "process is out of file descriptors");
503 DISPATCH_CLIENT_CRASH(err
, "kqueue() failure: "
504 "system is out of file descriptors");
507 DISPATCH_CLIENT_CRASH(err
, "kqueue() failure: "
508 "kernel is out of memory");
511 DISPATCH_INTERNAL_CRASH(err
, "kqueue() failure");
515 #if DISPATCH_USE_KEVENT_QOS
516 dispatch_assume_zero(kevent_qos(kqfd
, &kev
, 1, NULL
, 0, NULL
, NULL
, 0));
518 dispatch_assume_zero(kevent(kqfd
, &kev
, 1, NULL
, 0, NULL
));
525 _dispatch_kq_init(void *context
)
527 bool *kq_initialized
= context
;
529 _dispatch_fork_becomes_unsafe();
530 if (unlikely(getenv("LIBDISPATCH_TIMERS_FORCE_MAX_LEEWAY"))) {
531 _dispatch_timers_force_max_leeway
= true;
533 *kq_initialized
= true;
535 #if DISPATCH_USE_KEVENT_WORKQUEUE
536 _dispatch_kevent_workqueue_init();
537 if (_dispatch_kevent_workqueue_enabled
) {
539 int kqfd
= _dispatch_kq
;
540 const dispatch_kevent_s ke
= {
542 .filter
= EVFILT_USER
,
543 .flags
= EV_ADD
|EV_CLEAR
,
544 .qos
= _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG
,
545 .udata
= (uintptr_t)DISPATCH_WLH_MANAGER
,
548 r
= kevent_qos(kqfd
, &ke
, 1, NULL
, 0, NULL
, NULL
,
549 KEVENT_FLAG_WORKQ
|KEVENT_FLAG_IMMEDIATE
);
550 if (unlikely(r
== -1)) {
556 DISPATCH_CLIENT_CRASH(err
,
557 "Failed to initalize workqueue kevent");
563 #endif // DISPATCH_USE_KEVENT_WORKQUEUE
564 #if DISPATCH_USE_MGR_THREAD
565 _dispatch_kq
= _dispatch_kq_create(&_dispatch_mgr_q
);
566 dx_push(_dispatch_mgr_q
.do_targetq
, &_dispatch_mgr_q
, 0);
567 #endif // DISPATCH_USE_MGR_THREAD
570 #if DISPATCH_USE_MEMORYPRESSURE_SOURCE
571 static void _dispatch_memorypressure_init(void);
573 #define _dispatch_memorypressure_init() ((void)0)
578 _dispatch_kq_poll(dispatch_wlh_t wlh
, dispatch_kevent_t ke
, int n
,
579 dispatch_kevent_t ke_out
, int n_out
, void *buf
, size_t *avail
,
582 static dispatch_once_t pred
;
583 bool kq_initialized
= false;
586 dispatch_once_f(&pred
, &kq_initialized
, _dispatch_kq_init
);
587 if (unlikely(kq_initialized
)) {
588 // The calling thread was the one doing the initialization
590 // The event loop needs the memory pressure source and debug channel,
591 // however creating these will recursively call _dispatch_kq_poll(),
592 // so we can't quite initialize them under the dispatch once.
593 _dispatch_memorypressure_init();
594 _voucher_activity_debug_channel_init();
598 #if !DISPATCH_USE_KEVENT_QOS
599 if (flags
& KEVENT_FLAG_ERROR_EVENTS
) {
600 // emulate KEVENT_FLAG_ERROR_EVENTS
601 for (r
= 0; r
< n
; r
++) {
602 ke
[r
].flags
|= EV_RECEIPT
;
609 if (wlh
== DISPATCH_WLH_ANON
) {
610 int kqfd
= _dispatch_kq
;
611 #if DISPATCH_USE_KEVENT_QOS
612 if (_dispatch_kevent_workqueue_enabled
) {
613 flags
|= KEVENT_FLAG_WORKQ
;
615 r
= kevent_qos(kqfd
, ke
, n
, ke_out
, n_out
, buf
, avail
, flags
);
617 const struct timespec timeout_immediately
= {}, *timeout
= NULL
;
618 if (flags
& KEVENT_FLAG_IMMEDIATE
) timeout
= &timeout_immediately
;
619 r
= kevent(kqfd
, ke
, n
, ke_out
, n_out
, timeout
);
622 if (unlikely(r
== -1)) {
626 _dispatch_temporary_resource_shortage();
631 DISPATCH_CLIENT_CRASH(err
, "Do not close random Unix descriptors");
633 DISPATCH_CLIENT_CRASH(err
, "Unexpected error from kevent");
641 _dispatch_kq_drain(dispatch_wlh_t wlh
, dispatch_kevent_t ke
, int n
,
644 dispatch_kevent_s ke_out
[DISPATCH_DEFERRED_ITEMS_EVENT_COUNT
];
645 bool poll_for_events
= !(flags
& KEVENT_FLAG_ERROR_EVENTS
);
646 int i
, n_out
= countof(ke_out
), r
= 0;
647 size_t *avail
= NULL
;
650 #if DISPATCH_USE_KEVENT_QOS
652 if (poll_for_events
) {
653 size
= DISPATCH_MACH_RECEIVE_MAX_INLINE_MESSAGE_SIZE
+
654 DISPATCH_MACH_TRAILER_SIZE
;
661 for (r
= 0; r
< n
; r
++) {
662 if (ke
[r
].filter
!= EVFILT_USER
|| DISPATCH_MGR_QUEUE_DEBUG
) {
663 _dispatch_kevent_debug_n(NULL
, ke
+ r
, r
, n
);
668 if (poll_for_events
) _dispatch_clear_return_to_kernel();
669 n
= _dispatch_kq_poll(wlh
, ke
, n
, ke_out
, n_out
, buf
, avail
, flags
);
672 } else if (flags
& KEVENT_FLAG_ERROR_EVENTS
) {
673 for (i
= 0, r
= 0; i
< n
; i
++) {
674 if ((ke_out
[i
].flags
& EV_ERROR
) && ke_out
[i
].data
) {
675 _dispatch_kevent_drain(&ke_out
[i
]);
676 r
= (int)ke_out
[i
].data
;
680 for (i
= 0, r
= 0; i
< n
; i
++) {
681 _dispatch_kevent_drain(&ke_out
[i
]);
687 DISPATCH_ALWAYS_INLINE
689 _dispatch_kq_update_one(dispatch_wlh_t wlh
, dispatch_kevent_t ke
)
691 return _dispatch_kq_drain(wlh
, ke
, 1,
692 KEVENT_FLAG_IMMEDIATE
| KEVENT_FLAG_ERROR_EVENTS
);
695 DISPATCH_ALWAYS_INLINE
697 _dispatch_kq_update_all(dispatch_wlh_t wlh
, dispatch_kevent_t ke
, int n
)
699 (void)_dispatch_kq_drain(wlh
, ke
, n
,
700 KEVENT_FLAG_IMMEDIATE
| KEVENT_FLAG_ERROR_EVENTS
);
703 DISPATCH_ALWAYS_INLINE
705 _dispatch_kq_unote_set_kevent(dispatch_unote_t _du
, dispatch_kevent_t dk
,
708 dispatch_unote_class_t du
= _du
._du
;
709 dispatch_source_type_t dst
= du
->du_type
;
710 uint16_t flags
= dst
->dst_flags
| action
;
712 if ((flags
& EV_VANISHED
) && !(flags
& EV_ADD
)) {
713 flags
&= ~EV_VANISHED
;
715 pthread_priority_t pp
= _dispatch_priority_to_pp(du
->du_priority
);
716 *dk
= (dispatch_kevent_s
){
717 .ident
= du
->du_ident
,
718 .filter
= dst
->dst_filter
,
720 .udata
= (uintptr_t)du
,
721 .fflags
= du
->du_fflags
| dst
->dst_fflags
,
722 .data
= (typeof(dk
->data
))dst
->dst_data
,
723 #if DISPATCH_USE_KEVENT_QOS
724 .qos
= (typeof(dk
->qos
))pp
,
729 DISPATCH_ALWAYS_INLINE
731 _dispatch_kq_deferred_find_slot(dispatch_deferred_items_t ddi
,
732 int16_t filter
, uint64_t ident
, uint64_t udata
)
734 dispatch_kevent_t events
= ddi
->ddi_eventlist
;
737 for (i
= 0; i
< ddi
->ddi_nevents
; i
++) {
738 if (events
[i
].filter
== filter
&& events
[i
].ident
== ident
&&
739 events
[i
].udata
== udata
) {
746 DISPATCH_ALWAYS_INLINE
747 static inline dispatch_kevent_t
748 _dispatch_kq_deferred_reuse_slot(dispatch_wlh_t wlh
,
749 dispatch_deferred_items_t ddi
, int slot
)
751 if (wlh
!= DISPATCH_WLH_ANON
) _dispatch_set_return_to_kernel();
752 if (unlikely(slot
== ddi
->ddi_maxevents
)) {
753 int nevents
= ddi
->ddi_nevents
;
754 ddi
->ddi_nevents
= 1;
755 _dispatch_kq_update_all(wlh
, ddi
->ddi_eventlist
, nevents
);
756 dispatch_assert(ddi
->ddi_nevents
== 1);
758 } else if (slot
== ddi
->ddi_nevents
) {
761 return ddi
->ddi_eventlist
+ slot
;
764 DISPATCH_ALWAYS_INLINE
766 _dispatch_kq_deferred_discard_slot(dispatch_deferred_items_t ddi
, int slot
)
768 if (slot
< ddi
->ddi_nevents
) {
769 int last
= --ddi
->ddi_nevents
;
771 ddi
->ddi_eventlist
[slot
] = ddi
->ddi_eventlist
[last
];
778 _dispatch_kq_deferred_update(dispatch_wlh_t wlh
, dispatch_kevent_t ke
)
780 dispatch_deferred_items_t ddi
= _dispatch_deferred_items_get();
782 if (ddi
&& ddi
->ddi_maxevents
&& wlh
== _dispatch_get_wlh()) {
783 int slot
= _dispatch_kq_deferred_find_slot(ddi
, ke
->filter
, ke
->ident
,
785 dispatch_kevent_t dk
= _dispatch_kq_deferred_reuse_slot(wlh
, ddi
, slot
);
787 if (ke
->filter
!= EVFILT_USER
) {
788 _dispatch_kevent_mgr_debug("deferred", ke
);
791 _dispatch_kq_update_one(wlh
, ke
);
797 _dispatch_kq_immediate_update(dispatch_wlh_t wlh
, dispatch_kevent_t ke
)
799 dispatch_deferred_items_t ddi
= _dispatch_deferred_items_get();
800 if (ddi
&& wlh
== _dispatch_get_wlh()) {
801 int slot
= _dispatch_kq_deferred_find_slot(ddi
, ke
->filter
, ke
->ident
,
803 _dispatch_kq_deferred_discard_slot(ddi
, slot
);
805 return _dispatch_kq_update_one(wlh
, ke
);
810 _dispatch_kq_unote_update(dispatch_wlh_t wlh
, dispatch_unote_t _du
,
811 uint16_t action_flags
)
813 dispatch_deferred_items_t ddi
= _dispatch_deferred_items_get();
814 dispatch_unote_class_t du
= _du
._du
;
815 dispatch_kevent_t ke
;
818 if (action_flags
& EV_ADD
) {
819 // as soon as we register we may get an event delivery and it has to
820 // see du_wlh already set, else it will not unregister the kevent
821 dispatch_assert(du
->du_wlh
== NULL
);
822 _dispatch_wlh_retain(wlh
);
826 if (ddi
&& wlh
== _dispatch_get_wlh()) {
827 int slot
= _dispatch_kq_deferred_find_slot(ddi
,
828 du
->du_filter
, du
->du_ident
, (uintptr_t)du
);
829 if (slot
< ddi
->ddi_nevents
) {
830 // <rdar://problem/26202376> when deleting and an enable is pending,
831 // we must merge EV_ENABLE to do an immediate deletion
832 action_flags
|= (ddi
->ddi_eventlist
[slot
].flags
& EV_ENABLE
);
835 if (!(action_flags
& EV_ADD
) && (action_flags
& EV_ENABLE
)) {
836 // can be deferred, so do it!
837 ke
= _dispatch_kq_deferred_reuse_slot(wlh
, ddi
, slot
);
838 _dispatch_kq_unote_set_kevent(du
, ke
, action_flags
);
839 _dispatch_kevent_debug("deferred", ke
);
843 // get rid of the deferred item if any, we can't wait
844 _dispatch_kq_deferred_discard_slot(ddi
, slot
);
848 dispatch_kevent_s dk
;
849 _dispatch_kq_unote_set_kevent(du
, &dk
, action_flags
);
850 r
= _dispatch_kq_update_one(wlh
, &dk
);
854 if (action_flags
& EV_ADD
) {
856 _dispatch_wlh_release(du
->du_wlh
);
862 if (action_flags
& EV_DELETE
) {
863 if (r
== EINPROGRESS
) {
866 _dispatch_wlh_release(du
->du_wlh
);
870 dispatch_assume_zero(r
);
874 #pragma mark dispatch_muxnote_t
877 _dispatch_muxnotes_init(void *ctxt DISPATCH_UNUSED
)
880 for (i
= 0; i
< DSL_HASH_SIZE
; i
++) {
881 TAILQ_INIT(&_dispatch_sources
[i
]);
885 DISPATCH_ALWAYS_INLINE
886 static inline struct dispatch_muxnote_bucket_s
*
887 _dispatch_muxnote_bucket(uint64_t ident
, int16_t filter
)
891 case EVFILT_MACHPORT
:
892 case DISPATCH_EVFILT_MACH_NOTIFICATION
:
893 ident
= MACH_PORT_INDEX(ident
);
896 case EVFILT_SIGNAL
: // signo
897 case EVFILT_PROC
: // pid_t
902 dispatch_once_f(&_dispatch_muxnotes
.pred
, NULL
, _dispatch_muxnotes_init
);
903 return &_dispatch_sources
[DSL_HASH((uintptr_t)ident
)];
905 #define _dispatch_unote_muxnote_bucket(du) \
906 _dispatch_muxnote_bucket(du._du->du_ident, du._du->du_filter)
908 DISPATCH_ALWAYS_INLINE
909 static inline dispatch_muxnote_t
910 _dispatch_muxnote_find(struct dispatch_muxnote_bucket_s
*dmb
,
911 dispatch_wlh_t wlh
, uint64_t ident
, int16_t filter
)
913 dispatch_muxnote_t dmn
;
914 _dispatch_muxnotes_lock();
915 TAILQ_FOREACH(dmn
, dmb
, dmn_list
) {
916 if (dmn
->dmn_wlh
== wlh
&& dmn
->dmn_kev
.ident
== ident
&&
917 dmn
->dmn_kev
.filter
== filter
) {
921 _dispatch_muxnotes_unlock();
924 #define _dispatch_unote_muxnote_find(dmb, du, wlh) \
925 _dispatch_muxnote_find(dmb, wlh, du._du->du_ident, du._du->du_filter)
927 DISPATCH_ALWAYS_INLINE
928 static inline dispatch_muxnote_t
929 _dispatch_mach_muxnote_find(mach_port_t name
, int16_t filter
)
931 struct dispatch_muxnote_bucket_s
*dmb
;
932 dmb
= _dispatch_muxnote_bucket(name
, filter
);
933 return _dispatch_muxnote_find(dmb
, DISPATCH_WLH_ANON
, name
, filter
);
938 _dispatch_unote_register_muxed(dispatch_unote_t du
, dispatch_wlh_t wlh
)
940 struct dispatch_muxnote_bucket_s
*dmb
= _dispatch_unote_muxnote_bucket(du
);
941 dispatch_muxnote_t dmn
;
942 bool installed
= true;
944 dmn
= _dispatch_unote_muxnote_find(dmb
, du
, wlh
);
946 uint32_t flags
= du
._du
->du_fflags
& ~dmn
->dmn_kev
.fflags
;
948 dmn
->dmn_kev
.fflags
|= flags
;
949 if (unlikely(du
._du
->du_type
->dst_update_mux
)) {
950 installed
= du
._du
->du_type
->dst_update_mux(dmn
);
952 installed
= !_dispatch_kq_immediate_update(dmn
->dmn_wlh
,
955 if (!installed
) dmn
->dmn_kev
.fflags
&= ~flags
;
958 dmn
= _dispatch_calloc(1, sizeof(struct dispatch_muxnote_s
));
959 TAILQ_INIT(&dmn
->dmn_unotes_head
);
960 _dispatch_kq_unote_set_kevent(du
, &dmn
->dmn_kev
, EV_ADD
| EV_ENABLE
);
961 #if DISPATCH_USE_KEVENT_QOS
962 dmn
->dmn_kev
.qos
= _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG
;
964 dmn
->dmn_kev
.udata
= (uintptr_t)dmn
| DISPATCH_KEVENT_MUXED_MARKER
;
966 if (unlikely(du
._du
->du_type
->dst_update_mux
)) {
967 installed
= du
._du
->du_type
->dst_update_mux(dmn
);
969 installed
= !_dispatch_kq_immediate_update(dmn
->dmn_wlh
,
973 dmn
->dmn_kev
.flags
&= ~(EV_ADD
| EV_VANISHED
);
974 _dispatch_muxnotes_lock();
975 TAILQ_INSERT_TAIL(dmb
, dmn
, dmn_list
);
976 _dispatch_muxnotes_unlock();
983 dispatch_unote_linkage_t dul
= _dispatch_unote_get_linkage(du
);
984 TAILQ_INSERT_TAIL(&dmn
->dmn_unotes_head
, dul
, du_link
);
985 dul
->du_muxnote
= dmn
;
987 if (du
._du
->du_filter
== DISPATCH_EVFILT_MACH_NOTIFICATION
) {
988 bool armed
= DISPATCH_MACH_NOTIFICATION_ARMED(&dmn
->dmn_kev
);
989 os_atomic_store2o(du
._dmsr
, dmsr_notification_armed
, armed
,relaxed
);
991 du
._du
->du_wlh
= DISPATCH_WLH_ANON
;
997 _dispatch_unote_register(dispatch_unote_t du
, dispatch_wlh_t wlh
,
998 dispatch_priority_t pri
)
1000 dispatch_assert(!_dispatch_unote_registered(du
));
1001 du
._du
->du_priority
= pri
;
1002 switch (du
._du
->du_filter
) {
1003 case DISPATCH_EVFILT_CUSTOM_ADD
:
1004 case DISPATCH_EVFILT_CUSTOM_OR
:
1005 case DISPATCH_EVFILT_CUSTOM_REPLACE
:
1006 du
._du
->du_wlh
= DISPATCH_WLH_ANON
;
1009 if (!du
._du
->du_is_direct
) {
1010 return _dispatch_unote_register_muxed(du
, DISPATCH_WLH_ANON
);
1012 return _dispatch_kq_unote_update(wlh
, du
, EV_ADD
| EV_ENABLE
);
1016 _dispatch_unote_resume(dispatch_unote_t du
)
1018 dispatch_assert(_dispatch_unote_registered(du
));
1020 if (du
._du
->du_is_direct
) {
1021 dispatch_wlh_t wlh
= du
._du
->du_wlh
;
1022 _dispatch_kq_unote_update(wlh
, du
, EV_ENABLE
);
1023 } else if (unlikely(du
._du
->du_type
->dst_update_mux
)) {
1024 dispatch_unote_linkage_t dul
= _dispatch_unote_get_linkage(du
);
1025 du
._du
->du_type
->dst_update_mux(dul
->du_muxnote
);
1027 dispatch_unote_linkage_t dul
= _dispatch_unote_get_linkage(du
);
1028 dispatch_muxnote_t dmn
= dul
->du_muxnote
;
1029 _dispatch_kq_deferred_update(dmn
->dmn_wlh
, &dmn
->dmn_kev
);
1035 _dispatch_unote_unregister_muxed(dispatch_unote_t du
, uint32_t flags
)
1037 dispatch_unote_linkage_t dul
= _dispatch_unote_get_linkage(du
);
1038 dispatch_muxnote_t dmn
= dul
->du_muxnote
;
1039 bool update
= false, dispose
= false;
1041 if (dmn
->dmn_kev
.filter
== DISPATCH_EVFILT_MACH_NOTIFICATION
) {
1042 os_atomic_store2o(du
._dmsr
, dmsr_notification_armed
, false, relaxed
);
1044 dispatch_assert(du
._du
->du_wlh
== DISPATCH_WLH_ANON
);
1045 du
._du
->du_wlh
= NULL
;
1046 TAILQ_REMOVE(&dmn
->dmn_unotes_head
, dul
, du_link
);
1047 _TAILQ_TRASH_ENTRY(dul
, du_link
);
1048 dul
->du_muxnote
= NULL
;
1050 if (TAILQ_EMPTY(&dmn
->dmn_unotes_head
)) {
1051 dmn
->dmn_kev
.flags
|= EV_DELETE
;
1052 update
= dispose
= true;
1054 uint32_t fflags
= du
._du
->du_type
->dst_fflags
;
1055 TAILQ_FOREACH(dul
, &dmn
->dmn_unotes_head
, du_link
) {
1056 du
= _dispatch_unote_linkage_get_unote(dul
);
1057 fflags
|= du
._du
->du_fflags
;
1059 if (dmn
->dmn_kev
.fflags
& ~fflags
) {
1060 dmn
->dmn_kev
.fflags
&= fflags
;
1064 if (update
&& !(flags
& DU_UNREGISTER_ALREADY_DELETED
)) {
1065 if (unlikely(du
._du
->du_type
->dst_update_mux
)) {
1066 dispatch_assume(du
._du
->du_type
->dst_update_mux(dmn
));
1068 _dispatch_kq_deferred_update(dmn
->dmn_wlh
, &dmn
->dmn_kev
);
1072 struct dispatch_muxnote_bucket_s
*dmb
;
1073 dmb
= _dispatch_muxnote_bucket(dmn
->dmn_kev
.ident
, dmn
->dmn_kev
.filter
);
1074 _dispatch_muxnotes_lock();
1075 TAILQ_REMOVE(dmb
, dmn
, dmn_list
);
1076 _dispatch_muxnotes_unlock();
1083 _dispatch_unote_unregister(dispatch_unote_t du
, uint32_t flags
)
1085 switch (du
._du
->du_filter
) {
1086 case DISPATCH_EVFILT_CUSTOM_ADD
:
1087 case DISPATCH_EVFILT_CUSTOM_OR
:
1088 case DISPATCH_EVFILT_CUSTOM_REPLACE
:
1089 du
._du
->du_wlh
= NULL
;
1092 dispatch_wlh_t wlh
= du
._du
->du_wlh
;
1094 if (!du
._du
->du_is_direct
) {
1095 return _dispatch_unote_unregister_muxed(du
, flags
);
1097 uint16_t action_flags
;
1098 if (flags
& DU_UNREGISTER_ALREADY_DELETED
) {
1100 } else if (flags
& DU_UNREGISTER_IMMEDIATE_DELETE
) {
1101 action_flags
= EV_DELETE
| EV_ENABLE
;
1103 action_flags
= EV_DELETE
;
1105 return _dispatch_kq_unote_update(wlh
, du
, action_flags
);
1111 #pragma mark dispatch_event_loop
1114 _dispatch_event_loop_atfork_child(void)
1117 _dispatch_mach_host_port_pred
= 0;
1118 _dispatch_mach_host_port
= MACH_PORT_NULL
;
1125 _dispatch_event_loop_poke(dispatch_wlh_t wlh
, uint64_t dq_state
, uint32_t flags
)
1127 if (wlh
== DISPATCH_WLH_MANAGER
) {
1128 dispatch_kevent_s ke
= (dispatch_kevent_s
){
1130 .filter
= EVFILT_USER
,
1131 .fflags
= NOTE_TRIGGER
,
1132 .udata
= (uintptr_t)DISPATCH_WLH_MANAGER
,
1134 return _dispatch_kq_deferred_update(DISPATCH_WLH_ANON
, &ke
);
1135 } else if (wlh
&& wlh
!= DISPATCH_WLH_ANON
) {
1136 (void)dq_state
; (void)flags
;
1138 DISPATCH_INTERNAL_CRASH(wlh
, "Unsupported wlh configuration");
1143 _dispatch_event_loop_drain(uint32_t flags
)
1145 dispatch_wlh_t wlh
= _dispatch_get_wlh();
1146 dispatch_deferred_items_t ddi
= _dispatch_deferred_items_get();
1150 n
= ddi
->ddi_nevents
;
1151 ddi
->ddi_nevents
= 0;
1152 _dispatch_kq_drain(wlh
, ddi
->ddi_eventlist
, n
, flags
);
1154 if ((flags
& KEVENT_FLAG_IMMEDIATE
) &&
1155 !(flags
& KEVENT_FLAG_ERROR_EVENTS
) &&
1156 _dispatch_needs_to_return_to_kernel()) {
1162 _dispatch_event_loop_merge(dispatch_kevent_t events
, int nevents
)
1164 dispatch_deferred_items_t ddi
= _dispatch_deferred_items_get();
1165 dispatch_kevent_s kev
[nevents
];
1167 // now we can re-use the whole event list, but we need to save one slot
1168 // for the event loop poke
1169 memcpy(kev
, events
, sizeof(kev
));
1170 ddi
->ddi_maxevents
= DISPATCH_DEFERRED_ITEMS_EVENT_COUNT
- 1;
1172 for (int i
= 0; i
< nevents
; i
++) {
1173 _dispatch_kevent_drain(&kev
[i
]);
1176 dispatch_wlh_t wlh
= _dispatch_get_wlh();
1177 if (wlh
== DISPATCH_WLH_ANON
&& ddi
->ddi_stashed_dou
._do
) {
1178 if (ddi
->ddi_nevents
) {
1179 // We will drain the stashed item and not return to the kernel
1180 // right away. As a consequence, do not delay these updates.
1181 _dispatch_event_loop_drain(KEVENT_FLAG_IMMEDIATE
|
1182 KEVENT_FLAG_ERROR_EVENTS
);
1184 _dispatch_trace_continuation_push(ddi
->ddi_stashed_rq
,
1185 ddi
->ddi_stashed_dou
);
1190 _dispatch_event_loop_leave_immediate(dispatch_wlh_t wlh
, uint64_t dq_state
)
1192 (void)wlh
; (void)dq_state
;
1196 _dispatch_event_loop_leave_deferred(dispatch_wlh_t wlh
, uint64_t dq_state
)
1198 (void)wlh
; (void)dq_state
;
1202 _dispatch_event_loop_wake_owner(dispatch_sync_context_t dsc
,
1203 dispatch_wlh_t wlh
, uint64_t old_state
, uint64_t new_state
)
1205 (void)dsc
; (void)wlh
; (void)old_state
; (void)new_state
;
1209 _dispatch_event_loop_wait_for_ownership(dispatch_sync_context_t dsc
)
1211 if (dsc
->dsc_release_storage
) {
1212 _dispatch_queue_release_storage(dsc
->dc_data
);
1217 _dispatch_event_loop_end_ownership(dispatch_wlh_t wlh
, uint64_t old_state
,
1218 uint64_t new_state
, uint32_t flags
)
1220 (void)wlh
; (void)old_state
; (void)new_state
; (void)flags
;
1223 #if DISPATCH_WLH_DEBUG
1225 _dispatch_event_loop_assert_not_owned(dispatch_wlh_t wlh
)
1229 #endif // DISPATCH_WLH_DEBUG
1232 #pragma mark dispatch_event_loop timers
1234 #define DISPATCH_KEVENT_TIMEOUT_IDENT_MASK (~0ull << 8)
1238 _dispatch_kevent_timer_drain(dispatch_kevent_t ke
)
1240 dispatch_assert(ke
->data
> 0);
1241 dispatch_assert((ke
->ident
& DISPATCH_KEVENT_TIMEOUT_IDENT_MASK
) ==
1242 DISPATCH_KEVENT_TIMEOUT_IDENT_MASK
);
1243 uint32_t tidx
= ke
->ident
& ~DISPATCH_KEVENT_TIMEOUT_IDENT_MASK
;
1245 dispatch_assert(tidx
< DISPATCH_TIMER_COUNT
);
1246 _dispatch_timers_expired
= true;
1247 _dispatch_timers_processing_mask
|= 1 << tidx
;
1248 _dispatch_timers_heap
[tidx
].dth_flags
&= ~DTH_ARMED
;
1249 #if DISPATCH_USE_DTRACE
1250 _dispatch_timers_will_wake
|= 1 << DISPATCH_TIMER_QOS(tidx
);
1256 _dispatch_event_loop_timer_program(uint32_t tidx
,
1257 uint64_t target
, uint64_t leeway
, uint16_t action
)
1259 dispatch_kevent_s ke
= {
1260 .ident
= DISPATCH_KEVENT_TIMEOUT_IDENT_MASK
| tidx
,
1261 .filter
= EVFILT_TIMER
,
1262 .flags
= action
| EV_ONESHOT
,
1263 .fflags
= _dispatch_timer_index_to_fflags
[tidx
],
1264 .data
= (int64_t)target
,
1265 .udata
= (uintptr_t)&_dispatch_timers_heap
[tidx
],
1266 #if DISPATCH_HAVE_TIMER_COALESCING
1269 #if DISPATCH_USE_KEVENT_QOS
1270 .qos
= _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG
,
1274 _dispatch_kq_deferred_update(DISPATCH_WLH_ANON
, &ke
);
1278 _dispatch_event_loop_timer_arm(uint32_t tidx
, dispatch_timer_delay_s range
,
1279 dispatch_clock_now_cache_t nows
)
1281 if (unlikely(_dispatch_timers_force_max_leeway
)) {
1282 range
.delay
+= range
.leeway
;
1286 if (DISPATCH_TIMER_CLOCK(tidx
) == DISPATCH_CLOCK_WALL
) {
1287 _dispatch_mach_host_calendar_change_register();
1291 // <rdar://problem/13186331> EVFILT_TIMER NOTE_ABSOLUTE always expects
1293 uint64_t now
= _dispatch_time_now_cached(DISPATCH_CLOCK_WALL
, nows
);
1294 _dispatch_timers_heap
[tidx
].dth_flags
|= DTH_ARMED
;
1295 _dispatch_event_loop_timer_program(tidx
, now
+ range
.delay
, range
.leeway
,
1296 EV_ADD
| EV_ENABLE
);
1300 _dispatch_event_loop_timer_delete(uint32_t tidx
)
1302 _dispatch_timers_heap
[tidx
].dth_flags
&= ~DTH_ARMED
;
1303 _dispatch_event_loop_timer_program(tidx
, 0, 0, EV_DELETE
);
1307 #pragma mark kevent specific sources
1309 static dispatch_unote_t
1310 _dispatch_source_proc_create(dispatch_source_type_t dst DISPATCH_UNUSED
,
1311 uintptr_t handle
, unsigned long mask DISPATCH_UNUSED
)
1313 dispatch_unote_t du
= _dispatch_unote_create_with_handle(dst
, handle
, mask
);
1314 if (du
._du
&& (mask
& DISPATCH_PROC_EXIT_STATUS
)) {
1315 du
._du
->du_data_action
= DISPATCH_UNOTE_ACTION_DATA_OR_STATUS_SET
;
1320 const dispatch_source_type_s _dispatch_source_type_proc
= {
1322 .dst_filter
= EVFILT_PROC
,
1323 .dst_flags
= DISPATCH_EV_DIRECT
|EV_CLEAR
,
1324 .dst_fflags
= NOTE_EXIT
, // rdar://16655831
1325 .dst_mask
= NOTE_EXIT
|NOTE_FORK
|NOTE_EXEC
|NOTE_EXITSTATUS
1326 #if HAVE_DECL_NOTE_SIGNAL
1329 #if HAVE_DECL_NOTE_REAP
1333 .dst_size
= sizeof(struct dispatch_source_refs_s
),
1335 .dst_create
= _dispatch_source_proc_create
,
1336 .dst_merge_evt
= _dispatch_source_merge_evt
,
1339 const dispatch_source_type_s _dispatch_source_type_vnode
= {
1340 .dst_kind
= "vnode",
1341 .dst_filter
= EVFILT_VNODE
,
1342 .dst_flags
= DISPATCH_EV_DIRECT
|EV_CLEAR
|EV_VANISHED
,
1343 .dst_mask
= NOTE_DELETE
|NOTE_WRITE
|NOTE_EXTEND
|NOTE_ATTRIB
|NOTE_LINK
1344 |NOTE_RENAME
|NOTE_FUNLOCK
1345 #if HAVE_DECL_NOTE_REVOKE
1348 #if HAVE_DECL_NOTE_NONE
1352 .dst_size
= sizeof(struct dispatch_source_refs_s
),
1354 .dst_create
= _dispatch_unote_create_with_fd
,
1355 .dst_merge_evt
= _dispatch_source_merge_evt
,
1358 const dispatch_source_type_s _dispatch_source_type_vfs
= {
1360 .dst_filter
= EVFILT_FS
,
1361 .dst_flags
= DISPATCH_EV_DIRECT
|EV_CLEAR
,
1362 .dst_mask
= VQ_NOTRESP
|VQ_NEEDAUTH
|VQ_LOWDISK
|VQ_MOUNT
|VQ_UNMOUNT
1363 |VQ_DEAD
|VQ_ASSIST
|VQ_NOTRESPLOCK
1364 #if HAVE_DECL_VQ_UPDATE
1367 #if HAVE_DECL_VQ_VERYLOWDISK
1370 #if HAVE_DECL_VQ_QUOTA
1373 #if HAVE_DECL_VQ_NEARLOWDISK
1376 #if HAVE_DECL_VQ_DESIRED_DISK
1380 .dst_size
= sizeof(struct dispatch_source_refs_s
),
1382 .dst_create
= _dispatch_unote_create_without_handle
,
1383 .dst_merge_evt
= _dispatch_source_merge_evt
,
1387 const dispatch_source_type_s _dispatch_source_type_sock
= {
1389 .dst_filter
= EVFILT_SOCK
,
1390 .dst_flags
= DISPATCH_EV_DIRECT
|EV_CLEAR
|EV_VANISHED
,
1391 .dst_mask
= NOTE_CONNRESET
|NOTE_READCLOSED
|NOTE_WRITECLOSED
1392 |NOTE_TIMEOUT
|NOTE_NOSRCADDR
|NOTE_IFDENIED
|NOTE_SUSPEND
|NOTE_RESUME
1394 #ifdef NOTE_ADAPTIVE_WTIMO
1395 |NOTE_ADAPTIVE_WTIMO
|NOTE_ADAPTIVE_RTIMO
1397 #ifdef NOTE_CONNECTED
1398 |NOTE_CONNECTED
|NOTE_DISCONNECTED
|NOTE_CONNINFO_UPDATED
1400 #ifdef NOTE_NOTIFY_ACK
1404 .dst_size
= sizeof(struct dispatch_source_refs_s
),
1406 .dst_create
= _dispatch_unote_create_with_fd
,
1407 .dst_merge_evt
= _dispatch_source_merge_evt
,
1409 #endif // EVFILT_SOCK
1411 #ifdef EVFILT_NW_CHANNEL
1412 const dispatch_source_type_s _dispatch_source_type_nw_channel
= {
1413 .dst_kind
= "nw_channel",
1414 .dst_filter
= EVFILT_NW_CHANNEL
,
1415 .dst_flags
= DISPATCH_EV_DIRECT
|EV_CLEAR
|EV_VANISHED
,
1416 .dst_mask
= NOTE_FLOW_ADV_UPDATE
,
1417 .dst_size
= sizeof(struct dispatch_source_refs_s
),
1418 .dst_create
= _dispatch_unote_create_with_fd
,
1419 .dst_merge_evt
= _dispatch_source_merge_evt
,
1421 #endif // EVFILT_NW_CHANNEL
1423 #if DISPATCH_USE_MEMORYSTATUS
1425 #if DISPATCH_USE_MEMORYPRESSURE_SOURCE
1426 #define DISPATCH_MEMORYPRESSURE_SOURCE_MASK ( \
1427 DISPATCH_MEMORYPRESSURE_NORMAL | \
1428 DISPATCH_MEMORYPRESSURE_WARN | \
1429 DISPATCH_MEMORYPRESSURE_CRITICAL | \
1430 DISPATCH_MEMORYPRESSURE_PROC_LIMIT_WARN | \
1431 DISPATCH_MEMORYPRESSURE_PROC_LIMIT_CRITICAL | \
1432 DISPATCH_MEMORYPRESSURE_MSL_STATUS)
1434 #define DISPATCH_MEMORYPRESSURE_MALLOC_MASK ( \
1435 DISPATCH_MEMORYPRESSURE_WARN | \
1436 DISPATCH_MEMORYPRESSURE_CRITICAL | \
1437 DISPATCH_MEMORYPRESSURE_PROC_LIMIT_WARN | \
1438 DISPATCH_MEMORYPRESSURE_PROC_LIMIT_CRITICAL | \
1439 DISPATCH_MEMORYPRESSURE_MSL_STATUS)
1443 _dispatch_memorypressure_handler(void *context
)
1445 dispatch_source_t ds
= context
;
1446 unsigned long memorypressure
= dispatch_source_get_data(ds
);
1448 if (memorypressure
& DISPATCH_MEMORYPRESSURE_NORMAL
) {
1449 _dispatch_memory_warn
= false;
1450 _dispatch_continuation_cache_limit
= DISPATCH_CONTINUATION_CACHE_LIMIT
;
1451 #if VOUCHER_USE_MACH_VOUCHER
1452 if (_firehose_task_buffer
) {
1453 firehose_buffer_clear_bank_flags(_firehose_task_buffer
,
1454 FIREHOSE_BUFFER_BANK_FLAG_LOW_MEMORY
);
1458 if (memorypressure
& DISPATCH_MEMORYPRESSURE_WARN
) {
1459 _dispatch_memory_warn
= true;
1460 _dispatch_continuation_cache_limit
=
1461 DISPATCH_CONTINUATION_CACHE_LIMIT_MEMORYPRESSURE_PRESSURE_WARN
;
1462 #if VOUCHER_USE_MACH_VOUCHER
1463 if (_firehose_task_buffer
) {
1464 firehose_buffer_set_bank_flags(_firehose_task_buffer
,
1465 FIREHOSE_BUFFER_BANK_FLAG_LOW_MEMORY
);
1469 memorypressure
&= DISPATCH_MEMORYPRESSURE_MALLOC_MASK
;
1470 if (memorypressure
) {
1471 malloc_memory_event_handler(memorypressure
);
1476 _dispatch_memorypressure_init(void)
1478 dispatch_source_t ds
= dispatch_source_create(
1479 DISPATCH_SOURCE_TYPE_MEMORYPRESSURE
, 0,
1480 DISPATCH_MEMORYPRESSURE_SOURCE_MASK
, &_dispatch_mgr_q
);
1481 dispatch_set_context(ds
, ds
);
1482 dispatch_source_set_event_handler_f(ds
, _dispatch_memorypressure_handler
);
1483 dispatch_activate(ds
);
1485 #endif // DISPATCH_USE_MEMORYPRESSURE_SOURCE
1487 #if TARGET_OS_SIMULATOR // rdar://problem/9219483
1488 static int _dispatch_ios_simulator_memory_warnings_fd
= -1;
1490 _dispatch_ios_simulator_memorypressure_init(void *context DISPATCH_UNUSED
)
1492 char *e
= getenv("SIMULATOR_MEMORY_WARNINGS");
1494 _dispatch_ios_simulator_memory_warnings_fd
= open(e
, O_EVTONLY
);
1495 if (_dispatch_ios_simulator_memory_warnings_fd
== -1) {
1496 (void)dispatch_assume_zero(errno
);
1500 static dispatch_unote_t
1501 _dispatch_source_memorypressure_create(dispatch_source_type_t dst
,
1502 uintptr_t handle
, unsigned long mask
)
1504 static dispatch_once_t pred
;
1505 dispatch_once_f(&pred
, NULL
, _dispatch_ios_simulator_memorypressure_init
);
1508 return DISPATCH_UNOTE_NULL
;
1511 dst
= &_dispatch_source_type_vnode
;
1512 handle
= (uintptr_t)_dispatch_ios_simulator_memory_warnings_fd
;
1515 dispatch_unote_t du
= dux_create(dst
, handle
, mask
);
1517 du
._du
->du_memorypressure_override
= true;
1521 #endif // TARGET_OS_SIMULATOR
1523 const dispatch_source_type_s _dispatch_source_type_memorypressure
= {
1524 .dst_kind
= "memorystatus",
1525 .dst_filter
= EVFILT_MEMORYSTATUS
,
1526 .dst_flags
= EV_UDATA_SPECIFIC
|EV_DISPATCH
,
1527 .dst_mask
= NOTE_MEMORYSTATUS_PRESSURE_NORMAL
1528 |NOTE_MEMORYSTATUS_PRESSURE_WARN
|NOTE_MEMORYSTATUS_PRESSURE_CRITICAL
1529 |NOTE_MEMORYSTATUS_LOW_SWAP
|NOTE_MEMORYSTATUS_PROC_LIMIT_WARN
1530 |NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL
1531 |NOTE_MEMORYSTATUS_MSL_STATUS
,
1532 .dst_size
= sizeof(struct dispatch_source_refs_s
),
1534 #if TARGET_OS_SIMULATOR
1535 .dst_create
= _dispatch_source_memorypressure_create
,
1536 // redirected to _dispatch_source_type_vnode
1538 .dst_create
= _dispatch_unote_create_without_handle
,
1539 .dst_merge_evt
= _dispatch_source_merge_evt
,
1543 static dispatch_unote_t
1544 _dispatch_source_vm_create(dispatch_source_type_t dst DISPATCH_UNUSED
,
1545 uintptr_t handle
, unsigned long mask DISPATCH_UNUSED
)
1547 // Map legacy vm pressure to memorypressure warning rdar://problem/15907505
1548 dispatch_unote_t du
= dux_create(&_dispatch_source_type_memorypressure
,
1549 handle
, NOTE_MEMORYSTATUS_PRESSURE_WARN
);
1551 du
._du
->du_vmpressure_override
= 1;
1556 const dispatch_source_type_s _dispatch_source_type_vm
= {
1557 .dst_kind
= "vm (deprecated)",
1558 .dst_filter
= EVFILT_MEMORYSTATUS
,
1559 .dst_flags
= EV_UDATA_SPECIFIC
|EV_DISPATCH
,
1560 .dst_mask
= NOTE_VM_PRESSURE
,
1561 .dst_size
= sizeof(struct dispatch_source_refs_s
),
1563 .dst_create
= _dispatch_source_vm_create
,
1564 // redirected to _dispatch_source_type_memorypressure
1566 #endif // DISPATCH_USE_MEMORYSTATUS
1568 #pragma mark mach send / notifications
1571 // Flags for all notifications that are registered/unregistered when a
1572 // send-possible notification is requested/delivered
1573 #define _DISPATCH_MACH_SP_FLAGS (DISPATCH_MACH_SEND_POSSIBLE| \
1574 DISPATCH_MACH_SEND_DEAD|DISPATCH_MACH_SEND_DELETED)
1576 static void _dispatch_mach_host_notify_update(void *context
);
1578 static mach_port_t _dispatch_mach_notify_port
;
1579 static dispatch_source_t _dispatch_mach_notify_source
;
1582 _dispatch_timers_calendar_change(void)
1586 // calendar change may have gone past the wallclock deadline
1587 _dispatch_timers_expired
= true;
1588 for (qos
= 0; qos
< DISPATCH_TIMER_QOS_COUNT
; qos
++) {
1589 _dispatch_timers_processing_mask
|=
1590 1 << DISPATCH_TIMER_INDEX(DISPATCH_CLOCK_WALL
, qos
);
1594 static mach_msg_audit_trailer_t
*
1595 _dispatch_mach_msg_get_audit_trailer(mach_msg_header_t
*hdr
)
1597 mach_msg_trailer_t
*tlr
= NULL
;
1598 mach_msg_audit_trailer_t
*audit_tlr
= NULL
;
1599 tlr
= (mach_msg_trailer_t
*)((unsigned char *)hdr
+
1600 round_msg(hdr
->msgh_size
));
1601 // The trailer should always be of format zero.
1602 if (tlr
->msgh_trailer_type
== MACH_MSG_TRAILER_FORMAT_0
) {
1603 if (tlr
->msgh_trailer_size
>= sizeof(mach_msg_audit_trailer_t
)) {
1604 audit_tlr
= (mach_msg_audit_trailer_t
*)tlr
;
1612 _dispatch_mach_notify_source_invoke(mach_msg_header_t
*hdr
)
1614 mig_reply_error_t reply
;
1615 mach_msg_audit_trailer_t
*tlr
= NULL
;
1616 dispatch_assert(sizeof(mig_reply_error_t
) == sizeof(union
1617 __ReplyUnion___dispatch_libdispatch_internal_protocol_subsystem
));
1618 dispatch_assert(sizeof(mig_reply_error_t
) <
1619 DISPATCH_MACH_RECEIVE_MAX_INLINE_MESSAGE_SIZE
);
1620 tlr
= _dispatch_mach_msg_get_audit_trailer(hdr
);
1622 DISPATCH_INTERNAL_CRASH(0, "message received without expected trailer");
1624 if (hdr
->msgh_id
<= MACH_NOTIFY_LAST
1625 && dispatch_assume_zero(tlr
->msgh_audit
.val
[
1626 DISPATCH_MACH_AUDIT_TOKEN_PID
])) {
1627 mach_msg_destroy(hdr
);
1630 boolean_t success
= libdispatch_internal_protocol_server(hdr
, &reply
.Head
);
1631 if (!success
&& reply
.RetCode
== MIG_BAD_ID
&&
1632 (hdr
->msgh_id
== HOST_CALENDAR_SET_REPLYID
||
1633 hdr
->msgh_id
== HOST_CALENDAR_CHANGED_REPLYID
)) {
1634 _dispatch_debug("calendar-change notification");
1635 _dispatch_timers_calendar_change();
1636 _dispatch_mach_host_notify_update(NULL
);
1638 reply
.RetCode
= KERN_SUCCESS
;
1640 if (dispatch_assume(success
) && reply
.RetCode
!= MIG_NO_REPLY
) {
1641 (void)dispatch_assume_zero(reply
.RetCode
);
1643 if (!success
|| (reply
.RetCode
&& reply
.RetCode
!= MIG_NO_REPLY
)) {
1644 mach_msg_destroy(hdr
);
1650 _dispatch_mach_notify_port_init(void *context DISPATCH_UNUSED
)
1653 #if HAVE_MACH_PORT_CONSTRUCT
1654 mach_port_options_t opts
= { .flags
= MPO_CONTEXT_AS_GUARD
| MPO_STRICT
};
1655 #if DISPATCH_SIZEOF_PTR == 8
1656 const mach_port_context_t guard
= 0xfeed09071f1ca7edull
;
1658 const mach_port_context_t guard
= 0xff1ca7edull
;
1660 kr
= mach_port_construct(mach_task_self(), &opts
, guard
,
1661 &_dispatch_mach_notify_port
);
1663 kr
= mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE
,
1664 &_dispatch_mach_notify_port
);
1666 DISPATCH_VERIFY_MIG(kr
);
1668 DISPATCH_CLIENT_CRASH(kr
,
1669 "mach_port_construct() failed: cannot create receive right");
1672 static const struct dispatch_continuation_s dc
= {
1673 .dc_func
= (void*)_dispatch_mach_notify_source_invoke
,
1675 _dispatch_mach_notify_source
= _dispatch_source_create_mach_msg_direct_recv(
1676 _dispatch_mach_notify_port
, &dc
);
1677 dispatch_assert(_dispatch_mach_notify_source
);
1678 dispatch_activate(_dispatch_mach_notify_source
);
1682 _dispatch_mach_host_port_init(void *ctxt DISPATCH_UNUSED
)
1685 mach_port_t mp
, mhp
= mach_host_self();
1686 kr
= host_get_host_port(mhp
, &mp
);
1687 DISPATCH_VERIFY_MIG(kr
);
1689 // mach_host_self returned the HOST_PRIV port
1690 kr
= mach_port_deallocate(mach_task_self(), mhp
);
1691 DISPATCH_VERIFY_MIG(kr
);
1693 } else if (kr
!= KERN_INVALID_ARGUMENT
) {
1694 (void)dispatch_assume_zero(kr
);
1696 if (unlikely(!mhp
)) {
1697 DISPATCH_CLIENT_CRASH(kr
, "Could not get unprivileged host port");
1699 _dispatch_mach_host_port
= mhp
;
1703 _dispatch_get_mach_host_port(void)
1705 dispatch_once_f(&_dispatch_mach_host_port_pred
, NULL
,
1706 _dispatch_mach_host_port_init
);
1707 return _dispatch_mach_host_port
;
1710 DISPATCH_ALWAYS_INLINE
1711 static inline mach_port_t
1712 _dispatch_get_mach_notify_port(void)
1714 static dispatch_once_t pred
;
1715 dispatch_once_f(&pred
, NULL
, _dispatch_mach_notify_port_init
);
1716 return _dispatch_mach_notify_port
;
1720 _dispatch_mach_host_notify_update(void *context DISPATCH_UNUSED
)
1722 static int notify_type
= HOST_NOTIFY_CALENDAR_SET
;
1724 _dispatch_debug("registering for calendar-change notification");
1726 kr
= host_request_notification(_dispatch_get_mach_host_port(),
1727 notify_type
, _dispatch_get_mach_notify_port());
1728 // Fallback when missing support for newer _SET variant, fires strictly more
1729 if (kr
== KERN_INVALID_ARGUMENT
&&
1730 notify_type
!= HOST_NOTIFY_CALENDAR_CHANGE
) {
1731 notify_type
= HOST_NOTIFY_CALENDAR_CHANGE
;
1734 DISPATCH_VERIFY_MIG(kr
);
1735 (void)dispatch_assume_zero(kr
);
1738 DISPATCH_ALWAYS_INLINE
1740 _dispatch_mach_host_calendar_change_register(void)
1742 static dispatch_once_t pred
;
1743 dispatch_once_f(&pred
, NULL
, _dispatch_mach_host_notify_update
);
1746 static kern_return_t
1747 _dispatch_mach_notify_update(dispatch_muxnote_t dmn
, uint32_t new_flags
,
1748 uint32_t del_flags
, uint32_t mask
, mach_msg_id_t notify_msgid
,
1749 mach_port_mscount_t notify_sync
)
1751 mach_port_t previous
, port
= (mach_port_t
)dmn
->dmn_kev
.ident
;
1752 typeof(dmn
->dmn_kev
.data
) prev
= dmn
->dmn_kev
.data
;
1753 kern_return_t kr
, krr
= 0;
1755 // Update notification registration state.
1756 dmn
->dmn_kev
.data
|= (new_flags
| dmn
->dmn_kev
.fflags
) & mask
;
1757 dmn
->dmn_kev
.data
&= ~(del_flags
& mask
);
1759 _dispatch_debug_machport(port
);
1760 if ((dmn
->dmn_kev
.data
& mask
) && !(prev
& mask
)) {
1761 _dispatch_debug("machport[0x%08x]: registering for send-possible "
1762 "notification", port
);
1763 previous
= MACH_PORT_NULL
;
1764 krr
= mach_port_request_notification(mach_task_self(), port
,
1765 notify_msgid
, notify_sync
, _dispatch_get_mach_notify_port(),
1766 MACH_MSG_TYPE_MAKE_SEND_ONCE
, &previous
);
1767 DISPATCH_VERIFY_MIG(krr
);
1770 case KERN_INVALID_NAME
:
1771 case KERN_INVALID_RIGHT
:
1772 // Suppress errors & clear registration state
1773 dmn
->dmn_kev
.data
&= ~mask
;
1776 // Else, we don't expect any errors from mach. Log any errors
1777 if (dispatch_assume_zero(krr
)) {
1778 // log the error & clear registration state
1779 dmn
->dmn_kev
.data
&= ~mask
;
1780 } else if (dispatch_assume_zero(previous
)) {
1781 // Another subsystem has beat libdispatch to requesting the
1782 // specified Mach notification on this port. We should
1783 // technically cache the previous port and message it when the
1784 // kernel messages our port. Or we can just say screw those
1785 // subsystems and deallocate the previous port.
1786 // They should adopt libdispatch :-P
1787 kr
= mach_port_deallocate(mach_task_self(), previous
);
1788 DISPATCH_VERIFY_MIG(kr
);
1789 (void)dispatch_assume_zero(kr
);
1790 previous
= MACH_PORT_NULL
;
1793 } else if (!(dmn
->dmn_kev
.data
& mask
) && (prev
& mask
)) {
1794 _dispatch_debug("machport[0x%08x]: unregistering for send-possible "
1795 "notification", port
);
1796 previous
= MACH_PORT_NULL
;
1797 kr
= mach_port_request_notification(mach_task_self(), port
,
1798 notify_msgid
, notify_sync
, MACH_PORT_NULL
,
1799 MACH_MSG_TYPE_MOVE_SEND_ONCE
, &previous
);
1800 DISPATCH_VERIFY_MIG(kr
);
1803 case KERN_INVALID_NAME
:
1804 case KERN_INVALID_RIGHT
:
1805 case KERN_INVALID_ARGUMENT
:
1808 if (dispatch_assume_zero(kr
)) {
1815 if (unlikely(previous
)) {
1816 // the kernel has not consumed the send-once right yet
1817 (void)dispatch_assume_zero(
1818 _dispatch_send_consume_send_once_right(previous
));
1824 _dispatch_kevent_mach_notify_resume(dispatch_muxnote_t dmn
, uint32_t new_flags
,
1827 kern_return_t kr
= KERN_SUCCESS
;
1828 dispatch_assert_zero(new_flags
& del_flags
);
1829 if ((new_flags
& _DISPATCH_MACH_SP_FLAGS
) ||
1830 (del_flags
& _DISPATCH_MACH_SP_FLAGS
)) {
1831 // Requesting a (delayed) non-sync send-possible notification
1832 // registers for both immediate dead-name notification and delayed-arm
1833 // send-possible notification for the port.
1834 // The send-possible notification is armed when a mach_msg() with the
1835 // the MACH_SEND_NOTIFY to the port times out.
1836 // If send-possible is unavailable, fall back to immediate dead-name
1837 // registration rdar://problem/2527840&9008724
1838 kr
= _dispatch_mach_notify_update(dmn
, new_flags
, del_flags
,
1839 _DISPATCH_MACH_SP_FLAGS
, MACH_NOTIFY_SEND_POSSIBLE
,
1840 MACH_NOTIFY_SEND_POSSIBLE
== MACH_NOTIFY_DEAD_NAME
);
1842 return kr
== KERN_SUCCESS
;
1847 _dispatch_mach_notify_merge(mach_port_t name
, uint32_t data
, bool final
)
1849 dispatch_unote_linkage_t dul
, dul_next
;
1850 dispatch_muxnote_t dmn
;
1852 _dispatch_debug_machport(name
);
1853 dmn
= _dispatch_mach_muxnote_find(name
, DISPATCH_EVFILT_MACH_NOTIFICATION
);
1858 dmn
->dmn_kev
.data
&= ~_DISPATCH_MACH_SP_FLAGS
;
1860 // Re-register for notification before delivery
1861 final
= !_dispatch_kevent_mach_notify_resume(dmn
, data
, 0);
1864 uint32_t flags
= final
? EV_ONESHOT
: EV_ENABLE
;
1865 DISPATCH_MACH_NOTIFICATION_ARMED(&dmn
->dmn_kev
) = 0;
1866 TAILQ_FOREACH_SAFE(dul
, &dmn
->dmn_unotes_head
, du_link
, dul_next
) {
1867 dispatch_unote_t du
= _dispatch_unote_linkage_get_unote(dul
);
1868 os_atomic_store2o(du
._dmsr
, dmsr_notification_armed
, false, relaxed
);
1869 dux_merge_evt(du
._du
, flags
, (data
& du
._du
->du_fflags
), 0, 0);
1870 if (!dul_next
|| DISPATCH_MACH_NOTIFICATION_ARMED(&dmn
->dmn_kev
)) {
1871 // current merge is last in list (dmn might have been freed)
1872 // or it re-armed the notification
1879 _dispatch_mach_notify_port_deleted(mach_port_t notify DISPATCH_UNUSED
,
1880 mach_port_name_t name
)
1883 _dispatch_log("Corruption: Mach send/send-once/dead-name right 0x%x "
1884 "deleted prematurely", name
);
1886 _dispatch_debug_machport(name
);
1887 _dispatch_mach_notify_merge(name
, DISPATCH_MACH_SEND_DELETED
, true);
1888 return KERN_SUCCESS
;
1892 _dispatch_mach_notify_dead_name(mach_port_t notify DISPATCH_UNUSED
,
1893 mach_port_name_t name
)
1897 _dispatch_debug("machport[0x%08x]: dead-name notification", name
);
1898 _dispatch_debug_machport(name
);
1899 _dispatch_mach_notify_merge(name
, DISPATCH_MACH_SEND_DEAD
, true);
1901 // the act of receiving a dead name notification allocates a dead-name
1902 // right that must be deallocated
1903 kr
= mach_port_deallocate(mach_task_self(), name
);
1904 DISPATCH_VERIFY_MIG(kr
);
1905 //(void)dispatch_assume_zero(kr);
1906 return KERN_SUCCESS
;
1910 _dispatch_mach_notify_send_possible(mach_port_t notify DISPATCH_UNUSED
,
1911 mach_port_name_t name
)
1913 _dispatch_debug("machport[0x%08x]: send-possible notification", name
);
1914 _dispatch_debug_machport(name
);
1915 _dispatch_mach_notify_merge(name
, DISPATCH_MACH_SEND_POSSIBLE
, false);
1916 return KERN_SUCCESS
;
1920 _dispatch_mach_notification_set_armed(dispatch_mach_send_refs_t dmsr
)
1922 dispatch_muxnote_t dmn
= _dispatch_unote_get_linkage(dmsr
)->du_muxnote
;
1923 dispatch_unote_linkage_t dul
;
1924 dispatch_unote_t du
;
1926 if (!_dispatch_unote_registered(dmsr
)) {
1930 DISPATCH_MACH_NOTIFICATION_ARMED(&dmn
->dmn_kev
) = true;
1931 TAILQ_FOREACH(dul
, &dmn
->dmn_unotes_head
, du_link
) {
1932 du
= _dispatch_unote_linkage_get_unote(dul
);
1933 os_atomic_store2o(du
._dmsr
, dmsr_notification_armed
, true, relaxed
);
1937 static dispatch_unote_t
1938 _dispatch_source_mach_send_create(dispatch_source_type_t dst
,
1939 uintptr_t handle
, unsigned long mask
)
1942 // Preserve legacy behavior that (mask == 0) => DISPATCH_MACH_SEND_DEAD
1943 mask
= DISPATCH_MACH_SEND_DEAD
;
1946 handle
= MACH_PORT_DEAD
; // <rdar://problem/27651332>
1948 return _dispatch_unote_create_with_handle(dst
, handle
, mask
);
1952 _dispatch_mach_send_update(dispatch_muxnote_t dmn
)
1954 if (dmn
->dmn_kev
.flags
& EV_DELETE
) {
1955 return _dispatch_kevent_mach_notify_resume(dmn
, 0, dmn
->dmn_kev
.fflags
);
1957 return _dispatch_kevent_mach_notify_resume(dmn
, dmn
->dmn_kev
.fflags
, 0);
1961 const dispatch_source_type_s _dispatch_source_type_mach_send
= {
1962 .dst_kind
= "mach_send",
1963 .dst_filter
= DISPATCH_EVFILT_MACH_NOTIFICATION
,
1964 .dst_flags
= EV_CLEAR
,
1965 .dst_mask
= DISPATCH_MACH_SEND_DEAD
|DISPATCH_MACH_SEND_POSSIBLE
,
1966 .dst_size
= sizeof(struct dispatch_source_refs_s
),
1968 .dst_create
= _dispatch_source_mach_send_create
,
1969 .dst_update_mux
= _dispatch_mach_send_update
,
1970 .dst_merge_evt
= _dispatch_source_merge_evt
,
1973 static dispatch_unote_t
1974 _dispatch_mach_send_create(dispatch_source_type_t dst
,
1975 uintptr_t handle
, unsigned long mask
)
1977 // without handle because the mach code will set the ident later
1978 dispatch_unote_t du
=
1979 _dispatch_unote_create_without_handle(dst
, handle
, mask
);
1981 du
._dmsr
->dmsr_disconnect_cnt
= DISPATCH_MACH_NEVER_CONNECTED
;
1982 TAILQ_INIT(&du
._dmsr
->dmsr_replies
);
1987 const dispatch_source_type_s _dispatch_mach_type_send
= {
1988 .dst_kind
= "mach_send (mach)",
1989 .dst_filter
= DISPATCH_EVFILT_MACH_NOTIFICATION
,
1990 .dst_flags
= EV_CLEAR
,
1991 .dst_mask
= DISPATCH_MACH_SEND_DEAD
|DISPATCH_MACH_SEND_POSSIBLE
,
1992 .dst_size
= sizeof(struct dispatch_mach_send_refs_s
),
1994 .dst_create
= _dispatch_mach_send_create
,
1995 .dst_update_mux
= _dispatch_mach_send_update
,
1996 .dst_merge_evt
= _dispatch_mach_merge_notification
,
2000 #pragma mark mach recv / reply
2004 _dispatch_kevent_mach_msg_recv(dispatch_unote_t du
, uint32_t flags
,
2005 mach_msg_header_t
*hdr
)
2007 mach_msg_size_t siz
= hdr
->msgh_size
+ DISPATCH_MACH_TRAILER_SIZE
;
2008 mach_port_t name
= hdr
->msgh_local_port
;
2010 if (!dispatch_assume(hdr
->msgh_size
<= UINT_MAX
-
2011 DISPATCH_MACH_TRAILER_SIZE
)) {
2012 _dispatch_bug_client("_dispatch_kevent_mach_msg_recv: "
2013 "received overlarge message");
2014 } else if (!dispatch_assume(name
)) {
2015 _dispatch_bug_client("_dispatch_kevent_mach_msg_recv: "
2016 "received message with MACH_PORT_NULL port");
2018 _dispatch_debug_machport(name
);
2019 if (likely(du
._du
)) {
2020 return dux_merge_msg(du
._du
, flags
, hdr
, siz
);
2022 _dispatch_bug_client("_dispatch_kevent_mach_msg_recv: "
2023 "received message with no listeners");
2026 mach_msg_destroy(hdr
);
2027 if (flags
& DISPATCH_EV_MSG_NEEDS_FREE
) {
2034 _dispatch_kevent_mach_msg_drain(dispatch_kevent_t ke
)
2036 mach_msg_header_t
*hdr
= _dispatch_kevent_mach_msg_buf(ke
);
2037 mach_msg_size_t siz
;
2038 mach_msg_return_t kr
= (mach_msg_return_t
)ke
->fflags
;
2039 uint32_t flags
= ke
->flags
;
2040 dispatch_unote_t du
= _dispatch_kevent_get_unote(ke
);
2042 if (unlikely(!hdr
)) {
2043 DISPATCH_INTERNAL_CRASH(kr
, "EVFILT_MACHPORT with no message");
2046 _dispatch_kevent_mach_msg_recv(du
, flags
, hdr
);
2048 } else if (kr
!= MACH_RCV_TOO_LARGE
) {
2050 } else if (!ke
->data
) {
2051 DISPATCH_INTERNAL_CRASH(0, "MACH_RCV_LARGE_IDENTITY with no identity");
2053 if (unlikely(ke
->ext
[1] > (UINT_MAX
- DISPATCH_MACH_TRAILER_SIZE
))) {
2054 DISPATCH_INTERNAL_CRASH(ke
->ext
[1],
2055 "EVFILT_MACHPORT with overlarge message");
2057 siz
= _dispatch_kevent_mach_msg_size(ke
) + DISPATCH_MACH_TRAILER_SIZE
;
2059 if (dispatch_assume(hdr
)) {
2060 flags
|= DISPATCH_EV_MSG_NEEDS_FREE
;
2062 // Kernel will discard message too large to fit
2066 mach_port_t name
= (mach_port_name_t
)ke
->data
;
2067 const mach_msg_option_t options
= ((DISPATCH_MACH_RCV_OPTIONS
|
2068 MACH_RCV_TIMEOUT
) & ~MACH_RCV_LARGE
);
2069 kr
= mach_msg(hdr
, options
, 0, siz
, name
, MACH_MSG_TIMEOUT_NONE
,
2072 _dispatch_kevent_mach_msg_recv(du
, flags
, hdr
);
2074 } else if (kr
== MACH_RCV_TOO_LARGE
) {
2075 _dispatch_log("BUG in libdispatch client: "
2076 "_dispatch_kevent_mach_msg_drain: dropped message too "
2077 "large to fit in memory: id = 0x%x, size = %u",
2078 hdr
->msgh_id
, _dispatch_kevent_mach_msg_size(ke
));
2079 kr
= MACH_MSG_SUCCESS
;
2081 if (flags
& DISPATCH_EV_MSG_NEEDS_FREE
) {
2086 _dispatch_bug_mach_client("_dispatch_kevent_mach_msg_drain: "
2087 "message reception failed", kr
);
2091 const dispatch_source_type_s _dispatch_source_type_mach_recv
= {
2092 .dst_kind
= "mach_recv",
2093 .dst_filter
= EVFILT_MACHPORT
,
2094 .dst_flags
= EV_UDATA_SPECIFIC
|EV_DISPATCH
|EV_VANISHED
,
2096 .dst_size
= sizeof(struct dispatch_source_refs_s
),
2098 .dst_create
= _dispatch_unote_create_with_handle
,
2099 .dst_merge_evt
= _dispatch_source_merge_evt
,
2100 .dst_merge_msg
= NULL
, // never receives messages directly
2102 .dst_per_trigger_qos
= true,
2106 _dispatch_source_mach_recv_direct_merge_msg(dispatch_unote_t du
, uint32_t flags
,
2107 mach_msg_header_t
*msg
, mach_msg_size_t msgsz DISPATCH_UNUSED
)
2109 dispatch_continuation_t dc
= du
._dr
->ds_handler
[DS_EVENT_HANDLER
];
2110 dispatch_source_t ds
= _dispatch_source_from_refs(du
._dr
);
2111 dispatch_queue_t cq
= _dispatch_queue_get_current();
2113 // see firehose_client_push_notify_async
2114 _dispatch_queue_set_current(ds
->_as_dq
);
2116 _dispatch_queue_set_current(cq
);
2117 if (flags
& DISPATCH_EV_MSG_NEEDS_FREE
) {
2120 if ((ds
->dq_atomic_flags
& DSF_CANCELED
) ||
2121 (flags
& (EV_ONESHOT
| EV_DELETE
))) {
2122 return _dispatch_source_merge_evt(du
, flags
, 0, 0, 0);
2124 if (_dispatch_unote_needs_rearm(du
)) {
2125 return _dispatch_unote_resume(du
);
2130 _dispatch_mach_recv_direct_merge(dispatch_unote_t du
,
2131 uint32_t flags
, uintptr_t data
,
2132 uintptr_t status DISPATCH_UNUSED
,
2133 pthread_priority_t pp
)
2135 if (flags
& EV_VANISHED
) {
2136 DISPATCH_CLIENT_CRASH(du
._du
->du_ident
,
2137 "Unexpected EV_VANISHED (do not destroy random mach ports)");
2139 return _dispatch_source_merge_evt(du
, flags
, data
, 0, pp
);
2142 const dispatch_source_type_s _dispatch_source_type_mach_recv_direct
= {
2143 .dst_kind
= "direct mach_recv",
2144 .dst_filter
= EVFILT_MACHPORT
,
2145 .dst_flags
= EV_UDATA_SPECIFIC
|EV_DISPATCH
|EV_VANISHED
,
2146 .dst_fflags
= DISPATCH_MACH_RCV_OPTIONS
,
2147 .dst_size
= sizeof(struct dispatch_source_refs_s
),
2149 .dst_create
= _dispatch_unote_create_with_handle
,
2150 .dst_merge_evt
= _dispatch_mach_recv_direct_merge
,
2151 .dst_merge_msg
= _dispatch_source_mach_recv_direct_merge_msg
,
2153 .dst_per_trigger_qos
= true,
2156 const dispatch_source_type_s _dispatch_mach_type_recv
= {
2157 .dst_kind
= "mach_recv (channel)",
2158 .dst_filter
= EVFILT_MACHPORT
,
2159 .dst_flags
= EV_UDATA_SPECIFIC
|EV_DISPATCH
|EV_VANISHED
,
2160 .dst_fflags
= DISPATCH_MACH_RCV_OPTIONS
,
2161 .dst_size
= sizeof(struct dispatch_mach_recv_refs_s
),
2163 // without handle because the mach code will set the ident after connect
2164 .dst_create
= _dispatch_unote_create_without_handle
,
2165 .dst_merge_evt
= _dispatch_mach_recv_direct_merge
,
2166 .dst_merge_msg
= _dispatch_mach_merge_msg
,
2168 .dst_per_trigger_qos
= true,
2173 _dispatch_mach_reply_merge_evt(dispatch_unote_t du
,
2174 uint32_t flags DISPATCH_UNUSED
, uintptr_t data DISPATCH_UNUSED
,
2175 uintptr_t status DISPATCH_UNUSED
,
2176 pthread_priority_t pp DISPATCH_UNUSED
)
2178 DISPATCH_INTERNAL_CRASH(du
._du
->du_ident
, "Unexpected event");
2181 const dispatch_source_type_s _dispatch_mach_type_reply
= {
2182 .dst_kind
= "mach reply",
2183 .dst_filter
= EVFILT_MACHPORT
,
2184 .dst_flags
= EV_UDATA_SPECIFIC
|EV_DISPATCH
|EV_ONESHOT
|EV_VANISHED
,
2185 .dst_fflags
= DISPATCH_MACH_RCV_OPTIONS
,
2186 .dst_size
= sizeof(struct dispatch_mach_reply_refs_s
),
2188 .dst_create
= _dispatch_unote_create_with_handle
,
2189 .dst_merge_evt
= _dispatch_mach_reply_merge_evt
,
2190 .dst_merge_msg
= _dispatch_mach_reply_merge_msg
,
2193 #pragma mark Mach channel SIGTERM notification (for XPC channels only)
2195 const dispatch_source_type_s _dispatch_xpc_type_sigterm
= {
2196 .dst_kind
= "sigterm (xpc)",
2197 .dst_filter
= EVFILT_SIGNAL
,
2198 .dst_flags
= DISPATCH_EV_DIRECT
|EV_CLEAR
|EV_ONESHOT
,
2200 .dst_size
= sizeof(struct dispatch_xpc_term_refs_s
),
2202 .dst_create
= _dispatch_unote_create_with_handle
,
2203 .dst_merge_evt
= _dispatch_xpc_sigterm_merge
,
2208 #endif // DISPATCH_EVENT_BACKEND_KEVENT