Debian Codegraph @

crt/aws-c-io/source/bsd/kqueue_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
8 #include <aws/cal/cal.h>
9 #include <aws/common/atomics.h>
10 #include <aws/common/clock.h>
11 #include <aws/common/mutex.h>
12 #include <aws/common/task_scheduler.h>
13 #include <aws/common/thread.h>
14 #include <aws/io/logging.h>
15 #include <aws/io/private/event_loop_impl.h>
16
17 #if defined(__FreeBSD__) || defined(__NetBSD__)
18 # define __BSD_VISIBLE 1
19 # include <sys/types.h>
20 #endif
21
22 #include <sys/event.h>
23
24 #include <aws/io/io.h>
25 #include <limits.h>
26 #include <unistd.h>
27
28 static void s_start_destroy(struct aws_event_loop *event_loop);
29 static void s_complete_destroy(struct aws_event_loop *event_loop);
30 static int s_run(struct aws_event_loop *event_loop);
31 static int s_stop(struct aws_event_loop *event_loop);
32 static int s_wait_for_stop_completion(struct aws_event_loop *event_loop);
33 static void s_schedule_task_now(struct aws_event_loop *event_loop, struct aws_task *task);
34 static void s_schedule_task_now_serialized(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 (void)handle;
39 AWS_LOGF_ERROR(
40 AWS_LS_IO_EVENT_LOOP,
41 "id=%p: connect_to_io_completion_port() is not supported using KQueue Event Loops",
42 (void *)event_loop);
43 return aws_raise_error(AWS_ERROR_PLATFORM_NOT_SUPPORTED);
44 }
45 static int s_subscribe_to_io_events(
46 struct aws_event_loop *event_loop,
47 struct aws_io_handle *handle,
48 int events,
49 aws_event_loop_on_event_fn *on_event,
50 void *user_data);
51 static int s_unsubscribe_from_io_events(struct aws_event_loop *event_loop, struct aws_io_handle *handle);
52 static void s_free_io_event_resources(void *user_data);
53
54 static bool s_is_event_thread(struct aws_event_loop *event_loop);
55
56 static void aws_event_loop_thread(void *user_data);
57
58 int aws_open_nonblocking_posix_pipe(int pipe_fds[2]);
59
60 enum event_thread_state {
61 EVENT_THREAD_STATE_READY_TO_RUN,
62 EVENT_THREAD_STATE_RUNNING,
63 EVENT_THREAD_STATE_STOPPING,
64 };
65
66 enum pipe_fd_index {
67 READ_FD,
68 WRITE_FD,
69 };
70
71 struct kqueue_loop {
72 /* thread_created_on is the handle to the event loop thread. */
73 struct aws_thread thread_created_on;
74 /* thread_joined_to is used by the thread destroying the event loop. */
75 aws_thread_id_t thread_joined_to;
76 /* running_thread_id is NULL if the event loop thread is stopped or points-to the thread_id of the thread running
77 * the event loop (either thread_created_on or thread_joined_to). Atomic because of concurrent writes (e.g.,
78 * run/stop) and reads (e.g., is_event_loop_thread).
79 * An aws_thread_id_t variable itself cannot be atomic because it is an opaque type that is platform-dependent. */
80 struct aws_atomic_var running_thread_id;
81 int kq_fd; /* kqueue file descriptor */
82
83 /* Pipe for signaling to event-thread that cross_thread_data has changed. */
84 int cross_thread_signal_pipe[2];
85
86 /* cross_thread_data holds things that must be communicated across threads.
87 * When the event-thread is running, the mutex must be locked while anyone touches anything in cross_thread_data.
88 * If this data is modified outside the thread, the thread is signaled via activity on a pipe. */
89 struct {
90 struct aws_mutex mutex;
91 bool thread_signaled; /* whether thread has been signaled about changes to cross_thread_data */
92 struct aws_linked_list tasks_to_schedule;
93 enum event_thread_state state;
94 } cross_thread_data;
95
96 /* thread_data holds things which, when the event-thread is running, may only be touched by the thread */
97 struct {
98 struct aws_task_scheduler scheduler;
99
100 int connected_handle_count;
101
102 /* These variables duplicate ones in cross_thread_data. We move values out while holding the mutex and operate
103 * on them later */
104 enum event_thread_state state;
105 } thread_data;
106
107 struct aws_thread_options thread_options;
108 };
109
110 /* Data attached to aws_io_handle while the handle is subscribed to io events */
111 struct handle_data {
112 struct aws_io_handle *owner;
113 struct aws_event_loop *event_loop;
114 aws_event_loop_on_event_fn *on_event;
115 void *on_event_user_data;
116
117 int events_subscribed; /* aws_io_event_types this handle should be subscribed to */
118 int events_this_loop; /* aws_io_event_types received during current loop of the event-thread */
119
120 enum { HANDLE_STATE_SUBSCRIBING, HANDLE_STATE_SUBSCRIBED, HANDLE_STATE_UNSUBSCRIBED } state;
121
122 struct aws_task subscribe_task;
123 struct aws_task cleanup_task;
124 };
125
126 enum {
127 DEFAULT_TIMEOUT_SEC = 100, /* Max kevent() timeout per loop of the event-thread */
128 MAX_EVENTS = 100, /* Max kevents to process per loop of the event-thread */
129 };
130
131 struct aws_event_loop_vtable s_kqueue_vtable = {
132 .start_destroy = s_start_destroy,
133 .complete_destroy = s_complete_destroy,
134 .run = s_run,
135 .stop = s_stop,
136 .wait_for_stop_completion = s_wait_for_stop_completion,
137 .schedule_task_now = s_schedule_task_now,
138 .schedule_task_now_serialized = s_schedule_task_now_serialized,
139 .schedule_task_future = s_schedule_task_future,
140 .cancel_task = s_cancel_task,
141 .connect_to_io_completion_port = s_connect_to_io_completion_port,
142 .subscribe_to_io_events = s_subscribe_to_io_events,
143 .unsubscribe_from_io_events = s_unsubscribe_from_io_events,
144 .free_io_event_resources = s_free_io_event_resources,
145 .is_on_callers_thread = s_is_event_thread,
146 };
147
148 #ifdef AWS_ENABLE_KQUEUE
149 struct aws_event_loop *aws_event_loop_new_with_kqueue(
150 struct aws_allocator *alloc,
151 const struct aws_event_loop_options *options) {
152 AWS_ASSERT(alloc);
153 AWS_ASSERT(clock);
154 AWS_ASSERT(options);
155 AWS_ASSERT(options->clock);
156
157 bool clean_up_event_loop_mem = false;
158 bool clean_up_event_loop_base = false;
159 bool clean_up_impl_mem = false;
160 bool clean_up_thread = false;
161 bool clean_up_kqueue = false;
162 bool clean_up_signal_pipe = false;
163 bool clean_up_signal_kevent = false;
164 bool clean_up_mutex = false;
165
166 struct aws_event_loop *event_loop = aws_mem_acquire(alloc, sizeof(struct aws_event_loop));
167 if (!event_loop) {
168 return NULL;
169 }
170
171 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: Initializing edge-triggered kqueue", (void *)event_loop);
172 clean_up_event_loop_mem = true;
173
174 int err = aws_event_loop_init_base(event_loop, alloc, options->clock);
175 if (err) {
176 goto clean_up;
177 }
178 clean_up_event_loop_base = true;
179
180 struct kqueue_loop *impl = aws_mem_calloc(alloc, 1, sizeof(struct kqueue_loop));
181 if (!impl) {
182 goto clean_up;
183 }
184
185 if (options->thread_options) {
186 impl->thread_options = *options->thread_options;
187 } else {
188 impl->thread_options = *aws_default_thread_options();
189 }
190
191 /* intialize thread id to NULL. It will be set when the event loop thread starts. */
192 aws_atomic_init_ptr(&impl->running_thread_id, NULL);
193 clean_up_impl_mem = true;
194
195 err = aws_thread_init(&impl->thread_created_on, alloc);
196 if (err) {
197 goto clean_up;
198 }
199 clean_up_thread = true;
200
201 impl->kq_fd = kqueue();
202 if (impl->kq_fd == -1) {
203 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "id=%p: Failed to open kqueue handle.", (void *)event_loop);
204 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
205 goto clean_up;
206 }
207 clean_up_kqueue = true;
208
209 err = aws_open_nonblocking_posix_pipe(impl->cross_thread_signal_pipe);
210 if (err) {
211 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "id=%p: failed to open pipe handle.", (void *)event_loop);
212 goto clean_up;
213 }
214 AWS_LOGF_TRACE(
215 AWS_LS_IO_EVENT_LOOP,
216 "id=%p: pipe descriptors read %d, write %d.",
217 (void *)event_loop,
218 impl->cross_thread_signal_pipe[READ_FD],
219 impl->cross_thread_signal_pipe[WRITE_FD]);
220 clean_up_signal_pipe = true;
221
222 /* Set up kevent to handle activity on the cross_thread_signal_pipe */
223 struct kevent thread_signal_kevent;
224 EV_SET(
225 &thread_signal_kevent,
226 impl->cross_thread_signal_pipe[READ_FD],
227 EVFILT_READ /*filter*/,
228 EV_ADD | EV_CLEAR /*flags*/,
229 0 /*fflags*/,
230 0 /*data*/,
231 NULL /*udata*/);
232
233 int res = kevent(
234 impl->kq_fd,
235 &thread_signal_kevent /*changelist*/,
236 1 /*nchanges*/,
237 NULL /*eventlist*/,
238 0 /*nevents*/,
239 NULL /*timeout*/);
240
241 if (res == -1) {
242 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "id=%p: failed to create cross-thread signal kevent.", (void *)event_loop);
243 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
244 goto clean_up;
245 }
246 clean_up_signal_kevent = true;
247
248 err = aws_mutex_init(&impl->cross_thread_data.mutex);
249 if (err) {
250 goto clean_up;
251 }
252 clean_up_mutex = true;
253
254 impl->cross_thread_data.thread_signaled = false;
255
256 aws_linked_list_init(&impl->cross_thread_data.tasks_to_schedule);
257
258 impl->cross_thread_data.state = EVENT_THREAD_STATE_READY_TO_RUN;
259
260 err = aws_task_scheduler_init(&impl->thread_data.scheduler, alloc);
261 if (err) {
262 goto clean_up;
263 }
264
265 impl->thread_data.state = EVENT_THREAD_STATE_READY_TO_RUN;
266
267 event_loop->impl_data = impl;
268
269 event_loop->vtable = &s_kqueue_vtable;
270
271 event_loop->base_elg = options->parent_elg;
272
273 /* success */
274 return event_loop;
275
276 clean_up:
277 if (clean_up_mutex) {
278 aws_mutex_clean_up(&impl->cross_thread_data.mutex);
279 }
280 if (clean_up_signal_kevent) {
281 thread_signal_kevent.flags = EV_DELETE;
282 kevent(
283 impl->kq_fd,
284 &thread_signal_kevent /*changelist*/,
285 1 /*nchanges*/,
286 NULL /*eventlist*/,
287 0 /*nevents*/,
288 NULL /*timeout*/);
289 }
290 if (clean_up_signal_pipe) {
291 close(impl->cross_thread_signal_pipe[READ_FD]);
292 close(impl->cross_thread_signal_pipe[WRITE_FD]);
293 }
294 if (clean_up_kqueue) {
295 close(impl->kq_fd);
296 }
297 if (clean_up_thread) {
298 aws_thread_clean_up(&impl->thread_created_on);
299 }
300 if (clean_up_impl_mem) {
301 aws_mem_release(alloc, impl);
302 }
303 if (clean_up_event_loop_base) {
304 aws_event_loop_clean_up_base(event_loop);
305 }
306 if (clean_up_event_loop_mem) {
307 aws_mem_release(alloc, event_loop);
308 }
309 return NULL;
310 }
311 #endif // AWS_ENABLE_KQUEUE
312
313 static void s_start_destroy(struct aws_event_loop *event_loop) {
314 (void)event_loop;
315 }
316
317 static void s_complete_destroy(struct aws_event_loop *event_loop) {
318 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: destroying event_loop", (void *)event_loop);
319 struct kqueue_loop *impl = event_loop->impl_data;
320
321 /* Stop the event-thread. This might have already happened. It's safe to call multiple times. */
322 s_stop(event_loop);
323 int err = s_wait_for_stop_completion(event_loop);
324 if (err) {
325 AWS_LOGF_WARN(
326 AWS_LS_IO_EVENT_LOOP,
327 "id=%p: failed to destroy event-thread, resources have been leaked",
328 (void *)event_loop);
329 AWS_ASSERT("Failed to destroy event-thread, resources have been leaked." == NULL);
330 return;
331 }
332 /* setting this so that canceled tasks don't blow up when asking if they're on the event-loop thread. */
333 impl->thread_joined_to = aws_thread_current_thread_id();
334 aws_atomic_store_ptr(&impl->running_thread_id, &impl->thread_joined_to);
335
336 /* Clean up task-related stuff first. It's possible the a cancelled task adds further tasks to this event_loop.
337 * Tasks added in this way will be in cross_thread_data.tasks_to_schedule, so we clean that up last */
338
339 aws_task_scheduler_clean_up(&impl->thread_data.scheduler); /* Tasks in scheduler get cancelled*/
340
341 while (!aws_linked_list_empty(&impl->cross_thread_data.tasks_to_schedule)) {
342 struct aws_linked_list_node *node = aws_linked_list_pop_front(&impl->cross_thread_data.tasks_to_schedule);
343 struct aws_task *task = AWS_CONTAINER_OF(node, struct aws_task, node);
344 task->fn(task, task->arg, AWS_TASK_STATUS_CANCELED);
345 }
346
347 /* Warn user if aws_io_handle was subscribed, but never unsubscribed. This would cause memory leaks. */
348 AWS_ASSERT(impl->thread_data.connected_handle_count == 0);
349
350 /* Clean up everything else */
351 aws_mutex_clean_up(&impl->cross_thread_data.mutex);
352
353 struct kevent thread_signal_kevent;
354 EV_SET(
355 &thread_signal_kevent,
356 impl->cross_thread_signal_pipe[READ_FD],
357 EVFILT_READ /*filter*/,
358 EV_DELETE /*flags*/,
359 0 /*fflags*/,
360 0 /*data*/,
361 NULL /*udata*/);
362
363 kevent(
364 impl->kq_fd,
365 &thread_signal_kevent /*changelist*/,
366 1 /*nchanges*/,
367 NULL /*eventlist*/,
368 0 /*nevents*/,
369 NULL /*timeout*/);
370
371 close(impl->cross_thread_signal_pipe[READ_FD]);
372 close(impl->cross_thread_signal_pipe[WRITE_FD]);
373 close(impl->kq_fd);
374 aws_thread_clean_up(&impl->thread_created_on);
375 aws_mem_release(event_loop->alloc, impl);
376 aws_event_loop_clean_up_base(event_loop);
377 aws_mem_release(event_loop->alloc, event_loop);
378 }
379
380 static int s_run(struct aws_event_loop *event_loop) {
381 struct kqueue_loop *impl = event_loop->impl_data;
382
383 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: starting event-loop thread.", (void *)event_loop);
384 /* to re-run, call stop() and wait_for_stop_completion() */
385 AWS_ASSERT(impl->cross_thread_data.state == EVENT_THREAD_STATE_READY_TO_RUN);
386 AWS_ASSERT(impl->thread_data.state == EVENT_THREAD_STATE_READY_TO_RUN);
387
388 /* Since thread isn't running it's ok to touch thread_data,
389 * and it's ok to touch cross_thread_data without locking the mutex */
390 impl->cross_thread_data.state = EVENT_THREAD_STATE_RUNNING;
391
392 aws_thread_increment_unjoined_count();
393 int err =
394 aws_thread_launch(&impl->thread_created_on, aws_event_loop_thread, (void *)event_loop, &impl->thread_options);
395
396 if (err) {
397 aws_thread_decrement_unjoined_count();
398 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "id=%p: thread creation failed.", (void *)event_loop);
399 goto clean_up;
400 }
401
402 return AWS_OP_SUCCESS;
403
404 clean_up:
405 impl->cross_thread_data.state = EVENT_THREAD_STATE_READY_TO_RUN;
406 return AWS_OP_ERR;
407 }
408
409 /* This function can't fail, we're relying on the thread responding to critical messages (ex: stop thread) */
410 void signal_cross_thread_data_changed(struct aws_event_loop *event_loop) {
411 struct kqueue_loop *impl = event_loop->impl_data;
412
413 AWS_LOGF_TRACE(
414 AWS_LS_IO_EVENT_LOOP,
415 "id=%p: signaling event-loop that cross-thread tasks need to be scheduled.",
416 (void *)event_loop);
417 /* Doesn't actually matter what we write, any activity on pipe signals that cross_thread_data has changed,
418 * If the pipe is full and the write fails, that's fine, the event-thread will get the signal from some previous
419 * write */
420 uint32_t write_whatever = 0xC0FFEE;
421 write(impl->cross_thread_signal_pipe[WRITE_FD], &write_whatever, sizeof(write_whatever));
422 }
423
424 static int s_stop(struct aws_event_loop *event_loop) {
425 struct kqueue_loop *impl = event_loop->impl_data;
426
427 bool signal_thread = false;
428
429 { /* Begin critical section */
430 aws_mutex_lock(&impl->cross_thread_data.mutex);
431 if (impl->cross_thread_data.state == EVENT_THREAD_STATE_RUNNING) {
432 impl->cross_thread_data.state = EVENT_THREAD_STATE_STOPPING;
433 signal_thread = !impl->cross_thread_data.thread_signaled;
434 impl->cross_thread_data.thread_signaled = true;
435 }
436 aws_mutex_unlock(&impl->cross_thread_data.mutex);
437 } /* End critical section */
438
439 if (signal_thread) {
440 signal_cross_thread_data_changed(event_loop);
441 }
442
443 return AWS_OP_SUCCESS;
444 }
445
446 static int s_wait_for_stop_completion(struct aws_event_loop *event_loop) {
447 struct kqueue_loop *impl = event_loop->impl_data;
448
449 #ifdef DEBUG_BUILD
450 aws_mutex_lock(&impl->cross_thread_data.mutex);
451 /* call stop() before wait_for_stop_completion() or you'll wait forever */
452 AWS_ASSERT(impl->cross_thread_data.state != EVENT_THREAD_STATE_RUNNING);
453 aws_mutex_unlock(&impl->cross_thread_data.mutex);
454 #endif
455
456 int err = aws_thread_join(&impl->thread_created_on);
457 aws_thread_decrement_unjoined_count();
458 if (err) {
459 return AWS_OP_ERR;
460 }
461
462 /* Since thread is no longer running it's ok to touch thread_data,
463 * and it's ok to touch cross_thread_data without locking the mutex */
464 impl->cross_thread_data.state = EVENT_THREAD_STATE_READY_TO_RUN;
465 impl->thread_data.state = EVENT_THREAD_STATE_READY_TO_RUN;
466
467 return AWS_OP_SUCCESS;
468 }
469
470 static void s_schedule_task_cross_thread(
471 struct aws_event_loop *event_loop,
472 struct aws_task *task,
473 uint64_t run_at_nanos) {
474 struct kqueue_loop *impl = event_loop->impl_data;
475
476 AWS_LOGF_TRACE(
477 AWS_LS_IO_EVENT_LOOP,
478 "id=%p: scheduling task %p cross-thread for timestamp %llu",
479 (void *)event_loop,
480 (void *)task,
481 (unsigned long long)run_at_nanos);
482 task->timestamp = run_at_nanos;
483 bool should_signal_thread = false;
484
485 /* Begin critical section */
486 aws_mutex_lock(&impl->cross_thread_data.mutex);
487 aws_linked_list_push_back(&impl->cross_thread_data.tasks_to_schedule, &task->node);
488
489 /* Signal thread that cross_thread_data has changed (unless it's been signaled already) */
490 if (!impl->cross_thread_data.thread_signaled) {
491 should_signal_thread = true;
492 impl->cross_thread_data.thread_signaled = true;
493 }
494
495 aws_mutex_unlock(&impl->cross_thread_data.mutex);
496 /* End critical section */
497
498 if (should_signal_thread) {
499 signal_cross_thread_data_changed(event_loop);
500 }
501 }
502
503 /* Common functionality for "now" and "future" task scheduling.
504 * If `run_at_nanos` is zero then the task is scheduled as a "now" task. */
505 static void s_schedule_task_common(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos) {
506 AWS_ASSERT(task);
507 struct kqueue_loop *impl = event_loop->impl_data;
508
509 /* If we're on the event-thread, just schedule it directly */
510 if (s_is_event_thread(event_loop)) {
511 AWS_LOGF_TRACE(
512 AWS_LS_IO_EVENT_LOOP,
513 "id=%p: scheduling task %p in-thread for timestamp %llu",
514 (void *)event_loop,
515 (void *)task,
516 (unsigned long long)run_at_nanos);
517 if (run_at_nanos == 0) {
518 aws_task_scheduler_schedule_now(&impl->thread_data.scheduler, task);
519 } else {
520 aws_task_scheduler_schedule_future(&impl->thread_data.scheduler, task, run_at_nanos);
521 }
522 return;
523 }
524
525 /* Otherwise, add it to cross_thread_data.tasks_to_schedule and signal the event-thread to process it */
526 s_schedule_task_cross_thread(event_loop, task, run_at_nanos);
527 }
528
529 static void s_schedule_task_now(struct aws_event_loop *event_loop, struct aws_task *task) {
530 s_schedule_task_common(event_loop, task, 0); /* Zero is used to denote "now" tasks */
531 }
532
533 static void s_schedule_task_now_serialized(struct aws_event_loop *event_loop, struct aws_task *task) {
534 s_schedule_task_cross_thread(event_loop, task, 0); /* Zero is used to denote "now" tasks */
535 }
536
537 static void s_schedule_task_future(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos) {
538 s_schedule_task_common(event_loop, task, run_at_nanos);
539 }
540
541 static void s_cancel_task(struct aws_event_loop *event_loop, struct aws_task *task) {
542 struct kqueue_loop *kqueue_loop = event_loop->impl_data;
543 AWS_LOGF_TRACE(
544 AWS_LS_IO_EVENT_LOOP, "id=%p: cancelling %s task %p", (void *)event_loop, task->type_tag, (void *)task);
545 aws_task_scheduler_cancel_task(&kqueue_loop->thread_data.scheduler, task);
546 }
547
548 /* Scheduled task that connects aws_io_handle with the kqueue */
549 static void s_subscribe_task(struct aws_task *task, void *user_data, enum aws_task_status status) {
550 (void)task;
551 struct handle_data *handle_data = user_data;
552 struct aws_event_loop *event_loop = handle_data->event_loop;
553 struct kqueue_loop *impl = handle_data->event_loop->impl_data;
554
555 impl->thread_data.connected_handle_count++;
556
557 /* if task was cancelled, nothing to do */
558 if (status == AWS_TASK_STATUS_CANCELED) {
559 return;
560 }
561
562 /* If handle was unsubscribed before this task could execute, nothing to do */
563 if (handle_data->state == HANDLE_STATE_UNSUBSCRIBED) {
564 return;
565 }
566
567 AWS_ASSERT(handle_data->state == HANDLE_STATE_SUBSCRIBING);
568 AWS_LOGF_TRACE(
569 AWS_LS_IO_EVENT_LOOP, "id=%p: subscribing to events on fd %d", (void *)event_loop, handle_data->owner->data.fd);
570
571 /* In order to monitor both reads and writes, kqueue requires you to add two separate kevents.
572 * If we're adding two separate kevents, but one of those fails, we need to remove the other kevent.
573 * Therefore we use the EV_RECEIPT flag. This causes kevent() to tell whether each EV_ADD succeeded,
574 * rather than the usual behavior of telling us about recent events. */
575 struct kevent changelist[2];
576 AWS_ZERO_ARRAY(changelist);
577
578 int changelist_size = 0;
579
580 if (handle_data->events_subscribed & AWS_IO_EVENT_TYPE_READABLE) {
581 EV_SET(
582 &changelist[changelist_size++],
583 handle_data->owner->data.fd,
584 EVFILT_READ /*filter*/,
585 EV_ADD | EV_RECEIPT | EV_CLEAR /*flags*/,
586 0 /*fflags*/,
587 0 /*data*/,
588 handle_data /*udata*/);
589 }
590 if (handle_data->events_subscribed & AWS_IO_EVENT_TYPE_WRITABLE) {
591 EV_SET(
592 &changelist[changelist_size++],
593 handle_data->owner->data.fd,
594 EVFILT_WRITE /*filter*/,
595 EV_ADD | EV_RECEIPT | EV_CLEAR /*flags*/,
596 0 /*fflags*/,
597 0 /*data*/,
598 handle_data /*udata*/);
599 }
600
601 int num_events = kevent(
602 impl->kq_fd,
603 changelist /*changelist*/,
604 changelist_size /*nchanges*/,
605 changelist /*eventlist. It's OK to re-use the same memory for changelist input and eventlist output*/,
606 changelist_size /*nevents*/,
607 NULL /*timeout*/);
608 if (num_events == -1) {
609 goto subscribe_failed;
610 }
611
612 /* Look through results to see if any failed */
613 for (int i = 0; i < num_events; ++i) {
614 /* Every result should be flagged as error, that's just how EV_RECEIPT works */
615 AWS_ASSERT(changelist[i].flags & EV_ERROR);
616
617 /* If a real error occurred, .data contains the error code */
618 if (changelist[i].data != 0) {
619 goto subscribe_failed;
620 }
621 }
622
623 /* Success */
624 handle_data->state = HANDLE_STATE_SUBSCRIBED;
625 return;
626
627 subscribe_failed:
628 AWS_LOGF_ERROR(
629 AWS_LS_IO_EVENT_LOOP,
630 "id=%p: failed to subscribe to events on fd %d",
631 (void *)event_loop,
632 handle_data->owner->data.fd);
633 /* Remove any related kevents that succeeded */
634 for (int i = 0; i < num_events; ++i) {
635 if (changelist[i].data == 0) {
636 changelist[i].flags = EV_DELETE;
637 kevent(
638 impl->kq_fd,
639 &changelist[i] /*changelist*/,
640 1 /*nchanges*/,
641 NULL /*eventlist*/,
642 0 /*nevents*/,
643 NULL /*timeout*/);
644 }
645 }
646
647 /* We can't return an error code because this was a scheduled task.
648 * Notify the user of the failed subscription by passing AWS_IO_EVENT_TYPE_ERROR to the callback. */
649 handle_data->on_event(event_loop, handle_data->owner, AWS_IO_EVENT_TYPE_ERROR, handle_data->on_event_user_data);
650 }
651
652 static int s_subscribe_to_io_events(
653 struct aws_event_loop *event_loop,
654 struct aws_io_handle *handle,
655 int events,
656 aws_event_loop_on_event_fn *on_event,
657 void *user_data) {
658
659 AWS_ASSERT(event_loop);
660 AWS_ASSERT(handle->data.fd != -1);
661 AWS_ASSERT(handle->additional_data == NULL);
662 AWS_ASSERT(on_event);
663 /* Must subscribe for read, write, or both */
664 AWS_ASSERT(events & (AWS_IO_EVENT_TYPE_READABLE | AWS_IO_EVENT_TYPE_WRITABLE));
665
666 struct handle_data *handle_data = aws_mem_calloc(event_loop->alloc, 1, sizeof(struct handle_data));
667 if (!handle_data) {
668 return AWS_OP_ERR;
669 }
670
671 handle_data->owner = handle;
672 handle_data->event_loop = event_loop;
673 handle_data->on_event = on_event;
674 handle_data->on_event_user_data = user_data;
675 handle_data->events_subscribed = events;
676 handle_data->state = HANDLE_STATE_SUBSCRIBING;
677
678 handle->additional_data = handle_data;
679
680 /* We schedule a task to perform the actual changes to the kqueue, read on for an explanation why...
681 *
682 * kqueue requires separate registrations for read and write events.
683 * If the user wants to know about both read and write, we need register once for read and once for write.
684 * If the first registration succeeds, but the second registration fails, we need to delete the first registration.
685 * If this all happened outside the event-thread, the successful registration's events could begin processing
686 * in the brief window of time before the registration is deleted. */
687
688 aws_task_init(&handle_data->subscribe_task, s_subscribe_task, handle_data, "kqueue_event_loop_subscribe");
689 s_schedule_task_now(event_loop, &handle_data->subscribe_task);
690
691 return AWS_OP_SUCCESS;
692 }
693
694 static void s_free_io_event_resources(void *user_data) {
695 struct handle_data *handle_data = user_data;
696 struct kqueue_loop *impl = handle_data->event_loop->impl_data;
697
698 impl->thread_data.connected_handle_count--;
699
700 aws_mem_release(handle_data->event_loop->alloc, handle_data);
701 }
702
703 static void s_clean_up_handle_data_task(struct aws_task *task, void *user_data, enum aws_task_status status) {
704 (void)task;
705 (void)status;
706
707 struct handle_data *handle_data = user_data;
708 s_free_io_event_resources(handle_data);
709 }
710
711 static int s_unsubscribe_from_io_events(struct aws_event_loop *event_loop, struct aws_io_handle *handle) {
712 AWS_LOGF_TRACE(
713 AWS_LS_IO_EVENT_LOOP, "id=%p: un-subscribing from events on fd %d", (void *)event_loop, handle->data.fd);
714 AWS_ASSERT(handle->additional_data);
715 struct handle_data *handle_data = handle->additional_data;
716 struct kqueue_loop *impl = event_loop->impl_data;
717
718 AWS_ASSERT(event_loop == handle_data->event_loop);
719
720 /* If the handle was successfully subscribed to kqueue, then remove it. */
721 if (handle_data->state == HANDLE_STATE_SUBSCRIBED) {
722 struct kevent changelist[2];
723 int changelist_size = 0;
724
725 if (handle_data->events_subscribed & AWS_IO_EVENT_TYPE_READABLE) {
726 EV_SET(
727 &changelist[changelist_size++],
728 handle_data->owner->data.fd,
729 EVFILT_READ /*filter*/,
730 EV_DELETE /*flags*/,
731 0 /*fflags*/,
732 0 /*data*/,
733 handle_data /*udata*/);
734 }
735 if (handle_data->events_subscribed & AWS_IO_EVENT_TYPE_WRITABLE) {
736 EV_SET(
737 &changelist[changelist_size++],
738 handle_data->owner->data.fd,
739 EVFILT_WRITE /*filter*/,
740 EV_DELETE /*flags*/,
741 0 /*fflags*/,
742 0 /*data*/,
743 handle_data /*udata*/);
744 }
745
746 kevent(impl->kq_fd, changelist, changelist_size, NULL /*eventlist*/, 0 /*nevents*/, NULL /*timeout*/);
747 }
748
749 /* Schedule a task to clean up the memory. This is done in a task to prevent the following scenario:
750 * - While processing a batch of events, some callback unsubscribes another aws_io_handle.
751 * - One of the other events in this batch belongs to that other aws_io_handle.
752 * - If the handle_data were already deleted, there would be an access invalid memory. */
753
754 aws_task_init(
755 &handle_data->cleanup_task, s_clean_up_handle_data_task, handle_data, "kqueue_event_loop_clean_up_handle_data");
756 aws_event_loop_schedule_task_now(event_loop, &handle_data->cleanup_task);
757
758 handle_data->state = HANDLE_STATE_UNSUBSCRIBED;
759 handle->additional_data = NULL;
760
761 return AWS_OP_SUCCESS;
762 }
763
764 static bool s_is_event_thread(struct aws_event_loop *event_loop) {
765 struct kqueue_loop *impl = event_loop->impl_data;
766
767 aws_thread_id_t *thread_id = aws_atomic_load_ptr(&impl->running_thread_id);
768 return thread_id && aws_thread_thread_id_equal(*thread_id, aws_thread_current_thread_id());
769 }
770
771 /* Called from thread.
772 * Takes tasks from tasks_to_schedule and adds them to the scheduler. */
773 static void s_process_tasks_to_schedule(struct aws_event_loop *event_loop, struct aws_linked_list *tasks_to_schedule) {
774 struct kqueue_loop *impl = event_loop->impl_data;
775 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: processing cross-thread tasks", (void *)event_loop);
776
777 while (!aws_linked_list_empty(tasks_to_schedule)) {
778 struct aws_linked_list_node *node = aws_linked_list_pop_front(tasks_to_schedule);
779 struct aws_task *task = AWS_CONTAINER_OF(node, struct aws_task, node);
780
781 AWS_LOGF_TRACE(
782 AWS_LS_IO_EVENT_LOOP,
783 "id=%p: task %p pulled to event-loop, scheduling now.",
784 (void *)event_loop,
785 (void *)task);
786 /* Timestamp 0 is used to denote "now" tasks */
787 if (task->timestamp == 0) {
788 aws_task_scheduler_schedule_now(&impl->thread_data.scheduler, task);
789 } else {
790 aws_task_scheduler_schedule_future(&impl->thread_data.scheduler, task, task->timestamp);
791 }
792 }
793 }
794
795 static void s_process_cross_thread_data(struct aws_event_loop *event_loop) {
796 struct kqueue_loop *impl = event_loop->impl_data;
797
798 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: notified of cross-thread data to process", (void *)event_loop);
799 /* If there are tasks to schedule, grab them all out of synced_data.tasks_to_schedule.
800 * We'll process them later, so that we minimize time spent holding the mutex. */
801 struct aws_linked_list tasks_to_schedule;
802 aws_linked_list_init(&tasks_to_schedule);
803
804 { /* Begin critical section */
805 aws_mutex_lock(&impl->cross_thread_data.mutex);
806 impl->cross_thread_data.thread_signaled = false;
807
808 bool initiate_stop = (impl->cross_thread_data.state == EVENT_THREAD_STATE_STOPPING) &&
809 (impl->thread_data.state == EVENT_THREAD_STATE_RUNNING);
810 if (AWS_UNLIKELY(initiate_stop)) {
811 impl->thread_data.state = EVENT_THREAD_STATE_STOPPING;
812 }
813
814 aws_linked_list_swap_contents(&impl->cross_thread_data.tasks_to_schedule, &tasks_to_schedule);
815
816 aws_mutex_unlock(&impl->cross_thread_data.mutex);
817 } /* End critical section */
818
819 s_process_tasks_to_schedule(event_loop, &tasks_to_schedule);
820 }
821
822 static int s_aws_event_flags_from_kevent(struct kevent *kevent) {
823 int event_flags = 0;
824
825 if (kevent->flags & EV_ERROR) {
826 event_flags |= AWS_IO_EVENT_TYPE_ERROR;
827 } else if (kevent->filter == EVFILT_READ) {
828 if (kevent->data != 0) {
829 event_flags |= AWS_IO_EVENT_TYPE_READABLE;
830 }
831
832 if (kevent->flags & EV_EOF) {
833 event_flags |= AWS_IO_EVENT_TYPE_CLOSED;
834 }
835 } else if (kevent->filter == EVFILT_WRITE) {
836 if (kevent->data != 0) {
837 event_flags |= AWS_IO_EVENT_TYPE_WRITABLE;
838 }
839
840 if (kevent->flags & EV_EOF) {
841 event_flags |= AWS_IO_EVENT_TYPE_CLOSED;
842 }
843 }
844
845 return event_flags;
846 }
847
848 /**
849 * This just calls kevent()
850 *
851 * We broke this out into its own function so that the stacktrace clearly shows
852 * what this thread is doing. We've had a lot of cases where users think this
853 * thread is deadlocked because it's stuck here. We want it to be clear
854 * that it's doing nothing on purpose. It's waiting for events to happen...
855 */
856 AWS_NO_INLINE
857 static int aws_event_loop_listen_for_io_events(int kq_fd, struct kevent kevents[MAX_EVENTS], struct timespec *timeout) {
858 return kevent(kq_fd, NULL /*changelist*/, 0 /*nchanges*/, kevents /*eventlist*/, MAX_EVENTS /*nevents*/, timeout);
859 }
860
861 static void s_aws_kqueue_cleanup_aws_lc_thread_local_state(void *user_data) {
862 (void)user_data;
863
864 aws_cal_thread_clean_up();
865 }
866
867 static void aws_event_loop_thread(void *user_data) {
868 struct aws_event_loop *event_loop = user_data;
869 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: main loop started", (void *)event_loop);
870 struct kqueue_loop *impl = event_loop->impl_data;
871
872 /* set thread id to the event-loop's thread. */
873 aws_atomic_store_ptr(&impl->running_thread_id, &impl->thread_created_on.thread_id);
874
875 AWS_ASSERT(impl->thread_data.state == EVENT_THREAD_STATE_READY_TO_RUN);
876 impl->thread_data.state = EVENT_THREAD_STATE_RUNNING;
877
878 struct kevent kevents[MAX_EVENTS];
879
880 /* A single aws_io_handle could have two separate kevents if subscribed for both read and write.
881 * If both the read and write kevents fire in the same loop of the event-thread,
882 * combine the event-flags and deliver them in a single callback.
883 * This makes the kqueue_event_loop behave more like the other platform implementations. */
884 struct handle_data *io_handle_events[MAX_EVENTS];
885
886 struct timespec timeout = {
887 .tv_sec = DEFAULT_TIMEOUT_SEC,
888 .tv_nsec = 0,
889 };
890
891 AWS_LOGF_INFO(
892 AWS_LS_IO_EVENT_LOOP,
893 "id=%p: default timeout %ds, and max events to process per tick %d",
894 (void *)event_loop,
895 DEFAULT_TIMEOUT_SEC,
896 MAX_EVENTS);
897
898 aws_thread_current_at_exit(s_aws_kqueue_cleanup_aws_lc_thread_local_state, NULL);
899
900 while (impl->thread_data.state == EVENT_THREAD_STATE_RUNNING) {
901 int num_io_handle_events = 0;
902 bool should_process_cross_thread_data = false;
903
904 AWS_LOGF_TRACE(
905 AWS_LS_IO_EVENT_LOOP,
906 "id=%p: waiting for a maximum of %ds %lluns",
907 (void *)event_loop,
908 (int)timeout.tv_sec,
909 (unsigned long long)timeout.tv_nsec);
910
911 /* Process kqueue events */
912 int num_kevents = aws_event_loop_listen_for_io_events(impl->kq_fd, kevents, &timeout);
913
914 aws_event_loop_register_tick_start(event_loop);
915 AWS_LOGF_TRACE(
916 AWS_LS_IO_EVENT_LOOP, "id=%p: wake up with %d events to process.", (void *)event_loop, num_kevents);
917 if (num_kevents == -1) {
918 /* Raise an error, in case this is interesting to anyone monitoring,
919 * and continue on with this loop. We can't process events,
920 * but we can still process scheduled tasks */
921 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
922
923 /* Force the cross_thread_data to be processed.
924 * There might be valuable info in there, like the message to stop the thread.
925 * It's fine to do this even if nothing has changed, it just costs a mutex lock/unlock. */
926 should_process_cross_thread_data = true;
927 }
928
929 for (int i = 0; i < num_kevents; ++i) {
930 struct kevent *kevent = &kevents[i];
931
932 /* Was this event to signal that cross_thread_data has changed? */
933 if ((int)kevent->ident == impl->cross_thread_signal_pipe[READ_FD]) {
934 should_process_cross_thread_data = true;
935
936 /* Drain whatever data was written to the signaling pipe */
937 uint32_t read_whatever;
938 while (read((int)kevent->ident, &read_whatever, sizeof(read_whatever)) > 0) {
939 }
940
941 continue;
942 }
943
944 /* Otherwise this was a normal event on a subscribed handle. Figure out which flags to report. */
945 int event_flags = s_aws_event_flags_from_kevent(kevent);
946 if (event_flags == 0) {
947 continue;
948 }
949
950 /* Combine flags, in case multiple kevents correspond to one handle. (see notes at top of function) */
951 struct handle_data *handle_data = kevent->udata;
952 if (handle_data->events_this_loop == 0) {
953 io_handle_events[num_io_handle_events++] = handle_data;
954 }
955 handle_data->events_this_loop |= event_flags;
956 }
957
958 /* Invoke each handle's event callback (unless the handle has been unsubscribed) */
959 for (int i = 0; i < num_io_handle_events; ++i) {
960 struct handle_data *handle_data = io_handle_events[i];
961
962 if (handle_data->state == HANDLE_STATE_SUBSCRIBED) {
963 AWS_LOGF_TRACE(
964 AWS_LS_IO_EVENT_LOOP,
965 "id=%p: activity on fd %d, invoking handler.",
966 (void *)event_loop,
967 handle_data->owner->data.fd);
968 handle_data->on_event(
969 event_loop, handle_data->owner, handle_data->events_this_loop, handle_data->on_event_user_data);
970 }
971
972 handle_data->events_this_loop = 0;
973 }
974
975 /* Process cross_thread_data */
976 if (should_process_cross_thread_data) {
977 s_process_cross_thread_data(event_loop);
978 }
979
980 /* Run scheduled tasks */
981 uint64_t now_ns = 0;
982 event_loop->clock(&now_ns); /* If clock fails, now_ns will be 0 and tasks scheduled for a specific time
983 will not be run. That's ok, we'll handle them next time around. */
984 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: running scheduled tasks.", (void *)event_loop);
985 aws_task_scheduler_run_all(&impl->thread_data.scheduler, now_ns);
986
987 /* Set timeout for next kevent() call.
988 * If clock fails, or scheduler has no tasks, use default timeout */
989 bool use_default_timeout = false;
990
991 int err = event_loop->clock(&now_ns);
992 if (err) {
993 use_default_timeout = true;
994 }
995
996 uint64_t next_run_time_ns;
997 if (!aws_task_scheduler_has_tasks(&impl->thread_data.scheduler, &next_run_time_ns)) {
998
999 use_default_timeout = true;
1000 }
1001
1002 if (use_default_timeout) {
1003 AWS_LOGF_TRACE(
1004 AWS_LS_IO_EVENT_LOOP, "id=%p: no more scheduled tasks using default timeout.", (void *)event_loop);
1005 timeout.tv_sec = DEFAULT_TIMEOUT_SEC;
1006 timeout.tv_nsec = 0;
1007 } else {
1008 /* Convert from timestamp in nanoseconds, to timeout in seconds with nanosecond remainder */
1009 uint64_t timeout_ns = next_run_time_ns > now_ns ? next_run_time_ns - now_ns : 0;
1010
1011 uint64_t timeout_remainder_ns = 0;
1012 uint64_t timeout_sec =
1013 aws_timestamp_convert(timeout_ns, AWS_TIMESTAMP_NANOS, AWS_TIMESTAMP_SECS, &timeout_remainder_ns);
1014
1015 if (timeout_sec > LONG_MAX) { /* Check for overflow. On Darwin, these values are stored as longs */
1016 timeout_sec = LONG_MAX;
1017 timeout_remainder_ns = 0;
1018 }
1019
1020 AWS_LOGF_TRACE(
1021 AWS_LS_IO_EVENT_LOOP,
1022 "id=%p: detected more scheduled tasks with the next occurring at "
1023 "%llu using timeout of %ds %lluns.",
1024 (void *)event_loop,
1025 (unsigned long long)timeout_ns,
1026 (int)timeout_sec,
1027 (unsigned long long)timeout_remainder_ns);
1028 timeout.tv_sec = (time_t)(timeout_sec);
1029 timeout.tv_nsec = (long)(timeout_remainder_ns);
1030 }
1031
1032 aws_event_loop_register_tick_end(event_loop);
1033 }
1034
1035 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: exiting main loop", (void *)event_loop);
1036 /* reset to NULL. This should be updated again during destroy before tasks are canceled. */
1037 aws_atomic_store_ptr(&impl->running_thread_id, NULL);
1038 }