Debian Codegraph @

crt/aws-c-io/source/darwin/dispatch_queue_event_loop.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/io/event_loop.h>
7 #include <aws/io/private/event_loop_impl.h>
8
9 #include <aws/common/clock.h>
10 #include <aws/common/mutex.h>
11 #include <aws/common/task_scheduler.h>
12 #include <aws/common/uuid.h>
13
14 #include <aws/io/logging.h>
15
16 #include <unistd.h>
17
18 #include "./dispatch_queue_event_loop_private.h" // private header
19 #include <dispatch/dispatch.h>
20 #include <dispatch/queue.h>
21
22 // Maximum amount of time we schedule event loop service tasks out into the future. This bounds the maximum
23 // amount of time we have to wait for those scheduled tasks to resolve during shutdown, which in turn bounds
24 // how long shutdown can take.
25 //
26 // Start with a second for now.
27 #define AWS_DISPATCH_QUEUE_MAX_FUTURE_SERVICE_INTERVAL (AWS_TIMESTAMP_NANOS)
28
29 static void s_start_destroy(struct aws_event_loop *event_loop);
30 static void s_complete_destroy(struct aws_event_loop *event_loop);
31 static int s_run(struct aws_event_loop *event_loop);
32 static int s_stop(struct aws_event_loop *event_loop);
33 static int s_wait_for_stop_completion(struct aws_event_loop *event_loop);
34 static void s_schedule_task_now(struct aws_event_loop *event_loop, struct aws_task *task);
35 static void s_schedule_task_future(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos);
36 static void s_cancel_task(struct aws_event_loop *event_loop, struct aws_task *task);
37 static int s_connect_to_io_completion_port(struct aws_event_loop *event_loop, struct aws_io_handle *handle);
38 static int s_subscribe_to_io_events(
39 struct aws_event_loop *event_loop,
40 struct aws_io_handle *handle,
41 int events,
42 aws_event_loop_on_event_fn *on_event,
43 void *user_data) {
44 (void)event_loop;
45 (void)handle;
46 (void)events;
47 (void)on_event;
48 (void)user_data;
49 AWS_LOGF_ERROR(
50 AWS_LS_IO_EVENT_LOOP,
51 "id=%p: subscribe_to_io_events() is not supported using Dispatch Queue Event Loops",
52 (void *)event_loop);
53 return aws_raise_error(AWS_ERROR_PLATFORM_NOT_SUPPORTED);
54 }
55 static int s_unsubscribe_from_io_events(struct aws_event_loop *event_loop, struct aws_io_handle *handle) {
56 (void)handle;
57 AWS_LOGF_ERROR(
58 AWS_LS_IO_EVENT_LOOP,
59 "id=%p: unsubscribe_from_io_events() is not supported using Dispatch Queue Event Loops",
60 (void *)event_loop);
61 return aws_raise_error(AWS_ERROR_PLATFORM_NOT_SUPPORTED);
62 }
63 static void s_free_io_event_resources(void *user_data) {
64 /* No io event resources to free */
65 (void)user_data;
66 }
67 static bool s_is_on_callers_thread(struct aws_event_loop *event_loop);
68
69 static struct aws_event_loop_vtable s_vtable = {
70 .start_destroy = s_start_destroy,
71 .complete_destroy = s_complete_destroy,
72 .run = s_run,
73 .stop = s_stop,
74 .wait_for_stop_completion = s_wait_for_stop_completion,
75 .schedule_task_now = s_schedule_task_now,
76 /* dispatch queue event loop impl does not have any short-circuiting, so just use the base scheduling logic */
77 .schedule_task_now_serialized = s_schedule_task_now,
78 .schedule_task_future = s_schedule_task_future,
79 .cancel_task = s_cancel_task,
80 .connect_to_io_completion_port = s_connect_to_io_completion_port,
81 .subscribe_to_io_events = s_subscribe_to_io_events,
82 .unsubscribe_from_io_events = s_unsubscribe_from_io_events,
83 .free_io_event_resources = s_free_io_event_resources,
84 .is_on_callers_thread = s_is_on_callers_thread,
85 };
86
87 /**
88 * DISPATCH QUEUE
89 *
90 * Event loop is responsible for processing events and tasks by launching an execution loop on a single thread. Each
91 * iteration of this loop performs three primary jobs:
92 * 1. Process I/O events.
93 * 2. Process cross-thread tasks.
94 * 3. Execute all runnable tasks.
95 *
96 * Apple Dispatch queues can be given a concurrent or serial attribute on creation. We use Serial Dispatch Queues that
97 * are FIFO queues to which the application can submit tasks in the form of block objects. The block objects will be
98 * executed on a system defined thread pool. Instead of executing the loop on a single thread, we recurrently run
99 * iterations of the execution loop as dispatch queue block objects. aws-c-io library uses a serial dispatch
100 * queue to insure the tasks scheduled on the event loop task scheduler are executed in the correct order.
101 *
102 * Data Structures ******
103 * `scheduled_iteration_entry `: Each entry maps to an execution block submitted to Apple's dispatch queue. Since Apple
104 * ensures the dispatch queue remains active until all scheduled blocks have been executed, it is necessary to keep the
105 * aws_dispatch_loop alive accordingly. This is achieved by holding a reference to aws_dispatch_loop within each entry.
106 * An entry is created upon block submission and is destroyed once the block has been executed, preventing premature
107 * deallocation of the dispatch loop.
108 *
109 * `dispatch_loop`: Implementation of the event loop for dispatch queue.
110 *
111 * Functions ************
112 * `s_run_iteration`: This function represents the block scheduled in `scheduled_iteration_entry`'s
113 */
114
115 /* Help functions to lock status */
116
117 /* The synced_data_lock is held when any member of `aws_dispatch_loop`'s `synced_data` is accessed or modified */
118 static int s_lock_synced_data(struct aws_dispatch_loop *dispatch_loop) {
119 return aws_mutex_lock(&dispatch_loop->synced_data.synced_data_lock);
120 }
121
122 static int s_unlock_synced_data(struct aws_dispatch_loop *dispatch_loop) {
123 return aws_mutex_unlock(&dispatch_loop->synced_data.synced_data_lock);
124 }
125
126 static struct aws_dispatch_loop *s_dispatch_loop_acquire(struct aws_dispatch_loop *dispatch_loop) {
127 if (dispatch_loop) {
128 aws_ref_count_acquire(&dispatch_loop->ref_count);
129 }
130
131 return dispatch_loop;
132 }
133
134 static void s_dispatch_loop_release(struct aws_dispatch_loop *dispatch_loop) {
135 if (dispatch_loop) {
136 aws_ref_count_release(&dispatch_loop->ref_count);
137 }
138 }
139
140 /*
141 * The data structure used to track the dispatch queue execution iteration (block). Each entry is associated with
142 * a block scheduled on Apple Dispatch Queue that runs a service iteration.
143 */
144 struct scheduled_iteration_entry {
145 struct aws_allocator *allocator;
146 uint64_t timestamp;
147 struct aws_linked_list_node scheduled_entry_node;
148 struct aws_dispatch_loop *dispatch_loop;
149 };
150
151 /*
152 * Allocates and returns a new memory alocated `scheduled_iteration_entry` struct
153 * All scheduled_iteration_entry structs must have `s_scheduled_iteration_entry_destroy()` called on them.
154 */
155 static struct scheduled_iteration_entry *s_scheduled_iteration_entry_new(
156 struct aws_dispatch_loop *dispatch_loop,
157 uint64_t timestamp) {
158 struct scheduled_iteration_entry *entry =
159 aws_mem_calloc(dispatch_loop->allocator, 1, sizeof(struct scheduled_iteration_entry));
160
161 entry->allocator = dispatch_loop->allocator;
162 entry->timestamp = timestamp;
163 entry->dispatch_loop = s_dispatch_loop_acquire(dispatch_loop);
164
165 return entry;
166 }
167
168 /*
169 * Cleans up the memory allocated for a `scheduled_iteration_entry`.
170 */
171 static void s_scheduled_iteration_entry_destroy(struct scheduled_iteration_entry *entry) {
172 if (!entry) {
173 return;
174 }
175
176 struct aws_dispatch_loop *dispatch_loop_for_release = entry->dispatch_loop;
177 aws_mem_release(entry->allocator, entry);
178 s_dispatch_loop_release(dispatch_loop_for_release);
179 }
180
181 /* Manually called to destroy an aws_event_loop */
182 static void s_dispatch_event_loop_final_destroy(struct aws_event_loop *event_loop) {
183 struct aws_dispatch_loop *dispatch_loop = event_loop->impl_data;
184
185 if (aws_task_scheduler_is_valid(&dispatch_loop->scheduler)) {
186 aws_task_scheduler_clean_up(&dispatch_loop->scheduler);
187 }
188
189 dispatch_release(dispatch_loop->dispatch_queue);
190 aws_mutex_clean_up(&dispatch_loop->synced_data.synced_data_lock);
191 aws_condition_variable_clean_up(&dispatch_loop->synced_data.signal);
192 // We don't need to clean up the dispatch_loop->synced_data.scheduled_iterations, as all scheduling entries should
193 // have cleaned up before destroy call.
194 aws_mem_release(dispatch_loop->allocator, dispatch_loop);
195 aws_event_loop_clean_up_base(event_loop);
196 aws_mem_release(event_loop->alloc, event_loop);
197
198 aws_thread_decrement_unjoined_count();
199
200 AWS_LOGF_DEBUG(AWS_LS_IO_EVENT_LOOP, "id=%p: Destroyed Dispatch Queue Event Loop.", (void *)event_loop);
201 }
202
203 static const char AWS_LITERAL_APPLE_DISPATCH_QUEUE_ID_PREFIX[] = "com.amazonaws.commonruntime.eventloop.";
204 #define AWS_IO_APPLE_DISPATCH_QUEUE_ID_PREFIX_LENGTH \
205 (AWS_ARRAY_SIZE(AWS_LITERAL_APPLE_DISPATCH_QUEUE_ID_PREFIX) - 1) /* remove string terminator */
206 #define AWS_IO_APPLE_DISPATCH_QUEUE_ID_LENGTH (AWS_IO_APPLE_DISPATCH_QUEUE_ID_PREFIX_LENGTH + AWS_UUID_STR_LEN)
207 /**
208 * Generates a unique identifier for a dispatch queue in the format "com.amazonaws.commonruntime.eventloop.<UUID>".
209 * This identifier will be stored in the provided `result` buffer.
210 */
211 static void s_get_unique_dispatch_queue_id(char result[AWS_IO_APPLE_DISPATCH_QUEUE_ID_LENGTH]) {
212 struct aws_uuid uuid;
213 AWS_FATAL_ASSERT(aws_uuid_init(&uuid) == AWS_OP_SUCCESS);
214 char uuid_str[AWS_UUID_STR_LEN] = {0};
215 struct aws_byte_buf uuid_buf = aws_byte_buf_from_array(uuid_str, sizeof(uuid_str));
216 uuid_buf.len = 0;
217 aws_uuid_to_str(&uuid, &uuid_buf);
218
219 memcpy(result, AWS_LITERAL_APPLE_DISPATCH_QUEUE_ID_PREFIX, AWS_IO_APPLE_DISPATCH_QUEUE_ID_PREFIX_LENGTH);
220 memcpy(result + AWS_IO_APPLE_DISPATCH_QUEUE_ID_PREFIX_LENGTH, uuid_buf.buffer, uuid_buf.len);
221 }
222
223 static void s_dispatch_event_loop_on_zero_ref_count(void *user_data) {
224 struct aws_dispatch_loop *dispatch_loop = user_data;
225 if (dispatch_loop == NULL) {
226 return;
227 }
228
229 s_lock_synced_data(dispatch_loop);
230 AWS_FATAL_ASSERT(dispatch_loop->synced_data.execution_state == AWS_DLES_SHUTTING_DOWN);
231 dispatch_loop->synced_data.execution_state = AWS_DLES_TERMINATED;
232 s_unlock_synced_data(dispatch_loop);
233
234 aws_condition_variable_notify_all(&dispatch_loop->synced_data.signal);
235 }
236
237 /* Setup a dispatch_queue with a scheduler. */
238 struct aws_event_loop *aws_event_loop_new_with_dispatch_queue(
239 struct aws_allocator *alloc,
240 const struct aws_event_loop_options *options) {
241 AWS_PRECONDITION(options);
242 AWS_PRECONDITION(options->clock);
243
244 struct aws_dispatch_loop *dispatch_loop = NULL;
245 struct aws_event_loop *loop = aws_mem_calloc(alloc, 1, sizeof(struct aws_event_loop));
246
247 AWS_LOGF_DEBUG(AWS_LS_IO_EVENT_LOOP, "id=%p: Initializing Dispatch Queue Event Loop", (void *)loop);
248 if (aws_event_loop_init_base(loop, alloc, options->clock)) {
249 goto clean_up;
250 }
251
252 loop->vtable = &s_vtable;
253 loop->base_elg = options->parent_elg;
254
255 dispatch_loop = aws_mem_calloc(alloc, 1, sizeof(struct aws_dispatch_loop));
256 dispatch_loop->allocator = alloc;
257 loop->impl_data = dispatch_loop;
258 dispatch_loop->base_loop = loop;
259 dispatch_loop->synced_data.execution_state = AWS_DLES_SUSPENDED;
260 aws_ref_count_init(&dispatch_loop->ref_count, dispatch_loop, s_dispatch_event_loop_on_zero_ref_count);
261
262 if (aws_condition_variable_init(&dispatch_loop->synced_data.signal)) {
263 goto clean_up;
264 }
265
266 if (aws_mutex_init(&dispatch_loop->synced_data.synced_data_lock)) {
267 goto clean_up;
268 }
269
270 aws_thread_increment_unjoined_count();
271
272 char dispatch_queue_id[AWS_IO_APPLE_DISPATCH_QUEUE_ID_LENGTH] = {0};
273 s_get_unique_dispatch_queue_id(dispatch_queue_id);
274
275 /*
276 * Apple API dispatch_queue_create returns a dispatch_queue_t. This cannot fail and will crash if it does.
277 * A reference to the dispatch queue is retained and must be released explicitly with dispatch_release().
278 */
279 dispatch_loop->dispatch_queue = dispatch_queue_create(dispatch_queue_id, DISPATCH_QUEUE_SERIAL);
280
281 /*
282 * Calling `dispatch_suspend()` on a dispatch queue instructs the dispatch queue to not run any further blocks.
283 * Suspending a dispatch_queue will increase the dispatch queue's suspension count and Apple will not release the
284 * dispatch_queue. A suspended dispatch queue must be resumed before it can be fully released. We suspend the newly
285 * created Apple dispatch queue here to conform with other event loop types. A new event loop is expected to
286 * be in a stopped state until run is called.
287 *
288 * We call `s_run()` during the destruction of the event loop to insure both the execution of the cleanup/destroy
289 * task as well as to release the Apple suspension count.
290 */
291 dispatch_suspend(dispatch_loop->dispatch_queue);
292
293 AWS_LOGF_INFO(
294 AWS_LS_IO_EVENT_LOOP, "id=%p: Apple dispatch queue created with id: %s", (void *)loop, dispatch_queue_id);
295
296 /* The dispatch queue is suspended at this point. */
297 dispatch_loop->synced_data.is_executing = false;
298
299 if (aws_task_scheduler_init(&dispatch_loop->scheduler, alloc)) {
300 AWS_LOGF_ERROR(AWS_LS_IO_EVENT_LOOP, "id=%p: Initialization of task scheduler failed", (void *)loop);
301 goto clean_up;
302 }
303
304 aws_linked_list_init(&dispatch_loop->synced_data.cross_thread_tasks);
305 aws_linked_list_init(&dispatch_loop->synced_data.scheduled_iterations);
306
307 return loop;
308
309 clean_up:
310 if (dispatch_loop) {
311 if (dispatch_loop->dispatch_queue) {
312 /*
313 * We resume the dispatch queue in the event it has been suspended to decrement the suspension count placed
314 * on the dispatch queue by suspending it.
315 */
316 dispatch_resume(dispatch_loop->dispatch_queue);
317 }
318
319 /*
320 * We intentionally bypass the ref-count-initiated destruction and go directly to the final destroy here.
321 * The ref-counting mechanism is only for event loops that are successfully created (and thus get destroyed
322 * by _start_destroy -> _complete_destroy)
323 */
324 s_dispatch_event_loop_final_destroy(loop);
325 } else {
326 aws_mem_release(alloc, loop);
327 }
328 return NULL;
329 }
330
331 static void s_dispatch_queue_purge_cross_thread_tasks(void *context) {
332 struct aws_dispatch_loop *dispatch_loop = context;
333 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: Releasing Dispatch Queue.", (void *)dispatch_loop->base_loop);
334
335 s_lock_synced_data(dispatch_loop);
336 dispatch_loop->synced_data.current_thread_id = aws_thread_current_thread_id();
337 dispatch_loop->synced_data.is_executing = true;
338 s_unlock_synced_data(dispatch_loop);
339
340 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: Cancelling scheduled tasks.", (void *)dispatch_loop->base_loop);
341 /* Cancel all tasks currently scheduled in the task scheduler. */
342 aws_task_scheduler_clean_up(&dispatch_loop->scheduler);
343
344 struct aws_linked_list local_cross_thread_tasks;
345 aws_linked_list_init(&local_cross_thread_tasks);
346
347 bool done = false;
348 while (!done) {
349 /* Swap tasks from cross_thread_tasks into local_cross_thread_tasks to cancel them. */
350 s_lock_synced_data(dispatch_loop);
351 aws_linked_list_swap_contents(&dispatch_loop->synced_data.cross_thread_tasks, &local_cross_thread_tasks);
352 s_unlock_synced_data(dispatch_loop);
353
354 if (aws_linked_list_empty(&local_cross_thread_tasks)) {
355 done = true;
356 }
357
358 /* Cancel all tasks that were in cross_thread_tasks */
359 while (!aws_linked_list_empty(&local_cross_thread_tasks)) {
360 struct aws_linked_list_node *node = aws_linked_list_pop_front(&local_cross_thread_tasks);
361 struct aws_task *task = AWS_CONTAINER_OF(node, struct aws_task, node);
362 task->fn(task, task->arg, AWS_TASK_STATUS_CANCELED);
363 }
364 }
365
366 s_lock_synced_data(dispatch_loop);
367 dispatch_loop->synced_data.is_executing = false;
368 s_unlock_synced_data(dispatch_loop);
369 }
370
371 static void s_start_destroy(struct aws_event_loop *event_loop) {
372 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: Starting to destroy Dispatch Queue Event Loop", (void *)event_loop);
373 struct aws_dispatch_loop *dispatch_loop = event_loop->impl_data;
374
375 s_lock_synced_data(dispatch_loop);
376 enum aws_dispatch_loop_execution_state execution_state = dispatch_loop->synced_data.execution_state;
377 AWS_FATAL_ASSERT(execution_state == AWS_DLES_RUNNING || execution_state == AWS_DLES_SUSPENDED);
378 if (execution_state == AWS_DLES_SUSPENDED) {
379 dispatch_resume(dispatch_loop->dispatch_queue);
380 }
381 dispatch_loop->synced_data.execution_state = AWS_DLES_SHUTTING_DOWN;
382 s_unlock_synced_data(dispatch_loop);
383 }
384
385 static bool s_wait_for_terminated_state(void *user_data) {
386 struct aws_dispatch_loop *dispatch_loop = user_data;
387
388 return dispatch_loop->synced_data.execution_state == AWS_DLES_TERMINATED;
389 }
390
391 static void s_complete_destroy(struct aws_event_loop *event_loop) {
392 AWS_LOGF_TRACE(
393 AWS_LS_IO_EVENT_LOOP, "id=%p: Completing destruction of Dispatch Queue Event Loop", (void *)event_loop);
394 struct aws_dispatch_loop *dispatch_loop = event_loop->impl_data;
395
396 // This would be deadlock
397 AWS_FATAL_ASSERT(!aws_event_loop_thread_is_callers_thread(event_loop));
398
399 /*
400 * This is the release of the initial ref count of 1 that the event loop was created with.
401 */
402 s_dispatch_loop_release(dispatch_loop);
403
404 s_lock_synced_data(dispatch_loop);
405 aws_condition_variable_wait_pred(
406 &dispatch_loop->synced_data.signal,
407 &dispatch_loop->synced_data.synced_data_lock,
408 s_wait_for_terminated_state,
409 dispatch_loop);
410 s_unlock_synced_data(dispatch_loop);
411
412 /*
413 * There are no more references to the dispatch loop anywhere. Purge any remaining cross thread tasks.
414 */
415 s_dispatch_queue_purge_cross_thread_tasks(dispatch_loop);
416
417 /*
418 * We know that all scheduling entries have cleaned up. We can destroy ourselves now. Upon return, the caller
419 * is guaranteed that all memory related to the event loop has been released,
420 */
421 s_dispatch_event_loop_final_destroy(event_loop);
422 }
423
424 static int s_wait_for_stop_completion(struct aws_event_loop *event_loop) {
425 (void)event_loop;
426 /*
427 * This is typically called as part of the destroy process to merge running threads during cleanup. The nature
428 * of dispatch queue and Apple handling cleanup using its own reference counting system only requires us to
429 * drop all references to the dispatch queue and to leave it in a resumed state with no further blocks
430 * scheduled to run.
431 *
432 * We do not call `stop()` on the dispatch loop because a suspended dispatch queue retains a
433 * refcount and Apple will not release the dispatch loop.
434 */
435
436 return AWS_OP_SUCCESS;
437 }
438
439 static void s_try_schedule_new_iteration(struct aws_dispatch_loop *dispatch_loop, uint64_t timestamp);
440
441 /*
442 * Called to resume a suspended dispatch queue.
443 */
444 static int s_run(struct aws_event_loop *event_loop) {
445 struct aws_dispatch_loop *dispatch_loop = event_loop->impl_data;
446
447 s_lock_synced_data(dispatch_loop);
448 if (dispatch_loop->synced_data.execution_state == AWS_DLES_SUSPENDED) {
449 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: Starting event-loop thread.", (void *)event_loop);
450 dispatch_loop->synced_data.execution_state = AWS_DLES_RUNNING;
451 dispatch_resume(dispatch_loop->dispatch_queue);
452 s_try_schedule_new_iteration(dispatch_loop, 0);
453 }
454 s_unlock_synced_data(dispatch_loop);
455
456 return AWS_OP_SUCCESS;
457 }
458
459 /*
460 * Called to suspend dispatch queue
461 */
462 static int s_stop(struct aws_event_loop *event_loop) {
463 struct aws_dispatch_loop *dispatch_loop = event_loop->impl_data;
464
465 s_lock_synced_data(dispatch_loop);
466 if (dispatch_loop->synced_data.execution_state == AWS_DLES_RUNNING) {
467 dispatch_loop->synced_data.execution_state = AWS_DLES_SUSPENDED;
468 AWS_LOGF_INFO(
469 AWS_LS_IO_EVENT_LOOP, "id=%p: Suspending event loop's dispatch queue thread.", (void *)event_loop);
470
471 /*
472 * Suspend will increase the Apple's refcount on the dispatch queue. For Apple to fully release the dispatch
473 * queue, `dispatch_resume()` must be called on the dispatch queue to release the acquired refcount. Manually
474 * decreffing the dispatch queue will result in undetermined behavior.
475 */
476 dispatch_suspend(dispatch_loop->dispatch_queue);
477 }
478 s_unlock_synced_data(dispatch_loop);
479
480 return AWS_OP_SUCCESS;
481 }
482
483 /*
484 * This function is scheduled as a block to run on Apple's dispatch queue. It will only ever be executed on an Apple
485 * dispatch queue and upon completion, will determine whether or not to schedule another iteration of itself on the
486 * Apple dispatch queue.
487 */
488 static void s_run_iteration(void *service_entry) {
489 struct scheduled_iteration_entry *entry = service_entry;
490 struct aws_dispatch_loop *dispatch_loop = entry->dispatch_loop;
491
492 s_lock_synced_data(dispatch_loop);
493
494 AWS_FATAL_ASSERT(aws_linked_list_node_is_in_list(&entry->scheduled_entry_node));
495 aws_linked_list_remove(&entry->scheduled_entry_node);
496
497 /*
498 * If we're shutting down, then don't do anything. The destroy task handles purging and canceling tasks.
499 *
500 * Note that is possible race-wise to end up with execution_state being SUSPENDED here. In that case, just run
501 * normally.
502 */
503 if (entry->dispatch_loop->synced_data.execution_state == AWS_DLES_SHUTTING_DOWN) {
504 goto done;
505 }
506
507 dispatch_loop->synced_data.current_thread_id = aws_thread_current_thread_id();
508 dispatch_loop->synced_data.is_executing = true;
509
510 // swap the cross-thread tasks into task-local data
511 struct aws_linked_list local_cross_thread_tasks;
512 aws_linked_list_init(&local_cross_thread_tasks);
513 aws_linked_list_swap_contents(&dispatch_loop->synced_data.cross_thread_tasks, &local_cross_thread_tasks);
514
515 s_unlock_synced_data(dispatch_loop);
516
517 // run the full iteration here: local cross-thread tasks
518 while (!aws_linked_list_empty(&local_cross_thread_tasks)) {
519 struct aws_linked_list_node *node = aws_linked_list_pop_front(&local_cross_thread_tasks);
520 struct aws_task *task = AWS_CONTAINER_OF(node, struct aws_task, node);
521
522 /*
523 * Timestamp 0 is used to denote "now" tasks
524 *
525 * Because is_executing is true, no additional entries will be scheduled by these invocations.
526 */
527 if (task->timestamp == 0) {
528 aws_task_scheduler_schedule_now(&dispatch_loop->scheduler, task);
529 } else {
530 aws_task_scheduler_schedule_future(&dispatch_loop->scheduler, task, task->timestamp);
531 }
532 }
533
534 aws_event_loop_register_tick_start(dispatch_loop->base_loop);
535 // run all scheduled tasks
536 uint64_t now_ns = 0;
537 aws_event_loop_current_clock_time(dispatch_loop->base_loop, &now_ns);
538 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: running scheduled tasks.", (void *)dispatch_loop->base_loop);
539 aws_task_scheduler_run_all(&dispatch_loop->scheduler, now_ns);
540 aws_event_loop_register_tick_end(dispatch_loop->base_loop);
541
542 /* end of iteration cleanup and rescheduling */
543
544 s_lock_synced_data(dispatch_loop);
545
546 dispatch_loop->synced_data.is_executing = false;
547
548 bool should_schedule = false;
549 uint64_t should_schedule_at_time = 0;
550 /*
551 * We first check if there were any cross thread tasks scheduled during the execution of the current
552 * iteration. If there were, we schedule a new iteration to execute immediately during which cross thread tasks
553 * will be migrated into the dispatch_loop->scheduler.
554 */
555 if (!aws_linked_list_empty(&dispatch_loop->synced_data.cross_thread_tasks)) {
556 should_schedule = true;
557 }
558 /*
559 * If we are not scheduling a new iteration for immediate executuion, we check whether there are any tasks scheduled
560 * to execute now or in the future and scheudle the next iteration using that time.
561 */
562 else if (aws_task_scheduler_has_tasks(&dispatch_loop->scheduler, &should_schedule_at_time)) {
563 should_schedule = true;
564 }
565
566 if (should_schedule) {
567 s_try_schedule_new_iteration(dispatch_loop, should_schedule_at_time);
568 }
569
570 done:
571
572 s_unlock_synced_data(dispatch_loop);
573
574 /* destroy the completed service entry. */
575 s_scheduled_iteration_entry_destroy(entry);
576 }
577
578 /**
579 * Helper function to check if another scheduled iteration already exists that will handle our needs.
580 *
581 * The function should be wrapped with the synced_data_lock to safely access the scheduled_iterations list
582 */
583 static bool s_should_schedule_iteration(
584 struct aws_linked_list *scheduled_iterations,
585 uint64_t proposed_iteration_time) {
586 if (aws_linked_list_empty(scheduled_iterations)) {
587 return true;
588 }
589
590 struct aws_linked_list_node *entry_node = aws_linked_list_front(scheduled_iterations);
591 AWS_FATAL_ASSERT(entry_node != NULL);
592 struct scheduled_iteration_entry *entry =
593 AWS_CONTAINER_OF(entry_node, struct scheduled_iteration_entry, scheduled_entry_node);
594 AWS_FATAL_ASSERT(entry != NULL);
595
596 /* is the next scheduled iteration later than what we require? */
597 return entry->timestamp > proposed_iteration_time;
598 }
599
600 /**
601 * Checks if a new iteration task needs to be scheduled, given a target timestamp. If so, submits an iteration task to
602 * dispatch queue and registers the pending execution in the event loop's list of scheduled_services.
603 *
604 * If timestamp == 0, the function will always schedule a new iteration as long as the event loop is not suspended or
605 * being destroyed.
606 *
607 * This function should be wrapped with the synced_data_lock as it reads and writes to and from
608 * aws_dispatch_loop->sycned_data
609 */
610 static void s_try_schedule_new_iteration(struct aws_dispatch_loop *dispatch_loop, uint64_t timestamp) {
611 if (dispatch_loop->synced_data.execution_state != AWS_DLES_RUNNING || dispatch_loop->synced_data.is_executing) {
612 return;
613 }
614
615 /**
616 * Apple dispatch queue uses automatic reference counting (ARC). If an iteration is scheduled to run in the future,
617 * the dispatch queue will persist until it is executed. Scheduling a block far into the future will keep the
618 * dispatch queue alive unnecessarily long, which blocks event loop group shutdown from completion.
619 * To mitigate this, we ensure an iteration is scheduled no longer than
620 * AWS_DISPATCH_QUEUE_MAX_FUTURE_SERVICE_INTERVAL second in the future.
621 */
622 uint64_t now_ns = 0;
623 aws_event_loop_current_clock_time(dispatch_loop->base_loop, &now_ns);
624 uint64_t delta = timestamp > now_ns ? timestamp - now_ns : 0;
625 delta = aws_min_u64(delta, AWS_DISPATCH_QUEUE_MAX_FUTURE_SERVICE_INTERVAL);
626 uint64_t clamped_timestamp = now_ns + delta;
627
628 if (!s_should_schedule_iteration(&dispatch_loop->synced_data.scheduled_iterations, clamped_timestamp)) {
629 return;
630 }
631
632 struct scheduled_iteration_entry *entry = s_scheduled_iteration_entry_new(dispatch_loop, clamped_timestamp);
633 aws_linked_list_push_front(&dispatch_loop->synced_data.scheduled_iterations, &entry->scheduled_entry_node);
634
635 if (delta == 0) {
636 /*
637 * If the timestamp was set to execute immediately or in the past we schedule `s_run_iteration()` to run
638 * immediately using `dispatch_async_f()` which schedules a block to run on the dispatch queue in a FIFO order.
639 */
640 dispatch_async_f(dispatch_loop->dispatch_queue, entry, s_run_iteration);
641 AWS_LOGF_TRACE(
642 AWS_LS_IO_EVENT_LOOP, "id=%p: Scheduling run iteration on event loop.", (void *)dispatch_loop->base_loop);
643 } else {
644 /*
645 * If the timestamp is set to execute sometime in the future, we clamp the time based on a maximum delta,
646 * convert the time to the format dispatch queue expects, and then schedule `s_run_iteration()` to run in the
647 * future using `dispatch_after_f()`. `dispatch_after_f()` does not immediately place the block onto the
648 * dispatch queue but instead obtains a refcount of Apple's dispatch queue and then schedules onto it at the
649 * requested time. Any blocks scheduled using `dispatch_async_f()` or `dispatch_after_f()` with a closer
650 * dispatch time will be placed on the dispatch queue and execute in order.
651 */
652 dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, delta);
653 dispatch_after_f(when, dispatch_loop->dispatch_queue, entry, s_run_iteration);
654 AWS_LOGF_TRACE(
655 AWS_LS_IO_EVENT_LOOP,
656 "id=%p: Scheduling future run iteration on event loop with next occurring in %llu ns.",
657 (void *)dispatch_loop->base_loop,
658 delta);
659 }
660 }
661
662 static void s_schedule_task_common(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos) {
663 struct aws_dispatch_loop *dispatch_loop = event_loop->impl_data;
664 task->timestamp = run_at_nanos;
665
666 AWS_LOGF_TRACE(
667 AWS_LS_IO_EVENT_LOOP,
668 "id=%p: Scheduling %s task %p cross-thread for timestamp %llu",
669 (void *)event_loop,
670 task->type_tag,
671 (void *)task,
672 (unsigned long long)run_at_nanos);
673
674 s_lock_synced_data(dispatch_loop);
675 /*
676 * As we dont have sustained control of a specific thread when using Apple's dispatch queue. All tasks are treated
677 * as cross thread tasks that will be added to the aws_dispatch_loop's task scheduler in `s_run_iteration()`.
678 */
679 aws_linked_list_push_back(&dispatch_loop->synced_data.cross_thread_tasks, &task->node);
680
681 /*
682 * `s_try_schedule_new_iteration()` will determine whether the addition of this task will require a new
683 * scheduled_iteration_entry needs to be scheduled on the dispatch queue.
684 */
685 s_try_schedule_new_iteration(dispatch_loop, run_at_nanos);
686
687 s_unlock_synced_data(dispatch_loop);
688 }
689
690 static void s_schedule_task_now(struct aws_event_loop *event_loop, struct aws_task *task) {
691 s_schedule_task_common(event_loop, task, 0 /* zero denotes "now" task */);
692 }
693
694 static void s_schedule_task_future(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos) {
695 s_schedule_task_common(event_loop, task, run_at_nanos);
696 }
697
698 static void s_cancel_task(struct aws_event_loop *event_loop, struct aws_task *task) {
699 AWS_LOGF_TRACE(
700 AWS_LS_IO_EVENT_LOOP, "id=%p: cancelling %s task %p", (void *)event_loop, task->type_tag, (void *)task);
701 struct aws_dispatch_loop *dispatch_loop = event_loop->impl_data;
702
703 /* First we move all cross thread tasks into the scheduler in case the task to be cancelled hasn't moved yet. */
704 struct aws_linked_list local_cross_thread_tasks;
705 aws_linked_list_init(&local_cross_thread_tasks);
706 s_lock_synced_data(dispatch_loop);
707 aws_linked_list_swap_contents(&dispatch_loop->synced_data.cross_thread_tasks, &local_cross_thread_tasks);
708 s_unlock_synced_data(dispatch_loop);
709 while (!aws_linked_list_empty(&local_cross_thread_tasks)) {
710 struct aws_linked_list_node *node = aws_linked_list_pop_front(&local_cross_thread_tasks);
711 struct aws_task *task = AWS_CONTAINER_OF(node, struct aws_task, node);
712
713 /* Timestamp 0 is used to denote "now" tasks */
714 if (task->timestamp == 0) {
715 aws_task_scheduler_schedule_now(&dispatch_loop->scheduler, task);
716 } else {
717 aws_task_scheduler_schedule_future(&dispatch_loop->scheduler, task, task->timestamp);
718 }
719 }
720
721 /* Then we attempt to cancel the task. */
722 aws_task_scheduler_cancel_task(&dispatch_loop->scheduler, task);
723 }
724
725 /*
726 * We use this to obtain a direct pointer to the underlying dispatch queue. This is required to perform various
727 * operations in the socket, socket handler, and probably anything else that requires use of Apple API needing a
728 * dispatch queue.
729 */
730 static int s_connect_to_io_completion_port(struct aws_event_loop *event_loop, struct aws_io_handle *handle) {
731 AWS_PRECONDITION(handle->set_queue);
732 AWS_LOGF_TRACE(
733 AWS_LS_IO_EVENT_LOOP,
734 "id=%p: subscribing to events on handle %p",
735 (void *)event_loop,
736 (void *)handle->data.handle);
737
738 struct aws_dispatch_loop *dispatch_loop = event_loop->impl_data;
739 handle->set_queue(handle, dispatch_loop->dispatch_queue);
740
741 return AWS_OP_SUCCESS;
742 }
743
744 /*
745 * We use aws_thread_id_equal with syched_data.current_thread_id and synced_data.is_executing to determine
746 * if operation is being executed on the same dispatch queue thread.
747 */
748 static bool s_is_on_callers_thread(struct aws_event_loop *event_loop) {
749 struct aws_dispatch_loop *dispatch_queue = event_loop->impl_data;
750 s_lock_synced_data(dispatch_queue);
751 bool result =
752 dispatch_queue->synced_data.is_executing &&
753 aws_thread_thread_id_equal(dispatch_queue->synced_data.current_thread_id, aws_thread_current_thread_id());
754 s_unlock_synced_data(dispatch_queue);
755 return result;
756 }