]> git.saurik.com Git - apple/libdispatch.git/blob - src/event/event_kevent.c
libdispatch-913.20.5.tar.gz
[apple/libdispatch.git] / src / event / event_kevent.c
1 /*
2 * Copyright (c) 2008-2016 Apple Inc. All rights reserved.
3 *
4 * @APPLE_APACHE_LICENSE_HEADER_START@
5 *
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
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
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.
17 *
18 * @APPLE_APACHE_LICENSE_HEADER_END@
19 */
20
21 #include "internal.h"
22 #if DISPATCH_EVENT_BACKEND_KEVENT
23 #if HAVE_MACH
24 #include "protocol.h"
25 #include "protocolServer.h"
26 #endif
27
28 #if DISPATCH_USE_KEVENT_WORKQUEUE && !DISPATCH_USE_KEVENT_QOS
29 #error unsupported configuration
30 #endif
31
32 #define DISPATCH_KEVENT_MUXED_MARKER 1ul
33 #define DISPATCH_MACH_AUDIT_TOKEN_PID (5)
34
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;
41
42 static bool _dispatch_timers_force_max_leeway;
43 static int _dispatch_kq = -1;
44 static struct {
45 dispatch_once_t pred;
46 dispatch_unfair_lock_s lock;
47 } _dispatch_muxnotes;
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)
53 #else
54 #define _dispatch_muxnotes_lock()
55 #define _dispatch_muxnotes_unlock()
56 #endif // !DISPATCH_USE_KEVENT_WORKQUEUE
57
58 DISPATCH_CACHELINE_ALIGN
59 static TAILQ_HEAD(dispatch_muxnote_bucket_s, dispatch_muxnote_s)
60 _dispatch_sources[DSL_HASH_SIZE];
61
62 #define DISPATCH_NOTE_CLOCK_WALL NOTE_MACH_CONTINUOUS_TIME
63 #define DISPATCH_NOTE_CLOCK_MACH 0
64
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),
77 #endif
78 #undef DISPATCH_TIMER_FFLAGS_INIT
79 };
80
81 static void _dispatch_kevent_timer_drain(dispatch_kevent_t ke);
82
83 #pragma mark -
84 #pragma mark kevent debug
85
86 DISPATCH_NOINLINE
87 static const char *
88 _evfiltstr(short filt)
89 {
90 switch (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);
96
97 #ifdef DISPATCH_EVENT_BACKEND_KEVENT
98 _evfilt2(EVFILT_AIO);
99 _evfilt2(EVFILT_VNODE);
100 _evfilt2(EVFILT_PROC);
101 #if HAVE_MACH
102 _evfilt2(EVFILT_MACHPORT);
103 _evfilt2(DISPATCH_EVFILT_MACH_NOTIFICATION);
104 #endif
105 _evfilt2(EVFILT_FS);
106 _evfilt2(EVFILT_USER);
107 #ifdef EVFILT_SOCK
108 _evfilt2(EVFILT_SOCK);
109 #endif
110 #ifdef EVFILT_MEMORYSTATUS
111 _evfilt2(EVFILT_MEMORYSTATUS);
112 #endif
113 #endif // DISPATCH_EVENT_BACKEND_KEVENT
114
115 _evfilt2(DISPATCH_EVFILT_TIMER);
116 _evfilt2(DISPATCH_EVFILT_CUSTOM_ADD);
117 _evfilt2(DISPATCH_EVFILT_CUSTOM_OR);
118 _evfilt2(DISPATCH_EVFILT_CUSTOM_REPLACE);
119 default:
120 return "EVFILT_missing";
121 }
122 }
123
124 #if DISPATCH_DEBUG
125 static const char *
126 _evflagstr2(uint16_t *flagsp)
127 {
128 #define _evflag2(f) \
129 if ((*flagsp & (f)) == (f) && (f)) { \
130 *flagsp &= ~(f); \
131 return #f "|"; \
132 }
133 _evflag2(EV_ADD);
134 _evflag2(EV_DELETE);
135 _evflag2(EV_ENABLE);
136 _evflag2(EV_DISABLE);
137 _evflag2(EV_ONESHOT);
138 _evflag2(EV_CLEAR);
139 _evflag2(EV_RECEIPT);
140 _evflag2(EV_DISPATCH);
141 _evflag2(EV_UDATA_SPECIFIC);
142 #ifdef EV_POLL
143 _evflag2(EV_POLL);
144 #endif
145 #ifdef EV_OOBAND
146 _evflag2(EV_OOBAND);
147 #endif
148 _evflag2(EV_ERROR);
149 _evflag2(EV_EOF);
150 _evflag2(EV_VANISHED);
151 *flagsp = 0;
152 return "EV_UNKNOWN ";
153 }
154
155 DISPATCH_NOINLINE
156 static const char *
157 _evflagstr(uint16_t flags, char *str, size_t strsize)
158 {
159 str[0] = 0;
160 while (flags) {
161 strlcat(str, _evflagstr2(&flags), strsize);
162 }
163 size_t sz = strlen(str);
164 if (sz) str[sz-1] = 0;
165 return str;
166 }
167
168 DISPATCH_NOINLINE
169 static void
170 dispatch_kevent_debug(const char *verb, const dispatch_kevent_s *kev,
171 int i, int n, const char *function, unsigned int line)
172 {
173 char flagstr[256];
174 char i_n[31];
175
176 if (n > 1) {
177 snprintf(i_n, sizeof(i_n), "%d/%d ", i + 1, n);
178 } else {
179 i_n[0] = '\0';
180 }
181 if (verb == NULL) {
182 if (kev->flags & EV_DELETE) {
183 verb = "deleting";
184 } else if (kev->flags & EV_ADD) {
185 verb = "adding";
186 } else {
187 verb = "updating";
188 }
189 }
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],
198 function, line);
199 #else
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,
205 function, line);
206 #endif
207 }
208 #else
209 static inline void
210 dispatch_kevent_debug(const char *verb, const dispatch_kevent_s *kev,
211 int i, int n, const char *function, unsigned int line)
212 {
213 (void)verb; (void)kev; (void)i; (void)n; (void)function; (void)line;
214 }
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)
222 #else
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)
227 #else
228 #define _dispatch_kevent_wlh_debug(verb, kev) ((void)verb, (void)kev)
229 #endif // DISPATCH_WLH_DEBUG
230
231 #if DISPATCH_MACHPORT_DEBUG
232 #ifndef MACH_PORT_TYPE_SPREQUEST
233 #define MACH_PORT_TYPE_SPREQUEST 0x40000000
234 #endif
235
236 DISPATCH_NOINLINE
237 void
238 dispatch_debug_machport(mach_port_t name, const char* str)
239 {
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);
244 if (kr) {
245 _dispatch_log("machport[0x%08x] = { error(0x%x) \"%s\" }: %s", name,
246 kr, mach_error_string(kr), str);
247 return;
248 }
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));
252 }
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));
256 }
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));
260 }
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);
264 }
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);
286 } else {
287 _dispatch_log("machport[0x%08x] = { type(0x%08x) }: %s", name, type,
288 str);
289 }
290 }
291 #endif
292
293 #pragma mark dispatch_kevent_t
294
295 #if HAVE_MACH
296
297 static dispatch_once_t _dispatch_mach_host_port_pred;
298 static mach_port_t _dispatch_mach_host_port;
299
300 static inline void*
301 _dispatch_kevent_mach_msg_buf(dispatch_kevent_t ke)
302 {
303 return (void*)ke->ext[0];
304 }
305
306 static inline mach_msg_size_t
307 _dispatch_kevent_mach_msg_size(dispatch_kevent_t ke)
308 {
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];
312 }
313
314 static void _dispatch_kevent_mach_msg_drain(dispatch_kevent_t ke);
315 static inline void _dispatch_mach_host_calendar_change_register(void);
316
317 // DISPATCH_MACH_NOTIFICATION_ARMED are muxnotes that aren't registered with
318 // kevent for real, but with mach_port_request_notification()
319 //
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])
326 #endif
327
328 DISPATCH_ALWAYS_INLINE
329 static dispatch_muxnote_t
330 _dispatch_kevent_get_muxnote(dispatch_kevent_t ke)
331 {
332 uintptr_t dmn_addr = (uintptr_t)ke->udata & ~DISPATCH_KEVENT_MUXED_MARKER;
333 return (dispatch_muxnote_t)dmn_addr;
334 }
335
336 DISPATCH_ALWAYS_INLINE
337 static dispatch_unote_t
338 _dispatch_kevent_get_unote(dispatch_kevent_t ke)
339 {
340 dispatch_assert((ke->udata & DISPATCH_KEVENT_MUXED_MARKER) == 0);
341 return (dispatch_unote_t){ ._du = (dispatch_unote_class_t)ke->udata };
342 }
343
344 DISPATCH_NOINLINE
345 static void
346 _dispatch_kevent_print_error(dispatch_kevent_t ke)
347 {
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
354 return;
355 }
356 }
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))) {
363 ke->flags |= EV_ADD;
364 }
365 }
366
367 #if HAVE_MACH
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");
372 }
373 #endif
374
375 if (ke->data) {
376 // log the unexpected error
377 _dispatch_bug_kevent_client("kevent", _evfiltstr(ke->filter),
378 !ke->udata ? NULL :
379 ke->flags & EV_DELETE ? "delete" :
380 ke->flags & EV_ADD ? "add" :
381 ke->flags & EV_ENABLE ? "enable" : "monitor",
382 (int)ke->data);
383 }
384 }
385
386 DISPATCH_NOINLINE
387 static void
388 _dispatch_kevent_merge(dispatch_unote_t du, dispatch_kevent_t ke)
389 {
390 uintptr_t data;
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;
395 #endif
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;
402 #if HAVE_MACH
403 } else if (du._du->du_filter == EVFILT_MACHPORT) {
404 data = DISPATCH_MACH_RECV_MESSAGE;
405 #endif
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;
413 } else {
414 DISPATCH_INTERNAL_CRASH(action, "Corrupt unote action");
415 }
416 return dux_merge_evt(du._du, ke->flags, data, status, pp);
417 }
418
419 DISPATCH_NOINLINE
420 static void
421 _dispatch_kevent_merge_muxed(dispatch_kevent_t ke)
422 {
423 dispatch_muxnote_t dmn = _dispatch_kevent_get_muxnote(ke);
424 dispatch_unote_linkage_t dul, dul_next;
425
426 TAILQ_FOREACH_SAFE(dul, &dmn->dmn_unotes_head, du_link, dul_next) {
427 _dispatch_kevent_merge(_dispatch_unote_linkage_get_unote(dul), ke);
428 }
429 }
430
431 DISPATCH_NOINLINE
432 static void
433 _dispatch_kevent_drain(dispatch_kevent_t ke)
434 {
435 if (ke->filter == EVFILT_USER) {
436 _dispatch_kevent_mgr_debug("received", ke);
437 return;
438 }
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;
448 ke->data = 0;
449 _dispatch_kevent_debug("synthetic NOTE_EXIT", ke);
450 } else {
451 return _dispatch_kevent_print_error(ke);
452 }
453 }
454 if (ke->filter == EVFILT_TIMER) {
455 return _dispatch_kevent_timer_drain(ke);
456 }
457
458 #if HAVE_MACH
459 if (ke->filter == EVFILT_MACHPORT) {
460 if (_dispatch_kevent_mach_msg_size(ke)) {
461 return _dispatch_kevent_mach_msg_drain(ke);
462 }
463 }
464 #endif
465
466 if (ke->udata & DISPATCH_KEVENT_MUXED_MARKER) {
467 return _dispatch_kevent_merge_muxed(ke);
468 }
469 return _dispatch_kevent_merge(_dispatch_kevent_get_unote(ke), ke);
470 }
471
472 #pragma mark dispatch_kq
473
474 #if DISPATCH_USE_MGR_THREAD
475 DISPATCH_NOINLINE
476 static int
477 _dispatch_kq_create(const void *guard_ptr)
478 {
479 static const dispatch_kevent_s kev = {
480 .ident = 1,
481 .filter = EVFILT_USER,
482 .flags = EV_ADD|EV_CLEAR,
483 .udata = (uintptr_t)DISPATCH_WLH_MANAGER,
484 };
485 int kqfd;
486
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);
491 #else
492 (void)guard_ptr;
493 kqfd = kqueue();
494 #endif
495 if (kqfd == -1) {
496 int err = errno;
497 switch (err) {
498 case EMFILE:
499 DISPATCH_CLIENT_CRASH(err, "kqueue() failure: "
500 "process is out of file descriptors");
501 break;
502 case ENFILE:
503 DISPATCH_CLIENT_CRASH(err, "kqueue() failure: "
504 "system is out of file descriptors");
505 break;
506 case ENOMEM:
507 DISPATCH_CLIENT_CRASH(err, "kqueue() failure: "
508 "kernel is out of memory");
509 break;
510 default:
511 DISPATCH_INTERNAL_CRASH(err, "kqueue() failure");
512 break;
513 }
514 }
515 #if DISPATCH_USE_KEVENT_QOS
516 dispatch_assume_zero(kevent_qos(kqfd, &kev, 1, NULL, 0, NULL, NULL, 0));
517 #else
518 dispatch_assume_zero(kevent(kqfd, &kev, 1, NULL, 0, NULL));
519 #endif
520 return kqfd;
521 }
522 #endif
523
524 static void
525 _dispatch_kq_init(void *context)
526 {
527 bool *kq_initialized = context;
528
529 _dispatch_fork_becomes_unsafe();
530 if (unlikely(getenv("LIBDISPATCH_TIMERS_FORCE_MAX_LEEWAY"))) {
531 _dispatch_timers_force_max_leeway = true;
532 }
533 *kq_initialized = true;
534
535 #if DISPATCH_USE_KEVENT_WORKQUEUE
536 _dispatch_kevent_workqueue_init();
537 if (_dispatch_kevent_workqueue_enabled) {
538 int r;
539 int kqfd = _dispatch_kq;
540 const dispatch_kevent_s ke = {
541 .ident = 1,
542 .filter = EVFILT_USER,
543 .flags = EV_ADD|EV_CLEAR,
544 .qos = _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG,
545 .udata = (uintptr_t)DISPATCH_WLH_MANAGER,
546 };
547 retry:
548 r = kevent_qos(kqfd, &ke, 1, NULL, 0, NULL, NULL,
549 KEVENT_FLAG_WORKQ|KEVENT_FLAG_IMMEDIATE);
550 if (unlikely(r == -1)) {
551 int err = errno;
552 switch (err) {
553 case EINTR:
554 goto retry;
555 default:
556 DISPATCH_CLIENT_CRASH(err,
557 "Failed to initalize workqueue kevent");
558 break;
559 }
560 }
561 return;
562 }
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
568 }
569
570 #if DISPATCH_USE_MEMORYPRESSURE_SOURCE
571 static void _dispatch_memorypressure_init(void);
572 #else
573 #define _dispatch_memorypressure_init() ((void)0)
574 #endif
575
576 DISPATCH_NOINLINE
577 static int
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,
580 uint32_t flags)
581 {
582 static dispatch_once_t pred;
583 bool kq_initialized = false;
584 int r = 0;
585
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
589 //
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();
595 }
596
597
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;
603 }
604 out_n = n;
605 }
606 #endif
607
608 retry:
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;
614 }
615 r = kevent_qos(kqfd, ke, n, ke_out, n_out, buf, avail, flags);
616 #else
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);
620 #endif
621 }
622 if (unlikely(r == -1)) {
623 int err = errno;
624 switch (err) {
625 case ENOMEM:
626 _dispatch_temporary_resource_shortage();
627 /* FALLTHROUGH */
628 case EINTR:
629 goto retry;
630 case EBADF:
631 DISPATCH_CLIENT_CRASH(err, "Do not close random Unix descriptors");
632 default:
633 DISPATCH_CLIENT_CRASH(err, "Unexpected error from kevent");
634 }
635 }
636 return r;
637 }
638
639 DISPATCH_NOINLINE
640 static int
641 _dispatch_kq_drain(dispatch_wlh_t wlh, dispatch_kevent_t ke, int n,
642 uint32_t flags)
643 {
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;
648 void *buf = NULL;
649
650 #if DISPATCH_USE_KEVENT_QOS
651 size_t size;
652 if (poll_for_events) {
653 size = DISPATCH_MACH_RECEIVE_MAX_INLINE_MESSAGE_SIZE +
654 DISPATCH_MACH_TRAILER_SIZE;
655 buf = alloca(size);
656 avail = &size;
657 }
658 #endif
659
660 #if DISPATCH_DEBUG
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);
664 }
665 }
666 #endif
667
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);
670 if (n == 0) {
671 r = 0;
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;
677 }
678 }
679 } else {
680 for (i = 0, r = 0; i < n; i++) {
681 _dispatch_kevent_drain(&ke_out[i]);
682 }
683 }
684 return r;
685 }
686
687 DISPATCH_ALWAYS_INLINE
688 static inline int
689 _dispatch_kq_update_one(dispatch_wlh_t wlh, dispatch_kevent_t ke)
690 {
691 return _dispatch_kq_drain(wlh, ke, 1,
692 KEVENT_FLAG_IMMEDIATE | KEVENT_FLAG_ERROR_EVENTS);
693 }
694
695 DISPATCH_ALWAYS_INLINE
696 static inline void
697 _dispatch_kq_update_all(dispatch_wlh_t wlh, dispatch_kevent_t ke, int n)
698 {
699 (void)_dispatch_kq_drain(wlh, ke, n,
700 KEVENT_FLAG_IMMEDIATE | KEVENT_FLAG_ERROR_EVENTS);
701 }
702
703 DISPATCH_ALWAYS_INLINE
704 static inline void
705 _dispatch_kq_unote_set_kevent(dispatch_unote_t _du, dispatch_kevent_t dk,
706 uint16_t action)
707 {
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;
711
712 if ((flags & EV_VANISHED) && !(flags & EV_ADD)) {
713 flags &= ~EV_VANISHED;
714 }
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,
719 .flags = flags,
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,
725 #endif
726 };
727 }
728
729 DISPATCH_ALWAYS_INLINE
730 static inline int
731 _dispatch_kq_deferred_find_slot(dispatch_deferred_items_t ddi,
732 int16_t filter, uint64_t ident, uint64_t udata)
733 {
734 dispatch_kevent_t events = ddi->ddi_eventlist;
735 int i;
736
737 for (i = 0; i < ddi->ddi_nevents; i++) {
738 if (events[i].filter == filter && events[i].ident == ident &&
739 events[i].udata == udata) {
740 break;
741 }
742 }
743 return i;
744 }
745
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)
750 {
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);
757 slot = 0;
758 } else if (slot == ddi->ddi_nevents) {
759 ddi->ddi_nevents++;
760 }
761 return ddi->ddi_eventlist + slot;
762 }
763
764 DISPATCH_ALWAYS_INLINE
765 static inline void
766 _dispatch_kq_deferred_discard_slot(dispatch_deferred_items_t ddi, int slot)
767 {
768 if (slot < ddi->ddi_nevents) {
769 int last = --ddi->ddi_nevents;
770 if (slot != last) {
771 ddi->ddi_eventlist[slot] = ddi->ddi_eventlist[last];
772 }
773 }
774 }
775
776 DISPATCH_NOINLINE
777 static void
778 _dispatch_kq_deferred_update(dispatch_wlh_t wlh, dispatch_kevent_t ke)
779 {
780 dispatch_deferred_items_t ddi = _dispatch_deferred_items_get();
781
782 if (ddi && ddi->ddi_maxevents && wlh == _dispatch_get_wlh()) {
783 int slot = _dispatch_kq_deferred_find_slot(ddi, ke->filter, ke->ident,
784 ke->udata);
785 dispatch_kevent_t dk = _dispatch_kq_deferred_reuse_slot(wlh, ddi, slot);
786 *dk = *ke;
787 if (ke->filter != EVFILT_USER) {
788 _dispatch_kevent_mgr_debug("deferred", ke);
789 }
790 } else {
791 _dispatch_kq_update_one(wlh, ke);
792 }
793 }
794
795 DISPATCH_NOINLINE
796 static int
797 _dispatch_kq_immediate_update(dispatch_wlh_t wlh, dispatch_kevent_t ke)
798 {
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,
802 ke->udata);
803 _dispatch_kq_deferred_discard_slot(ddi, slot);
804 }
805 return _dispatch_kq_update_one(wlh, ke);
806 }
807
808 DISPATCH_NOINLINE
809 static bool
810 _dispatch_kq_unote_update(dispatch_wlh_t wlh, dispatch_unote_t _du,
811 uint16_t action_flags)
812 {
813 dispatch_deferred_items_t ddi = _dispatch_deferred_items_get();
814 dispatch_unote_class_t du = _du._du;
815 dispatch_kevent_t ke;
816 int r = 0;
817
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);
823 du->du_wlh = wlh;
824 }
825
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);
833 }
834
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);
840 goto done;
841 }
842
843 // get rid of the deferred item if any, we can't wait
844 _dispatch_kq_deferred_discard_slot(ddi, slot);
845 }
846
847 if (action_flags) {
848 dispatch_kevent_s dk;
849 _dispatch_kq_unote_set_kevent(du, &dk, action_flags);
850 r = _dispatch_kq_update_one(wlh, &dk);
851 }
852
853 done:
854 if (action_flags & EV_ADD) {
855 if (unlikely(r)) {
856 _dispatch_wlh_release(du->du_wlh);
857 du->du_wlh = NULL;
858 }
859 return r == 0;
860 }
861
862 if (action_flags & EV_DELETE) {
863 if (r == EINPROGRESS) {
864 return false;
865 }
866 _dispatch_wlh_release(du->du_wlh);
867 du->du_wlh = NULL;
868 }
869
870 dispatch_assume_zero(r);
871 return true;
872 }
873
874 #pragma mark dispatch_muxnote_t
875
876 static void
877 _dispatch_muxnotes_init(void *ctxt DISPATCH_UNUSED)
878 {
879 uint32_t i;
880 for (i = 0; i < DSL_HASH_SIZE; i++) {
881 TAILQ_INIT(&_dispatch_sources[i]);
882 }
883 }
884
885 DISPATCH_ALWAYS_INLINE
886 static inline struct dispatch_muxnote_bucket_s *
887 _dispatch_muxnote_bucket(uint64_t ident, int16_t filter)
888 {
889 switch (filter) {
890 #if HAVE_MACH
891 case EVFILT_MACHPORT:
892 case DISPATCH_EVFILT_MACH_NOTIFICATION:
893 ident = MACH_PORT_INDEX(ident);
894 break;
895 #endif
896 case EVFILT_SIGNAL: // signo
897 case EVFILT_PROC: // pid_t
898 default: // fd
899 break;
900 }
901
902 dispatch_once_f(&_dispatch_muxnotes.pred, NULL, _dispatch_muxnotes_init);
903 return &_dispatch_sources[DSL_HASH((uintptr_t)ident)];
904 }
905 #define _dispatch_unote_muxnote_bucket(du) \
906 _dispatch_muxnote_bucket(du._du->du_ident, du._du->du_filter)
907
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)
912 {
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) {
918 break;
919 }
920 }
921 _dispatch_muxnotes_unlock();
922 return dmn;
923 }
924 #define _dispatch_unote_muxnote_find(dmb, du, wlh) \
925 _dispatch_muxnote_find(dmb, wlh, du._du->du_ident, du._du->du_filter)
926
927 DISPATCH_ALWAYS_INLINE
928 static inline dispatch_muxnote_t
929 _dispatch_mach_muxnote_find(mach_port_t name, int16_t filter)
930 {
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);
934 }
935
936 DISPATCH_NOINLINE
937 static bool
938 _dispatch_unote_register_muxed(dispatch_unote_t du, dispatch_wlh_t wlh)
939 {
940 struct dispatch_muxnote_bucket_s *dmb = _dispatch_unote_muxnote_bucket(du);
941 dispatch_muxnote_t dmn;
942 bool installed = true;
943
944 dmn = _dispatch_unote_muxnote_find(dmb, du, wlh);
945 if (dmn) {
946 uint32_t flags = du._du->du_fflags & ~dmn->dmn_kev.fflags;
947 if (flags) {
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);
951 } else {
952 installed = !_dispatch_kq_immediate_update(dmn->dmn_wlh,
953 &dmn->dmn_kev);
954 }
955 if (!installed) dmn->dmn_kev.fflags &= ~flags;
956 }
957 } else {
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;
963 #endif
964 dmn->dmn_kev.udata = (uintptr_t)dmn | DISPATCH_KEVENT_MUXED_MARKER;
965 dmn->dmn_wlh = wlh;
966 if (unlikely(du._du->du_type->dst_update_mux)) {
967 installed = du._du->du_type->dst_update_mux(dmn);
968 } else {
969 installed = !_dispatch_kq_immediate_update(dmn->dmn_wlh,
970 &dmn->dmn_kev);
971 }
972 if (installed) {
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();
977 } else {
978 free(dmn);
979 }
980 }
981
982 if (installed) {
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;
986
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);
990 }
991 du._du->du_wlh = DISPATCH_WLH_ANON;
992 }
993 return installed;
994 }
995
996 bool
997 _dispatch_unote_register(dispatch_unote_t du, dispatch_wlh_t wlh,
998 dispatch_priority_t pri)
999 {
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;
1007 return true;
1008 }
1009 if (!du._du->du_is_direct) {
1010 return _dispatch_unote_register_muxed(du, DISPATCH_WLH_ANON);
1011 }
1012 return _dispatch_kq_unote_update(wlh, du, EV_ADD | EV_ENABLE);
1013 }
1014
1015 void
1016 _dispatch_unote_resume(dispatch_unote_t du)
1017 {
1018 dispatch_assert(_dispatch_unote_registered(du));
1019
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);
1026 } else {
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);
1030 }
1031 }
1032
1033 DISPATCH_NOINLINE
1034 static bool
1035 _dispatch_unote_unregister_muxed(dispatch_unote_t du, uint32_t flags)
1036 {
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;
1040
1041 if (dmn->dmn_kev.filter == DISPATCH_EVFILT_MACH_NOTIFICATION) {
1042 os_atomic_store2o(du._dmsr, dmsr_notification_armed, false, relaxed);
1043 }
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;
1049
1050 if (TAILQ_EMPTY(&dmn->dmn_unotes_head)) {
1051 dmn->dmn_kev.flags |= EV_DELETE;
1052 update = dispose = true;
1053 } else {
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;
1058 }
1059 if (dmn->dmn_kev.fflags & ~fflags) {
1060 dmn->dmn_kev.fflags &= fflags;
1061 update = true;
1062 }
1063 }
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));
1067 } else {
1068 _dispatch_kq_deferred_update(dmn->dmn_wlh, &dmn->dmn_kev);
1069 }
1070 }
1071 if (dispose) {
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();
1077 free(dmn);
1078 }
1079 return true;
1080 }
1081
1082 bool
1083 _dispatch_unote_unregister(dispatch_unote_t du, uint32_t flags)
1084 {
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;
1090 return true;
1091 }
1092 dispatch_wlh_t wlh = du._du->du_wlh;
1093 if (wlh) {
1094 if (!du._du->du_is_direct) {
1095 return _dispatch_unote_unregister_muxed(du, flags);
1096 }
1097 uint16_t action_flags;
1098 if (flags & DU_UNREGISTER_ALREADY_DELETED) {
1099 action_flags = 0;
1100 } else if (flags & DU_UNREGISTER_IMMEDIATE_DELETE) {
1101 action_flags = EV_DELETE | EV_ENABLE;
1102 } else {
1103 action_flags = EV_DELETE;
1104 }
1105 return _dispatch_kq_unote_update(wlh, du, action_flags);
1106 }
1107 return true;
1108 }
1109
1110 #pragma mark -
1111 #pragma mark dispatch_event_loop
1112
1113 void
1114 _dispatch_event_loop_atfork_child(void)
1115 {
1116 #if HAVE_MACH
1117 _dispatch_mach_host_port_pred = 0;
1118 _dispatch_mach_host_port = MACH_PORT_NULL;
1119 #endif
1120 }
1121
1122
1123 DISPATCH_NOINLINE
1124 void
1125 _dispatch_event_loop_poke(dispatch_wlh_t wlh, uint64_t dq_state, uint32_t flags)
1126 {
1127 if (wlh == DISPATCH_WLH_MANAGER) {
1128 dispatch_kevent_s ke = (dispatch_kevent_s){
1129 .ident = 1,
1130 .filter = EVFILT_USER,
1131 .fflags = NOTE_TRIGGER,
1132 .udata = (uintptr_t)DISPATCH_WLH_MANAGER,
1133 };
1134 return _dispatch_kq_deferred_update(DISPATCH_WLH_ANON, &ke);
1135 } else if (wlh && wlh != DISPATCH_WLH_ANON) {
1136 (void)dq_state; (void)flags;
1137 }
1138 DISPATCH_INTERNAL_CRASH(wlh, "Unsupported wlh configuration");
1139 }
1140
1141 DISPATCH_NOINLINE
1142 void
1143 _dispatch_event_loop_drain(uint32_t flags)
1144 {
1145 dispatch_wlh_t wlh = _dispatch_get_wlh();
1146 dispatch_deferred_items_t ddi = _dispatch_deferred_items_get();
1147 int n;
1148
1149 again:
1150 n = ddi->ddi_nevents;
1151 ddi->ddi_nevents = 0;
1152 _dispatch_kq_drain(wlh, ddi->ddi_eventlist, n, flags);
1153
1154 if ((flags & KEVENT_FLAG_IMMEDIATE) &&
1155 !(flags & KEVENT_FLAG_ERROR_EVENTS) &&
1156 _dispatch_needs_to_return_to_kernel()) {
1157 goto again;
1158 }
1159 }
1160
1161 void
1162 _dispatch_event_loop_merge(dispatch_kevent_t events, int nevents)
1163 {
1164 dispatch_deferred_items_t ddi = _dispatch_deferred_items_get();
1165 dispatch_kevent_s kev[nevents];
1166
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 - 2;
1171
1172 for (int i = 0; i < nevents; i++) {
1173 _dispatch_kevent_drain(&kev[i]);
1174 }
1175
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);
1183 }
1184 _dispatch_trace_continuation_push(ddi->ddi_stashed_rq,
1185 ddi->ddi_stashed_dou);
1186 }
1187 }
1188
1189 void
1190 _dispatch_event_loop_leave_immediate(dispatch_wlh_t wlh, uint64_t dq_state)
1191 {
1192 (void)wlh; (void)dq_state;
1193 }
1194
1195 void
1196 _dispatch_event_loop_leave_deferred(dispatch_wlh_t wlh, uint64_t dq_state)
1197 {
1198 (void)wlh; (void)dq_state;
1199 }
1200
1201 void
1202 _dispatch_event_loop_wake_owner(dispatch_sync_context_t dsc,
1203 dispatch_wlh_t wlh, uint64_t old_state, uint64_t new_state)
1204 {
1205 (void)dsc; (void)wlh; (void)old_state; (void)new_state;
1206 }
1207
1208 void
1209 _dispatch_event_loop_wait_for_ownership(dispatch_sync_context_t dsc)
1210 {
1211 if (dsc->dsc_release_storage) {
1212 _dispatch_queue_release_storage(dsc->dc_data);
1213 }
1214 }
1215
1216 void
1217 _dispatch_event_loop_end_ownership(dispatch_wlh_t wlh, uint64_t old_state,
1218 uint64_t new_state, uint32_t flags)
1219 {
1220 (void)wlh; (void)old_state; (void)new_state; (void)flags;
1221 }
1222
1223 #if DISPATCH_WLH_DEBUG
1224 void
1225 _dispatch_event_loop_assert_not_owned(dispatch_wlh_t wlh)
1226 {
1227 (void)wlh;
1228 }
1229 #endif // DISPATCH_WLH_DEBUG
1230
1231 #pragma mark -
1232 #pragma mark dispatch_event_loop timers
1233
1234 #define DISPATCH_KEVENT_TIMEOUT_IDENT_MASK (~0ull << 8)
1235
1236 DISPATCH_NOINLINE
1237 static void
1238 _dispatch_kevent_timer_drain(dispatch_kevent_t ke)
1239 {
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;
1244
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);
1251 #endif
1252 }
1253
1254 DISPATCH_NOINLINE
1255 static void
1256 _dispatch_event_loop_timer_program(uint32_t tidx,
1257 uint64_t target, uint64_t leeway, uint16_t action)
1258 {
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
1267 .ext[1] = leeway,
1268 #endif
1269 #if DISPATCH_USE_KEVENT_QOS
1270 .qos = _PTHREAD_PRIORITY_EVENT_MANAGER_FLAG,
1271 #endif
1272 };
1273
1274 _dispatch_kq_deferred_update(DISPATCH_WLH_ANON, &ke);
1275 }
1276
1277 void
1278 _dispatch_event_loop_timer_arm(uint32_t tidx, dispatch_timer_delay_s range,
1279 dispatch_clock_now_cache_t nows)
1280 {
1281 if (unlikely(_dispatch_timers_force_max_leeway)) {
1282 range.delay += range.leeway;
1283 range.leeway = 0;
1284 }
1285 #if HAVE_MACH
1286 if (DISPATCH_TIMER_CLOCK(tidx) == DISPATCH_CLOCK_WALL) {
1287 _dispatch_mach_host_calendar_change_register();
1288 }
1289 #endif
1290
1291 // <rdar://problem/13186331> EVFILT_TIMER NOTE_ABSOLUTE always expects
1292 // a WALL deadline
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);
1297 }
1298
1299 void
1300 _dispatch_event_loop_timer_delete(uint32_t tidx)
1301 {
1302 _dispatch_timers_heap[tidx].dth_flags &= ~DTH_ARMED;
1303 _dispatch_event_loop_timer_program(tidx, 0, 0, EV_DELETE);
1304 }
1305
1306 #pragma mark -
1307 #pragma mark kevent specific sources
1308
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)
1312 {
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;
1316 }
1317 return du;
1318 }
1319
1320 const dispatch_source_type_s _dispatch_source_type_proc = {
1321 .dst_kind = "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
1327 |NOTE_SIGNAL
1328 #endif
1329 #if HAVE_DECL_NOTE_REAP
1330 |NOTE_REAP
1331 #endif
1332 ,
1333 .dst_size = sizeof(struct dispatch_source_refs_s),
1334
1335 .dst_create = _dispatch_source_proc_create,
1336 .dst_merge_evt = _dispatch_source_merge_evt,
1337 };
1338
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
1346 |NOTE_REVOKE
1347 #endif
1348 #if HAVE_DECL_NOTE_NONE
1349 |NOTE_NONE
1350 #endif
1351 ,
1352 .dst_size = sizeof(struct dispatch_source_refs_s),
1353
1354 .dst_create = _dispatch_unote_create_with_fd,
1355 .dst_merge_evt = _dispatch_source_merge_evt,
1356 };
1357
1358 const dispatch_source_type_s _dispatch_source_type_vfs = {
1359 .dst_kind = "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
1365 |VQ_UPDATE
1366 #endif
1367 #if HAVE_DECL_VQ_VERYLOWDISK
1368 |VQ_VERYLOWDISK
1369 #endif
1370 #if HAVE_DECL_VQ_QUOTA
1371 |VQ_QUOTA
1372 #endif
1373 #if HAVE_DECL_VQ_NEARLOWDISK
1374 |VQ_NEARLOWDISK
1375 #endif
1376 #if HAVE_DECL_VQ_DESIRED_DISK
1377 |VQ_DESIRED_DISK
1378 #endif
1379 ,
1380 .dst_size = sizeof(struct dispatch_source_refs_s),
1381
1382 .dst_create = _dispatch_unote_create_without_handle,
1383 .dst_merge_evt = _dispatch_source_merge_evt,
1384 };
1385
1386 #ifdef EVFILT_SOCK
1387 const dispatch_source_type_s _dispatch_source_type_sock = {
1388 .dst_kind = "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
1393 |NOTE_KEEPALIVE
1394 #ifdef NOTE_ADAPTIVE_WTIMO
1395 |NOTE_ADAPTIVE_WTIMO|NOTE_ADAPTIVE_RTIMO
1396 #endif
1397 #ifdef NOTE_CONNECTED
1398 |NOTE_CONNECTED|NOTE_DISCONNECTED|NOTE_CONNINFO_UPDATED
1399 #endif
1400 #ifdef NOTE_NOTIFY_ACK
1401 |NOTE_NOTIFY_ACK
1402 #endif
1403 ,
1404 .dst_size = sizeof(struct dispatch_source_refs_s),
1405
1406 .dst_create = _dispatch_unote_create_with_fd,
1407 .dst_merge_evt = _dispatch_source_merge_evt,
1408 };
1409 #endif // EVFILT_SOCK
1410
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,
1420 };
1421 #endif // EVFILT_NW_CHANNEL
1422
1423 #if DISPATCH_USE_MEMORYSTATUS
1424
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)
1433
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)
1440
1441
1442 static void
1443 _dispatch_memorypressure_handler(void *context)
1444 {
1445 dispatch_source_t ds = context;
1446 unsigned long memorypressure = dispatch_source_get_data(ds);
1447
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);
1455 }
1456 #endif
1457 }
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);
1466 }
1467 #endif
1468 }
1469 memorypressure &= DISPATCH_MEMORYPRESSURE_MALLOC_MASK;
1470 if (memorypressure) {
1471 malloc_memory_event_handler(memorypressure);
1472 }
1473 }
1474
1475 static void
1476 _dispatch_memorypressure_init(void)
1477 {
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);
1484 }
1485 #endif // DISPATCH_USE_MEMORYPRESSURE_SOURCE
1486
1487 #if TARGET_OS_SIMULATOR // rdar://problem/9219483
1488 static int _dispatch_ios_simulator_memory_warnings_fd = -1;
1489 static void
1490 _dispatch_ios_simulator_memorypressure_init(void *context DISPATCH_UNUSED)
1491 {
1492 char *e = getenv("SIMULATOR_MEMORY_WARNINGS");
1493 if (!e) return;
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);
1497 }
1498 }
1499
1500 static dispatch_unote_t
1501 _dispatch_source_memorypressure_create(dispatch_source_type_t dst,
1502 uintptr_t handle, unsigned long mask)
1503 {
1504 static dispatch_once_t pred;
1505 dispatch_once_f(&pred, NULL, _dispatch_ios_simulator_memorypressure_init);
1506
1507 if (handle) {
1508 return DISPATCH_UNOTE_NULL;
1509 }
1510
1511 dst = &_dispatch_source_type_vnode;
1512 handle = (uintptr_t)_dispatch_ios_simulator_memory_warnings_fd;
1513 mask = NOTE_ATTRIB;
1514
1515 dispatch_unote_t du = dux_create(dst, handle, mask);
1516 if (du._du) {
1517 du._du->du_memorypressure_override = true;
1518 }
1519 return du;
1520 }
1521 #endif // TARGET_OS_SIMULATOR
1522
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),
1533
1534 #if TARGET_OS_SIMULATOR
1535 .dst_create = _dispatch_source_memorypressure_create,
1536 // redirected to _dispatch_source_type_vnode
1537 #else
1538 .dst_create = _dispatch_unote_create_without_handle,
1539 .dst_merge_evt = _dispatch_source_merge_evt,
1540 #endif
1541 };
1542
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)
1546 {
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);
1550 if (du._du) {
1551 du._du->du_vmpressure_override = 1;
1552 }
1553 return du;
1554 }
1555
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),
1562
1563 .dst_create = _dispatch_source_vm_create,
1564 // redirected to _dispatch_source_type_memorypressure
1565 };
1566 #endif // DISPATCH_USE_MEMORYSTATUS
1567
1568 #pragma mark mach send / notifications
1569 #if HAVE_MACH
1570
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)
1575
1576 static void _dispatch_mach_host_notify_update(void *context);
1577
1578 static mach_port_t _dispatch_mach_notify_port;
1579 static dispatch_source_t _dispatch_mach_notify_source;
1580
1581 static void
1582 _dispatch_timers_calendar_change(void)
1583 {
1584 uint32_t qos;
1585
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);
1591 }
1592 }
1593
1594 static mach_msg_audit_trailer_t *
1595 _dispatch_mach_msg_get_audit_trailer(mach_msg_header_t *hdr)
1596 {
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;
1605 }
1606 }
1607 return audit_tlr;
1608 }
1609
1610 DISPATCH_NOINLINE
1611 static void
1612 _dispatch_mach_notify_source_invoke(mach_msg_header_t *hdr)
1613 {
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);
1621 if (!tlr) {
1622 DISPATCH_INTERNAL_CRASH(0, "message received without expected trailer");
1623 }
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);
1628 return;
1629 }
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);
1637 success = TRUE;
1638 reply.RetCode = KERN_SUCCESS;
1639 }
1640 if (dispatch_assume(success) && reply.RetCode != MIG_NO_REPLY) {
1641 (void)dispatch_assume_zero(reply.RetCode);
1642 }
1643 if (!success || (reply.RetCode && reply.RetCode != MIG_NO_REPLY)) {
1644 mach_msg_destroy(hdr);
1645 }
1646 }
1647
1648 DISPATCH_NOINLINE
1649 static void
1650 _dispatch_mach_notify_port_init(void *context DISPATCH_UNUSED)
1651 {
1652 kern_return_t kr;
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;
1657 #else
1658 const mach_port_context_t guard = 0xff1ca7edull;
1659 #endif
1660 kr = mach_port_construct(mach_task_self(), &opts, guard,
1661 &_dispatch_mach_notify_port);
1662 #else
1663 kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE,
1664 &_dispatch_mach_notify_port);
1665 #endif
1666 DISPATCH_VERIFY_MIG(kr);
1667 if (unlikely(kr)) {
1668 DISPATCH_CLIENT_CRASH(kr,
1669 "mach_port_construct() failed: cannot create receive right");
1670 }
1671
1672 static const struct dispatch_continuation_s dc = {
1673 .dc_func = (void*)_dispatch_mach_notify_source_invoke,
1674 };
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);
1679 }
1680
1681 static void
1682 _dispatch_mach_host_port_init(void *ctxt DISPATCH_UNUSED)
1683 {
1684 kern_return_t kr;
1685 mach_port_t mp, mhp = mach_host_self();
1686 kr = host_get_host_port(mhp, &mp);
1687 DISPATCH_VERIFY_MIG(kr);
1688 if (likely(!kr)) {
1689 // mach_host_self returned the HOST_PRIV port
1690 kr = mach_port_deallocate(mach_task_self(), mhp);
1691 DISPATCH_VERIFY_MIG(kr);
1692 mhp = mp;
1693 } else if (kr != KERN_INVALID_ARGUMENT) {
1694 (void)dispatch_assume_zero(kr);
1695 }
1696 if (unlikely(!mhp)) {
1697 DISPATCH_CLIENT_CRASH(kr, "Could not get unprivileged host port");
1698 }
1699 _dispatch_mach_host_port = mhp;
1700 }
1701
1702 mach_port_t
1703 _dispatch_get_mach_host_port(void)
1704 {
1705 dispatch_once_f(&_dispatch_mach_host_port_pred, NULL,
1706 _dispatch_mach_host_port_init);
1707 return _dispatch_mach_host_port;
1708 }
1709
1710 DISPATCH_ALWAYS_INLINE
1711 static inline mach_port_t
1712 _dispatch_get_mach_notify_port(void)
1713 {
1714 static dispatch_once_t pred;
1715 dispatch_once_f(&pred, NULL, _dispatch_mach_notify_port_init);
1716 return _dispatch_mach_notify_port;
1717 }
1718
1719 static void
1720 _dispatch_mach_host_notify_update(void *context DISPATCH_UNUSED)
1721 {
1722 static int notify_type = HOST_NOTIFY_CALENDAR_SET;
1723 kern_return_t kr;
1724 _dispatch_debug("registering for calendar-change notification");
1725 retry:
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;
1732 goto retry;
1733 }
1734 DISPATCH_VERIFY_MIG(kr);
1735 (void)dispatch_assume_zero(kr);
1736 }
1737
1738 DISPATCH_ALWAYS_INLINE
1739 static inline void
1740 _dispatch_mach_host_calendar_change_register(void)
1741 {
1742 static dispatch_once_t pred;
1743 dispatch_once_f(&pred, NULL, _dispatch_mach_host_notify_update);
1744 }
1745
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)
1750 {
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;
1754
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);
1758
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);
1768
1769 switch (krr) {
1770 case KERN_INVALID_NAME:
1771 case KERN_INVALID_RIGHT:
1772 // Suppress errors & clear registration state
1773 dmn->dmn_kev.data &= ~mask;
1774 break;
1775 default:
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;
1791 }
1792 }
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);
1801
1802 switch (kr) {
1803 case KERN_INVALID_NAME:
1804 case KERN_INVALID_RIGHT:
1805 case KERN_INVALID_ARGUMENT:
1806 break;
1807 default:
1808 if (dispatch_assume_zero(kr)) {
1809 // log the error
1810 }
1811 }
1812 } else {
1813 return 0;
1814 }
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));
1819 }
1820 return krr;
1821 }
1822
1823 static bool
1824 _dispatch_kevent_mach_notify_resume(dispatch_muxnote_t dmn, uint32_t new_flags,
1825 uint32_t del_flags)
1826 {
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);
1841 }
1842 return kr == KERN_SUCCESS;
1843 }
1844
1845 DISPATCH_NOINLINE
1846 static void
1847 _dispatch_mach_notify_merge(mach_port_t name, uint32_t data, bool final)
1848 {
1849 dispatch_unote_linkage_t dul, dul_next;
1850 dispatch_muxnote_t dmn;
1851
1852 _dispatch_debug_machport(name);
1853 dmn = _dispatch_mach_muxnote_find(name, DISPATCH_EVFILT_MACH_NOTIFICATION);
1854 if (!dmn) {
1855 return;
1856 }
1857
1858 dmn->dmn_kev.data &= ~_DISPATCH_MACH_SP_FLAGS;
1859 if (!final) {
1860 // Re-register for notification before delivery
1861 final = !_dispatch_kevent_mach_notify_resume(dmn, data, 0);
1862 }
1863
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
1873 break;
1874 }
1875 }
1876 }
1877
1878 kern_return_t
1879 _dispatch_mach_notify_port_deleted(mach_port_t notify DISPATCH_UNUSED,
1880 mach_port_name_t name)
1881 {
1882 #if DISPATCH_DEBUG
1883 _dispatch_log("Corruption: Mach send/send-once/dead-name right 0x%x "
1884 "deleted prematurely", name);
1885 #endif
1886 _dispatch_debug_machport(name);
1887 _dispatch_mach_notify_merge(name, DISPATCH_MACH_SEND_DELETED, true);
1888 return KERN_SUCCESS;
1889 }
1890
1891 kern_return_t
1892 _dispatch_mach_notify_dead_name(mach_port_t notify DISPATCH_UNUSED,
1893 mach_port_name_t name)
1894 {
1895 kern_return_t kr;
1896
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);
1900
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;
1907 }
1908
1909 kern_return_t
1910 _dispatch_mach_notify_send_possible(mach_port_t notify DISPATCH_UNUSED,
1911 mach_port_name_t name)
1912 {
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;
1917 }
1918
1919 void
1920 _dispatch_mach_notification_set_armed(dispatch_mach_send_refs_t dmsr)
1921 {
1922 dispatch_muxnote_t dmn = _dispatch_unote_get_linkage(dmsr)->du_muxnote;
1923 dispatch_unote_linkage_t dul;
1924 dispatch_unote_t du;
1925
1926 if (!_dispatch_unote_registered(dmsr)) {
1927 return;
1928 }
1929
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);
1934 }
1935 }
1936
1937 static dispatch_unote_t
1938 _dispatch_source_mach_send_create(dispatch_source_type_t dst,
1939 uintptr_t handle, unsigned long mask)
1940 {
1941 if (!mask) {
1942 // Preserve legacy behavior that (mask == 0) => DISPATCH_MACH_SEND_DEAD
1943 mask = DISPATCH_MACH_SEND_DEAD;
1944 }
1945 if (!handle) {
1946 handle = MACH_PORT_DEAD; // <rdar://problem/27651332>
1947 }
1948 return _dispatch_unote_create_with_handle(dst, handle, mask);
1949 }
1950
1951 static bool
1952 _dispatch_mach_send_update(dispatch_muxnote_t dmn)
1953 {
1954 if (dmn->dmn_kev.flags & EV_DELETE) {
1955 return _dispatch_kevent_mach_notify_resume(dmn, 0, dmn->dmn_kev.fflags);
1956 } else {
1957 return _dispatch_kevent_mach_notify_resume(dmn, dmn->dmn_kev.fflags, 0);
1958 }
1959 }
1960
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),
1967
1968 .dst_create = _dispatch_source_mach_send_create,
1969 .dst_update_mux = _dispatch_mach_send_update,
1970 .dst_merge_evt = _dispatch_source_merge_evt,
1971 };
1972
1973 static dispatch_unote_t
1974 _dispatch_mach_send_create(dispatch_source_type_t dst,
1975 uintptr_t handle, unsigned long mask)
1976 {
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);
1980 if (du._dmsr) {
1981 du._dmsr->dmsr_disconnect_cnt = DISPATCH_MACH_NEVER_CONNECTED;
1982 TAILQ_INIT(&du._dmsr->dmsr_replies);
1983 }
1984 return du;
1985 }
1986
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),
1993
1994 .dst_create = _dispatch_mach_send_create,
1995 .dst_update_mux = _dispatch_mach_send_update,
1996 .dst_merge_evt = _dispatch_mach_merge_notification,
1997 };
1998
1999 #endif // HAVE_MACH
2000 #pragma mark mach recv / reply
2001 #if HAVE_MACH
2002
2003 static void
2004 _dispatch_kevent_mach_msg_recv(dispatch_unote_t du, uint32_t flags,
2005 mach_msg_header_t *hdr)
2006 {
2007 mach_msg_size_t siz = hdr->msgh_size + DISPATCH_MACH_TRAILER_SIZE;
2008 mach_port_t name = hdr->msgh_local_port;
2009
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");
2017 } else {
2018 _dispatch_debug_machport(name);
2019 if (likely(du._du)) {
2020 return dux_merge_msg(du._du, flags, hdr, siz);
2021 }
2022 _dispatch_bug_client("_dispatch_kevent_mach_msg_recv: "
2023 "received message with no listeners");
2024 }
2025
2026 mach_msg_destroy(hdr);
2027 if (flags & DISPATCH_EV_MSG_NEEDS_FREE) {
2028 free(hdr);
2029 }
2030 }
2031
2032 DISPATCH_NOINLINE
2033 static void
2034 _dispatch_kevent_mach_msg_drain(dispatch_kevent_t ke)
2035 {
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);
2041
2042 if (unlikely(!hdr)) {
2043 DISPATCH_INTERNAL_CRASH(kr, "EVFILT_MACHPORT with no message");
2044 }
2045 if (likely(!kr)) {
2046 _dispatch_kevent_mach_msg_recv(du, flags, hdr);
2047 goto out;
2048 } else if (kr != MACH_RCV_TOO_LARGE) {
2049 goto out;
2050 } else if (!ke->data) {
2051 DISPATCH_INTERNAL_CRASH(0, "MACH_RCV_LARGE_IDENTITY with no identity");
2052 }
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");
2056 }
2057 siz = _dispatch_kevent_mach_msg_size(ke) + DISPATCH_MACH_TRAILER_SIZE;
2058 hdr = malloc(siz);
2059 if (dispatch_assume(hdr)) {
2060 flags |= DISPATCH_EV_MSG_NEEDS_FREE;
2061 } else {
2062 // Kernel will discard message too large to fit
2063 hdr = NULL;
2064 siz = 0;
2065 }
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,
2070 MACH_PORT_NULL);
2071 if (likely(!kr)) {
2072 _dispatch_kevent_mach_msg_recv(du, flags, hdr);
2073 goto out;
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;
2080 }
2081 if (flags & DISPATCH_EV_MSG_NEEDS_FREE) {
2082 free(hdr);
2083 }
2084 out:
2085 if (unlikely(kr)) {
2086 _dispatch_bug_mach_client("_dispatch_kevent_mach_msg_drain: "
2087 "message reception failed", kr);
2088 }
2089 }
2090
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,
2095 .dst_fflags = 0,
2096 .dst_size = sizeof(struct dispatch_source_refs_s),
2097
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
2101
2102 .dst_per_trigger_qos = true,
2103 };
2104
2105 static void
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)
2108 {
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();
2112
2113 // see firehose_client_push_notify_async
2114 _dispatch_queue_set_current(ds->_as_dq);
2115 dc->dc_func(msg);
2116 _dispatch_queue_set_current(cq);
2117 if (flags & DISPATCH_EV_MSG_NEEDS_FREE) {
2118 free(msg);
2119 }
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);
2123 }
2124 if (_dispatch_unote_needs_rearm(du)) {
2125 return _dispatch_unote_resume(du);
2126 }
2127 }
2128
2129 static void
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)
2134 {
2135 if (flags & EV_VANISHED) {
2136 DISPATCH_CLIENT_CRASH(du._du->du_ident,
2137 "Unexpected EV_VANISHED (do not destroy random mach ports)");
2138 }
2139 return _dispatch_source_merge_evt(du, flags, data, 0, pp);
2140 }
2141
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),
2148
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,
2152
2153 .dst_per_trigger_qos = true,
2154 };
2155
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),
2162
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,
2167
2168 .dst_per_trigger_qos = true,
2169 };
2170
2171 DISPATCH_NORETURN
2172 static void
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)
2177 {
2178 DISPATCH_INTERNAL_CRASH(du._du->du_ident, "Unexpected event");
2179 }
2180
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),
2187
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,
2191 };
2192
2193 #pragma mark Mach channel SIGTERM notification (for XPC channels only)
2194
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,
2199 .dst_fflags = 0,
2200 .dst_size = sizeof(struct dispatch_xpc_term_refs_s),
2201
2202 .dst_create = _dispatch_unote_create_with_handle,
2203 .dst_merge_evt = _dispatch_xpc_sigterm_merge,
2204 };
2205
2206 #endif // HAVE_MACH
2207
2208 #endif // DISPATCH_EVENT_BACKEND_KEVENT