Debian Codegraph @

crt/aws-c-io/source/linux/epoll_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/cal/cal.h>
7 #include <aws/common/atomics.h>
8 #include <aws/common/clock.h>
9 #include <aws/common/mutex.h>
10 #include <aws/common/task_scheduler.h>
11 #include <aws/common/thread.h>
12 #include <aws/io/event_loop.h>
13 #include <aws/io/logging.h>
14 #include <aws/io/private/event_loop_impl.h>
15 #include <aws/io/private/tracing.h>
16
17 #include <sys/epoll.h>
18
19 #include <errno.h>
20 #include <limits.h>
21 #include <unistd.h>
22
23 #if !defined(COMPAT_MODE) && defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 8) || __GLIBC__ > 2)
24 # define USE_EFD 1
25 #else
26 # define USE_EFD 0
27 #endif
28
29 #if USE_EFD
30 # include <aws/io/io.h>
31 # include <sys/eventfd.h>
32
33 #else
34 # include <aws/io/pipe.h>
35 #endif
36
37 /* This isn't defined on ancient linux distros (breaking the builds).
38 * However, if this is a prebuild, we purposely build on an ancient system, but
39 * we want the kernel calls to still be the same as a modern build since that's likely the target of the application
40 * calling this code. Just define this if it isn't there already. GlibC and the kernel don't really care how the flag
41 * gets passed as long as it does.
42 */
43 #ifndef EPOLLRDHUP
44 # define EPOLLRDHUP 0x2000
45 #endif
46
47 static void s_start_destroy(struct aws_event_loop *event_loop);
48 static void s_complete_destroy(struct aws_event_loop *event_loop);
49 static int s_run(struct aws_event_loop *event_loop);
50 static int s_stop(struct aws_event_loop *event_loop);
51 static int s_wait_for_stop_completion(struct aws_event_loop *event_loop);
52 static void s_schedule_task_now(struct aws_event_loop *event_loop, struct aws_task *task);
53 static void s_schedule_task_now_serialized(struct aws_event_loop *event_loop, struct aws_task *task);
54 static void s_schedule_task_future(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos);
55 static void s_cancel_task(struct aws_event_loop *event_loop, struct aws_task *task);
56 static int s_connect_to_io_completion_port(struct aws_event_loop *event_loop, struct aws_io_handle *handle) {
57 (void)handle;
58 AWS_LOGF_ERROR(
59 AWS_LS_IO_EVENT_LOOP,
60 "id=%p: connect_to_io_completion_port() is not supported using Epoll Event Loops",
61 (void *)event_loop);
62 return aws_raise_error(AWS_ERROR_PLATFORM_NOT_SUPPORTED);
63 }
64 static int s_subscribe_to_io_events(
65 struct aws_event_loop *event_loop,
66 struct aws_io_handle *handle,
67 int events,
68 aws_event_loop_on_event_fn *on_event,
69 void *user_data);
70 static int s_unsubscribe_from_io_events(struct aws_event_loop *event_loop, struct aws_io_handle *handle);
71 static void s_free_io_event_resources(void *user_data);
72 static bool s_is_on_callers_thread(struct aws_event_loop *event_loop);
73
74 static void aws_event_loop_thread(void *args);
75
76 static struct aws_event_loop_vtable s_vtable = {
77 .start_destroy = s_start_destroy,
78 .complete_destroy = s_complete_destroy,
79 .run = s_run,
80 .stop = s_stop,
81 .wait_for_stop_completion = s_wait_for_stop_completion,
82 .schedule_task_now = s_schedule_task_now,
83 .schedule_task_now_serialized = s_schedule_task_now_serialized,
84 .schedule_task_future = s_schedule_task_future,
85 .cancel_task = s_cancel_task,
86 .connect_to_io_completion_port = s_connect_to_io_completion_port,
87 .subscribe_to_io_events = s_subscribe_to_io_events,
88 .unsubscribe_from_io_events = s_unsubscribe_from_io_events,
89 .free_io_event_resources = s_free_io_event_resources,
90 .is_on_callers_thread = s_is_on_callers_thread,
91 };
92
93 struct epoll_loop {
94 struct aws_task_scheduler scheduler;
95 struct aws_thread thread_created_on;
96 struct aws_thread_options thread_options;
97 aws_thread_id_t thread_joined_to;
98 struct aws_atomic_var running_thread_id;
99 struct aws_io_handle read_task_handle;
100 struct aws_io_handle write_task_handle;
101 struct aws_mutex task_pre_queue_mutex;
102 struct aws_linked_list task_pre_queue;
103 struct aws_task stop_task;
104 struct aws_atomic_var stop_task_ptr;
105 int epoll_fd;
106 bool should_process_task_pre_queue;
107 bool should_continue;
108 };
109
110 struct epoll_event_data {
111 struct aws_allocator *alloc;
112 struct aws_io_handle *handle;
113 aws_event_loop_on_event_fn *on_event;
114 void *user_data;
115 struct aws_task cleanup_task;
116 bool is_subscribed; /* false when handle is unsubscribed, but this struct hasn't been cleaned up yet */
117 };
118
119 /* default timeout is 100 seconds */
120 enum {
121 DEFAULT_TIMEOUT = 100 * 1000,
122 MAX_EVENTS = 100,
123 };
124
125 int aws_open_nonblocking_posix_pipe(int pipe_fds[2]);
126
127 /* Setup edge triggered epoll with a scheduler. */
128 struct aws_event_loop *aws_event_loop_new_with_epoll(
129 struct aws_allocator *alloc,
130 const struct aws_event_loop_options *options) {
131 AWS_PRECONDITION(options);
132 AWS_PRECONDITION(options->clock);
133
134 struct aws_event_loop *loop = aws_mem_calloc(alloc, 1, sizeof(struct aws_event_loop));
135 if (!loop) {
136 return NULL;
137 }
138
139 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: Initializing edge-triggered epoll", (void *)loop);
140 if (aws_event_loop_init_base(loop, alloc, options->clock)) {
141 goto clean_up_loop;
142 }
143
144 struct epoll_loop *epoll_loop = aws_mem_calloc(alloc, 1, sizeof(struct epoll_loop));
145 if (!epoll_loop) {
146 goto cleanup_base_loop;
147 }
148
149 if (options->thread_options) {
150 epoll_loop->thread_options = *options->thread_options;
151 } else {
152 epoll_loop->thread_options = *aws_default_thread_options();
153 }
154
155 /* initialize thread id to NULL, it should be updated when the event loop thread starts. */
156 aws_atomic_init_ptr(&epoll_loop->running_thread_id, NULL);
157
158 aws_linked_list_init(&epoll_loop->task_pre_queue);
159 epoll_loop->task_pre_queue_mutex = (struct aws_mutex)AWS_MUTEX_INIT;
160 aws_atomic_init_ptr(&epoll_loop->stop_task_ptr, NULL);
161
162 epoll_loop->epoll_fd = epoll_create(100);
163 if (epoll_loop->epoll_fd < 0) {
164 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "id=%p: Failed to open epoll handle.", (void *)loop);
165 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
166 goto clean_up_epoll;
167 }
168
169 if (aws_thread_init(&epoll_loop->thread_created_on, alloc)) {
170 goto clean_up_epoll;
171 }
172
173 #if USE_EFD
174 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: Using eventfd for cross-thread notifications.", (void *)loop);
175 int fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
176
177 if (fd < 0) {
178 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "id=%p: Failed to open eventfd handle.", (void *)loop);
179 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
180 goto clean_up_thread;
181 }
182
183 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: eventfd descriptor %d.", (void *)loop, fd);
184 epoll_loop->write_task_handle = (struct aws_io_handle){.data.fd = fd, .additional_data = NULL};
185 epoll_loop->read_task_handle = (struct aws_io_handle){.data.fd = fd, .additional_data = NULL};
186 #else
187 AWS_LOGF_DEBUG(
188 AWS_LS_IO_EVENT_LOOP,
189 "id=%p: Eventfd not available, falling back to pipe for cross-thread notification.",
190 (void *)loop);
191
192 int pipe_fds[2] = {0};
193 /* this pipe is for task scheduling. */
194 if (aws_open_nonblocking_posix_pipe(pipe_fds)) {
195 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "id=%p: failed to open pipe handle.", (void *)loop);
196 goto clean_up_thread;
197 }
198
199 AWS_LOGF_TRACE(
200 AWS_LS_IO_EVENT_LOOP, "id=%p: pipe descriptors read %d, write %d.", (void *)loop, pipe_fds[0], pipe_fds[1]);
201 epoll_loop->write_task_handle.data.fd = pipe_fds[1];
202 epoll_loop->read_task_handle.data.fd = pipe_fds[0];
203 #endif
204
205 if (aws_task_scheduler_init(&epoll_loop->scheduler, alloc)) {
206 goto clean_up_pipe;
207 }
208
209 epoll_loop->should_continue = false;
210
211 loop->impl_data = epoll_loop;
212 loop->vtable = &s_vtable;
213 loop->base_elg = options->parent_elg;
214
215 return loop;
216
217 clean_up_pipe:
218 #if USE_EFD
219 close(epoll_loop->write_task_handle.data.fd);
220 epoll_loop->write_task_handle.data.fd = -1;
221 epoll_loop->read_task_handle.data.fd = -1;
222 #else
223 close(epoll_loop->read_task_handle.data.fd);
224 close(epoll_loop->write_task_handle.data.fd);
225 #endif
226
227 clean_up_thread:
228 aws_thread_clean_up(&epoll_loop->thread_created_on);
229
230 clean_up_epoll:
231 if (epoll_loop->epoll_fd >= 0) {
232 close(epoll_loop->epoll_fd);
233 }
234
235 aws_mem_release(alloc, epoll_loop);
236
237 cleanup_base_loop:
238 aws_event_loop_clean_up_base(loop);
239
240 clean_up_loop:
241 aws_mem_release(alloc, loop);
242
243 return NULL;
244 }
245
246 static void s_start_destroy(struct aws_event_loop *event_loop) {
247 (void)event_loop;
248 }
249
250 static void s_complete_destroy(struct aws_event_loop *event_loop) {
251 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: Destroying event_loop", (void *)event_loop);
252
253 struct epoll_loop *epoll_loop = event_loop->impl_data;
254
255 /* we don't know if stop() has been called by someone else,
256 * just call stop() again and wait for event-loop to finish. */
257 aws_event_loop_stop(event_loop);
258 s_wait_for_stop_completion(event_loop);
259
260 /* setting this so that canceled tasks don't blow up when asking if they're on the event-loop thread. */
261 epoll_loop->thread_joined_to = aws_thread_current_thread_id();
262 aws_atomic_store_ptr(&epoll_loop->running_thread_id, &epoll_loop->thread_joined_to);
263 aws_task_scheduler_clean_up(&epoll_loop->scheduler);
264
265 while (!aws_linked_list_empty(&epoll_loop->task_pre_queue)) {
266 struct aws_linked_list_node *node = aws_linked_list_pop_front(&epoll_loop->task_pre_queue);
267 struct aws_task *task = AWS_CONTAINER_OF(node, struct aws_task, node);
268 task->fn(task, task->arg, AWS_TASK_STATUS_CANCELED);
269 }
270
271 aws_thread_clean_up(&epoll_loop->thread_created_on);
272 #if USE_EFD
273 close(epoll_loop->write_task_handle.data.fd);
274 epoll_loop->write_task_handle.data.fd = -1;
275 epoll_loop->read_task_handle.data.fd = -1;
276 #else
277 close(epoll_loop->read_task_handle.data.fd);
278 close(epoll_loop->write_task_handle.data.fd);
279 #endif
280
281 close(epoll_loop->epoll_fd);
282 aws_mem_release(event_loop->alloc, epoll_loop);
283 aws_event_loop_clean_up_base(event_loop);
284 aws_mem_release(event_loop->alloc, event_loop);
285 }
286
287 static int s_run(struct aws_event_loop *event_loop) {
288 struct epoll_loop *epoll_loop = event_loop->impl_data;
289
290 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: Starting event-loop thread.", (void *)event_loop);
291
292 epoll_loop->should_continue = true;
293 aws_thread_increment_unjoined_count();
294 if (aws_thread_launch(
295 &epoll_loop->thread_created_on, &aws_event_loop_thread, event_loop, &epoll_loop->thread_options)) {
296
297 aws_thread_decrement_unjoined_count();
298 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "id=%p: thread creation failed.", (void *)event_loop);
299 epoll_loop->should_continue = false;
300 return AWS_OP_ERR;
301 }
302
303 return AWS_OP_SUCCESS;
304 }
305
306 static void s_stop_task(struct aws_task *task, void *args, enum aws_task_status status) {
307
308 (void)task;
309 struct aws_event_loop *event_loop = args;
310 struct epoll_loop *epoll_loop = event_loop->impl_data;
311
312 /* now okay to reschedule stop tasks. */
313 aws_atomic_store_ptr(&epoll_loop->stop_task_ptr, NULL);
314 if (status == AWS_TASK_STATUS_RUN_READY) {
315 /*
316 * this allows the event loop to invoke the callback once the event loop has completed.
317 */
318 epoll_loop->should_continue = false;
319 }
320 }
321
322 static int s_stop(struct aws_event_loop *event_loop) {
323 struct epoll_loop *epoll_loop = event_loop->impl_data;
324
325 void *expected_ptr = NULL;
326 bool update_succeeded =
327 aws_atomic_compare_exchange_ptr(&epoll_loop->stop_task_ptr, &expected_ptr, &epoll_loop->stop_task);
328 if (!update_succeeded) {
329 /* the stop task is already scheduled. */
330 return AWS_OP_SUCCESS;
331 }
332 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: Stopping event-loop thread.", (void *)event_loop);
333 aws_task_init(&epoll_loop->stop_task, s_stop_task, event_loop, "epoll_event_loop_stop");
334 s_schedule_task_now(event_loop, &epoll_loop->stop_task);
335
336 return AWS_OP_SUCCESS;
337 }
338
339 static int s_wait_for_stop_completion(struct aws_event_loop *event_loop) {
340 struct epoll_loop *epoll_loop = event_loop->impl_data;
341 int result = aws_thread_join(&epoll_loop->thread_created_on);
342 aws_thread_decrement_unjoined_count();
343 return result;
344 }
345
346 static void s_schedule_task_cross_thread(
347 struct aws_event_loop *event_loop,
348 struct aws_task *task,
349 uint64_t run_at_nanos) {
350 struct epoll_loop *epoll_loop = event_loop->impl_data;
351
352 AWS_LOGF_TRACE(
353 AWS_LS_IO_EVENT_LOOP,
354 "id=%p: Scheduling %s task %p cross-thread for timestamp %llu",
355 (void *)event_loop,
356 task->type_tag,
357 (void *)task,
358 (unsigned long long)run_at_nanos);
359 task->timestamp = run_at_nanos;
360 aws_mutex_lock(&epoll_loop->task_pre_queue_mutex);
361
362 uint64_t counter = 1;
363
364 bool is_first_task = aws_linked_list_empty(&epoll_loop->task_pre_queue);
365
366 aws_linked_list_push_back(&epoll_loop->task_pre_queue, &task->node);
367
368 /* if the list was not empty, we already have a pending read on the pipe/eventfd, no need to write again. */
369 if (is_first_task) {
370 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: Waking up event-loop thread", (void *)event_loop);
371
372 /* If the write fails because the buffer is full, we don't actually care because that means there's a pending
373 * read on the pipe/eventfd and thus the event loop will end up checking to see if something has been queued.*/
374 ssize_t do_not_care = write(epoll_loop->write_task_handle.data.fd, (void *)&counter, sizeof(counter));
375 (void)do_not_care;
376 }
377
378 aws_mutex_unlock(&epoll_loop->task_pre_queue_mutex);
379 }
380
381 static void s_schedule_task_common(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos) {
382 struct epoll_loop *epoll_loop = event_loop->impl_data;
383
384 /* if event loop and the caller are the same thread, just schedule and be done with it. */
385 if (s_is_on_callers_thread(event_loop)) {
386 AWS_LOGF_TRACE(
387 AWS_LS_IO_EVENT_LOOP,
388 "id=%p: scheduling %s task %p in-thread for timestamp %llu",
389 (void *)event_loop,
390 task->type_tag,
391 (void *)task,
392 (unsigned long long)run_at_nanos);
393 if (run_at_nanos == 0) {
394 /* zero denotes "now" task */
395 aws_task_scheduler_schedule_now(&epoll_loop->scheduler, task);
396 } else {
397 aws_task_scheduler_schedule_future(&epoll_loop->scheduler, task, run_at_nanos);
398 }
399 return;
400 }
401
402 s_schedule_task_cross_thread(event_loop, task, run_at_nanos);
403 }
404
405 static void s_schedule_task_now(struct aws_event_loop *event_loop, struct aws_task *task) {
406 s_schedule_task_common(event_loop, task, 0 /* zero denotes "now" task */);
407 }
408
409 static void s_schedule_task_now_serialized(struct aws_event_loop *event_loop, struct aws_task *task) {
410 s_schedule_task_cross_thread(event_loop, task, 0);
411 }
412
413 static void s_schedule_task_future(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos) {
414 s_schedule_task_common(event_loop, task, run_at_nanos);
415 }
416
417 static void s_cancel_task(struct aws_event_loop *event_loop, struct aws_task *task) {
418 AWS_LOGF_TRACE(
419 AWS_LS_IO_EVENT_LOOP, "id=%p: cancelling %s task %p", (void *)event_loop, task->type_tag, (void *)task);
420 struct epoll_loop *epoll_loop = event_loop->impl_data;
421 aws_task_scheduler_cancel_task(&epoll_loop->scheduler, task);
422 }
423
424 static int s_subscribe_to_io_events(
425 struct aws_event_loop *event_loop,
426 struct aws_io_handle *handle,
427 int events,
428 aws_event_loop_on_event_fn *on_event,
429 void *user_data) {
430
431 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: subscribing to events on fd %d", (void *)event_loop, handle->data.fd);
432 struct epoll_event_data *epoll_event_data = aws_mem_calloc(event_loop->alloc, 1, sizeof(struct epoll_event_data));
433 handle->additional_data = epoll_event_data;
434 if (!epoll_event_data) {
435 return AWS_OP_ERR;
436 }
437
438 struct epoll_loop *epoll_loop = event_loop->impl_data;
439 epoll_event_data->alloc = event_loop->alloc;
440 epoll_event_data->user_data = user_data;
441 epoll_event_data->handle = handle;
442 epoll_event_data->on_event = on_event;
443 epoll_event_data->is_subscribed = true;
444
445 /*everyone is always registered for edge-triggered, hang up, remote hang up, errors. */
446 uint32_t event_mask = EPOLLET | EPOLLHUP | EPOLLRDHUP | EPOLLERR;
447
448 if (events & AWS_IO_EVENT_TYPE_READABLE) {
449 event_mask |= EPOLLIN;
450 }
451
452 if (events & AWS_IO_EVENT_TYPE_WRITABLE) {
453 event_mask |= EPOLLOUT;
454 }
455
456 /* this guy is copied by epoll_ctl */
457 struct epoll_event epoll_event = {
458 .data = {.ptr = epoll_event_data},
459 .events = event_mask,
460 };
461
462 if (epoll_ctl(epoll_loop->epoll_fd, EPOLL_CTL_ADD, handle->data.fd, &epoll_event)) {
463 AWS_LOGF_ERROR(
464 AWS_LS_IO_EVENT_LOOP, "id=%p: failed to subscribe to events on fd %d", (void *)event_loop, handle->data.fd);
465 handle->additional_data = NULL;
466 aws_mem_release(event_loop->alloc, epoll_event_data);
467 return aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
468 }
469
470 return AWS_OP_SUCCESS;
471 }
472
473 static void s_free_io_event_resources(void *user_data) {
474 struct epoll_event_data *event_data = user_data;
475 aws_mem_release(event_data->alloc, (void *)event_data);
476 }
477
478 static void s_unsubscribe_cleanup_task(struct aws_task *task, void *arg, enum aws_task_status status) {
479 (void)task;
480 (void)status;
481 struct epoll_event_data *event_data = (struct epoll_event_data *)arg;
482 s_free_io_event_resources(event_data);
483 }
484
485 static int s_unsubscribe_from_io_events(struct aws_event_loop *event_loop, struct aws_io_handle *handle) {
486 AWS_LOGF_TRACE(
487 AWS_LS_IO_EVENT_LOOP, "id=%p: un-subscribing from events on fd %d", (void *)event_loop, handle->data.fd);
488 struct epoll_loop *epoll_loop = event_loop->impl_data;
489
490 AWS_ASSERT(handle->additional_data);
491 struct epoll_event_data *additional_handle_data = handle->additional_data;
492
493 struct epoll_event dummy_event;
494
495 if (AWS_UNLIKELY(epoll_ctl(epoll_loop->epoll_fd, EPOLL_CTL_DEL, handle->data.fd, &dummy_event /*ignored*/))) {
496 AWS_LOGF_ERROR(
497 AWS_LS_IO_EVENT_LOOP,
498 "id=%p: failed to un-subscribe from events on fd %d",
499 (void *)event_loop,
500 handle->data.fd);
501 return aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
502 }
503
504 /* We can't clean up yet, because we have schedule tasks and more events to process,
505 * mark it as unsubscribed and schedule a cleanup task. */
506 additional_handle_data->is_subscribed = false;
507
508 aws_task_init(
509 &additional_handle_data->cleanup_task,
510 s_unsubscribe_cleanup_task,
511 additional_handle_data,
512 "epoll_event_loop_unsubscribe_cleanup");
513 s_schedule_task_now(event_loop, &additional_handle_data->cleanup_task);
514
515 handle->additional_data = NULL;
516 return AWS_OP_SUCCESS;
517 }
518
519 static bool s_is_on_callers_thread(struct aws_event_loop *event_loop) {
520 struct epoll_loop *epoll_loop = event_loop->impl_data;
521
522 aws_thread_id_t *thread_id = aws_atomic_load_ptr(&epoll_loop->running_thread_id);
523 return thread_id && aws_thread_thread_id_equal(*thread_id, aws_thread_current_thread_id());
524 }
525
526 /* We treat the pipe fd with a subscription to io events just like any other managed file descriptor.
527 * This is the event handler for events on that pipe.*/
528 static void s_on_tasks_to_schedule(
529 struct aws_event_loop *event_loop,
530 struct aws_io_handle *handle,
531 int events,
532 void *user_data) {
533
534 (void)handle;
535 (void)user_data;
536
537 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: notified of cross-thread tasks to schedule", (void *)event_loop);
538 struct epoll_loop *epoll_loop = event_loop->impl_data;
539 if (events & AWS_IO_EVENT_TYPE_READABLE) {
540 epoll_loop->should_process_task_pre_queue = true;
541 }
542 }
543
544 static void s_process_task_pre_queue(struct aws_event_loop *event_loop) {
545 struct epoll_loop *epoll_loop = event_loop->impl_data;
546
547 if (!epoll_loop->should_process_task_pre_queue) {
548 return;
549 }
550
551 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: processing cross-thread tasks", (void *)event_loop);
552 epoll_loop->should_process_task_pre_queue = false;
553
554 struct aws_linked_list task_pre_queue;
555 aws_linked_list_init(&task_pre_queue);
556
557 uint64_t count_ignore = 0;
558
559 aws_mutex_lock(&epoll_loop->task_pre_queue_mutex);
560
561 /* several tasks could theoretically have been written (though this should never happen), make sure we drain the
562 * eventfd/pipe. */
563 while (read(epoll_loop->read_task_handle.data.fd, &count_ignore, sizeof(count_ignore)) > -1) {
564 }
565
566 aws_linked_list_swap_contents(&epoll_loop->task_pre_queue, &task_pre_queue);
567
568 aws_mutex_unlock(&epoll_loop->task_pre_queue_mutex);
569
570 while (!aws_linked_list_empty(&task_pre_queue)) {
571 struct aws_linked_list_node *node = aws_linked_list_pop_front(&task_pre_queue);
572 struct aws_task *task = AWS_CONTAINER_OF(node, struct aws_task, node);
573 AWS_LOGF_TRACE(
574 AWS_LS_IO_EVENT_LOOP,
575 "id=%p: task %s %p pulled to event-loop, scheduling now.",
576 (void *)event_loop,
577 task->type_tag,
578 (void *)task);
579 /* Timestamp 0 is used to denote "now" tasks */
580 if (task->timestamp == 0) {
581 aws_task_scheduler_schedule_now(&epoll_loop->scheduler, task);
582 } else {
583 aws_task_scheduler_schedule_future(&epoll_loop->scheduler, task, task->timestamp);
584 }
585 }
586 }
587
588 /**
589 * This just calls epoll_wait()
590 *
591 * We broke this out into its own function so that the stacktrace clearly shows
592 * what this thread is doing. We've had a lot of cases where users think this
593 * thread is deadlocked because it's stuck here. We want it to be clear
594 * that it's doing nothing on purpose. It's waiting for events to happen...
595 */
596 AWS_NO_INLINE
597 static int aws_event_loop_listen_for_io_events(int epoll_fd, struct epoll_event events[MAX_EVENTS], int timeout) {
598 return epoll_wait(epoll_fd, events, MAX_EVENTS, timeout);
599 }
600
601 static void s_aws_epoll_cleanup_aws_lc_thread_local_state(void *user_data) {
602 (void)user_data;
603
604 aws_cal_thread_clean_up();
605 }
606
607 static void aws_event_loop_thread(void *args) {
608 struct aws_event_loop *event_loop = args;
609 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: main loop started", (void *)event_loop);
610 struct epoll_loop *epoll_loop = event_loop->impl_data;
611
612 /* set thread id to the thread of the event loop */
613 aws_atomic_store_ptr(&epoll_loop->running_thread_id, &epoll_loop->thread_created_on.thread_id);
614
615 int err = s_subscribe_to_io_events(
616 event_loop, &epoll_loop->read_task_handle, AWS_IO_EVENT_TYPE_READABLE, s_on_tasks_to_schedule, NULL);
617 if (err) {
618 return;
619 }
620
621 aws_thread_current_at_exit(s_aws_epoll_cleanup_aws_lc_thread_local_state, NULL);
622
623 int timeout = DEFAULT_TIMEOUT;
624
625 struct epoll_event events[MAX_EVENTS];
626
627 AWS_LOGF_INFO(
628 AWS_LS_IO_EVENT_LOOP,
629 "id=%p: default timeout %d, and max events to process per tick %d",
630 (void *)event_loop,
631 timeout,
632 MAX_EVENTS);
633
634 /*
635 * until stop is called,
636 * call epoll_wait, if a task is scheduled, or a file descriptor has activity, it will
637 * return.
638 *
639 * process all events,
640 *
641 * run all scheduled tasks.
642 *
643 * process queued subscription cleanups.
644 */
645 while (epoll_loop->should_continue) {
646
647 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: waiting for a maximum of %d ms", (void *)event_loop, timeout);
648 int event_count = aws_event_loop_listen_for_io_events(epoll_loop->epoll_fd, events, timeout);
649 aws_event_loop_register_tick_start(event_loop);
650
651 AWS_LOGF_TRACE(
652 AWS_LS_IO_EVENT_LOOP, "id=%p: wake up with %d events to process.", (void *)event_loop, event_count);
653
654 __itt_task_begin(io_tracing_domain, __itt_null, __itt_null, tracing_event_loop_events);
655 for (int i = 0; i < event_count; ++i) {
656 struct epoll_event_data *event_data = (struct epoll_event_data *)events[i].data.ptr;
657
658 int event_mask = 0;
659 if (events[i].events & EPOLLIN) {
660 event_mask |= AWS_IO_EVENT_TYPE_READABLE;
661 }
662
663 if (events[i].events & EPOLLOUT) {
664 event_mask |= AWS_IO_EVENT_TYPE_WRITABLE;
665 }
666
667 if (events[i].events & EPOLLRDHUP) {
668 event_mask |= AWS_IO_EVENT_TYPE_REMOTE_HANG_UP;
669 }
670
671 if (events[i].events & EPOLLHUP) {
672 event_mask |= AWS_IO_EVENT_TYPE_CLOSED;
673 }
674
675 if (events[i].events & EPOLLERR) {
676 event_mask |= AWS_IO_EVENT_TYPE_ERROR;
677 }
678
679 if (event_data->is_subscribed) {
680 AWS_LOGF_TRACE(
681 AWS_LS_IO_EVENT_LOOP,
682 "id=%p: activity on fd %d, invoking handler.",
683 (void *)event_loop,
684 event_data->handle->data.fd);
685 __itt_task_begin(io_tracing_domain, __itt_null, __itt_null, tracing_event_loop_event);
686 event_data->on_event(event_loop, event_data->handle, event_mask, event_data->user_data);
687 __itt_task_end(io_tracing_domain);
688 }
689 }
690 __itt_task_end(io_tracing_domain);
691
692 /* run scheduled tasks */
693 s_process_task_pre_queue(event_loop);
694
695 uint64_t now_ns = 0;
696 event_loop->clock(&now_ns); /* if clock fails, now_ns will be 0 and tasks scheduled for a specific time
697 will not be run. That's ok, we'll handle them next time around. */
698 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: running scheduled tasks.", (void *)event_loop);
699 __itt_task_begin(io_tracing_domain, __itt_null, __itt_null, tracing_event_loop_run_tasks);
700 aws_task_scheduler_run_all(&epoll_loop->scheduler, now_ns);
701 __itt_task_end(io_tracing_domain);
702
703 /* set timeout for next epoll_wait() call.
704 * if clock fails, or scheduler has no tasks, use default timeout */
705 bool use_default_timeout = false;
706
707 if (event_loop->clock(&now_ns)) {
708 use_default_timeout = true;
709 }
710
711 uint64_t next_run_time_ns;
712 if (!aws_task_scheduler_has_tasks(&epoll_loop->scheduler, &next_run_time_ns)) {
713 use_default_timeout = true;
714 }
715
716 if (use_default_timeout) {
717 AWS_LOGF_TRACE(
718 AWS_LS_IO_EVENT_LOOP, "id=%p: no more scheduled tasks using default timeout.", (void *)event_loop);
719 timeout = DEFAULT_TIMEOUT;
720 } else {
721 /* Translate timestamp (in nanoseconds) to timeout (in milliseconds) */
722 uint64_t timeout_ns = (next_run_time_ns > now_ns) ? (next_run_time_ns - now_ns) : 0;
723 uint64_t timeout_ms64 = aws_timestamp_convert(timeout_ns, AWS_TIMESTAMP_NANOS, AWS_TIMESTAMP_MILLIS, NULL);
724 timeout = timeout_ms64 > INT_MAX ? INT_MAX : (int)timeout_ms64;
725 AWS_LOGF_TRACE(
726 AWS_LS_IO_EVENT_LOOP,
727 "id=%p: detected more scheduled tasks with the next occurring at "
728 "%llu, using timeout of %d.",
729 (void *)event_loop,
730 (unsigned long long)timeout_ns,
731 timeout);
732 }
733
734 aws_event_loop_register_tick_end(event_loop);
735 }
736
737 AWS_LOGF_DEBUG(AWS_LS_IO_EVENT_LOOP, "id=%p: exiting main loop", (void *)event_loop);
738 s_unsubscribe_from_io_events(event_loop, &epoll_loop->read_task_handle);
739 /* set thread id back to NULL. This should be updated again in destroy, before tasks are canceled. */
740 aws_atomic_store_ptr(&epoll_loop->running_thread_id, NULL);
741 }