Debian Codegraph @

crt/aws-c-io/source/windows/iocp/iocp_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 #include <aws/io/event_loop.h>
6
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
13 #include <aws/io/logging.h>
14 #include <aws/io/private/event_loop_impl.h>
15
16 /*
17 * Note: windows.h does not include ntstatus when compiled lean and mean.
18 * winternl is the proper place to pickup ntstatus
19 */
20 #include <windows.h>
21 #include <winternl.h>
22
23 /* The next set of struct definitions are taken directly from the
24 windows documentation. We can't include the header files directly
25 due to winsock. Also some of the definitions here aren't in the public API
26 but it's the only way to do the thing we need to do. So we just declare it
27 here and use dynamic binding to do the voodoo magic. */
28 struct FILE_BASIC_INFORMATION {
29 LARGE_INTEGER CreationTime;
30 LARGE_INTEGER LastAccessTime;
31 LARGE_INTEGER LastWriteTime;
32 LARGE_INTEGER ChangeTime;
33 DWORD FileAttributes;
34 };
35
36 struct FILE_COMPLETION_INFORMATION {
37 HANDLE Port;
38 PVOID Key;
39 };
40
41 struct IO_STATUS_BLOCK {
42 union {
43 NTSTATUS Status;
44 PVOID Pointer;
45 } status_block;
46
47 ULONG_PTR Information;
48 };
49
50 enum FILE_INFORMATION_CLASS {
51 FileReplaceCompletionInformation = 0x3D,
52 };
53 typedef NTSTATUS(NTAPI NTSetInformationFile)(
54 HANDLE file_handle,
55 struct IO_STATUS_BLOCK *io_status_block,
56 void *file_information,
57 ULONG length,
58 enum FILE_INFORMATION_CLASS file_information_class);
59
60 NTSetInformationFile *s_set_info_fn = NULL;
61 /* END of windows hackery here. */
62
63 typedef enum event_thread_state {
64 EVENT_THREAD_STATE_READY_TO_RUN,
65 EVENT_THREAD_STATE_RUNNING,
66 EVENT_THREAD_STATE_STOPPING,
67 } event_thread_state;
68
69 struct iocp_loop {
70 HANDLE iocp_handle;
71 struct aws_thread thread_created_on;
72 aws_thread_id_t thread_joined_to;
73 struct aws_atomic_var running_thread_id;
74
75 /* synced_data holds things that must be communicated across threads.
76 * When the event-thread is running, the mutex must be locked while anyone touches anything in synced_data.
77 * If this data is modified outside the event-thread, the thread is signaled via activity on a pipe. */
78 struct {
79 struct aws_mutex mutex;
80 bool thread_signaled; /* whether thread has been signaled about changes to synced_data */
81 struct aws_linked_list tasks_to_schedule;
82 event_thread_state state;
83 } synced_data;
84
85 /* thread_data holds things which, when the event-thread is running, may only be touched by the thread */
86 struct {
87 struct aws_task_scheduler scheduler;
88
89 /* These variables duplicate ones in synced_data.
90 * We move values out while holding the mutex and operate on them later */
91 event_thread_state state;
92 } thread_data;
93
94 struct aws_thread_options thread_options;
95 };
96
97 enum {
98 DEFAULT_TIMEOUT_MS = 100000,
99
100 /* Max I/O completion packets to process per loop of the event-thread */
101 MAX_COMPLETION_PACKETS_PER_LOOP = 100,
102 };
103
104 static void s_start_destroy(struct aws_event_loop *event_loop);
105 static void s_complete_destroy(struct aws_event_loop *event_loop);
106 static int s_run(struct aws_event_loop *event_loop);
107 static int s_stop(struct aws_event_loop *event_loop);
108 static int s_wait_for_stop_completion(struct aws_event_loop *event_loop);
109 static void s_schedule_task_now(struct aws_event_loop *event_loop, struct aws_task *task);
110 static void s_schedule_task_now_serialized(struct aws_event_loop *event_loop, struct aws_task *task);
111 static void s_schedule_task_future(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos);
112 static void s_cancel_task(struct aws_event_loop *event_loop, struct aws_task *task);
113 static int s_connect_to_io_completion_port(struct aws_event_loop *event_loop, struct aws_io_handle *handle);
114 static bool s_is_event_thread(struct aws_event_loop *event_loop);
115 static int s_subscribe_to_io_events(
116 struct aws_event_loop *event_loop,
117 struct aws_io_handle *handle,
118 int events,
119 aws_event_loop_on_event_fn *on_event,
120 void *user_data) {
121 (void)handle;
122 (void)events;
123 (void)on_event;
124 (void)user_data;
125 AWS_LOGF_ERROR(
126 AWS_LS_IO_EVENT_LOOP,
127 "id=%p: subscribe_to_io_events() is not supported using IOCP Event Loops",
128 (void *)event_loop);
129 return aws_raise_error(AWS_ERROR_PLATFORM_NOT_SUPPORTED);
130 }
131 static int s_unsubscribe_from_io_events(struct aws_event_loop *event_loop, struct aws_io_handle *handle);
132 static void s_free_io_event_resources(void *user_data);
133 static void aws_event_loop_thread(void *user_data);
134
135 void aws_overlapped_init(
136 struct aws_overlapped *overlapped,
137 aws_event_loop_on_completion_fn *on_completion,
138 void *user_data) {
139
140 AWS_ASSERT(overlapped);
141
142 AWS_ZERO_STRUCT(overlapped->overlapped);
143 overlapped->on_completion = on_completion;
144 overlapped->user_data = user_data;
145 }
146
147 void aws_overlapped_reset(struct aws_overlapped *overlapped) {
148 AWS_ASSERT(overlapped);
149 AWS_ZERO_STRUCT(overlapped->overlapped);
150 }
151
152 struct _OVERLAPPED *aws_overlapped_to_windows_overlapped(struct aws_overlapped *overlapped) {
153 return (struct _OVERLAPPED *)&overlapped->overlapped;
154 }
155
156 struct aws_event_loop_vtable s_iocp_vtable = {
157 .start_destroy = s_start_destroy,
158 .complete_destroy = s_complete_destroy,
159 .run = s_run,
160 .stop = s_stop,
161 .wait_for_stop_completion = s_wait_for_stop_completion,
162 .schedule_task_now = s_schedule_task_now,
163 .schedule_task_now_serialized = s_schedule_task_now_serialized,
164 .schedule_task_future = s_schedule_task_future,
165 .cancel_task = s_cancel_task,
166 .connect_to_io_completion_port = s_connect_to_io_completion_port,
167 .subscribe_to_io_events = s_subscribe_to_io_events,
168 .unsubscribe_from_io_events = s_unsubscribe_from_io_events,
169 .free_io_event_resources = s_free_io_event_resources,
170 .is_on_callers_thread = s_is_event_thread,
171 };
172
173 struct aws_event_loop *aws_event_loop_new_with_iocp(
174 struct aws_allocator *alloc,
175 const struct aws_event_loop_options *options) {
176 AWS_ASSERT(alloc);
177 AWS_ASSERT(options);
178 AWS_ASSERT(options->clock);
179
180 if (!s_set_info_fn) {
181 HMODULE ntdll = GetModuleHandleA("ntdll.dll");
182
183 if (!ntdll) {
184 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "static: failed to load ntdll.dll");
185 AWS_ASSERT(0);
186 exit(-1);
187 }
188
189 s_set_info_fn = (NTSetInformationFile *)GetProcAddress(ntdll, "NtSetInformationFile");
190 if (!s_set_info_fn) {
191 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "static: failed to load NtSetInformationFile()");
192 AWS_ASSERT(0);
193 exit(-1);
194 }
195 }
196
197 int err = 0;
198
199 struct aws_event_loop *event_loop = NULL;
200 bool clean_up_event_loop_base = false;
201 struct iocp_loop *impl = NULL;
202 bool clean_up_iocp_handle = false;
203 bool clean_up_thread = false;
204 bool clean_up_mutex = false;
205 bool clean_up_scheduler = false;
206
207 event_loop = aws_mem_acquire(alloc, sizeof(struct aws_event_loop));
208 if (!event_loop) {
209 return NULL;
210 }
211
212 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: Initializing IO Completion Port", (void *)event_loop);
213 err = aws_event_loop_init_base(event_loop, alloc, options->clock);
214 if (err) {
215 goto clean_up;
216 }
217 clean_up_event_loop_base = true;
218
219 impl = aws_mem_calloc(alloc, 1, sizeof(struct iocp_loop));
220 if (!impl) {
221 goto clean_up;
222 }
223
224 if (options->thread_options) {
225 impl->thread_options = *options->thread_options;
226 } else {
227 impl->thread_options = *aws_default_thread_options();
228 }
229
230 /* initialize thread id to NULL. This will be updated once the event loop thread starts. */
231 aws_atomic_init_ptr(&impl->running_thread_id, NULL);
232
233 impl->iocp_handle = CreateIoCompletionPort(
234 INVALID_HANDLE_VALUE, /* FileHandle: passing invalid handle creates a new IOCP */
235 NULL, /* ExistingCompletionPort: should be NULL when file handle is invalid. */
236 0, /* CompletionKey: should be 0 when file handle is invalid */
237 1); /* NumberOfConcurrentThreads */
238 if (impl->iocp_handle == NULL) {
239 AWS_LOGF_FATAL(
240 AWS_LS_IO_EVENT_LOOP,
241 "id=%p: CreateIOCompletionPort failed with error %d",
242 (void *)event_loop,
243 (int)GetLastError());
244 aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
245 goto clean_up;
246 }
247 clean_up_iocp_handle = true;
248
249 err = aws_thread_init(&impl->thread_created_on, alloc);
250 if (err) {
251 goto clean_up;
252 }
253 clean_up_thread = true;
254
255 err = aws_mutex_init(&impl->synced_data.mutex);
256 if (err) {
257 goto clean_up;
258 }
259 clean_up_mutex = true;
260
261 aws_linked_list_init(&impl->synced_data.tasks_to_schedule);
262
263 err = aws_task_scheduler_init(&impl->thread_data.scheduler, alloc);
264 if (err) {
265 goto clean_up;
266 }
267 clean_up_scheduler = true;
268
269 event_loop->impl_data = impl;
270
271 event_loop->vtable = &s_iocp_vtable;
272 event_loop->base_elg = options->parent_elg;
273
274 return event_loop;
275
276 clean_up:
277
278 if (clean_up_scheduler) {
279 aws_task_scheduler_clean_up(&impl->thread_data.scheduler);
280 }
281
282 if (clean_up_mutex) {
283 aws_mutex_clean_up(&impl->synced_data.mutex);
284 }
285
286 if (clean_up_thread) {
287 aws_thread_clean_up(&impl->thread_created_on);
288 }
289
290 if (clean_up_iocp_handle) {
291 CloseHandle(impl->iocp_handle);
292 }
293
294 if (impl) {
295 aws_mem_release(alloc, impl);
296 }
297
298 if (clean_up_event_loop_base) {
299 aws_event_loop_clean_up_base(event_loop);
300 }
301
302 if (event_loop) {
303 aws_mem_release(alloc, event_loop);
304 }
305
306 return NULL;
307 }
308
309 static void s_start_destroy(struct aws_event_loop *event_loop) {
310 (void)event_loop;
311 }
312
313 /* Should not be called from event-thread */
314 static void s_complete_destroy(struct aws_event_loop *event_loop) {
315 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: destroying event-loop", (void *)event_loop);
316
317 struct iocp_loop *impl = event_loop->impl_data;
318 AWS_ASSERT(impl);
319
320 /* Stop the event-thread. This might have already happened. It's safe to call multiple times. */
321 aws_event_loop_stop(event_loop);
322 int err = aws_event_loop_wait_for_stop_completion(event_loop);
323 if (err) {
324 AWS_LOGF_ERROR(
325 AWS_LS_IO_EVENT_LOOP,
326 "id=%p: Failed to destroy event-thread, resources have been leaked.",
327 (void *)event_loop);
328 AWS_ASSERT(0 && "Failed to destroy event-thread, resources have been leaked.");
329 return;
330 }
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.
337 * It's possible the a cancelled task adds further tasks to this event_loop, these new tasks would end up in
338 * synced_data.tasks_to_schedule, so clean that up last */
339
340 aws_task_scheduler_clean_up(&impl->thread_data.scheduler); /* cancels remaining tasks in scheduler */
341
342 while (!aws_linked_list_empty(&impl->synced_data.tasks_to_schedule)) {
343 struct aws_linked_list_node *node = aws_linked_list_pop_front(&impl->synced_data.tasks_to_schedule);
344 struct aws_task *task = AWS_CONTAINER_OF(node, struct aws_task, node);
345 task->fn(task, task->arg, AWS_TASK_STATUS_CANCELED);
346 }
347
348 /* Clean up everything else */
349 bool close_iocp_success = CloseHandle(impl->iocp_handle);
350 AWS_ASSERT(close_iocp_success);
351 (void)close_iocp_success;
352
353 aws_mutex_clean_up(&impl->synced_data.mutex);
354 aws_thread_clean_up(&impl->thread_created_on);
355 aws_mem_release(event_loop->alloc, impl);
356 aws_event_loop_clean_up_base(event_loop);
357 aws_mem_release(event_loop->alloc, event_loop);
358 }
359
360 /* Called from any thread.
361 /* Signal to the event-loop thread that synced_data has changed.
362 * This should only be called after changing synced_data.thread_signaled from false to true. */
363 static void s_signal_synced_data_changed(struct aws_event_loop *event_loop) {
364 struct iocp_loop *impl = event_loop->impl_data;
365 AWS_ASSERT(impl);
366
367 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: notified of cross-thread tasks to schedule", (void *)event_loop);
368 /* Enqueue a special completion packet to inform the event-loop that synced_data has changed.
369 * We identify the special packet by using the iocp handle as the completion key.
370 * This wakes the event-loop thread if it was idle. */
371 ULONG_PTR completion_key = (ULONG_PTR)impl->iocp_handle;
372 PostQueuedCompletionStatus(
373 impl->iocp_handle, /* CompletionPort */
374 0, /* dwNumberOfBytesTransferred */
375 completion_key, /* dwCompletionKey */
376 NULL); /* lpOverlapped */
377 }
378
379 static int s_run(struct aws_event_loop *event_loop) {
380 struct iocp_loop *impl = event_loop->impl_data;
381
382 /* Since thread isn't running it's ok to touch thread_data,
383 * and it's ok to touch synced_data without locking the mutex */
384
385 /* If asserts hit, you must call stop() and wait_for_stop_completion() before calling run() again */
386 AWS_ASSERT(impl->thread_data.state == EVENT_THREAD_STATE_READY_TO_RUN);
387
388 impl->synced_data.state = EVENT_THREAD_STATE_RUNNING;
389
390 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: Starting event-loop thread.", (void *)event_loop);
391 aws_thread_increment_unjoined_count();
392 int err = aws_thread_launch(&impl->thread_created_on, aws_event_loop_thread, event_loop, &impl->thread_options);
393 if (err) {
394 aws_thread_decrement_unjoined_count();
395 AWS_LOGF_FATAL(AWS_LS_IO_EVENT_LOOP, "id=%p: thread creation failed.", (void *)event_loop);
396 goto clean_up;
397 }
398
399 return AWS_OP_SUCCESS;
400
401 clean_up:
402 impl->synced_data.state = EVENT_THREAD_STATE_READY_TO_RUN;
403 return AWS_OP_ERR;
404 }
405
406 /* Called from any thread */
407 static int s_stop(struct aws_event_loop *event_loop) {
408 struct iocp_loop *impl = event_loop->impl_data;
409 AWS_ASSERT(impl);
410
411 bool signal_thread = false;
412 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: Stopping event-loop thread.", (void *)event_loop);
413 { /* Begin critical section */
414 aws_mutex_lock(&impl->synced_data.mutex);
415 if (impl->synced_data.state == EVENT_THREAD_STATE_RUNNING) {
416 impl->synced_data.state = EVENT_THREAD_STATE_STOPPING;
417 signal_thread = !impl->synced_data.thread_signaled;
418 impl->synced_data.thread_signaled = true;
419 }
420 aws_mutex_unlock(&impl->synced_data.mutex);
421 } /* End critical section */
422
423 if (signal_thread) {
424 s_signal_synced_data_changed(event_loop);
425 }
426
427 return AWS_OP_SUCCESS;
428 }
429
430 /* Should not be called from event-thread */
431 static int s_wait_for_stop_completion(struct aws_event_loop *event_loop) {
432 struct iocp_loop *impl = event_loop->impl_data;
433 AWS_ASSERT(impl);
434
435 #ifdef DEBUG_BUILD
436 aws_mutex_lock(&impl->synced_data.mutex);
437 /* call stop() before wait_for_stop_completion() or you'll wait forever */
438 AWS_ASSERT(impl->synced_data.state != EVENT_THREAD_STATE_RUNNING);
439 aws_mutex_unlock(&impl->synced_data.mutex);
440 #endif
441
442 int err = aws_thread_join(&impl->thread_created_on);
443 aws_thread_decrement_unjoined_count();
444 if (err) {
445 return AWS_OP_ERR;
446 }
447
448 /* Since thread is no longer running it's ok to touch thread_data,
449 * and it's ok to touch synced_data without locking the mutex */
450 impl->synced_data.state = EVENT_THREAD_STATE_READY_TO_RUN;
451 impl->thread_data.state = EVENT_THREAD_STATE_READY_TO_RUN;
452
453 return AWS_OP_SUCCESS;
454 }
455
456 static void s_schedule_task_cross_thread(
457 struct aws_event_loop *event_loop,
458 struct aws_task *task,
459 uint64_t run_at_nanos) {
460 struct iocp_loop *impl = event_loop->impl_data;
461
462 AWS_LOGF_TRACE(
463 AWS_LS_IO_EVENT_LOOP,
464 "id=%p: Scheduling %s task %p cross-thread for timestamp %llu",
465 (void *)event_loop,
466 task->type_tag,
467 (void *)task,
468 (unsigned long long)run_at_nanos);
469 /* Otherwise, add it to synced_data.tasks_to_schedule and signal the event-thread to process it */
470 task->timestamp = run_at_nanos;
471 bool should_signal_thread = false;
472
473 { /* Begin critical section */
474 aws_mutex_lock(&impl->synced_data.mutex);
475 aws_linked_list_push_back(&impl->synced_data.tasks_to_schedule, &task->node);
476
477 /* Signal thread that synced_data has changed (unless it's been signaled already) */
478 if (!impl->synced_data.thread_signaled) {
479 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: Waking up event-loop thread", (void *)event_loop);
480 should_signal_thread = true;
481 impl->synced_data.thread_signaled = true;
482 }
483
484 aws_mutex_unlock(&impl->synced_data.mutex);
485 } /* End critical section */
486
487 if (should_signal_thread) {
488 s_signal_synced_data_changed(event_loop);
489 }
490 }
491
492 /* Common function used by schedule_task_now() and schedule_task_future().
493 * When run_at_nanos is 0, it's treated as a "now" task.
494 * Called from any thread */
495 static void s_schedule_task_common(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos) {
496 struct iocp_loop *impl = event_loop->impl_data;
497 AWS_ASSERT(impl);
498 AWS_ASSERT(task);
499
500 /* If we're on the event-thread, just schedule it directly */
501 if (s_is_event_thread(event_loop)) {
502 AWS_LOGF_TRACE(
503 AWS_LS_IO_EVENT_LOOP,
504 "id=%p: scheduling %s task %p in-thread for timestamp %llu",
505 (void *)event_loop,
506 task->type_tag,
507 (void *)task,
508 (unsigned long long)run_at_nanos);
509 if (run_at_nanos == 0) {
510 aws_task_scheduler_schedule_now(&impl->thread_data.scheduler, task);
511 } else {
512 aws_task_scheduler_schedule_future(&impl->thread_data.scheduler, task, run_at_nanos);
513 }
514 return;
515 }
516
517 s_schedule_task_cross_thread(event_loop, task, run_at_nanos);
518 }
519
520 /* Called from any thread */
521 static void s_schedule_task_now(struct aws_event_loop *event_loop, struct aws_task *task) {
522 s_schedule_task_common(event_loop, task, 0 /* use zero to denote it's a "now" task */);
523 }
524
525 static void s_schedule_task_now_serialized(struct aws_event_loop *event_loop, struct aws_task *task) {
526 s_schedule_task_cross_thread(event_loop, task, 0 /* use zero to denote it's a "now" task */);
527 }
528
529 /* Called from any thread */
530 static void s_schedule_task_future(struct aws_event_loop *event_loop, struct aws_task *task, uint64_t run_at_nanos) {
531 s_schedule_task_common(event_loop, task, run_at_nanos);
532 }
533
534 static void s_cancel_task(struct aws_event_loop *event_loop, struct aws_task *task) {
535 AWS_LOGF_TRACE(
536 AWS_LS_IO_EVENT_LOOP, "id=%p: cancelling %s task %p", (void *)event_loop, task->type_tag, (void *)task);
537 struct iocp_loop *iocp_loop = event_loop->impl_data;
538 aws_task_scheduler_cancel_task(&iocp_loop->thread_data.scheduler, task);
539 }
540
541 /* Called from any thread */
542 static bool s_is_event_thread(struct aws_event_loop *event_loop) {
543 struct iocp_loop *impl = event_loop->impl_data;
544 AWS_ASSERT(impl);
545
546 aws_thread_id_t *el_thread_id = aws_atomic_load_ptr(&impl->running_thread_id);
547 return el_thread_id && aws_thread_thread_id_equal(*el_thread_id, aws_thread_current_thread_id());
548 }
549
550 /* Called from any thread */
551 static int s_connect_to_io_completion_port(struct aws_event_loop *event_loop, struct aws_io_handle *handle) {
552 struct iocp_loop *impl = event_loop->impl_data;
553 AWS_ASSERT(impl);
554 AWS_ASSERT(handle);
555
556 AWS_LOGF_TRACE(
557 AWS_LS_IO_EVENT_LOOP,
558 "id=%p: subscribing to events on handle %p",
559 (void *)event_loop,
560 (void *)handle->data.handle);
561
562 const HANDLE iocp_handle = CreateIoCompletionPort(
563 handle->data.handle, /* FileHandle */
564 impl->iocp_handle, /* ExistingCompletionPort */
565 0, /* CompletionKey */
566 1); /* NumberOfConcurrentThreads */
567
568 /* iocp_handle should be the event loop's handle if this succeeded */
569 bool iocp_associated = iocp_handle == impl->iocp_handle;
570
571 /* clang-format off */
572 #if defined(AWS_SUPPORT_WIN7)
573 /*
574 * When associating named pipes, it is possible to open the same pipe in the same
575 * process for read and write, causing multiple attempts to associate. This will
576 * return ERROR_INVALID_PARAMETER from GetLastError on the second association on Win7,
577 * but the prior association will continue. Detecting this before attempting to
578 * associate requires the DDK API.
579 */
580 const bool already_associated =
581 GetLastError() == ERROR_INVALID_PARAMETER &&
582 /* Both handles should be valid prior to the above call. If they are,
583 * and we got ERROR_INVALID_PARAMETER, the file handle already has an IOCP association */
584 handle->data.handle != INVALID_HANDLE_VALUE && impl->iocp_handle != INVALID_HANDLE_VALUE;
585 iocp_associated |= already_associated;
586 #endif
587 /* clang-format on */
588
589 if (!iocp_associated) {
590 AWS_LOGF_ERROR(
591 AWS_LS_IO_EVENT_LOOP,
592 "id=%p: CreateIoCompletionPort() failed with error %d",
593 (void *)event_loop,
594 (int)GetLastError());
595 return aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
596 }
597
598 /* As an optimization, tell Windows not to bother signaling the handle when async I/O completes.
599 * We're using I/O completion ports, we don't need further mechanisms to know when I/O completes. */
600 SetFileCompletionNotificationModes(handle->data.handle, FILE_SKIP_SET_EVENT_ON_HANDLE);
601
602 /* iocp_event_loop has no need to store additional data per aws_io_handle */
603 handle->additional_data = NULL;
604
605 return AWS_OP_SUCCESS;
606 }
607
608 /* Called from event-thread.
609 * Takes tasks from tasks_to_schedule and adds them to the scheduler. */
610 static void s_process_tasks_to_schedule(struct aws_event_loop *event_loop, struct aws_linked_list *tasks_to_schedule) {
611 struct iocp_loop *impl = event_loop->impl_data;
612 AWS_ASSERT(impl);
613
614 while (!aws_linked_list_empty(tasks_to_schedule)) {
615 struct aws_linked_list_node *node = aws_linked_list_pop_front(tasks_to_schedule);
616 struct aws_task *task = AWS_CONTAINER_OF(node, struct aws_task, node);
617
618 /* We use timestamp of 0 to denote that it's a "now" task */
619 if (task->timestamp == 0) {
620 aws_task_scheduler_schedule_now(&impl->thread_data.scheduler, task);
621 } else {
622 aws_task_scheduler_schedule_future(&impl->thread_data.scheduler, task, task->timestamp);
623 }
624 }
625 }
626
627 /* Runs on the event-thread. */
628 static void s_process_synced_data(struct aws_event_loop *event_loop) {
629 struct iocp_loop *impl = event_loop->impl_data;
630
631 /* If there are tasks to schedule, grab them all out of synced_data.tasks_to_schedule.
632 * We'll process them later, so that we minimize time spent holding the mutex. */
633 struct aws_linked_list tasks_to_schedule;
634 aws_linked_list_init(&tasks_to_schedule);
635
636 { /* Begin critical section */
637 aws_mutex_lock(&impl->synced_data.mutex);
638 impl->synced_data.thread_signaled = false;
639
640 bool initiate_stop = (impl->synced_data.state == EVENT_THREAD_STATE_STOPPING) &&
641 (impl->thread_data.state == EVENT_THREAD_STATE_RUNNING);
642 if (AWS_UNLIKELY(initiate_stop)) {
643 impl->thread_data.state = EVENT_THREAD_STATE_STOPPING;
644 }
645
646 aws_linked_list_swap_contents(&impl->synced_data.tasks_to_schedule, &tasks_to_schedule);
647
648 aws_mutex_unlock(&impl->synced_data.mutex);
649 } /* End critical section */
650
651 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: notified of cross-thread tasks to schedule", (void *)event_loop);
652 s_process_tasks_to_schedule(event_loop, &tasks_to_schedule);
653 }
654
655 static int s_unsubscribe_from_io_events(struct aws_event_loop *event_loop, struct aws_io_handle *handle) {
656 (void)event_loop;
657 AWS_LOGF_TRACE(
658 AWS_LS_IO_EVENT_LOOP,
659 "id=%p: un-subscribing from events on handle %p",
660 (void *)event_loop,
661 (void *)handle->data.handle);
662
663 struct FILE_COMPLETION_INFORMATION file_completion_info;
664 file_completion_info.Key = NULL;
665 file_completion_info.Port = NULL;
666
667 struct IO_STATUS_BLOCK status_block;
668 AWS_ZERO_STRUCT(status_block);
669
670 NTSTATUS status = s_set_info_fn(
671 handle->data.handle,
672 &status_block,
673 &file_completion_info,
674 sizeof(file_completion_info),
675 FileReplaceCompletionInformation);
676
677 if (!status) {
678 return AWS_OP_SUCCESS;
679 }
680
681 AWS_LOGF_ERROR(
682 AWS_LS_IO_EVENT_LOOP,
683 "id=%p: failed to un-subscribe from events on handle %p",
684 (void *)event_loop,
685 (void *)handle->data.handle);
686 return aws_raise_error(AWS_ERROR_SYS_CALL_FAILURE);
687 }
688
689 static void s_free_io_event_resources(void *user_data) {
690 /* iocp has no additional data stored to handle I/O events */
691 (void)user_data;
692 }
693
694 /**
695 * This just calls GetQueuedCompletionStatusEx()
696 *
697 * We broke this out into its own function so that the stacktrace clearly shows
698 * what this thread is doing. We've had a lot of cases where users think this
699 * thread is deadlocked because it's stuck here. We want it to be clear
700 * that it's doing nothing on purpose. It's waiting for events to happen...
701 */
702 AWS_NO_INLINE
703 static bool aws_event_loop_listen_for_io_events(
704 HANDLE iocp_handle,
705 OVERLAPPED_ENTRY completion_packets[MAX_COMPLETION_PACKETS_PER_LOOP],
706 ULONG *num_entries,
707 DWORD timeout_ms) {
708
709 return GetQueuedCompletionStatusEx(
710 iocp_handle, /* Completion port */
711 completion_packets, /* Out: completion port entries */
712 MAX_COMPLETION_PACKETS_PER_LOOP, /* max number of entries to remove */
713 num_entries, /* Out: number of entries removed */
714 timeout_ms, /* Timeout in ms. If timeout reached then FALSE is returned. */
715 false); /* Alertable */
716 }
717
718 /* Called from event-thread */
719 static void aws_event_loop_thread(void *user_data) {
720 struct aws_event_loop *event_loop = user_data;
721 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: main loop started", (void *)event_loop);
722
723 struct iocp_loop *impl = event_loop->impl_data;
724
725 /* Set thread id to event loop thread id. */
726 aws_atomic_store_ptr(&impl->running_thread_id, &impl->thread_created_on.thread_id);
727
728 AWS_ASSERT(impl->thread_data.state == EVENT_THREAD_STATE_READY_TO_RUN);
729 impl->thread_data.state = EVENT_THREAD_STATE_RUNNING;
730
731 DWORD timeout_ms = DEFAULT_TIMEOUT_MS;
732
733 OVERLAPPED_ENTRY completion_packets[MAX_COMPLETION_PACKETS_PER_LOOP];
734 AWS_ZERO_ARRAY(completion_packets);
735
736 AWS_LOGF_INFO(AWS_LS_IO_EVENT_LOOP, "id=%p: default timeout %d", (void *)event_loop, (int)timeout_ms);
737
738 while (impl->thread_data.state == EVENT_THREAD_STATE_RUNNING) {
739 ULONG num_entries = 0;
740 bool should_process_synced_data = false;
741 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: waiting for a maximum of %d ms", (void *)event_loop, timeout_ms);
742 bool has_completion_entries = aws_event_loop_listen_for_io_events(
743 impl->iocp_handle, /* Completion port */
744 completion_packets, /* Out: completion port entries */
745 &num_entries, /* Out: number of entries removed */
746 timeout_ms); /* Timeout in ms. If timeout reached then FALSE is returned. */
747
748 aws_event_loop_register_tick_start(event_loop);
749
750 if (has_completion_entries) {
751 AWS_LOGF_TRACE(
752 AWS_LS_IO_EVENT_LOOP,
753 "id=%p: wake up with %lu events to process.",
754 (void *)event_loop,
755 (unsigned long)num_entries);
756 for (ULONG i = 0; i < num_entries; ++i) {
757 OVERLAPPED_ENTRY *completion = &completion_packets[i];
758
759 /* Is this a special completion packet which signals that synced_data has changed?
760 * (We use iocp_handle's value as the completion key for these special packets) */
761 if (completion->lpCompletionKey == (ULONG_PTR)impl->iocp_handle) {
762 should_process_synced_data = true;
763 } else {
764 /* Otherwise this was a normal completion on a connected aws_io_handle.
765 * Get our hands on the aws_overlapped which owns this OVERLAPPED,
766 * and invoke its callback */
767 struct aws_overlapped *overlapped =
768 AWS_CONTAINER_OF(completion->lpOverlapped, struct aws_overlapped, overlapped);
769
770 if (overlapped->on_completion) {
771 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: invoking handler.", (void *)event_loop);
772 overlapped->on_completion(
773 event_loop,
774 overlapped,
775 (int)overlapped->overlapped.Internal, /* Status code for the completed request */
776 completion->dwNumberOfBytesTransferred);
777 }
778 }
779 }
780 } else {
781 /* If no completion entries were dequeued then the timeout must have triggered */
782 AWS_ASSERT(GetLastError() == WAIT_TIMEOUT);
783 }
784
785 /* Process synced_data */
786 if (should_process_synced_data) {
787 s_process_synced_data(event_loop);
788 }
789
790 /* Run scheduled tasks */
791 uint64_t now_ns = 0;
792 event_loop->clock(&now_ns); /* If clock fails, now_ns will be 0 and tasks scheduled for a specific time
793 will not be run. That's ok, we'll handle them next time around. */
794 AWS_LOGF_TRACE(AWS_LS_IO_EVENT_LOOP, "id=%p: running scheduled tasks.", (void *)event_loop);
795 aws_task_scheduler_run_all(&impl->thread_data.scheduler, now_ns);
796
797 /* Set timeout for next GetQueuedCompletionStatus() call.
798 * If clock fails, or scheduler has no tasks, use default timeout */
799 bool use_default_timeout = false;
800
801 int err = event_loop->clock(&now_ns);
802 if (err) {
803 use_default_timeout = true;
804 }
805
806 uint64_t next_run_time_ns;
807 if (!aws_task_scheduler_has_tasks(&impl->thread_data.scheduler, &next_run_time_ns)) {
808 use_default_timeout = true;
809 }
810
811 if (use_default_timeout) {
812 AWS_LOGF_TRACE(
813 AWS_LS_IO_EVENT_LOOP, "id=%p: no more scheduled tasks using default timeout.", (void *)event_loop);
814 timeout_ms = DEFAULT_TIMEOUT_MS;
815 } else {
816 /* Translate timestamp (in nanoseconds) to timeout (in milliseconds) */
817 uint64_t timeout_ns = (next_run_time_ns > now_ns) ? (next_run_time_ns - now_ns) : 0;
818 uint64_t timeout_ms64 = aws_timestamp_convert(timeout_ns, AWS_TIMESTAMP_NANOS, AWS_TIMESTAMP_MILLIS, NULL);
819 timeout_ms = timeout_ms64 > MAXDWORD ? MAXDWORD : (DWORD)timeout_ms64;
820 AWS_LOGF_TRACE(
821 AWS_LS_IO_EVENT_LOOP,
822 "id=%p: detected more scheduled tasks with the next occurring at "
823 "%llu, using timeout of %d.",
824 (void *)event_loop,
825 (unsigned long long)next_run_time_ns,
826 (int)timeout_ms);
827 }
828
829 aws_event_loop_register_tick_end(event_loop);
830 }
831 AWS_LOGF_DEBUG(AWS_LS_IO_EVENT_LOOP, "id=%p: exiting main loop", (void *)event_loop);
832 /* set back to NULL. This should be updated again in destroy, right before task cancelation happens. */
833 aws_atomic_store_ptr(&impl->running_thread_id, NULL);
834 }