]> git.saurik.com Git - apple/libdispatch.git/blob - src/source.c
libdispatch-187.5.tar.gz
[apple/libdispatch.git] / src / source.c
1 /*
2 * Copyright (c) 2008-2011 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 HAVE_MACH
23 #include "protocol.h"
24 #include "protocolServer.h"
25 #endif
26 #include <sys/mount.h>
27
28 static void _dispatch_source_dispose(dispatch_source_t ds);
29 static dispatch_queue_t _dispatch_source_invoke(dispatch_source_t ds);
30 static bool _dispatch_source_probe(dispatch_source_t ds);
31 static void _dispatch_source_merge_kevent(dispatch_source_t ds,
32 const struct kevent *ke);
33 static void _dispatch_kevent_register(dispatch_source_t ds);
34 static void _dispatch_kevent_unregister(dispatch_source_t ds);
35 static bool _dispatch_kevent_resume(dispatch_kevent_t dk, uint32_t new_flags,
36 uint32_t del_flags);
37 static inline void _dispatch_source_timer_init(void);
38 static void _dispatch_timer_list_update(dispatch_source_t ds);
39 static inline unsigned long _dispatch_source_timer_data(
40 dispatch_source_refs_t dr, unsigned long prev);
41 #if HAVE_MACH
42 static kern_return_t _dispatch_kevent_machport_resume(dispatch_kevent_t dk,
43 uint32_t new_flags, uint32_t del_flags);
44 static void _dispatch_drain_mach_messages(struct kevent *ke);
45 #endif
46 static size_t _dispatch_source_kevent_debug(dispatch_source_t ds,
47 char* buf, size_t bufsiz);
48 #if DISPATCH_DEBUG
49 static void _dispatch_kevent_debugger(void *context);
50 #endif
51
52 #pragma mark -
53 #pragma mark dispatch_source_t
54
55 const struct dispatch_source_vtable_s _dispatch_source_kevent_vtable = {
56 .do_type = DISPATCH_SOURCE_KEVENT_TYPE,
57 .do_kind = "kevent-source",
58 .do_invoke = _dispatch_source_invoke,
59 .do_dispose = _dispatch_source_dispose,
60 .do_probe = _dispatch_source_probe,
61 .do_debug = _dispatch_source_kevent_debug,
62 };
63
64 dispatch_source_t
65 dispatch_source_create(dispatch_source_type_t type,
66 uintptr_t handle,
67 unsigned long mask,
68 dispatch_queue_t q)
69 {
70 const struct kevent *proto_kev = &type->ke;
71 dispatch_source_t ds = NULL;
72 dispatch_kevent_t dk = NULL;
73
74 // input validation
75 if (type == NULL || (mask & ~type->mask)) {
76 goto out_bad;
77 }
78
79 switch (type->ke.filter) {
80 case EVFILT_SIGNAL:
81 if (handle >= NSIG) {
82 goto out_bad;
83 }
84 break;
85 case EVFILT_FS:
86 #if DISPATCH_USE_VM_PRESSURE
87 case EVFILT_VM:
88 #endif
89 case DISPATCH_EVFILT_CUSTOM_ADD:
90 case DISPATCH_EVFILT_CUSTOM_OR:
91 case DISPATCH_EVFILT_TIMER:
92 if (handle) {
93 goto out_bad;
94 }
95 break;
96 default:
97 break;
98 }
99
100 ds = calloc(1ul, sizeof(struct dispatch_source_s));
101 if (slowpath(!ds)) {
102 goto out_bad;
103 }
104 dk = calloc(1ul, sizeof(struct dispatch_kevent_s));
105 if (slowpath(!dk)) {
106 goto out_bad;
107 }
108
109 dk->dk_kevent = *proto_kev;
110 dk->dk_kevent.ident = handle;
111 dk->dk_kevent.flags |= EV_ADD|EV_ENABLE;
112 dk->dk_kevent.fflags |= (uint32_t)mask;
113 dk->dk_kevent.udata = dk;
114 TAILQ_INIT(&dk->dk_sources);
115
116 // Initialize as a queue first, then override some settings below.
117 _dispatch_queue_init((dispatch_queue_t)ds);
118 strlcpy(ds->dq_label, "source", sizeof(ds->dq_label));
119
120 // Dispatch Object
121 ds->do_vtable = &_dispatch_source_kevent_vtable;
122 ds->do_ref_cnt++; // the reference the manger queue holds
123 ds->do_ref_cnt++; // since source is created suspended
124 ds->do_suspend_cnt = DISPATCH_OBJECT_SUSPEND_INTERVAL;
125 // The initial target queue is the manager queue, in order to get
126 // the source installed. <rdar://problem/8928171>
127 ds->do_targetq = &_dispatch_mgr_q;
128
129 // Dispatch Source
130 ds->ds_ident_hack = dk->dk_kevent.ident;
131 ds->ds_dkev = dk;
132 ds->ds_pending_data_mask = dk->dk_kevent.fflags;
133 if ((EV_DISPATCH|EV_ONESHOT) & proto_kev->flags) {
134 ds->ds_is_level = true;
135 ds->ds_needs_rearm = true;
136 } else if (!(EV_CLEAR & proto_kev->flags)) {
137 // we cheat and use EV_CLEAR to mean a "flag thingy"
138 ds->ds_is_adder = true;
139 }
140
141 // Some sources require special processing
142 if (type->init != NULL) {
143 type->init(ds, type, handle, mask, q);
144 }
145 if (fastpath(!ds->ds_refs)) {
146 ds->ds_refs = calloc(1ul, sizeof(struct dispatch_source_refs_s));
147 if (slowpath(!ds->ds_refs)) {
148 goto out_bad;
149 }
150 }
151 ds->ds_refs->dr_source_wref = _dispatch_ptr2wref(ds);
152 dispatch_assert(!(ds->ds_is_level && ds->ds_is_adder));
153
154 // First item on the queue sets the user-specified target queue
155 dispatch_set_target_queue(ds, q);
156 #if DISPATCH_DEBUG
157 dispatch_debug(ds, "%s", __FUNCTION__);
158 #endif
159 return ds;
160
161 out_bad:
162 free(ds);
163 free(dk);
164 return NULL;
165 }
166
167 static void
168 _dispatch_source_dispose(dispatch_source_t ds)
169 {
170 free(ds->ds_refs);
171 _dispatch_queue_dispose((dispatch_queue_t)ds);
172 }
173
174 void
175 _dispatch_source_xref_release(dispatch_source_t ds)
176 {
177 if (slowpath(DISPATCH_OBJECT_SUSPENDED(ds))) {
178 // Arguments for and against this assert are within 6705399
179 DISPATCH_CLIENT_CRASH("Release of a suspended object");
180 }
181 _dispatch_wakeup(ds);
182 _dispatch_release(ds);
183 }
184
185 void
186 dispatch_source_cancel(dispatch_source_t ds)
187 {
188 #if DISPATCH_DEBUG
189 dispatch_debug(ds, "%s", __FUNCTION__);
190 #endif
191 // Right after we set the cancel flag, someone else
192 // could potentially invoke the source, do the cancelation,
193 // unregister the source, and deallocate it. We would
194 // need to therefore retain/release before setting the bit
195
196 _dispatch_retain(ds);
197 (void)dispatch_atomic_or2o(ds, ds_atomic_flags, DSF_CANCELED);
198 _dispatch_wakeup(ds);
199 _dispatch_release(ds);
200 }
201
202 long
203 dispatch_source_testcancel(dispatch_source_t ds)
204 {
205 return (bool)(ds->ds_atomic_flags & DSF_CANCELED);
206 }
207
208
209 unsigned long
210 dispatch_source_get_mask(dispatch_source_t ds)
211 {
212 return ds->ds_pending_data_mask;
213 }
214
215 uintptr_t
216 dispatch_source_get_handle(dispatch_source_t ds)
217 {
218 return (int)ds->ds_ident_hack;
219 }
220
221 unsigned long
222 dispatch_source_get_data(dispatch_source_t ds)
223 {
224 return ds->ds_data;
225 }
226
227 void
228 dispatch_source_merge_data(dispatch_source_t ds, unsigned long val)
229 {
230 struct kevent kev = {
231 .fflags = (typeof(kev.fflags))val,
232 .data = val,
233 };
234
235 dispatch_assert(
236 ds->ds_dkev->dk_kevent.filter == DISPATCH_EVFILT_CUSTOM_ADD ||
237 ds->ds_dkev->dk_kevent.filter == DISPATCH_EVFILT_CUSTOM_OR);
238
239 _dispatch_source_merge_kevent(ds, &kev);
240 }
241
242 #pragma mark -
243 #pragma mark dispatch_source_handler
244
245 #ifdef __BLOCKS__
246 // 6618342 Contact the team that owns the Instrument DTrace probe before
247 // renaming this symbol
248 static void
249 _dispatch_source_set_event_handler2(void *context)
250 {
251 struct Block_layout *bl = context;
252
253 dispatch_source_t ds = (dispatch_source_t)_dispatch_queue_get_current();
254 dispatch_assert(ds->do_vtable == &_dispatch_source_kevent_vtable);
255 dispatch_source_refs_t dr = ds->ds_refs;
256
257 if (ds->ds_handler_is_block && dr->ds_handler_ctxt) {
258 Block_release(dr->ds_handler_ctxt);
259 }
260 dr->ds_handler_func = bl ? (void *)bl->invoke : NULL;
261 dr->ds_handler_ctxt = bl;
262 ds->ds_handler_is_block = true;
263 }
264
265 void
266 dispatch_source_set_event_handler(dispatch_source_t ds,
267 dispatch_block_t handler)
268 {
269 handler = _dispatch_Block_copy(handler);
270 dispatch_barrier_async_f((dispatch_queue_t)ds, handler,
271 _dispatch_source_set_event_handler2);
272 }
273 #endif /* __BLOCKS__ */
274
275 static void
276 _dispatch_source_set_event_handler_f(void *context)
277 {
278 dispatch_source_t ds = (dispatch_source_t)_dispatch_queue_get_current();
279 dispatch_assert(ds->do_vtable == &_dispatch_source_kevent_vtable);
280 dispatch_source_refs_t dr = ds->ds_refs;
281
282 #ifdef __BLOCKS__
283 if (ds->ds_handler_is_block && dr->ds_handler_ctxt) {
284 Block_release(dr->ds_handler_ctxt);
285 }
286 #endif
287 dr->ds_handler_func = context;
288 dr->ds_handler_ctxt = ds->do_ctxt;
289 ds->ds_handler_is_block = false;
290 }
291
292 void
293 dispatch_source_set_event_handler_f(dispatch_source_t ds,
294 dispatch_function_t handler)
295 {
296 dispatch_barrier_async_f((dispatch_queue_t)ds, handler,
297 _dispatch_source_set_event_handler_f);
298 }
299
300 #ifdef __BLOCKS__
301 // 6618342 Contact the team that owns the Instrument DTrace probe before
302 // renaming this symbol
303 static void
304 _dispatch_source_set_cancel_handler2(void *context)
305 {
306 dispatch_source_t ds = (dispatch_source_t)_dispatch_queue_get_current();
307 dispatch_assert(ds->do_vtable == &_dispatch_source_kevent_vtable);
308 dispatch_source_refs_t dr = ds->ds_refs;
309
310 if (ds->ds_cancel_is_block && dr->ds_cancel_handler) {
311 Block_release(dr->ds_cancel_handler);
312 }
313 dr->ds_cancel_handler = context;
314 ds->ds_cancel_is_block = true;
315 }
316
317 void
318 dispatch_source_set_cancel_handler(dispatch_source_t ds,
319 dispatch_block_t handler)
320 {
321 handler = _dispatch_Block_copy(handler);
322 dispatch_barrier_async_f((dispatch_queue_t)ds, handler,
323 _dispatch_source_set_cancel_handler2);
324 }
325 #endif /* __BLOCKS__ */
326
327 static void
328 _dispatch_source_set_cancel_handler_f(void *context)
329 {
330 dispatch_source_t ds = (dispatch_source_t)_dispatch_queue_get_current();
331 dispatch_assert(ds->do_vtable == &_dispatch_source_kevent_vtable);
332 dispatch_source_refs_t dr = ds->ds_refs;
333
334 #ifdef __BLOCKS__
335 if (ds->ds_cancel_is_block && dr->ds_cancel_handler) {
336 Block_release(dr->ds_cancel_handler);
337 }
338 #endif
339 dr->ds_cancel_handler = context;
340 ds->ds_cancel_is_block = false;
341 }
342
343 void
344 dispatch_source_set_cancel_handler_f(dispatch_source_t ds,
345 dispatch_function_t handler)
346 {
347 dispatch_barrier_async_f((dispatch_queue_t)ds, handler,
348 _dispatch_source_set_cancel_handler_f);
349 }
350
351 #ifdef __BLOCKS__
352 static void
353 _dispatch_source_set_registration_handler2(void *context)
354 {
355 dispatch_source_t ds = (dispatch_source_t)_dispatch_queue_get_current();
356 dispatch_assert(ds->do_vtable == &_dispatch_source_kevent_vtable);
357 dispatch_source_refs_t dr = ds->ds_refs;
358
359 if (ds->ds_registration_is_block && dr->ds_registration_handler) {
360 Block_release(dr->ds_registration_handler);
361 }
362 dr->ds_registration_handler = context;
363 ds->ds_registration_is_block = true;
364 }
365
366 void
367 dispatch_source_set_registration_handler(dispatch_source_t ds,
368 dispatch_block_t handler)
369 {
370 handler = _dispatch_Block_copy(handler);
371 dispatch_barrier_async_f((dispatch_queue_t)ds, handler,
372 _dispatch_source_set_registration_handler2);
373 }
374 #endif /* __BLOCKS__ */
375
376 static void
377 _dispatch_source_set_registration_handler_f(void *context)
378 {
379 dispatch_source_t ds = (dispatch_source_t)_dispatch_queue_get_current();
380 dispatch_assert(ds->do_vtable == &_dispatch_source_kevent_vtable);
381 dispatch_source_refs_t dr = ds->ds_refs;
382
383 #ifdef __BLOCKS__
384 if (ds->ds_registration_is_block && dr->ds_registration_handler) {
385 Block_release(dr->ds_registration_handler);
386 }
387 #endif
388 dr->ds_registration_handler = context;
389 ds->ds_registration_is_block = false;
390 }
391
392 void
393 dispatch_source_set_registration_handler_f(dispatch_source_t ds,
394 dispatch_function_t handler)
395 {
396 dispatch_barrier_async_f((dispatch_queue_t)ds, handler,
397 _dispatch_source_set_registration_handler_f);
398 }
399
400 #pragma mark -
401 #pragma mark dispatch_source_invoke
402
403 static void
404 _dispatch_source_registration_callout(dispatch_source_t ds)
405 {
406 dispatch_source_refs_t dr = ds->ds_refs;
407
408 if ((ds->ds_atomic_flags & DSF_CANCELED) || (ds->do_xref_cnt == 0)) {
409 // no registration callout if source is canceled rdar://problem/8955246
410 #ifdef __BLOCKS__
411 if (ds->ds_registration_is_block) {
412 Block_release(dr->ds_registration_handler);
413 }
414 } else if (ds->ds_registration_is_block) {
415 dispatch_block_t b = dr->ds_registration_handler;
416 _dispatch_client_callout_block(b);
417 Block_release(dr->ds_registration_handler);
418 #endif
419 } else {
420 dispatch_function_t f = dr->ds_registration_handler;
421 _dispatch_client_callout(ds->do_ctxt, f);
422 }
423 ds->ds_registration_is_block = false;
424 dr->ds_registration_handler = NULL;
425 }
426
427 static void
428 _dispatch_source_cancel_callout(dispatch_source_t ds)
429 {
430 dispatch_source_refs_t dr = ds->ds_refs;
431
432 ds->ds_pending_data_mask = 0;
433 ds->ds_pending_data = 0;
434 ds->ds_data = 0;
435
436 #ifdef __BLOCKS__
437 if (ds->ds_handler_is_block) {
438 Block_release(dr->ds_handler_ctxt);
439 ds->ds_handler_is_block = false;
440 dr->ds_handler_func = NULL;
441 dr->ds_handler_ctxt = NULL;
442 }
443 if (ds->ds_registration_is_block) {
444 Block_release(dr->ds_registration_handler);
445 ds->ds_registration_is_block = false;
446 dr->ds_registration_handler = NULL;
447 }
448 #endif
449
450 if (!dr->ds_cancel_handler) {
451 return;
452 }
453 if (ds->ds_cancel_is_block) {
454 #ifdef __BLOCKS__
455 dispatch_block_t b = dr->ds_cancel_handler;
456 if (ds->ds_atomic_flags & DSF_CANCELED) {
457 _dispatch_client_callout_block(b);
458 }
459 Block_release(dr->ds_cancel_handler);
460 ds->ds_cancel_is_block = false;
461 #endif
462 } else {
463 dispatch_function_t f = dr->ds_cancel_handler;
464 if (ds->ds_atomic_flags & DSF_CANCELED) {
465 _dispatch_client_callout(ds->do_ctxt, f);
466 }
467 }
468 dr->ds_cancel_handler = NULL;
469 }
470
471 static void
472 _dispatch_source_latch_and_call(dispatch_source_t ds)
473 {
474 unsigned long prev;
475
476 if ((ds->ds_atomic_flags & DSF_CANCELED) || (ds->do_xref_cnt == 0)) {
477 return;
478 }
479 dispatch_source_refs_t dr = ds->ds_refs;
480 prev = dispatch_atomic_xchg2o(ds, ds_pending_data, 0);
481 if (ds->ds_is_level) {
482 ds->ds_data = ~prev;
483 } else if (ds->ds_is_timer && ds_timer(dr).target && prev) {
484 ds->ds_data = _dispatch_source_timer_data(dr, prev);
485 } else {
486 ds->ds_data = prev;
487 }
488 if (dispatch_assume(prev) && dr->ds_handler_func) {
489 _dispatch_client_callout(dr->ds_handler_ctxt, dr->ds_handler_func);
490 }
491 }
492
493 static void
494 _dispatch_source_kevent_resume(dispatch_source_t ds, uint32_t new_flags)
495 {
496 switch (ds->ds_dkev->dk_kevent.filter) {
497 case DISPATCH_EVFILT_TIMER:
498 // called on manager queue only
499 return _dispatch_timer_list_update(ds);
500 case EVFILT_MACHPORT:
501 if (ds->ds_pending_data_mask & DISPATCH_MACH_RECV_MESSAGE) {
502 new_flags |= DISPATCH_MACH_RECV_MESSAGE; // emulate EV_DISPATCH
503 }
504 break;
505 }
506 if (_dispatch_kevent_resume(ds->ds_dkev, new_flags, 0)) {
507 _dispatch_kevent_unregister(ds);
508 }
509 }
510
511 static dispatch_queue_t
512 _dispatch_source_invoke(dispatch_source_t ds)
513 {
514 // This function performs all source actions. Each action is responsible
515 // for verifying that it takes place on the appropriate queue. If the
516 // current queue is not the correct queue for this action, the correct queue
517 // will be returned and the invoke will be re-driven on that queue.
518
519 // The order of tests here in invoke and in probe should be consistent.
520
521 dispatch_queue_t dq = _dispatch_queue_get_current();
522 dispatch_source_refs_t dr = ds->ds_refs;
523
524 if (!ds->ds_is_installed) {
525 // The source needs to be installed on the manager queue.
526 if (dq != &_dispatch_mgr_q) {
527 return &_dispatch_mgr_q;
528 }
529 _dispatch_kevent_register(ds);
530 if (dr->ds_registration_handler) {
531 return ds->do_targetq;
532 }
533 if (slowpath(ds->do_xref_cnt == 0)) {
534 return &_dispatch_mgr_q; // rdar://problem/9558246
535 }
536 } else if (slowpath(DISPATCH_OBJECT_SUSPENDED(ds))) {
537 // Source suspended by an item drained from the source queue.
538 return NULL;
539 } else if (dr->ds_registration_handler) {
540 // The source has been registered and the registration handler needs
541 // to be delivered on the target queue.
542 if (dq != ds->do_targetq) {
543 return ds->do_targetq;
544 }
545 // clears ds_registration_handler
546 _dispatch_source_registration_callout(ds);
547 if (slowpath(ds->do_xref_cnt == 0)) {
548 return &_dispatch_mgr_q; // rdar://problem/9558246
549 }
550 } else if ((ds->ds_atomic_flags & DSF_CANCELED) || (ds->do_xref_cnt == 0)) {
551 // The source has been cancelled and needs to be uninstalled from the
552 // manager queue. After uninstallation, the cancellation handler needs
553 // to be delivered to the target queue.
554 if (ds->ds_dkev) {
555 if (dq != &_dispatch_mgr_q) {
556 return &_dispatch_mgr_q;
557 }
558 _dispatch_kevent_unregister(ds);
559 return ds->do_targetq;
560 } else if (dr->ds_cancel_handler) {
561 if (dq != ds->do_targetq) {
562 return ds->do_targetq;
563 }
564 }
565 _dispatch_source_cancel_callout(ds);
566 } else if (ds->ds_pending_data) {
567 // The source has pending data to deliver via the event handler callback
568 // on the target queue. Some sources need to be rearmed on the manager
569 // queue after event delivery.
570 if (dq != ds->do_targetq) {
571 return ds->do_targetq;
572 }
573 _dispatch_source_latch_and_call(ds);
574 if (ds->ds_needs_rearm) {
575 return &_dispatch_mgr_q;
576 }
577 } else if (ds->ds_needs_rearm && !(ds->ds_atomic_flags & DSF_ARMED)) {
578 // The source needs to be rearmed on the manager queue.
579 if (dq != &_dispatch_mgr_q) {
580 return &_dispatch_mgr_q;
581 }
582 _dispatch_source_kevent_resume(ds, 0);
583 (void)dispatch_atomic_or2o(ds, ds_atomic_flags, DSF_ARMED);
584 }
585
586 return NULL;
587 }
588
589 static bool
590 _dispatch_source_probe(dispatch_source_t ds)
591 {
592 // This function determines whether the source needs to be invoked.
593 // The order of tests here in probe and in invoke should be consistent.
594
595 dispatch_source_refs_t dr = ds->ds_refs;
596 if (!ds->ds_is_installed) {
597 // The source needs to be installed on the manager queue.
598 return true;
599 } else if (dr->ds_registration_handler) {
600 // The registration handler needs to be delivered to the target queue.
601 return true;
602 } else if ((ds->ds_atomic_flags & DSF_CANCELED) || (ds->do_xref_cnt == 0)) {
603 // The source needs to be uninstalled from the manager queue, or the
604 // cancellation handler needs to be delivered to the target queue.
605 // Note: cancellation assumes installation.
606 if (ds->ds_dkev || dr->ds_cancel_handler) {
607 return true;
608 }
609 } else if (ds->ds_pending_data) {
610 // The source has pending data to deliver to the target queue.
611 return true;
612 } else if (ds->ds_needs_rearm && !(ds->ds_atomic_flags & DSF_ARMED)) {
613 // The source needs to be rearmed on the manager queue.
614 return true;
615 }
616 // Nothing to do.
617 return false;
618 }
619
620 #pragma mark -
621 #pragma mark dispatch_source_kevent
622
623 static void
624 _dispatch_source_merge_kevent(dispatch_source_t ds, const struct kevent *ke)
625 {
626 struct kevent fake;
627
628 if ((ds->ds_atomic_flags & DSF_CANCELED) || (ds->do_xref_cnt == 0)) {
629 return;
630 }
631
632 // EVFILT_PROC may fail with ESRCH when the process exists but is a zombie
633 // <rdar://problem/5067725>. As a workaround, we simulate an exit event for
634 // any EVFILT_PROC with an invalid pid <rdar://problem/6626350>.
635 if (ke->flags & EV_ERROR) {
636 if (ke->filter == EVFILT_PROC && ke->data == ESRCH) {
637 fake = *ke;
638 fake.flags &= ~EV_ERROR;
639 fake.fflags = NOTE_EXIT;
640 fake.data = 0;
641 ke = &fake;
642 #if DISPATCH_USE_VM_PRESSURE
643 } else if (ke->filter == EVFILT_VM && ke->data == ENOTSUP) {
644 // Memory pressure kevent is not supported on all platforms
645 // <rdar://problem/8636227>
646 return;
647 #endif
648 } else {
649 // log the unexpected error
650 (void)dispatch_assume_zero(ke->data);
651 return;
652 }
653 }
654
655 if (ds->ds_is_level) {
656 // ke->data is signed and "negative available data" makes no sense
657 // zero bytes happens when EV_EOF is set
658 // 10A268 does not fail this assert with EVFILT_READ and a 10 GB file
659 dispatch_assert(ke->data >= 0l);
660 ds->ds_pending_data = ~ke->data;
661 } else if (ds->ds_is_adder) {
662 (void)dispatch_atomic_add2o(ds, ds_pending_data, ke->data);
663 } else if (ke->fflags & ds->ds_pending_data_mask) {
664 (void)dispatch_atomic_or2o(ds, ds_pending_data,
665 ke->fflags & ds->ds_pending_data_mask);
666 }
667
668 // EV_DISPATCH and EV_ONESHOT sources are no longer armed after delivery
669 if (ds->ds_needs_rearm) {
670 (void)dispatch_atomic_and2o(ds, ds_atomic_flags, ~DSF_ARMED);
671 }
672
673 _dispatch_wakeup(ds);
674 }
675
676 void
677 _dispatch_source_drain_kevent(struct kevent *ke)
678 {
679 dispatch_kevent_t dk = ke->udata;
680 dispatch_source_refs_t dri;
681
682 #if DISPATCH_DEBUG
683 static dispatch_once_t pred;
684 dispatch_once_f(&pred, NULL, _dispatch_kevent_debugger);
685 #endif
686
687 dispatch_debug_kevents(ke, 1, __func__);
688
689 #if HAVE_MACH
690 if (ke->filter == EVFILT_MACHPORT) {
691 return _dispatch_drain_mach_messages(ke);
692 }
693 #endif
694 dispatch_assert(dk);
695
696 if (ke->flags & EV_ONESHOT) {
697 dk->dk_kevent.flags |= EV_ONESHOT;
698 }
699
700 TAILQ_FOREACH(dri, &dk->dk_sources, dr_list) {
701 _dispatch_source_merge_kevent(_dispatch_source_from_refs(dri), ke);
702 }
703 }
704
705 #pragma mark -
706 #pragma mark dispatch_kevent_t
707
708 static struct dispatch_kevent_s _dispatch_kevent_data_or = {
709 .dk_kevent = {
710 .filter = DISPATCH_EVFILT_CUSTOM_OR,
711 .flags = EV_CLEAR,
712 .udata = &_dispatch_kevent_data_or,
713 },
714 .dk_sources = TAILQ_HEAD_INITIALIZER(_dispatch_kevent_data_or.dk_sources),
715 };
716 static struct dispatch_kevent_s _dispatch_kevent_data_add = {
717 .dk_kevent = {
718 .filter = DISPATCH_EVFILT_CUSTOM_ADD,
719 .udata = &_dispatch_kevent_data_add,
720 },
721 .dk_sources = TAILQ_HEAD_INITIALIZER(_dispatch_kevent_data_add.dk_sources),
722 };
723
724 #if TARGET_OS_EMBEDDED
725 #define DSL_HASH_SIZE 64u // must be a power of two
726 #else
727 #define DSL_HASH_SIZE 256u // must be a power of two
728 #endif
729 #define DSL_HASH(x) ((x) & (DSL_HASH_SIZE - 1))
730
731 DISPATCH_CACHELINE_ALIGN
732 static TAILQ_HEAD(, dispatch_kevent_s) _dispatch_sources[DSL_HASH_SIZE];
733
734 static dispatch_once_t __dispatch_kevent_init_pred;
735
736 static void
737 _dispatch_kevent_init(void *context DISPATCH_UNUSED)
738 {
739 unsigned int i;
740 for (i = 0; i < DSL_HASH_SIZE; i++) {
741 TAILQ_INIT(&_dispatch_sources[i]);
742 }
743
744 TAILQ_INSERT_TAIL(&_dispatch_sources[0],
745 &_dispatch_kevent_data_or, dk_list);
746 TAILQ_INSERT_TAIL(&_dispatch_sources[0],
747 &_dispatch_kevent_data_add, dk_list);
748
749 _dispatch_source_timer_init();
750 }
751
752 static inline uintptr_t
753 _dispatch_kevent_hash(uintptr_t ident, short filter)
754 {
755 uintptr_t value;
756 #if HAVE_MACH
757 value = (filter == EVFILT_MACHPORT ? MACH_PORT_INDEX(ident) : ident);
758 #else
759 value = ident;
760 #endif
761 return DSL_HASH(value);
762 }
763
764 static dispatch_kevent_t
765 _dispatch_kevent_find(uintptr_t ident, short filter)
766 {
767 uintptr_t hash = _dispatch_kevent_hash(ident, filter);
768 dispatch_kevent_t dki;
769
770 TAILQ_FOREACH(dki, &_dispatch_sources[hash], dk_list) {
771 if (dki->dk_kevent.ident == ident && dki->dk_kevent.filter == filter) {
772 break;
773 }
774 }
775 return dki;
776 }
777
778 static void
779 _dispatch_kevent_insert(dispatch_kevent_t dk)
780 {
781 uintptr_t hash = _dispatch_kevent_hash(dk->dk_kevent.ident,
782 dk->dk_kevent.filter);
783
784 TAILQ_INSERT_TAIL(&_dispatch_sources[hash], dk, dk_list);
785 }
786
787 // Find existing kevents, and merge any new flags if necessary
788 static void
789 _dispatch_kevent_register(dispatch_source_t ds)
790 {
791 dispatch_kevent_t dk;
792 typeof(dk->dk_kevent.fflags) new_flags;
793 bool do_resume = false;
794
795 if (ds->ds_is_installed) {
796 return;
797 }
798 ds->ds_is_installed = true;
799
800 dispatch_once_f(&__dispatch_kevent_init_pred,
801 NULL, _dispatch_kevent_init);
802
803 dk = _dispatch_kevent_find(ds->ds_dkev->dk_kevent.ident,
804 ds->ds_dkev->dk_kevent.filter);
805
806 if (dk) {
807 // If an existing dispatch kevent is found, check to see if new flags
808 // need to be added to the existing kevent
809 new_flags = ~dk->dk_kevent.fflags & ds->ds_dkev->dk_kevent.fflags;
810 dk->dk_kevent.fflags |= ds->ds_dkev->dk_kevent.fflags;
811 free(ds->ds_dkev);
812 ds->ds_dkev = dk;
813 do_resume = new_flags;
814 } else {
815 dk = ds->ds_dkev;
816 _dispatch_kevent_insert(dk);
817 new_flags = dk->dk_kevent.fflags;
818 do_resume = true;
819 }
820
821 TAILQ_INSERT_TAIL(&dk->dk_sources, ds->ds_refs, dr_list);
822
823 // Re-register the kevent with the kernel if new flags were added
824 // by the dispatch kevent
825 if (do_resume) {
826 dk->dk_kevent.flags |= EV_ADD;
827 }
828 if (do_resume || ds->ds_needs_rearm) {
829 _dispatch_source_kevent_resume(ds, new_flags);
830 }
831 (void)dispatch_atomic_or2o(ds, ds_atomic_flags, DSF_ARMED);
832 }
833
834 static bool
835 _dispatch_kevent_resume(dispatch_kevent_t dk, uint32_t new_flags,
836 uint32_t del_flags)
837 {
838 long r;
839 switch (dk->dk_kevent.filter) {
840 case DISPATCH_EVFILT_TIMER:
841 case DISPATCH_EVFILT_CUSTOM_ADD:
842 case DISPATCH_EVFILT_CUSTOM_OR:
843 // these types not registered with kevent
844 return 0;
845 #if HAVE_MACH
846 case EVFILT_MACHPORT:
847 return _dispatch_kevent_machport_resume(dk, new_flags, del_flags);
848 #endif
849 case EVFILT_PROC:
850 if (dk->dk_kevent.flags & EV_ONESHOT) {
851 return 0;
852 }
853 // fall through
854 default:
855 r = _dispatch_update_kq(&dk->dk_kevent);
856 if (dk->dk_kevent.flags & EV_DISPATCH) {
857 dk->dk_kevent.flags &= ~EV_ADD;
858 }
859 return r;
860 }
861 }
862
863 static void
864 _dispatch_kevent_dispose(dispatch_kevent_t dk)
865 {
866 uintptr_t hash;
867
868 switch (dk->dk_kevent.filter) {
869 case DISPATCH_EVFILT_TIMER:
870 case DISPATCH_EVFILT_CUSTOM_ADD:
871 case DISPATCH_EVFILT_CUSTOM_OR:
872 // these sources live on statically allocated lists
873 return;
874 #if HAVE_MACH
875 case EVFILT_MACHPORT:
876 _dispatch_kevent_machport_resume(dk, 0, dk->dk_kevent.fflags);
877 break;
878 #endif
879 case EVFILT_PROC:
880 if (dk->dk_kevent.flags & EV_ONESHOT) {
881 break; // implicitly deleted
882 }
883 // fall through
884 default:
885 if (~dk->dk_kevent.flags & EV_DELETE) {
886 dk->dk_kevent.flags |= EV_DELETE;
887 _dispatch_update_kq(&dk->dk_kevent);
888 }
889 break;
890 }
891
892 hash = _dispatch_kevent_hash(dk->dk_kevent.ident,
893 dk->dk_kevent.filter);
894 TAILQ_REMOVE(&_dispatch_sources[hash], dk, dk_list);
895 free(dk);
896 }
897
898 static void
899 _dispatch_kevent_unregister(dispatch_source_t ds)
900 {
901 dispatch_kevent_t dk = ds->ds_dkev;
902 dispatch_source_refs_t dri;
903 uint32_t del_flags, fflags = 0;
904
905 ds->ds_dkev = NULL;
906
907 TAILQ_REMOVE(&dk->dk_sources, ds->ds_refs, dr_list);
908
909 if (TAILQ_EMPTY(&dk->dk_sources)) {
910 _dispatch_kevent_dispose(dk);
911 } else {
912 TAILQ_FOREACH(dri, &dk->dk_sources, dr_list) {
913 dispatch_source_t dsi = _dispatch_source_from_refs(dri);
914 fflags |= (uint32_t)dsi->ds_pending_data_mask;
915 }
916 del_flags = (uint32_t)ds->ds_pending_data_mask & ~fflags;
917 if (del_flags) {
918 dk->dk_kevent.flags |= EV_ADD;
919 dk->dk_kevent.fflags = fflags;
920 _dispatch_kevent_resume(dk, 0, del_flags);
921 }
922 }
923
924 (void)dispatch_atomic_and2o(ds, ds_atomic_flags, ~DSF_ARMED);
925 ds->ds_needs_rearm = false; // re-arm is pointless and bad now
926 _dispatch_release(ds); // the retain is done at creation time
927 }
928
929 #pragma mark -
930 #pragma mark dispatch_timer
931
932 DISPATCH_CACHELINE_ALIGN
933 static struct dispatch_kevent_s _dispatch_kevent_timer[] = {
934 [DISPATCH_TIMER_INDEX_WALL] = {
935 .dk_kevent = {
936 .ident = DISPATCH_TIMER_INDEX_WALL,
937 .filter = DISPATCH_EVFILT_TIMER,
938 .udata = &_dispatch_kevent_timer[DISPATCH_TIMER_INDEX_WALL],
939 },
940 .dk_sources = TAILQ_HEAD_INITIALIZER(
941 _dispatch_kevent_timer[DISPATCH_TIMER_INDEX_WALL].dk_sources),
942 },
943 [DISPATCH_TIMER_INDEX_MACH] = {
944 .dk_kevent = {
945 .ident = DISPATCH_TIMER_INDEX_MACH,
946 .filter = DISPATCH_EVFILT_TIMER,
947 .udata = &_dispatch_kevent_timer[DISPATCH_TIMER_INDEX_MACH],
948 },
949 .dk_sources = TAILQ_HEAD_INITIALIZER(
950 _dispatch_kevent_timer[DISPATCH_TIMER_INDEX_MACH].dk_sources),
951 },
952 [DISPATCH_TIMER_INDEX_DISARM] = {
953 .dk_kevent = {
954 .ident = DISPATCH_TIMER_INDEX_DISARM,
955 .filter = DISPATCH_EVFILT_TIMER,
956 .udata = &_dispatch_kevent_timer[DISPATCH_TIMER_INDEX_DISARM],
957 },
958 .dk_sources = TAILQ_HEAD_INITIALIZER(
959 _dispatch_kevent_timer[DISPATCH_TIMER_INDEX_DISARM].dk_sources),
960 },
961 };
962 // Don't count disarmed timer list
963 #define DISPATCH_TIMER_COUNT ((sizeof(_dispatch_kevent_timer) \
964 / sizeof(_dispatch_kevent_timer[0])) - 1)
965
966 static inline void
967 _dispatch_source_timer_init(void)
968 {
969 TAILQ_INSERT_TAIL(&_dispatch_sources[DSL_HASH(DISPATCH_TIMER_INDEX_WALL)],
970 &_dispatch_kevent_timer[DISPATCH_TIMER_INDEX_WALL], dk_list);
971 TAILQ_INSERT_TAIL(&_dispatch_sources[DSL_HASH(DISPATCH_TIMER_INDEX_MACH)],
972 &_dispatch_kevent_timer[DISPATCH_TIMER_INDEX_MACH], dk_list);
973 TAILQ_INSERT_TAIL(&_dispatch_sources[DSL_HASH(DISPATCH_TIMER_INDEX_DISARM)],
974 &_dispatch_kevent_timer[DISPATCH_TIMER_INDEX_DISARM], dk_list);
975 }
976
977 DISPATCH_ALWAYS_INLINE
978 static inline unsigned int
979 _dispatch_source_timer_idx(dispatch_source_refs_t dr)
980 {
981 return ds_timer(dr).flags & DISPATCH_TIMER_WALL_CLOCK ?
982 DISPATCH_TIMER_INDEX_WALL : DISPATCH_TIMER_INDEX_MACH;
983 }
984
985 DISPATCH_ALWAYS_INLINE
986 static inline uint64_t
987 _dispatch_source_timer_now2(unsigned int timer)
988 {
989 switch (timer) {
990 case DISPATCH_TIMER_INDEX_MACH:
991 return _dispatch_absolute_time();
992 case DISPATCH_TIMER_INDEX_WALL:
993 return _dispatch_get_nanoseconds();
994 default:
995 DISPATCH_CRASH("Invalid timer");
996 }
997 }
998
999 DISPATCH_ALWAYS_INLINE
1000 static inline uint64_t
1001 _dispatch_source_timer_now(dispatch_source_refs_t dr)
1002 {
1003 return _dispatch_source_timer_now2(_dispatch_source_timer_idx(dr));
1004 }
1005
1006 // Updates the ordered list of timers based on next fire date for changes to ds.
1007 // Should only be called from the context of _dispatch_mgr_q.
1008 static void
1009 _dispatch_timer_list_update(dispatch_source_t ds)
1010 {
1011 dispatch_source_refs_t dr = ds->ds_refs, dri = NULL;
1012
1013 dispatch_assert(_dispatch_queue_get_current() == &_dispatch_mgr_q);
1014
1015 // do not reschedule timers unregistered with _dispatch_kevent_unregister()
1016 if (!ds->ds_dkev) {
1017 return;
1018 }
1019
1020 // Ensure the source is on the global kevent lists before it is removed and
1021 // readded below.
1022 _dispatch_kevent_register(ds);
1023
1024 TAILQ_REMOVE(&ds->ds_dkev->dk_sources, dr, dr_list);
1025
1026 // Move timers that are disabled, suspended or have missed intervals to the
1027 // disarmed list, rearm after resume resp. source invoke will reenable them
1028 if (!ds_timer(dr).target || DISPATCH_OBJECT_SUSPENDED(ds) ||
1029 ds->ds_pending_data) {
1030 (void)dispatch_atomic_and2o(ds, ds_atomic_flags, ~DSF_ARMED);
1031 ds->ds_dkev = &_dispatch_kevent_timer[DISPATCH_TIMER_INDEX_DISARM];
1032 TAILQ_INSERT_TAIL(&ds->ds_dkev->dk_sources, (dispatch_source_refs_t)dr,
1033 dr_list);
1034 return;
1035 }
1036
1037 // change the list if the clock type has changed
1038 ds->ds_dkev = &_dispatch_kevent_timer[_dispatch_source_timer_idx(dr)];
1039
1040 TAILQ_FOREACH(dri, &ds->ds_dkev->dk_sources, dr_list) {
1041 if (ds_timer(dri).target == 0 ||
1042 ds_timer(dr).target < ds_timer(dri).target) {
1043 break;
1044 }
1045 }
1046
1047 if (dri) {
1048 TAILQ_INSERT_BEFORE(dri, dr, dr_list);
1049 } else {
1050 TAILQ_INSERT_TAIL(&ds->ds_dkev->dk_sources, dr, dr_list);
1051 }
1052 }
1053
1054 static inline void
1055 _dispatch_run_timers2(unsigned int timer)
1056 {
1057 dispatch_source_refs_t dr;
1058 dispatch_source_t ds;
1059 uint64_t now, missed;
1060
1061 now = _dispatch_source_timer_now2(timer);
1062 while ((dr = TAILQ_FIRST(&_dispatch_kevent_timer[timer].dk_sources))) {
1063 ds = _dispatch_source_from_refs(dr);
1064 // We may find timers on the wrong list due to a pending update from
1065 // dispatch_source_set_timer. Force an update of the list in that case.
1066 if (timer != ds->ds_ident_hack) {
1067 _dispatch_timer_list_update(ds);
1068 continue;
1069 }
1070 if (!ds_timer(dr).target) {
1071 // no configured timers on the list
1072 break;
1073 }
1074 if (ds_timer(dr).target > now) {
1075 // Done running timers for now.
1076 break;
1077 }
1078 // Remove timers that are suspended or have missed intervals from the
1079 // list, rearm after resume resp. source invoke will reenable them
1080 if (DISPATCH_OBJECT_SUSPENDED(ds) || ds->ds_pending_data) {
1081 _dispatch_timer_list_update(ds);
1082 continue;
1083 }
1084 // Calculate number of missed intervals.
1085 missed = (now - ds_timer(dr).target) / ds_timer(dr).interval;
1086 if (++missed > INT_MAX) {
1087 missed = INT_MAX;
1088 }
1089 ds_timer(dr).target += missed * ds_timer(dr).interval;
1090 _dispatch_timer_list_update(ds);
1091 ds_timer(dr).last_fire = now;
1092 (void)dispatch_atomic_add2o(ds, ds_pending_data, (int)missed);
1093 _dispatch_wakeup(ds);
1094 }
1095 }
1096
1097 void
1098 _dispatch_run_timers(void)
1099 {
1100 dispatch_once_f(&__dispatch_kevent_init_pred,
1101 NULL, _dispatch_kevent_init);
1102
1103 unsigned int i;
1104 for (i = 0; i < DISPATCH_TIMER_COUNT; i++) {
1105 if (!TAILQ_EMPTY(&_dispatch_kevent_timer[i].dk_sources)) {
1106 _dispatch_run_timers2(i);
1107 }
1108 }
1109 }
1110
1111 static inline unsigned long
1112 _dispatch_source_timer_data(dispatch_source_refs_t dr, unsigned long prev)
1113 {
1114 // calculate the number of intervals since last fire
1115 unsigned long data, missed;
1116 uint64_t now = _dispatch_source_timer_now(dr);
1117 missed = (unsigned long)((now - ds_timer(dr).last_fire) /
1118 ds_timer(dr).interval);
1119 // correct for missed intervals already delivered last time
1120 data = prev - ds_timer(dr).missed + missed;
1121 ds_timer(dr).missed = missed;
1122 return data;
1123 }
1124
1125 // approx 1 year (60s * 60m * 24h * 365d)
1126 #define FOREVER_NSEC 31536000000000000ull
1127
1128 struct timespec *
1129 _dispatch_get_next_timer_fire(struct timespec *howsoon)
1130 {
1131 // <rdar://problem/6459649>
1132 // kevent(2) does not allow large timeouts, so we use a long timeout
1133 // instead (approximately 1 year).
1134 dispatch_source_refs_t dr = NULL;
1135 unsigned int timer;
1136 uint64_t now, delta_tmp, delta = UINT64_MAX;
1137
1138 for (timer = 0; timer < DISPATCH_TIMER_COUNT; timer++) {
1139 // Timers are kept in order, first one will fire next
1140 dr = TAILQ_FIRST(&_dispatch_kevent_timer[timer].dk_sources);
1141 if (!dr || !ds_timer(dr).target) {
1142 // Empty list or disabled timer
1143 continue;
1144 }
1145 now = _dispatch_source_timer_now(dr);
1146 if (ds_timer(dr).target <= now) {
1147 howsoon->tv_sec = 0;
1148 howsoon->tv_nsec = 0;
1149 return howsoon;
1150 }
1151 // the subtraction cannot go negative because the previous "if"
1152 // verified that the target is greater than now.
1153 delta_tmp = ds_timer(dr).target - now;
1154 if (!(ds_timer(dr).flags & DISPATCH_TIMER_WALL_CLOCK)) {
1155 delta_tmp = _dispatch_time_mach2nano(delta_tmp);
1156 }
1157 if (delta_tmp < delta) {
1158 delta = delta_tmp;
1159 }
1160 }
1161 if (slowpath(delta > FOREVER_NSEC)) {
1162 return NULL;
1163 } else {
1164 howsoon->tv_sec = (time_t)(delta / NSEC_PER_SEC);
1165 howsoon->tv_nsec = (long)(delta % NSEC_PER_SEC);
1166 }
1167 return howsoon;
1168 }
1169
1170 struct dispatch_set_timer_params {
1171 dispatch_source_t ds;
1172 uintptr_t ident;
1173 struct dispatch_timer_source_s values;
1174 };
1175
1176 static void
1177 _dispatch_source_set_timer3(void *context)
1178 {
1179 // Called on the _dispatch_mgr_q
1180 struct dispatch_set_timer_params *params = context;
1181 dispatch_source_t ds = params->ds;
1182 ds->ds_ident_hack = params->ident;
1183 ds_timer(ds->ds_refs) = params->values;
1184 // Clear any pending data that might have accumulated on
1185 // older timer params <rdar://problem/8574886>
1186 ds->ds_pending_data = 0;
1187 _dispatch_timer_list_update(ds);
1188 dispatch_resume(ds);
1189 dispatch_release(ds);
1190 free(params);
1191 }
1192
1193 static void
1194 _dispatch_source_set_timer2(void *context)
1195 {
1196 // Called on the source queue
1197 struct dispatch_set_timer_params *params = context;
1198 dispatch_suspend(params->ds);
1199 dispatch_barrier_async_f(&_dispatch_mgr_q, params,
1200 _dispatch_source_set_timer3);
1201 }
1202
1203 void
1204 dispatch_source_set_timer(dispatch_source_t ds,
1205 dispatch_time_t start,
1206 uint64_t interval,
1207 uint64_t leeway)
1208 {
1209 if (slowpath(!ds->ds_is_timer)) {
1210 DISPATCH_CLIENT_CRASH("Attempt to set timer on a non-timer source");
1211 }
1212
1213 struct dispatch_set_timer_params *params;
1214
1215 // we use zero internally to mean disabled
1216 if (interval == 0) {
1217 interval = 1;
1218 } else if ((int64_t)interval < 0) {
1219 // 6866347 - make sure nanoseconds won't overflow
1220 interval = INT64_MAX;
1221 }
1222 if ((int64_t)leeway < 0) {
1223 leeway = INT64_MAX;
1224 }
1225
1226 if (start == DISPATCH_TIME_NOW) {
1227 start = _dispatch_absolute_time();
1228 } else if (start == DISPATCH_TIME_FOREVER) {
1229 start = INT64_MAX;
1230 }
1231
1232 while (!(params = calloc(1ul, sizeof(struct dispatch_set_timer_params)))) {
1233 sleep(1);
1234 }
1235
1236 params->ds = ds;
1237 params->values.flags = ds_timer(ds->ds_refs).flags;
1238
1239 if ((int64_t)start < 0) {
1240 // wall clock
1241 params->ident = DISPATCH_TIMER_INDEX_WALL;
1242 params->values.target = -((int64_t)start);
1243 params->values.interval = interval;
1244 params->values.leeway = leeway;
1245 params->values.flags |= DISPATCH_TIMER_WALL_CLOCK;
1246 } else {
1247 // absolute clock
1248 params->ident = DISPATCH_TIMER_INDEX_MACH;
1249 params->values.target = start;
1250 params->values.interval = _dispatch_time_nano2mach(interval);
1251
1252 // rdar://problem/7287561 interval must be at least one in
1253 // in order to avoid later division by zero when calculating
1254 // the missed interval count. (NOTE: the wall clock's
1255 // interval is already "fixed" to be 1 or more)
1256 if (params->values.interval < 1) {
1257 params->values.interval = 1;
1258 }
1259
1260 params->values.leeway = _dispatch_time_nano2mach(leeway);
1261 params->values.flags &= ~DISPATCH_TIMER_WALL_CLOCK;
1262 }
1263 // Suspend the source so that it doesn't fire with pending changes
1264 // The use of suspend/resume requires the external retain/release
1265 dispatch_retain(ds);
1266 dispatch_barrier_async_f((dispatch_queue_t)ds, params,
1267 _dispatch_source_set_timer2);
1268 }
1269
1270 #pragma mark -
1271 #pragma mark dispatch_mach
1272
1273 #if HAVE_MACH
1274
1275 #if DISPATCH_DEBUG && DISPATCH_MACHPORT_DEBUG
1276 #define _dispatch_debug_machport(name) \
1277 dispatch_debug_machport((name), __func__)
1278 #else
1279 #define _dispatch_debug_machport(name)
1280 #endif
1281
1282 // Flags for all notifications that are registered/unregistered when a
1283 // send-possible notification is requested/delivered
1284 #define _DISPATCH_MACH_SP_FLAGS (DISPATCH_MACH_SEND_POSSIBLE| \
1285 DISPATCH_MACH_SEND_DEAD|DISPATCH_MACH_SEND_DELETED)
1286
1287 #define _DISPATCH_IS_POWER_OF_TWO(v) (!(v & (v - 1)) && v)
1288 #define _DISPATCH_HASH(x, y) (_DISPATCH_IS_POWER_OF_TWO(y) ? \
1289 (MACH_PORT_INDEX(x) & ((y) - 1)) : (MACH_PORT_INDEX(x) % (y)))
1290
1291 #define _DISPATCH_MACHPORT_HASH_SIZE 32
1292 #define _DISPATCH_MACHPORT_HASH(x) \
1293 _DISPATCH_HASH((x), _DISPATCH_MACHPORT_HASH_SIZE)
1294
1295 static dispatch_source_t _dispatch_mach_notify_source;
1296 static mach_port_t _dispatch_port_set;
1297 static mach_port_t _dispatch_event_port;
1298
1299 static kern_return_t _dispatch_mach_notify_update(dispatch_kevent_t dk,
1300 uint32_t new_flags, uint32_t del_flags, uint32_t mask,
1301 mach_msg_id_t notify_msgid, mach_port_mscount_t notify_sync);
1302
1303 static void
1304 _dispatch_port_set_init(void *context DISPATCH_UNUSED)
1305 {
1306 struct kevent kev = {
1307 .filter = EVFILT_MACHPORT,
1308 .flags = EV_ADD,
1309 };
1310 kern_return_t kr;
1311
1312 kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_PORT_SET,
1313 &_dispatch_port_set);
1314 DISPATCH_VERIFY_MIG(kr);
1315 if (kr) {
1316 _dispatch_bug_mach_client(
1317 "_dispatch_port_set_init: mach_port_allocate() failed", kr);
1318 DISPATCH_CLIENT_CRASH(
1319 "mach_port_allocate() failed: cannot create port set");
1320 }
1321 kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE,
1322 &_dispatch_event_port);
1323 DISPATCH_VERIFY_MIG(kr);
1324 if (kr) {
1325 _dispatch_bug_mach_client(
1326 "_dispatch_port_set_init: mach_port_allocate() failed", kr);
1327 DISPATCH_CLIENT_CRASH(
1328 "mach_port_allocate() failed: cannot create receive right");
1329 }
1330 kr = mach_port_move_member(mach_task_self(), _dispatch_event_port,
1331 _dispatch_port_set);
1332 DISPATCH_VERIFY_MIG(kr);
1333 if (kr) {
1334 _dispatch_bug_mach_client(
1335 "_dispatch_port_set_init: mach_port_move_member() failed", kr);
1336 DISPATCH_CLIENT_CRASH("mach_port_move_member() failed");
1337 }
1338
1339 kev.ident = _dispatch_port_set;
1340
1341 _dispatch_update_kq(&kev);
1342 }
1343
1344 static mach_port_t
1345 _dispatch_get_port_set(void)
1346 {
1347 static dispatch_once_t pred;
1348
1349 dispatch_once_f(&pred, NULL, _dispatch_port_set_init);
1350
1351 return _dispatch_port_set;
1352 }
1353
1354 static kern_return_t
1355 _dispatch_kevent_machport_enable(dispatch_kevent_t dk)
1356 {
1357 mach_port_t mp = (mach_port_t)dk->dk_kevent.ident;
1358 kern_return_t kr;
1359
1360 _dispatch_debug_machport(mp);
1361 kr = mach_port_move_member(mach_task_self(), mp, _dispatch_get_port_set());
1362 if (slowpath(kr)) {
1363 DISPATCH_VERIFY_MIG(kr);
1364 switch (kr) {
1365 case KERN_INVALID_NAME:
1366 #if DISPATCH_DEBUG
1367 _dispatch_log("Corruption: Mach receive right 0x%x destroyed "
1368 "prematurely", mp);
1369 #endif
1370 break;
1371 case KERN_INVALID_RIGHT:
1372 _dispatch_bug_mach_client("_dispatch_kevent_machport_enable: "
1373 "mach_port_move_member() failed ", kr);
1374 break;
1375 default:
1376 (void)dispatch_assume_zero(kr);
1377 break;
1378 }
1379 }
1380 return kr;
1381 }
1382
1383 static void
1384 _dispatch_kevent_machport_disable(dispatch_kevent_t dk)
1385 {
1386 mach_port_t mp = (mach_port_t)dk->dk_kevent.ident;
1387 kern_return_t kr;
1388
1389 _dispatch_debug_machport(mp);
1390 kr = mach_port_move_member(mach_task_self(), mp, 0);
1391 if (slowpath(kr)) {
1392 DISPATCH_VERIFY_MIG(kr);
1393 switch (kr) {
1394 case KERN_INVALID_RIGHT:
1395 case KERN_INVALID_NAME:
1396 #if DISPATCH_DEBUG
1397 _dispatch_log("Corruption: Mach receive right 0x%x destroyed "
1398 "prematurely", mp);
1399 #endif
1400 break;
1401 default:
1402 (void)dispatch_assume_zero(kr);
1403 break;
1404 }
1405 }
1406 }
1407
1408 kern_return_t
1409 _dispatch_kevent_machport_resume(dispatch_kevent_t dk, uint32_t new_flags,
1410 uint32_t del_flags)
1411 {
1412 kern_return_t kr_recv = 0, kr_sp = 0;
1413
1414 dispatch_assert_zero(new_flags & del_flags);
1415 if (new_flags & DISPATCH_MACH_RECV_MESSAGE) {
1416 kr_recv = _dispatch_kevent_machport_enable(dk);
1417 } else if (del_flags & DISPATCH_MACH_RECV_MESSAGE) {
1418 _dispatch_kevent_machport_disable(dk);
1419 }
1420 if ((new_flags & _DISPATCH_MACH_SP_FLAGS) ||
1421 (del_flags & _DISPATCH_MACH_SP_FLAGS)) {
1422 // Requesting a (delayed) non-sync send-possible notification
1423 // registers for both immediate dead-name notification and delayed-arm
1424 // send-possible notification for the port.
1425 // The send-possible notification is armed when a mach_msg() with the
1426 // the MACH_SEND_NOTIFY to the port times out.
1427 // If send-possible is unavailable, fall back to immediate dead-name
1428 // registration rdar://problem/2527840&9008724
1429 kr_sp = _dispatch_mach_notify_update(dk, new_flags, del_flags,
1430 _DISPATCH_MACH_SP_FLAGS, MACH_NOTIFY_SEND_POSSIBLE,
1431 MACH_NOTIFY_SEND_POSSIBLE == MACH_NOTIFY_DEAD_NAME ? 1 : 0);
1432 }
1433
1434 return (kr_recv ? kr_recv : kr_sp);
1435 }
1436
1437 void
1438 _dispatch_drain_mach_messages(struct kevent *ke)
1439 {
1440 mach_port_t name = (mach_port_name_t)ke->data;
1441 dispatch_source_refs_t dri;
1442 dispatch_kevent_t dk;
1443 struct kevent kev;
1444
1445 if (!dispatch_assume(name)) {
1446 return;
1447 }
1448 _dispatch_debug_machport(name);
1449 dk = _dispatch_kevent_find(name, EVFILT_MACHPORT);
1450 if (!dispatch_assume(dk)) {
1451 return;
1452 }
1453 _dispatch_kevent_machport_disable(dk); // emulate EV_DISPATCH
1454
1455 EV_SET(&kev, name, EVFILT_MACHPORT, EV_ADD|EV_ENABLE|EV_DISPATCH,
1456 DISPATCH_MACH_RECV_MESSAGE, 0, dk);
1457
1458 TAILQ_FOREACH(dri, &dk->dk_sources, dr_list) {
1459 _dispatch_source_merge_kevent(_dispatch_source_from_refs(dri), &kev);
1460 }
1461 }
1462
1463 static inline void
1464 _dispatch_mach_notify_merge(mach_port_t name, uint32_t flag, uint32_t unreg,
1465 bool final)
1466 {
1467 dispatch_source_refs_t dri;
1468 dispatch_kevent_t dk;
1469 struct kevent kev;
1470
1471 dk = _dispatch_kevent_find(name, EVFILT_MACHPORT);
1472 if (!dk) {
1473 return;
1474 }
1475
1476 // Update notification registration state.
1477 dk->dk_kevent.data &= ~unreg;
1478 if (!final) {
1479 // Re-register for notification before delivery
1480 _dispatch_kevent_resume(dk, flag, 0);
1481 }
1482
1483 EV_SET(&kev, name, EVFILT_MACHPORT, EV_ADD|EV_ENABLE, flag, 0, dk);
1484
1485 TAILQ_FOREACH(dri, &dk->dk_sources, dr_list) {
1486 _dispatch_source_merge_kevent(_dispatch_source_from_refs(dri), &kev);
1487 if (final) {
1488 // this can never happen again
1489 // this must happen after the merge
1490 // this may be racy in the future, but we don't provide a 'setter'
1491 // API for the mask yet
1492 _dispatch_source_from_refs(dri)->ds_pending_data_mask &= ~unreg;
1493 }
1494 }
1495
1496 if (final) {
1497 // no more sources have these flags
1498 dk->dk_kevent.fflags &= ~unreg;
1499 }
1500 }
1501
1502 static kern_return_t
1503 _dispatch_mach_notify_update(dispatch_kevent_t dk, uint32_t new_flags,
1504 uint32_t del_flags, uint32_t mask, mach_msg_id_t notify_msgid,
1505 mach_port_mscount_t notify_sync)
1506 {
1507 mach_port_t previous, port = (mach_port_t)dk->dk_kevent.ident;
1508 typeof(dk->dk_kevent.data) prev = dk->dk_kevent.data;
1509 kern_return_t kr, krr = 0;
1510
1511 // Update notification registration state.
1512 dk->dk_kevent.data |= (new_flags | dk->dk_kevent.fflags) & mask;
1513 dk->dk_kevent.data &= ~(del_flags & mask);
1514
1515 _dispatch_debug_machport(port);
1516 if ((dk->dk_kevent.data & mask) && !(prev & mask)) {
1517 previous = MACH_PORT_NULL;
1518 krr = mach_port_request_notification(mach_task_self(), port,
1519 notify_msgid, notify_sync, _dispatch_event_port,
1520 MACH_MSG_TYPE_MAKE_SEND_ONCE, &previous);
1521 DISPATCH_VERIFY_MIG(krr);
1522
1523 switch(krr) {
1524 case KERN_INVALID_NAME:
1525 case KERN_INVALID_RIGHT:
1526 // Supress errors & clear registration state
1527 dk->dk_kevent.data &= ~mask;
1528 break;
1529 default:
1530 // Else, we dont expect any errors from mach. Log any errors
1531 if (dispatch_assume_zero(krr)) {
1532 // log the error & clear registration state
1533 dk->dk_kevent.data &= ~mask;
1534 } else if (dispatch_assume_zero(previous)) {
1535 // Another subsystem has beat libdispatch to requesting the
1536 // specified Mach notification on this port. We should
1537 // technically cache the previous port and message it when the
1538 // kernel messages our port. Or we can just say screw those
1539 // subsystems and deallocate the previous port.
1540 // They should adopt libdispatch :-P
1541 kr = mach_port_deallocate(mach_task_self(), previous);
1542 DISPATCH_VERIFY_MIG(kr);
1543 (void)dispatch_assume_zero(kr);
1544 previous = MACH_PORT_NULL;
1545 }
1546 }
1547 } else if (!(dk->dk_kevent.data & mask) && (prev & mask)) {
1548 previous = MACH_PORT_NULL;
1549 kr = mach_port_request_notification(mach_task_self(), port,
1550 notify_msgid, notify_sync, MACH_PORT_NULL,
1551 MACH_MSG_TYPE_MOVE_SEND_ONCE, &previous);
1552 DISPATCH_VERIFY_MIG(kr);
1553
1554 switch (kr) {
1555 case KERN_INVALID_NAME:
1556 case KERN_INVALID_RIGHT:
1557 case KERN_INVALID_ARGUMENT:
1558 break;
1559 default:
1560 if (dispatch_assume_zero(kr)) {
1561 // log the error
1562 }
1563 }
1564 } else {
1565 return 0;
1566 }
1567 if (slowpath(previous)) {
1568 // the kernel has not consumed the send-once right yet
1569 (void)dispatch_assume_zero(
1570 _dispatch_send_consume_send_once_right(previous));
1571 }
1572 return krr;
1573 }
1574
1575 static void
1576 _dispatch_mach_notify_source2(void *context)
1577 {
1578 dispatch_source_t ds = context;
1579 size_t maxsz = MAX(sizeof(union
1580 __RequestUnion___dispatch_send_libdispatch_internal_protocol_subsystem),
1581 sizeof(union
1582 __ReplyUnion___dispatch_libdispatch_internal_protocol_subsystem));
1583
1584 dispatch_mig_server(ds, maxsz, libdispatch_internal_protocol_server);
1585 }
1586
1587 void
1588 _dispatch_mach_notify_source_init(void *context DISPATCH_UNUSED)
1589 {
1590 _dispatch_get_port_set();
1591
1592 _dispatch_mach_notify_source = dispatch_source_create(
1593 DISPATCH_SOURCE_TYPE_MACH_RECV, _dispatch_event_port, 0,
1594 &_dispatch_mgr_q);
1595 dispatch_assert(_dispatch_mach_notify_source);
1596 dispatch_set_context(_dispatch_mach_notify_source,
1597 _dispatch_mach_notify_source);
1598 dispatch_source_set_event_handler_f(_dispatch_mach_notify_source,
1599 _dispatch_mach_notify_source2);
1600 dispatch_resume(_dispatch_mach_notify_source);
1601 }
1602
1603 kern_return_t
1604 _dispatch_mach_notify_port_deleted(mach_port_t notify DISPATCH_UNUSED,
1605 mach_port_name_t name)
1606 {
1607 #if DISPATCH_DEBUG
1608 _dispatch_log("Corruption: Mach send/send-once/dead-name right 0x%x "
1609 "deleted prematurely", name);
1610 #endif
1611
1612 _dispatch_debug_machport(name);
1613 _dispatch_mach_notify_merge(name, DISPATCH_MACH_SEND_DELETED,
1614 _DISPATCH_MACH_SP_FLAGS, true);
1615
1616 return KERN_SUCCESS;
1617 }
1618
1619 kern_return_t
1620 _dispatch_mach_notify_dead_name(mach_port_t notify DISPATCH_UNUSED,
1621 mach_port_name_t name)
1622 {
1623 kern_return_t kr;
1624
1625 #if DISPATCH_DEBUG
1626 _dispatch_log("machport[0x%08x]: dead-name notification: %s",
1627 name, __func__);
1628 #endif
1629 _dispatch_debug_machport(name);
1630 _dispatch_mach_notify_merge(name, DISPATCH_MACH_SEND_DEAD,
1631 _DISPATCH_MACH_SP_FLAGS, true);
1632
1633 // the act of receiving a dead name notification allocates a dead-name
1634 // right that must be deallocated
1635 kr = mach_port_deallocate(mach_task_self(), name);
1636 DISPATCH_VERIFY_MIG(kr);
1637 //(void)dispatch_assume_zero(kr);
1638
1639 return KERN_SUCCESS;
1640 }
1641
1642 kern_return_t
1643 _dispatch_mach_notify_send_possible(mach_port_t notify DISPATCH_UNUSED,
1644 mach_port_name_t name)
1645 {
1646 #if DISPATCH_DEBUG
1647 _dispatch_log("machport[0x%08x]: send-possible notification: %s",
1648 name, __func__);
1649 #endif
1650 _dispatch_debug_machport(name);
1651 _dispatch_mach_notify_merge(name, DISPATCH_MACH_SEND_POSSIBLE,
1652 _DISPATCH_MACH_SP_FLAGS, false);
1653
1654 return KERN_SUCCESS;
1655 }
1656
1657 mach_msg_return_t
1658 dispatch_mig_server(dispatch_source_t ds, size_t maxmsgsz,
1659 dispatch_mig_callback_t callback)
1660 {
1661 mach_msg_options_t options = MACH_RCV_MSG | MACH_RCV_TIMEOUT
1662 | MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_CTX)
1663 | MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0);
1664 mach_msg_options_t tmp_options;
1665 mig_reply_error_t *bufTemp, *bufRequest, *bufReply;
1666 mach_msg_return_t kr = 0;
1667 unsigned int cnt = 1000; // do not stall out serial queues
1668 int demux_success;
1669 bool received = false;
1670 size_t rcv_size = maxmsgsz + MAX_TRAILER_SIZE;
1671
1672 // XXX FIXME -- allocate these elsewhere
1673 bufRequest = alloca(rcv_size);
1674 bufReply = alloca(rcv_size);
1675 bufReply->Head.msgh_size = 0; // make CLANG happy
1676 bufRequest->RetCode = 0;
1677
1678 #if DISPATCH_DEBUG
1679 options |= MACH_RCV_LARGE; // rdar://problem/8422992
1680 #endif
1681 tmp_options = options;
1682 // XXX FIXME -- change this to not starve out the target queue
1683 for (;;) {
1684 if (DISPATCH_OBJECT_SUSPENDED(ds) || (--cnt == 0)) {
1685 options &= ~MACH_RCV_MSG;
1686 tmp_options &= ~MACH_RCV_MSG;
1687
1688 if (!(tmp_options & MACH_SEND_MSG)) {
1689 break;
1690 }
1691 }
1692 kr = mach_msg(&bufReply->Head, tmp_options, bufReply->Head.msgh_size,
1693 (mach_msg_size_t)rcv_size, (mach_port_t)ds->ds_ident_hack, 0,0);
1694
1695 tmp_options = options;
1696
1697 if (slowpath(kr)) {
1698 switch (kr) {
1699 case MACH_SEND_INVALID_DEST:
1700 case MACH_SEND_TIMED_OUT:
1701 if (bufReply->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) {
1702 mach_msg_destroy(&bufReply->Head);
1703 }
1704 break;
1705 case MACH_RCV_TIMED_OUT:
1706 // Don't return an error if a message was sent this time or
1707 // a message was successfully received previously
1708 // rdar://problems/7363620&7791738
1709 if(bufReply->Head.msgh_remote_port || received) {
1710 kr = MACH_MSG_SUCCESS;
1711 }
1712 break;
1713 case MACH_RCV_INVALID_NAME:
1714 break;
1715 #if DISPATCH_DEBUG
1716 case MACH_RCV_TOO_LARGE:
1717 // receive messages that are too large and log their id and size
1718 // rdar://problem/8422992
1719 tmp_options &= ~MACH_RCV_LARGE;
1720 size_t large_size = bufReply->Head.msgh_size + MAX_TRAILER_SIZE;
1721 void *large_buf = malloc(large_size);
1722 if (large_buf) {
1723 rcv_size = large_size;
1724 bufReply = large_buf;
1725 }
1726 if (!mach_msg(&bufReply->Head, tmp_options, 0,
1727 (mach_msg_size_t)rcv_size,
1728 (mach_port_t)ds->ds_ident_hack, 0, 0)) {
1729 _dispatch_log("BUG in libdispatch client: "
1730 "dispatch_mig_server received message larger than "
1731 "requested size %zd: id = 0x%x, size = %d",
1732 maxmsgsz, bufReply->Head.msgh_id,
1733 bufReply->Head.msgh_size);
1734 }
1735 if (large_buf) {
1736 free(large_buf);
1737 }
1738 // fall through
1739 #endif
1740 default:
1741 _dispatch_bug_mach_client(
1742 "dispatch_mig_server: mach_msg() failed", kr);
1743 break;
1744 }
1745 break;
1746 }
1747
1748 if (!(tmp_options & MACH_RCV_MSG)) {
1749 break;
1750 }
1751 received = true;
1752
1753 bufTemp = bufRequest;
1754 bufRequest = bufReply;
1755 bufReply = bufTemp;
1756
1757 demux_success = callback(&bufRequest->Head, &bufReply->Head);
1758
1759 if (!demux_success) {
1760 // destroy the request - but not the reply port
1761 bufRequest->Head.msgh_remote_port = 0;
1762 mach_msg_destroy(&bufRequest->Head);
1763 } else if (!(bufReply->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX)) {
1764 // if MACH_MSGH_BITS_COMPLEX is _not_ set, then bufReply->RetCode
1765 // is present
1766 if (slowpath(bufReply->RetCode)) {
1767 if (bufReply->RetCode == MIG_NO_REPLY) {
1768 continue;
1769 }
1770
1771 // destroy the request - but not the reply port
1772 bufRequest->Head.msgh_remote_port = 0;
1773 mach_msg_destroy(&bufRequest->Head);
1774 }
1775 }
1776
1777 if (bufReply->Head.msgh_remote_port) {
1778 tmp_options |= MACH_SEND_MSG;
1779 if (MACH_MSGH_BITS_REMOTE(bufReply->Head.msgh_bits) !=
1780 MACH_MSG_TYPE_MOVE_SEND_ONCE) {
1781 tmp_options |= MACH_SEND_TIMEOUT;
1782 }
1783 }
1784 }
1785
1786 return kr;
1787 }
1788
1789 #endif /* HAVE_MACH */
1790
1791 #pragma mark -
1792 #pragma mark dispatch_source_debug
1793
1794 DISPATCH_NOINLINE
1795 static const char *
1796 _evfiltstr(short filt)
1797 {
1798 switch (filt) {
1799 #define _evfilt2(f) case (f): return #f
1800 _evfilt2(EVFILT_READ);
1801 _evfilt2(EVFILT_WRITE);
1802 _evfilt2(EVFILT_AIO);
1803 _evfilt2(EVFILT_VNODE);
1804 _evfilt2(EVFILT_PROC);
1805 _evfilt2(EVFILT_SIGNAL);
1806 _evfilt2(EVFILT_TIMER);
1807 #ifdef EVFILT_VM
1808 _evfilt2(EVFILT_VM);
1809 #endif
1810 #if HAVE_MACH
1811 _evfilt2(EVFILT_MACHPORT);
1812 #endif
1813 _evfilt2(EVFILT_FS);
1814 _evfilt2(EVFILT_USER);
1815
1816 _evfilt2(DISPATCH_EVFILT_TIMER);
1817 _evfilt2(DISPATCH_EVFILT_CUSTOM_ADD);
1818 _evfilt2(DISPATCH_EVFILT_CUSTOM_OR);
1819 default:
1820 return "EVFILT_missing";
1821 }
1822 }
1823
1824 static size_t
1825 _dispatch_source_debug_attr(dispatch_source_t ds, char* buf, size_t bufsiz)
1826 {
1827 dispatch_queue_t target = ds->do_targetq;
1828 return snprintf(buf, bufsiz, "target = %s[%p], pending_data = 0x%lx, "
1829 "pending_data_mask = 0x%lx, ",
1830 target ? target->dq_label : "", target,
1831 ds->ds_pending_data, ds->ds_pending_data_mask);
1832 }
1833
1834 static size_t
1835 _dispatch_timer_debug_attr(dispatch_source_t ds, char* buf, size_t bufsiz)
1836 {
1837 dispatch_source_refs_t dr = ds->ds_refs;
1838 return snprintf(buf, bufsiz, "timer = { target = 0x%llx, "
1839 "last_fire = 0x%llx, interval = 0x%llx, flags = 0x%llx }, ",
1840 ds_timer(dr).target, ds_timer(dr).last_fire, ds_timer(dr).interval,
1841 ds_timer(dr).flags);
1842 }
1843
1844 static size_t
1845 _dispatch_source_debug(dispatch_source_t ds, char* buf, size_t bufsiz)
1846 {
1847 size_t offset = 0;
1848 offset += snprintf(&buf[offset], bufsiz - offset, "%s[%p] = { ",
1849 dx_kind(ds), ds);
1850 offset += _dispatch_object_debug_attr(ds, &buf[offset], bufsiz - offset);
1851 offset += _dispatch_source_debug_attr(ds, &buf[offset], bufsiz - offset);
1852 if (ds->ds_is_timer) {
1853 offset += _dispatch_timer_debug_attr(ds, &buf[offset], bufsiz - offset);
1854 }
1855 return offset;
1856 }
1857
1858 static size_t
1859 _dispatch_source_kevent_debug(dispatch_source_t ds, char* buf, size_t bufsiz)
1860 {
1861 size_t offset = _dispatch_source_debug(ds, buf, bufsiz);
1862 offset += snprintf(&buf[offset], bufsiz - offset, "filter = %s }",
1863 ds->ds_dkev ? _evfiltstr(ds->ds_dkev->dk_kevent.filter) : "????");
1864 return offset;
1865 }
1866
1867 #if DISPATCH_DEBUG
1868 void
1869 dispatch_debug_kevents(struct kevent* kev, size_t count, const char* str)
1870 {
1871 size_t i;
1872 for (i = 0; i < count; ++i) {
1873 _dispatch_log("kevent[%lu] = { ident = %p, filter = %s, flags = 0x%x, "
1874 "fflags = 0x%x, data = %p, udata = %p }: %s",
1875 i, (void*)kev[i].ident, _evfiltstr(kev[i].filter), kev[i].flags,
1876 kev[i].fflags, (void*)kev[i].data, (void*)kev[i].udata, str);
1877 }
1878 }
1879
1880 static void
1881 _dispatch_kevent_debugger2(void *context)
1882 {
1883 struct sockaddr sa;
1884 socklen_t sa_len = sizeof(sa);
1885 int c, fd = (int)(long)context;
1886 unsigned int i;
1887 dispatch_kevent_t dk;
1888 dispatch_source_t ds;
1889 dispatch_source_refs_t dr;
1890 FILE *debug_stream;
1891
1892 c = accept(fd, &sa, &sa_len);
1893 if (c == -1) {
1894 if (errno != EAGAIN) {
1895 (void)dispatch_assume_zero(errno);
1896 }
1897 return;
1898 }
1899 #if 0
1900 int r = fcntl(c, F_SETFL, 0); // disable non-blocking IO
1901 if (r == -1) {
1902 (void)dispatch_assume_zero(errno);
1903 }
1904 #endif
1905 debug_stream = fdopen(c, "a");
1906 if (!dispatch_assume(debug_stream)) {
1907 close(c);
1908 return;
1909 }
1910
1911 fprintf(debug_stream, "HTTP/1.0 200 OK\r\n");
1912 fprintf(debug_stream, "Content-type: text/html\r\n");
1913 fprintf(debug_stream, "Pragma: nocache\r\n");
1914 fprintf(debug_stream, "\r\n");
1915 fprintf(debug_stream, "<html>\n");
1916 fprintf(debug_stream, "<head><title>PID %u</title></head>\n", getpid());
1917 fprintf(debug_stream, "<body>\n<ul>\n");
1918
1919 //fprintf(debug_stream, "<tr><td>DK</td><td>DK</td><td>DK</td><td>DK</td>"
1920 // "<td>DK</td><td>DK</td><td>DK</td></tr>\n");
1921
1922 for (i = 0; i < DSL_HASH_SIZE; i++) {
1923 if (TAILQ_EMPTY(&_dispatch_sources[i])) {
1924 continue;
1925 }
1926 TAILQ_FOREACH(dk, &_dispatch_sources[i], dk_list) {
1927 fprintf(debug_stream, "\t<br><li>DK %p ident %lu filter %s flags "
1928 "0x%hx fflags 0x%x data 0x%lx udata %p\n",
1929 dk, (unsigned long)dk->dk_kevent.ident,
1930 _evfiltstr(dk->dk_kevent.filter), dk->dk_kevent.flags,
1931 dk->dk_kevent.fflags, (unsigned long)dk->dk_kevent.data,
1932 dk->dk_kevent.udata);
1933 fprintf(debug_stream, "\t\t<ul>\n");
1934 TAILQ_FOREACH(dr, &dk->dk_sources, dr_list) {
1935 ds = _dispatch_source_from_refs(dr);
1936 fprintf(debug_stream, "\t\t\t<li>DS %p refcnt 0x%x suspend "
1937 "0x%x data 0x%lx mask 0x%lx flags 0x%x</li>\n",
1938 ds, ds->do_ref_cnt, ds->do_suspend_cnt,
1939 ds->ds_pending_data, ds->ds_pending_data_mask,
1940 ds->ds_atomic_flags);
1941 if (ds->do_suspend_cnt == DISPATCH_OBJECT_SUSPEND_LOCK) {
1942 dispatch_queue_t dq = ds->do_targetq;
1943 fprintf(debug_stream, "\t\t<br>DQ: %p refcnt 0x%x suspend "
1944 "0x%x label: %s\n", dq, dq->do_ref_cnt,
1945 dq->do_suspend_cnt, dq->dq_label);
1946 }
1947 }
1948 fprintf(debug_stream, "\t\t</ul>\n");
1949 fprintf(debug_stream, "\t</li>\n");
1950 }
1951 }
1952 fprintf(debug_stream, "</ul>\n</body>\n</html>\n");
1953 fflush(debug_stream);
1954 fclose(debug_stream);
1955 }
1956
1957 static void
1958 _dispatch_kevent_debugger2_cancel(void *context)
1959 {
1960 int ret, fd = (int)(long)context;
1961
1962 ret = close(fd);
1963 if (ret != -1) {
1964 (void)dispatch_assume_zero(errno);
1965 }
1966 }
1967
1968 static void
1969 _dispatch_kevent_debugger(void *context DISPATCH_UNUSED)
1970 {
1971 union {
1972 struct sockaddr_in sa_in;
1973 struct sockaddr sa;
1974 } sa_u = {
1975 .sa_in = {
1976 .sin_family = AF_INET,
1977 .sin_addr = { htonl(INADDR_LOOPBACK), },
1978 },
1979 };
1980 dispatch_source_t ds;
1981 const char *valstr;
1982 int val, r, fd, sock_opt = 1;
1983 socklen_t slen = sizeof(sa_u);
1984
1985 if (issetugid()) {
1986 return;
1987 }
1988 valstr = getenv("LIBDISPATCH_DEBUGGER");
1989 if (!valstr) {
1990 return;
1991 }
1992 val = atoi(valstr);
1993 if (val == 2) {
1994 sa_u.sa_in.sin_addr.s_addr = 0;
1995 }
1996 fd = socket(PF_INET, SOCK_STREAM, 0);
1997 if (fd == -1) {
1998 (void)dispatch_assume_zero(errno);
1999 return;
2000 }
2001 r = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&sock_opt,
2002 (socklen_t) sizeof sock_opt);
2003 if (r == -1) {
2004 (void)dispatch_assume_zero(errno);
2005 goto out_bad;
2006 }
2007 #if 0
2008 r = fcntl(fd, F_SETFL, O_NONBLOCK);
2009 if (r == -1) {
2010 (void)dispatch_assume_zero(errno);
2011 goto out_bad;
2012 }
2013 #endif
2014 r = bind(fd, &sa_u.sa, sizeof(sa_u));
2015 if (r == -1) {
2016 (void)dispatch_assume_zero(errno);
2017 goto out_bad;
2018 }
2019 r = listen(fd, SOMAXCONN);
2020 if (r == -1) {
2021 (void)dispatch_assume_zero(errno);
2022 goto out_bad;
2023 }
2024 r = getsockname(fd, &sa_u.sa, &slen);
2025 if (r == -1) {
2026 (void)dispatch_assume_zero(errno);
2027 goto out_bad;
2028 }
2029
2030 ds = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0,
2031 &_dispatch_mgr_q);
2032 if (dispatch_assume(ds)) {
2033 _dispatch_log("LIBDISPATCH: debug port: %hu",
2034 (in_port_t)ntohs(sa_u.sa_in.sin_port));
2035
2036 /* ownership of fd transfers to ds */
2037 dispatch_set_context(ds, (void *)(long)fd);
2038 dispatch_source_set_event_handler_f(ds, _dispatch_kevent_debugger2);
2039 dispatch_source_set_cancel_handler_f(ds,
2040 _dispatch_kevent_debugger2_cancel);
2041 dispatch_resume(ds);
2042
2043 return;
2044 }
2045 out_bad:
2046 close(fd);
2047 }
2048
2049 #if HAVE_MACH
2050
2051 #ifndef MACH_PORT_TYPE_SPREQUEST
2052 #define MACH_PORT_TYPE_SPREQUEST 0x40000000
2053 #endif
2054
2055 void
2056 dispatch_debug_machport(mach_port_t name, const char* str)
2057 {
2058 mach_port_type_t type;
2059 mach_msg_bits_t ns = 0, nr = 0, nso = 0, nd = 0;
2060 unsigned int dnreqs = 0, dnrsiz;
2061 kern_return_t kr = mach_port_type(mach_task_self(), name, &type);
2062 if (kr) {
2063 _dispatch_log("machport[0x%08x] = { error(0x%x) \"%s\" }: %s", name,
2064 kr, mach_error_string(kr), str);
2065 return;
2066 }
2067 if (type & MACH_PORT_TYPE_SEND) {
2068 (void)dispatch_assume_zero(mach_port_get_refs(mach_task_self(), name,
2069 MACH_PORT_RIGHT_SEND, &ns));
2070 }
2071 if (type & MACH_PORT_TYPE_SEND_ONCE) {
2072 (void)dispatch_assume_zero(mach_port_get_refs(mach_task_self(), name,
2073 MACH_PORT_RIGHT_SEND_ONCE, &nso));
2074 }
2075 if (type & MACH_PORT_TYPE_DEAD_NAME) {
2076 (void)dispatch_assume_zero(mach_port_get_refs(mach_task_self(), name,
2077 MACH_PORT_RIGHT_DEAD_NAME, &nd));
2078 }
2079 if (type & (MACH_PORT_TYPE_RECEIVE|MACH_PORT_TYPE_SEND|
2080 MACH_PORT_TYPE_SEND_ONCE)) {
2081 (void)dispatch_assume_zero(mach_port_dnrequest_info(mach_task_self(),
2082 name, &dnrsiz, &dnreqs));
2083 }
2084 if (type & MACH_PORT_TYPE_RECEIVE) {
2085 mach_port_status_t status = { .mps_pset = 0, };
2086 mach_msg_type_number_t cnt = MACH_PORT_RECEIVE_STATUS_COUNT;
2087 (void)dispatch_assume_zero(mach_port_get_refs(mach_task_self(), name,
2088 MACH_PORT_RIGHT_RECEIVE, &nr));
2089 (void)dispatch_assume_zero(mach_port_get_attributes(mach_task_self(),
2090 name, MACH_PORT_RECEIVE_STATUS, (void*)&status, &cnt));
2091 _dispatch_log("machport[0x%08x] = { R(%03u) S(%03u) SO(%03u) D(%03u) "
2092 "dnreqs(%03u) spreq(%s) nsreq(%s) pdreq(%s) srights(%s) "
2093 "sorights(%03u) qlim(%03u) msgcount(%03u) mkscount(%03u) "
2094 "seqno(%03u) }: %s", name, nr, ns, nso, nd, dnreqs,
2095 type & MACH_PORT_TYPE_SPREQUEST ? "Y":"N",
2096 status.mps_nsrequest ? "Y":"N", status.mps_pdrequest ? "Y":"N",
2097 status.mps_srights ? "Y":"N", status.mps_sorights,
2098 status.mps_qlimit, status.mps_msgcount, status.mps_mscount,
2099 status.mps_seqno, str);
2100 } else if (type & (MACH_PORT_TYPE_SEND|MACH_PORT_TYPE_SEND_ONCE|
2101 MACH_PORT_TYPE_DEAD_NAME)) {
2102 _dispatch_log("machport[0x%08x] = { R(%03u) S(%03u) SO(%03u) D(%03u) "
2103 "dnreqs(%03u) spreq(%s) }: %s", name, nr, ns, nso, nd, dnreqs,
2104 type & MACH_PORT_TYPE_SPREQUEST ? "Y":"N", str);
2105 } else {
2106 _dispatch_log("machport[0x%08x] = { type(0x%08x) }: %s", name, type,
2107 str);
2108 }
2109 }
2110
2111 #endif // HAVE_MACH
2112
2113 #endif // DISPATCH_DEBUG