Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #include <chashmap.h>
26 : #include <cthreadcomm.h>
27 : #include <cthreadpool.h>
28 : #include <cvector.h>
29 : #include <errno.h>
30 : #include <internal/catfork.h>
31 : #include <internal/cdeadline.h>
32 : #include <internal/chashinsert.h>
33 : #include <internal/cpoll.h>
34 : #include <internal/cqueueowner.h>
35 : #include <internal/test_helpers/common.h>
36 : #include <internal/test_helpers/cthreadcomm.h>
37 : #include <limits.h>
38 : #include <poll.h>
39 : #include <stdatomic.h>
40 : #include <stdint.h>
41 : #include <stdlib.h>
42 : #include <string.h>
43 : #include <sys/stat.h>
44 : #include <unistd.h>
45 :
46 : #ifdef RUNNING_UNIT_TESTS
47 : #include <assert.h>
48 : #endif
49 :
50 : // Initialises cond so its timed waits measure deadlines on CLOCK_MONOTONIC.
51 : // Every condition variable of this file that a timed wait can block on comes
52 : // from here and every deadline from CLOCK_MONOTONIC, so a step of the wall
53 : // clock can't stretch a timeout. Gives 0 or the first error the library
54 : // reports.
55 12417 : static int init_monotonic_cond_var(ccol__cond_var *cond) {
56 12417 : ccol__cond_var_attr attr;
57 12417 : int rv = ccol__cond_var_attr_init(attr);
58 12418 : if (rv != 0) return rv;
59 12419 : rv = ccol__cond_var_attr_setclock(attr, CLOCK_MONOTONIC);
60 12420 : if (rv == 0) rv = ccol__cond_var_init_ca(*cond, attr);
61 12420 : ccol__cond_var_attr_destroy(attr);
62 12420 : return rv;
63 : }
64 :
65 : // A waiter node, linked into a queue's read or write list by a cselect() call
66 : // (for the length of the call) or by a loop registration (for its whole life).
67 : // The list and every field here are read and changed under the owning queue's
68 : // mutex, which keeps the nodes valid while a producer walks the list. efd is
69 : // the eventfd of epoll mode, -1 in condition-variable mode. fwd_hops (under
70 : // *sel_mtx) counts how many listeners the outstanding wake has visited without
71 : // any of them moving a message; a fresh wake carries 0.
72 : typedef struct ccol_sel_waiter {
73 : ccol__mutex *sel_mtx;
74 : ccol__cond_var *sel_cond;
75 : bool *ready;
76 : int efd;
77 : uint32_t fwd_hops;
78 : struct ccol_sel_waiter *prev;
79 : struct ccol_sel_waiter *next;
80 : } ccol_sel_waiter;
81 :
82 : #ifdef RUNNING_UNIT_TESTS
83 : // Test-only delay in notify_waiter() between holding the queue's mutex and
84 : // locking sel_mtx, so a test can land a fork() inside that window.
85 : static _Atomic int g_notify_waiter_test_delay_us = 0;
86 2 : void cthreadcomm__notify_waiter_test_set_delay_us(int us) {
87 2 : atomic_store(&g_notify_waiter_test_delay_us, us);
88 2 : }
89 :
90 : // Test-only count of the eventfd wakes that notify_waiter() delivers.
91 : static _Atomic uint64_t g_notify_waiter_eventfd_wakes = 0;
92 12 : uint64_t cselect__test_eventfd_wake_count(void) {
93 12 : return atomic_load_explicit(&g_notify_waiter_eventfd_wakes,
94 : memory_order_relaxed);
95 : }
96 : #endif
97 :
98 : // Thin wrappers over the wake descriptor of internal/cpoll.h: notify makes it
99 : // readable and drain makes it quiet. Every eventfd of this file goes through
100 : // them, so the file has one wake call whatever the system.
101 68101 : static void eventfd_notify(int efd) { ccol_wakefd_notify(efd); }
102 :
103 25524 : static void eventfd_drain(int efd) { ccol_wakefd_drain(efd); }
104 :
105 : // Wakes one waiter node. Every send, receive, state change and cascade step
106 : // wakes a listener through it. The caller holds the owning queue's mutex.
107 : // *ready is the only record of an outstanding wake: The first notify after the
108 : // owner cleared it sets it and delivers (an eventfd write, or a signal when the
109 : // node has no eventfd), and later ones deliver nothing, so a busy queue costs
110 : // one write per dispatch. The eventfd write happens under sel_mtx with the
111 : // store to *ready, and the owner clears *ready and drains the eventfd in one
112 : // critical section under the same mutex, so the two never disagree and no wake
113 : // is lost. A fresh wake resets fwd_hops to 0.
114 229319 : static void notify_waiter(ccol_sel_waiter *w) {
115 : #ifdef RUNNING_UNIT_TESTS
116 229319 : int delay_us = atomic_load(&g_notify_waiter_test_delay_us);
117 229319 : if (delay_us > 0) {
118 1 : struct timespec ts = {.tv_sec = delay_us / 1000000,
119 1 : .tv_nsec = (long)(delay_us % 1000000) * 1000L};
120 1 : nanosleep(&ts, NULL);
121 : }
122 : #endif
123 229319 : ccol__mutex_lock(*w->sel_mtx);
124 229319 : bool already_pending = *w->ready;
125 229319 : *w->ready = true;
126 229319 : w->fwd_hops = 0;
127 229319 : if (!already_pending && w->efd >= 0) {
128 : #ifdef RUNNING_UNIT_TESTS
129 17745 : atomic_fetch_add_explicit(&g_notify_waiter_eventfd_wakes, (uint64_t)1,
130 : memory_order_relaxed);
131 : #endif
132 17745 : eventfd_notify(w->efd);
133 : }
134 229319 : ccol__mutex_unlock(*w->sel_mtx);
135 229319 : if (!already_pending && w->efd < 0) ccol__cond_var_signal(*w->sel_cond);
136 229319 : }
137 :
138 : // Like notify_waiter(), for a wake a listener forwards after a dispatch that
139 : // moved nothing; hops is how many listeners it has visited. When a wake is
140 : // already outstanding the smaller hop count wins, so a forward never shortens
141 : // the walk of a wake already on its way.
142 2967 : static void notify_waiter_forwarded(ccol_sel_waiter *w, uint32_t hops) {
143 2967 : ccol__mutex_lock(*w->sel_mtx);
144 2967 : bool already_pending = *w->ready;
145 2967 : *w->ready = true;
146 2967 : if (!already_pending || hops < w->fwd_hops) w->fwd_hops = hops;
147 2967 : if (!already_pending && w->efd >= 0) {
148 : #ifdef RUNNING_UNIT_TESTS
149 822 : atomic_fetch_add_explicit(&g_notify_waiter_eventfd_wakes, (uint64_t)1,
150 : memory_order_relaxed);
151 : #endif
152 822 : eventfd_notify(w->efd);
153 : }
154 2967 : ccol__mutex_unlock(*w->sel_mtx);
155 2967 : if (!already_pending && w->efd < 0) ccol__cond_var_signal(*w->sel_cond);
156 2967 : }
157 :
158 : // Says whether the list at head has more than k nodes, stopping after k + 1.
159 : // The cascade step uses it to stop a forwarded wake once it has visited every
160 : // listener. The caller holds the queue's mutex.
161 925 : static bool sel_list_longer_than(const ccol_sel_waiter *head, uint32_t k) {
162 925 : uint32_t seen = 0;
163 2617 : for (const ccol_sel_waiter *w = head; w != NULL; w = w->next) {
164 1857 : if (seen == k) return true;
165 1692 : seen++;
166 : }
167 : return false;
168 : }
169 :
170 : // Wakes one waiter of a list and moves *rotor on, so successive calls rotate
171 : // through every linked waiter. It's for a message or a free slot, where waking
172 : // more than one is a thundering herd. *rotor is NULL (start at *head) or a node
173 : // of this list; sel_unlink_waiter_locked keeps that true. The rotation matters
174 : // because a loop registration stays linked and new waiters prepend: Without it
175 : // the newest registration would get every notify and an older one whose sibling
176 : // keeps the queue drained would never be called. The caller holds the queue's
177 : // mutex.
178 580155 : static void notify_one_sel_waiter(ccol_sel_waiter **head,
179 : ccol_sel_waiter **rotor) {
180 1340399 : ccol_sel_waiter *target = *rotor ? *rotor : *head;
181 542768 : if (!target) return;
182 217476 : notify_waiter(target);
183 217476 : *rotor = target->next;
184 : }
185 :
186 : // Wakes every waiter of a list, for disable_sending and enable_sending, after
187 : // which all of them must look at the state again. The caller holds the queue's
188 : // mutex.
189 352 : static void notify_all_sel_waiters(ccol_sel_waiter *head) {
190 355 : for (ccol_sel_waiter *w = head; w != NULL; w = w->next) notify_waiter(w);
191 : }
192 :
193 : // The thread-specific key that holds the queue whose loop callback runs on the
194 : // calling thread, or NULL. One key answers that for every queue. live says the
195 : // key exists: Creation can fail, and a value set on a key we don't own would
196 : // reach another component's destructor. ceventloop_create_mp refuses to build a
197 : // loop while live is false, so only an existing key is ever set. The key is
198 : // deleted when the loop slot table is released, so dlopen() and dlclose()
199 : // cycles don't use up keys.
200 : static struct {
201 : ccol__thread_ls_key key;
202 : ccol__once_flag once;
203 : atomic_bool live;
204 : } queue_dispatch_marker_bundle = {.once = CCOL__ONCE_INIT};
205 :
206 : // Creates the marker key and records whether that worked. It runs once,
207 : // through queue_dispatch_marker_bundle.once, before the key is first needed.
208 46 : static void queue_dispatch_marker_init(void) {
209 46 : if (ccol__thread_ls_key_create(queue_dispatch_marker_bundle.key, NULL) == 0)
210 46 : atomic_store(&queue_dispatch_marker_bundle.live, true);
211 46 : }
212 :
213 : // True when the marker key exists. ceventloop_create_mp asks this first.
214 39413 : static bool queue_dispatch_marker_available(void) {
215 39413 : ccol__call_once(queue_dispatch_marker_bundle.once,
216 : queue_dispatch_marker_init);
217 39413 : return atomic_load(&queue_dispatch_marker_bundle.live);
218 : }
219 :
220 : #ifdef RUNNING_UNIT_TESTS
221 : // Test-only count of upcoming thread mark stores that fail as without memory.
222 : static _Atomic uint32_t g_mark_set_failures = 0;
223 :
224 : // Test-only: Arms the failing mark stores.
225 4 : void ceventloop__test_fail_next_marks(uint32_t count) {
226 4 : atomic_store(&g_mark_set_failures, count);
227 4 : }
228 : #endif
229 :
230 : // Stores value on key for the calling thread and gives 0 or an error number.
231 : // Every thread mark of the module goes through it, so a test can make the store
232 : // fail as it can for real when the C library can't allocate the thread's slot.
233 76927 : static int cthreadcomm_mark_set(ccol__thread_ls_key key, void *value) {
234 : #ifdef RUNNING_UNIT_TESTS
235 76927 : uint32_t left = atomic_load(&g_mark_set_failures);
236 76927 : while (left > 0) {
237 6 : if (atomic_compare_exchange_weak(&g_mark_set_failures, &left, left - 1))
238 : return ENOMEM;
239 : }
240 : #endif
241 76921 : return ccol__thread_ls_set(key, value);
242 : }
243 :
244 : // The queue mark of a thread whose key store failed. A mark tries the key
245 : // first, the thread clears this copy itself, and a check reads both. Without it
246 : // a destroy from a callback would wait for itself instead of being reported.
247 : static __thread const void *queue_dispatch_mark_fallback;
248 :
249 : // Marks the calling thread as running queue's loop callback, so that a destroy
250 : // of the queue from that callback is caught instead of waiting for itself. Only
251 : // a live loop's dispatch calls it, so the key exists. Gives true when the
252 : // fallback copy holds the mark; pass that to queue_dispatch_unmark().
253 16074 : static bool queue_dispatch_mark(void *queue) {
254 16074 : ccol__call_once(queue_dispatch_marker_bundle.once,
255 : queue_dispatch_marker_init);
256 16074 : if (cthreadcomm_mark_set(queue_dispatch_marker_bundle.key, queue) == 0)
257 : return false;
258 2 : queue_dispatch_mark_fallback = queue;
259 2 : return true;
260 : }
261 :
262 : // Clears the queue mark when the callback returns, so the thread's later work
263 : // stays unmarked. Setting NULL on the key needs no storage and can't fail.
264 16074 : static void queue_dispatch_unmark(bool fell_back) {
265 16074 : if (fell_back)
266 2 : queue_dispatch_mark_fallback = NULL;
267 : else
268 16072 : (void)ccol__thread_ls_set(queue_dispatch_marker_bundle.key, NULL);
269 : }
270 :
271 : // Says whether the calling thread runs a callback of queue; the destroy wait
272 : // asks it to catch a destroy from that callback. Without the key no loop
273 : // exists, so the answer is false.
274 5 : static bool queue_dispatch_marker_is(const void *queue) {
275 5 : if (!queue_dispatch_marker_available()) return false;
276 10 : return ccol__thread_ls_get(queue_dispatch_marker_bundle.key) == queue ||
277 5 : queue_dispatch_mark_fallback == queue;
278 : }
279 :
280 : #ifdef RUNNING_UNIT_TESTS
281 : // Test-only: Whether the calling thread runs a callback of queue, the answer
282 : // the queue destroy uses.
283 2 : bool ceventloop__test_dispatches_queue(const void *queue) {
284 2 : return queue_dispatch_marker_is(queue);
285 : }
286 : #endif
287 :
288 : // Waits until no loop dispatch holds a reference to the queue; a queue destroy
289 : // calls it after the caller drained the queue and removed its registrations.
290 : // ceventloop_remove doesn't wait for a callback already running, so such a
291 : // callback can still be inside the queue, and freeing the queue under it is a
292 : // use-after-free. Only a running dispatch holds a reference (see
293 : // queue_dispatch_ref_acquire). This thread holds no lock here, so the wait
294 : // can't close a lock cycle. A destroy from that same callback would wait for
295 : // itself and is a fatal error. It polls a single atomic with short sleeps,
296 : // since a signal would cost every dispatch a condition variable signal for a
297 : // wait that is cold.
298 1025 : static void queue_wait_for_dispatch_refs(_Atomic size_t *refs,
299 : const void *queue) {
300 1025 : if (atomic_load(refs) == 0) return;
301 :
302 3 : if (queue_dispatch_marker_is(queue)) {
303 0 : ccol__fatal_err(
304 : "a queue must not be destroyed from inside an ceventloop "
305 : "callback dispatching that same queue (queue=%p)",
306 : queue);
307 : }
308 :
309 3203 : while (atomic_load(refs) != 0) {
310 3200 : struct timespec ts = {.tv_sec = 0, .tv_nsec = 200000L};
311 3200 : nanosleep(&ts, NULL);
312 : }
313 : }
314 :
315 : // Queue mutex fork safety. A fork() while another thread holds a queue's mutex
316 : // leaves that mutex locked for ever in the child. This registry keeps the mutex
317 : // of every live ccircq and cdynmq (a cchan is two ccircqs), so the fork
318 : // handlers can lock them all before fork() and unlock them after. A queue owns
319 : // no thread and no kernel object, so after the unlock its state is valid in the
320 : // child. The registry has no fork handlers of its own: Two independent sets
321 : // would run in an order that depends on which subsystem the process used first,
322 : // and could lock a queue's mutex after a registration's wait_mtx, the reverse
323 : // of notify_waiter's order. One merged set, cthreadcomm_atfork_prepare and its
324 : // release functions, locks each queue's mutex after the stripe locks that own
325 : // its registrations and before their wait_mtx, which matches every nesting in
326 : // this file.
327 : #if CCOL_FORK_SAFETY_REQUIRED
328 : // One registry entry: A live queue's mutex and the address of that queue's
329 : // registry_idx, which always holds the entry's position.
330 : typedef struct {
331 : ccol__mutex *mutex;
332 : size_t *index;
333 : } queue_mutex_registry_entry;
334 :
335 : // The registry. addrs is an unordered vector, so a remove moves the last entry
336 : // into the hole in O(1); it's NULL once the exit destructor released it.
337 : // release_deferred is set when that destructor found a live queue, and the
338 : // remove of the last entry then does the release.
339 : static struct {
340 : ccol__mutex mutex;
341 : ccol__once_flag once;
342 : cvec addrs;
343 : bool release_deferred;
344 : } queue_mutex_registry = {0};
345 : #endif
346 :
347 : // Guards the one merged ccol__at_fork() registration for the queue registry
348 : // and the loop slot table. It's here so the registry can register the handlers
349 : // itself, in a process that never touches ceventloop.
350 : static ccol__once_flag g_cthreadcomm_atfork_once = CCOL__ONCE_INIT;
351 :
352 : static void cthreadcomm_register_atfork_once(void);
353 :
354 : #if CCOL_FORK_SAFETY_REQUIRED
355 : // Creates the registry's mutex and vector on first use, before anything adds,
356 : // removes or walks entries. A failure is fatal.
357 51 : static void queue_mutex_registry_init_globals(void) {
358 51 : if (ccol__mutex_init(queue_mutex_registry.mutex) != 0)
359 0 : ccol__fatal_err("queue mutex registry: failed to initialize mutex");
360 51 : queue_mutex_registry.addrs =
361 51 : cvector_create(sizeof(queue_mutex_registry_entry), NULL);
362 51 : if (!queue_mutex_registry.addrs)
363 0 : ccol__fatal_err("queue mutex registry: failed to allocate address vector");
364 51 : }
365 :
366 : // Registers m, with the queue's registry_idx at index, so a fork() locks it.
367 : // Each queue calls it once, after it's fully built. Gives false when the vector
368 : // can't grow, or after the exit destructor released the registry; the queue
369 : // constructor treats that as an allocation failure. Takes the registry mutex.
370 1067 : static bool queue_mutex_registry_add(ccol__mutex *m, size_t *index) {
371 1067 : ccol__call_once(queue_mutex_registry.once, queue_mutex_registry_init_globals);
372 1067 : ccol__call_once(g_cthreadcomm_atfork_once, cthreadcomm_register_atfork_once);
373 1067 : ccol__mutex_lock(queue_mutex_registry.mutex);
374 1067 : bool ok = false;
375 1067 : if (queue_mutex_registry.addrs != NULL) {
376 1065 : queue_mutex_registry_entry e = {.mutex = m, .index = index};
377 1065 : *index = cvector_size(queue_mutex_registry.addrs);
378 1065 : ok = cvector_push_back(queue_mutex_registry.addrs, &e) == ccol_success;
379 : }
380 1067 : ccol__mutex_unlock(queue_mutex_registry.mutex);
381 1067 : return ok;
382 : }
383 :
384 : #ifdef RUNNING_UNIT_TESTS
385 : // Test-only count of the entries removes examine.
386 : static _Atomic uint64_t g_queue_registry_remove_probes_for_tests = 0;
387 : #endif
388 :
389 : // Unregisters m, so the fork handlers never lock a destroyed mutex; the queue
390 : // destroy calls it before it destroys the mutex. The last entry moves into m's
391 : // position (and that queue's registry_idx is updated), since the fork walk
392 : // needs no order. An entry at *index that isn't m is left alone. When the exit
393 : // destructor deferred the release, removing the last entry frees the vector.
394 : // Takes the registry mutex.
395 1023 : static void queue_mutex_registry_remove(ccol__mutex *m, size_t *index) {
396 1023 : ccol__call_once(queue_mutex_registry.once, queue_mutex_registry_init_globals);
397 1023 : ccol__call_once(g_cthreadcomm_atfork_once, cthreadcomm_register_atfork_once);
398 1023 : ccol__mutex_lock(queue_mutex_registry.mutex);
399 1023 : if (!queue_mutex_registry.addrs) {
400 0 : ccol__mutex_unlock(queue_mutex_registry.mutex);
401 0 : return;
402 : }
403 1023 : size_t n = cvector_size(queue_mutex_registry.addrs);
404 1023 : size_t i = *index;
405 : #ifdef RUNNING_UNIT_TESTS
406 1023 : atomic_fetch_add_explicit(&g_queue_registry_remove_probes_for_tests,
407 : (uint64_t)1, memory_order_relaxed);
408 : #endif
409 1023 : if (i < n &&
410 1023 : ((queue_mutex_registry_entry *)cvector_at(queue_mutex_registry.addrs, i))
411 1023 : ->mutex == m) {
412 1023 : queue_mutex_registry_entry last;
413 1023 : cvector_pop_back(queue_mutex_registry.addrs, &last);
414 1023 : if (i != n - 1) {
415 503 : *(queue_mutex_registry_entry *)cvector_at(queue_mutex_registry.addrs, i) =
416 : last;
417 503 : *last.index = i;
418 : }
419 : }
420 1027 : if (queue_mutex_registry.release_deferred &&
421 4 : cvector_size(queue_mutex_registry.addrs) == 0) {
422 3 : cvector_destroy(queue_mutex_registry.addrs);
423 3 : queue_mutex_registry.release_deferred = false;
424 : }
425 1023 : ccol__mutex_unlock(queue_mutex_registry.mutex);
426 : }
427 :
428 : #ifdef RUNNING_UNIT_TESTS
429 : // Test-only: Checks that every entry's registry_idx names its position, and
430 : // gives the entry count and the probes removes made, so a test can prove a
431 : // remove is O(1).
432 259 : bool ccol__queue_mutex_registry_check_for_tests(size_t *count,
433 : uint64_t *remove_probes) {
434 259 : ccol__call_once(queue_mutex_registry.once, queue_mutex_registry_init_globals);
435 259 : ccol__mutex_lock(queue_mutex_registry.mutex);
436 518 : size_t n =
437 259 : queue_mutex_registry.addrs ? cvector_size(queue_mutex_registry.addrs) : 0;
438 259 : bool ok = true;
439 33155 : for (size_t k = 0; k < n; k++) {
440 32896 : queue_mutex_registry_entry *e =
441 32896 : (queue_mutex_registry_entry *)cvector_at(queue_mutex_registry.addrs, k);
442 32896 : if (*e->index != k) ok = false;
443 : }
444 259 : ccol__mutex_unlock(queue_mutex_registry.mutex);
445 259 : if (count) *count = n;
446 259 : if (remove_probes)
447 2 : *remove_probes = atomic_load(&g_queue_registry_remove_probes_for_tests);
448 259 : return ok;
449 : }
450 : #endif
451 :
452 : // Frees the registry's vector at process exit, so valgrind doesn't report it.
453 : // While a queue is still registered it only sets release_deferred, and the
454 : // remove of the last entry frees the vector. The mutex stays, since the fork
455 : // handlers can still take it.
456 98 : __attribute__((destructor)) static void cleanup_queue_mutex_registry(void) {
457 98 : ccol__call_once(queue_mutex_registry.once, queue_mutex_registry_init_globals);
458 98 : ccol__mutex_lock(queue_mutex_registry.mutex);
459 98 : if (queue_mutex_registry.addrs) {
460 98 : if (cvector_size(queue_mutex_registry.addrs) > 0)
461 33 : queue_mutex_registry.release_deferred = true;
462 : else
463 65 : cvector_destroy(queue_mutex_registry.addrs);
464 : }
465 98 : ccol__mutex_unlock(queue_mutex_registry.mutex);
466 98 : }
467 : #endif
468 :
469 : // Stores the error of a failed condition wait in errno, as the timed calls
470 : // promise. It's out of line so the timed functions keep no register for it.
471 3 : static __attribute__((noinline, cold)) void ccol_store_wait_errno(int err) {
472 3 : errno = err;
473 3 : }
474 :
475 : // Circular queue
476 :
477 : // The circular queue. Every field is guarded by mutex except dispatch_refs,
478 : // which is atomic and sits last, away from what send and receive read.
479 : struct ccircq {
480 : ccol__mutex mutex;
481 : ccol__cond_var read_cond;
482 : ccol__cond_var write_cond;
483 :
484 : // Threads blocked on read_cond and write_cond. A send or receive signals only
485 : // when the count isn't zero, so every wait site, timed ones included, keeps
486 : // them.
487 : size_t readers_waiting;
488 : size_t writers_waiting;
489 :
490 : size_t read_index;
491 : size_t write_index;
492 : size_t max_size;
493 : size_t msg_count;
494 :
495 : ccol_memmgmt_procs *m_procs;
496 :
497 : cmessage *msg_array;
498 : bool writing_disabled;
499 :
500 : ccol_sel_waiter *sel_read_waiters_head;
501 : ccol_sel_waiter *sel_write_waiters_head;
502 :
503 : // Rotation cursors of notify_one_sel_waiter(); NULL starts at the head.
504 : ccol_sel_waiter *sel_read_rotor;
505 : ccol_sel_waiter *sel_write_rotor;
506 : // Registrations of shut-down loops that still name this queue although their
507 : // nodes left the lists. A destroy refuses the queue while it isn't zero.
508 : size_t detached_loop_regs;
509 :
510 : // Loop dispatches running a callback on this queue right now; the destroy
511 : // waits for it to reach zero.
512 : _Atomic size_t dispatch_refs;
513 :
514 : #if CCOL_FORK_SAFETY_REQUIRED
515 : // Position in queue_mutex_registry, under the registry mutex.
516 : size_t registry_idx;
517 : #endif
518 : };
519 :
520 : // Checks the arguments of ccircq_create_mp() before it allocates anything:
521 : // max_size from 1 to ccol_max_elem_count and small enough that
522 : // max_size * sizeof(cmessage) doesn't overflow (the array is allocated with a
523 : // plain multiplication), and a well-formed allocator. Sets *err_str on
524 : // failure.
525 700 : static bool verify_circular_queue_create_inputs(size_t max_size,
526 : ccol_memmgmt_procs *mmgmt_procs,
527 : char **err_str) {
528 700 : if (max_size == 0) {
529 2 : if (err_str) {
530 2 : *err_str = CCOL__ERR_STR("max_size should be positive");
531 : }
532 2 : return false;
533 : }
534 :
535 698 : if (max_size > ccol_max_elem_count) {
536 2 : if (err_str) {
537 2 : *err_str = CCOL__ERR_STR("max_size can not exceed ccol_max_elem_count");
538 : }
539 2 : return false;
540 : }
541 :
542 696 : if (max_size > SIZE_MAX / sizeof(cmessage)) {
543 2 : if (err_str) {
544 2 : *err_str = CCOL__ERR_STR(
545 : "max_size is too large: max_size * sizeof(cmessage) would "
546 : "overflow size_t");
547 : }
548 2 : return false;
549 : }
550 :
551 694 : if (!ccol__verify_memmgmt_procs(mmgmt_procs, err_str)) {
552 1 : return false;
553 : }
554 :
555 : return true;
556 : }
557 :
558 : // Creates a circular queue, the constructor behind ccircq_create() and both
559 : // directions of a cchan: The struct, its message array, the mutex and the two
560 : // monotonic condition variables, with sends on. Gives the queue, or NULL with
561 : // *err_str set. Registering the mutex for fork safety is the last step, so its
562 : // failure unwinds like any allocation failure.
563 700 : ccircq *ccircq_create_mp(size_t max_size, ccol_memmgmt_procs *mmgmt_procs,
564 : char **err_str) {
565 700 : if (!verify_circular_queue_create_inputs(max_size, mmgmt_procs, err_str)) {
566 : return NULL;
567 : }
568 :
569 693 : ccircq *cq = (ccircq *)ccol__mem_alloc(mmgmt_procs, sizeof(ccircq));
570 693 : if (!cq) {
571 1 : if (err_str) {
572 1 : *err_str = CCOL__ERR_STR("Failed to allocate memory for ccircq");
573 : }
574 1 : return NULL;
575 : }
576 :
577 692 : if (!ccol__populate_mem_mgmt_procs(cq, mmgmt_procs, err_str)) {
578 1 : ccol__mem_free(mmgmt_procs, cq);
579 1 : return NULL;
580 : }
581 :
582 691 : cq->msg_array =
583 691 : (cmessage *)ccol__mem_alloc(mmgmt_procs, max_size * sizeof(cmessage));
584 691 : if (!cq->msg_array) {
585 1 : if (err_str) {
586 1 : *err_str = CCOL__ERR_STR("Failed to allocate memory for cq msg_array");
587 : }
588 1 : ccol__mem_free(mmgmt_procs, cq->m_procs);
589 1 : ccol__mem_free(mmgmt_procs, cq);
590 1 : return NULL;
591 : }
592 :
593 690 : if (ccol__mutex_init(cq->mutex) != 0) {
594 0 : if (err_str) *err_str = CCOL__ERR_STR("Failed to initialize cq mutex");
595 0 : ccol__mem_free(mmgmt_procs, cq->msg_array);
596 0 : ccol__mem_free(mmgmt_procs, cq->m_procs);
597 0 : ccol__mem_free(mmgmt_procs, cq);
598 0 : return NULL;
599 : }
600 690 : if (init_monotonic_cond_var(&cq->read_cond) != 0) {
601 0 : if (err_str) *err_str = CCOL__ERR_STR("Failed to initialize cq read_cond");
602 0 : ccol__mutex_destroy(cq->mutex);
603 0 : ccol__mem_free(mmgmt_procs, cq->msg_array);
604 0 : ccol__mem_free(mmgmt_procs, cq->m_procs);
605 0 : ccol__mem_free(mmgmt_procs, cq);
606 0 : return NULL;
607 : }
608 690 : if (init_monotonic_cond_var(&cq->write_cond) != 0) {
609 0 : if (err_str) *err_str = CCOL__ERR_STR("Failed to initialize cq write_cond");
610 0 : ccol__mutex_destroy(cq->mutex);
611 0 : ccol__cond_var_destroy(cq->read_cond);
612 0 : ccol__mem_free(mmgmt_procs, cq->msg_array);
613 0 : ccol__mem_free(mmgmt_procs, cq->m_procs);
614 0 : ccol__mem_free(mmgmt_procs, cq);
615 0 : return NULL;
616 : }
617 690 : cq->read_index = 0;
618 690 : cq->write_index = 0;
619 690 : cq->max_size = max_size;
620 690 : cq->msg_count = 0;
621 690 : cq->readers_waiting = 0;
622 690 : cq->writers_waiting = 0;
623 690 : cq->writing_disabled = false;
624 690 : cq->sel_read_waiters_head = NULL;
625 690 : cq->sel_write_waiters_head = NULL;
626 690 : cq->sel_read_rotor = NULL;
627 690 : cq->sel_write_rotor = NULL;
628 690 : cq->detached_loop_regs = 0;
629 690 : atomic_init(&cq->dispatch_refs, (size_t)0);
630 :
631 : #if CCOL_FORK_SAFETY_REQUIRED
632 690 : if (!queue_mutex_registry_add(&cq->mutex, &cq->registry_idx)) {
633 1 : if (err_str) {
634 0 : *err_str =
635 : CCOL__ERR_STR("Failed to register ccircq's mutex for fork safety");
636 : }
637 1 : ccol__mutex_destroy(cq->mutex);
638 1 : ccol__cond_var_destroy(cq->read_cond);
639 1 : ccol__cond_var_destroy(cq->write_cond);
640 1 : ccol__mem_free(mmgmt_procs, cq->msg_array);
641 0 : ccol__mem_free(mmgmt_procs, cq->m_procs);
642 1 : ccol__mem_free(mmgmt_procs, cq);
643 1 : return NULL;
644 : }
645 : #endif
646 :
647 689 : if (err_str) {
648 96 : *err_str = NULL;
649 : }
650 :
651 : return cq;
652 : }
653 :
654 : // Destroys a circular queue; ccircq_destroy() and cchan__destroy() call it.
655 : // It asserts when a waiter is linked or a detached registration still names the
656 : // queue (checked under the mutex), since the unlink of such a node later reads
657 : // the queue. Then it waits for running dispatches, and only after that asserts
658 : // on queued messages, because a write callback can still send in that time. The
659 : // mutex leaves the fork registry before it's destroyed.
660 678 : void ccircq__destroy(ccircq *cq) {
661 678 : if (cq) {
662 678 : ccol__mutex_lock(cq->mutex);
663 2031 : bool has_sel_waiters = (cq->sel_read_waiters_head != NULL) ||
664 678 : (cq->sel_write_waiters_head != NULL) ||
665 675 : cq->detached_loop_regs != 0;
666 678 : ccol__mutex_unlock(cq->mutex);
667 678 : if (has_sel_waiters) {
668 4 : ccol__assert(false);
669 : }
670 :
671 674 : queue_wait_for_dispatch_refs(&cq->dispatch_refs, cq);
672 :
673 1348 : if (ccircq_msg_count(cq) > 0) {
674 1 : ccol__assert(false);
675 : }
676 :
677 673 : if (cq->msg_array) {
678 673 : ccol__mem_free(cq->m_procs, cq->msg_array);
679 673 : cq->msg_array = NULL;
680 : }
681 :
682 : #if CCOL_FORK_SAFETY_REQUIRED
683 673 : queue_mutex_registry_remove(&cq->mutex, &cq->registry_idx);
684 : #endif
685 :
686 673 : ccol__mutex_destroy(cq->mutex);
687 673 : ccol__cond_var_destroy(cq->read_cond);
688 673 : ccol__cond_var_destroy(cq->write_cond);
689 :
690 673 : if (cq->m_procs) {
691 78 : ccol_free free_func = cq->m_procs->free;
692 78 : free_func(cq->m_procs);
693 78 : free_func(cq);
694 : } else {
695 595 : ccol__default_mem_free(cq);
696 : }
697 : }
698 673 : }
699 :
700 : #ifdef RUNNING_UNIT_TESTS
701 : // Test-only: Locks and unlocks cq's mutex directly.
702 1 : void ccircq__test_lock_mutex_for_tests(ccircq *cq) {
703 1 : ccol__mutex_lock(cq->mutex);
704 1 : }
705 :
706 1 : void ccircq__test_unlock_mutex_for_tests(ccircq *cq) {
707 1 : ccol__mutex_unlock(cq->mutex);
708 1 : }
709 :
710 : // Test-only: Whether a cselect() waiter is linked into the read list, read
711 : // under the mutex, so a test can wait for one in a bounded loop.
712 8 : bool ccircq__test_has_sel_read_waiter_for_tests(ccircq *cq) {
713 8 : ccol__mutex_lock(cq->mutex);
714 8 : bool has_waiter = cq->sel_read_waiters_head != NULL;
715 8 : ccol__mutex_unlock(cq->mutex);
716 8 : return has_waiter;
717 : }
718 :
719 : // Test-only: Counts the waiters of the read list under the mutex.
720 812 : size_t ccircq__test_sel_read_waiter_count_for_tests(ccircq *cq) {
721 812 : ccol__mutex_lock(cq->mutex);
722 812 : size_t n = 0;
723 1620 : for (ccol_sel_waiter *w = cq->sel_read_waiters_head; w; w = w->next) ++n;
724 812 : ccol__mutex_unlock(cq->mutex);
725 812 : return n;
726 : }
727 :
728 : // Test-only: The blocked reader and writer counts, read under the mutex, so a
729 : // test can wait until a thread really parked.
730 3 : size_t ccircq__waiting_readers_for_tests(ccircq *cq) {
731 3 : ccol__mutex_lock(cq->mutex);
732 3 : size_t n = cq->readers_waiting;
733 3 : ccol__mutex_unlock(cq->mutex);
734 3 : return n;
735 : }
736 :
737 3 : size_t ccircq__waiting_writers_for_tests(ccircq *cq) {
738 3 : ccol__mutex_lock(cq->mutex);
739 3 : size_t n = cq->writers_waiting;
740 3 : ccol__mutex_unlock(cq->mutex);
741 3 : return n;
742 : }
743 : #endif
744 :
745 : // Stores msg at write_index, takes msg->data from the sender (the zero-copy
746 : // hand-over), counts it and wakes one reader and one read waiter. Every send
747 : // path of the circular queue ends here. The caller holds the mutex and has
748 : // checked that there is room.
749 180622 : static void sendto_cq(ccircq *cq, cmessage *msg) {
750 180622 : cq->msg_array[cq->write_index].data = msg->data;
751 180622 : cq->msg_array[cq->write_index++].size = (msg->data == NULL) ? 0 : msg->size;
752 180622 : msg->data = NULL;
753 180622 : if (cq->write_index == cq->max_size) {
754 2842 : cq->write_index = 0;
755 : }
756 180622 : ++cq->msg_count;
757 :
758 180622 : if (cq->readers_waiting) ccol__cond_var_signal(cq->read_cond);
759 180622 : notify_one_sel_waiter(&cq->sel_read_waiters_head, &cq->sel_read_rotor);
760 180622 : }
761 :
762 : // Checks the arguments of every circular queue send: non-NULL queue and
763 : // message, and data and size that agree (a pointer needs a size, NULL needs
764 : // 0).
765 183033 : static bool verify_circq_send_zc_params(ccircq *cq, cmessage *msg) {
766 183033 : if (!cq || !msg || (msg->size == 0 && msg->data != NULL) ||
767 183026 : (msg->data == NULL && msg->size != 0)) {
768 : return false;
769 : }
770 :
771 : return true;
772 : }
773 :
774 : // Sends msg, blocking on write_cond while the queue is full; it's the send for
775 : // a producer that should wait for room (backpressure). Gives
776 : // ccol_not_permitted when sends are off, checked before and after the wait.
777 16398 : ccol_retval ccircq_send(ccircq *cq, cmessage *msg) {
778 16398 : if (!verify_circq_send_zc_params(cq, msg)) {
779 : return ccol_invalid_args;
780 : }
781 :
782 16393 : ccol__mutex_lock(cq->mutex);
783 :
784 16396 : if (cq->writing_disabled) {
785 29 : ccol__mutex_unlock(cq->mutex);
786 29 : return ccol_not_permitted;
787 : }
788 :
789 23866 : while (cq->msg_count == cq->max_size && !cq->writing_disabled) {
790 7499 : ++cq->writers_waiting;
791 7499 : ccol__cond_var_wait(cq->write_cond, cq->mutex);
792 7499 : --cq->writers_waiting;
793 : }
794 :
795 16367 : if (cq->writing_disabled) {
796 0 : ccol__mutex_unlock(cq->mutex);
797 0 : return ccol_not_permitted;
798 : }
799 :
800 16367 : sendto_cq(cq, msg);
801 :
802 16367 : ccol__mutex_unlock(cq->mutex);
803 :
804 16367 : return ccol_success;
805 : }
806 :
807 : // Sends msg when there's room and gives ccol_container_full otherwise, for a
808 : // producer that must never block. Gives ccol_not_permitted when sends are
809 : // off.
810 166597 : ccol_retval ccircq_try_send(ccircq *cq, cmessage *msg) {
811 166597 : if (!verify_circq_send_zc_params(cq, msg)) {
812 : return ccol_invalid_args;
813 : }
814 :
815 166593 : ccol_retval result = ccol_container_full;
816 :
817 166593 : ccol__mutex_lock(cq->mutex);
818 :
819 166593 : if (cq->writing_disabled) {
820 13 : ccol__mutex_unlock(cq->mutex);
821 13 : return ccol_not_permitted;
822 : }
823 :
824 166580 : if (cq->msg_count < cq->max_size) {
825 164227 : sendto_cq(cq, msg);
826 164227 : result = ccol_success;
827 : }
828 :
829 166580 : ccol__mutex_unlock(cq->mutex);
830 :
831 166580 : return result;
832 : }
833 :
834 : static void recvfrom_cq(ccircq *cq, cmessage *target_buf);
835 :
836 : #ifdef RUNNING_UNIT_TESTS
837 : // Test-only state of the forced wait error of ccircq_timed_send: The armed
838 : // flag, the "also race" flag, and the message that the imitated concurrent
839 : // receive took out.
840 : static _Atomic bool g_circq_send_force_condvar_wait_error = false;
841 : static _Atomic bool g_circq_send_force_condvar_wait_error_also_race = false;
842 : static cmessage g_circq_send_race_freed_msg = {0};
843 :
844 : // Test-only: Arms the forced wait error of the next timed send.
845 1 : void ccircq__test_force_next_send_condvar_wait_error(void) {
846 1 : atomic_store(&g_circq_send_force_condvar_wait_error, true);
847 1 : }
848 :
849 : // Test-only: Arms the forced wait error together with an imitated receive that
850 : // frees a slot under the same mutex.
851 1 : void ccircq__test_force_next_send_condvar_wait_error_racing_ready(void) {
852 1 : atomic_store(&g_circq_send_force_condvar_wait_error, true);
853 1 : atomic_store(&g_circq_send_force_condvar_wait_error_also_race, true);
854 1 : }
855 :
856 : // Test-only: Hands out, once, the message the imitated receive took.
857 1 : cmessage ccircq__test_take_race_freed_msg(void) {
858 1 : cmessage m = g_circq_send_race_freed_msg;
859 1 : g_circq_send_race_freed_msg = (cmessage){0};
860 1 : return m;
861 : }
862 : #endif
863 :
864 : // Sends msg, waiting at most timeout_us for room, for a producer that may wait
865 : // but not for ever (0 is ccircq_try_send()). The deadline is computed once
866 : // before the loop, so a spurious wake can't stretch it. Its wait is counted in
867 : // writers_waiting like the untimed one, or a receiver would never signal it.
868 : // After a failed wait it looks at the queue again before giving up, since a
869 : // receiver can free a slot just before an unrelated error or the timeout is
870 : // seen; a free slot or turned-off sends win over the error.
871 20 : ccol_retval ccircq_timed_send(ccircq *cq, cmessage *msg, uint64_t timeout_us) {
872 20 : if (timeout_us == 0) return ccircq_try_send(cq, msg);
873 17 : if (!verify_circq_send_zc_params(cq, msg)) {
874 : return ccol_invalid_args;
875 : }
876 :
877 13 : ccol__mutex_lock(cq->mutex);
878 :
879 13 : if (cq->writing_disabled) {
880 1 : ccol__mutex_unlock(cq->mutex);
881 1 : return ccol_not_permitted;
882 : }
883 :
884 12 : if (cq->msg_count == cq->max_size) {
885 9 : int retval;
886 9 : struct timespec abs_time;
887 9 : ccol_deadline_after_us(timeout_us, &abs_time);
888 :
889 12 : while (cq->msg_count == cq->max_size && !cq->writing_disabled) {
890 9 : ++cq->writers_waiting;
891 : #ifdef RUNNING_UNIT_TESTS
892 9 : if (atomic_load(&g_circq_send_force_condvar_wait_error)) {
893 2 : atomic_store(&g_circq_send_force_condvar_wait_error, false);
894 2 : retval = EINVAL;
895 2 : if (atomic_load(&g_circq_send_force_condvar_wait_error_also_race)) {
896 1 : atomic_store(&g_circq_send_force_condvar_wait_error_also_race, false);
897 1 : recvfrom_cq(cq, &g_circq_send_race_freed_msg);
898 : }
899 : } else {
900 7 : retval = ccol__cond_var_timedwait(cq->write_cond, cq->mutex, abs_time);
901 : }
902 : #else
903 : retval = ccol__cond_var_timedwait(cq->write_cond, cq->mutex, abs_time);
904 : #endif
905 9 : --cq->writers_waiting;
906 9 : if (retval) {
907 6 : if (cq->msg_count < cq->max_size || cq->writing_disabled) break;
908 5 : if (retval != ETIMEDOUT) {
909 1 : ccol_store_wait_errno(retval);
910 1 : ccol__mutex_unlock(cq->mutex);
911 5 : return ccol_unexpected_failure;
912 : }
913 4 : ccol__mutex_unlock(cq->mutex);
914 4 : return ccol_timed_out;
915 : }
916 : }
917 : }
918 :
919 7 : if (cq->writing_disabled) {
920 0 : ccol__mutex_unlock(cq->mutex);
921 0 : return ccol_not_permitted;
922 : }
923 :
924 7 : sendto_cq(cq, msg);
925 :
926 7 : ccol__mutex_unlock(cq->mutex);
927 :
928 7 : return ccol_success;
929 : }
930 :
931 : // Sends msg whether sends are on or off (see internal/cqueueowner.h), waiting
932 : // at most timeout_us for room with the same wait as the timed send. 0 gives
933 : // ccol_container_full on a full queue.
934 21 : ccol_retval ccircq_owner_send(ccircq *cq, cmessage *msg, uint64_t timeout_us) {
935 21 : if (!verify_circq_send_zc_params(cq, msg)) return ccol_invalid_args;
936 21 : ccol__mutex_lock(cq->mutex);
937 21 : if (cq->msg_count == cq->max_size) {
938 1 : if (timeout_us == 0) {
939 1 : ccol__mutex_unlock(cq->mutex);
940 1 : return ccol_container_full;
941 : }
942 0 : struct timespec abs_time;
943 0 : ccol_deadline_after_us(timeout_us, &abs_time);
944 0 : while (cq->msg_count == cq->max_size) {
945 0 : ++cq->writers_waiting;
946 0 : int retval =
947 0 : ccol__cond_var_timedwait(cq->write_cond, cq->mutex, abs_time);
948 0 : --cq->writers_waiting;
949 0 : if (retval && cq->msg_count == cq->max_size) {
950 0 : if (retval != ETIMEDOUT) ccol_store_wait_errno(retval);
951 0 : ccol__mutex_unlock(cq->mutex);
952 0 : return retval == ETIMEDOUT ? ccol_timed_out : ccol_unexpected_failure;
953 : }
954 : }
955 : }
956 20 : sendto_cq(cq, msg);
957 20 : ccol__mutex_unlock(cq->mutex);
958 20 : return ccol_success;
959 : }
960 :
961 : // Takes the message at read_index into target_buf and wakes one blocked sender
962 : // and one write waiter. Every receive path of the circular queue ends here,
963 : // and the owner send's test hook uses it to imitate a receive. The caller holds
964 : // the mutex and has checked that a message is queued.
965 180615 : static void recvfrom_cq(ccircq *cq, cmessage *target_buf) {
966 180615 : target_buf->data = cq->msg_array[cq->read_index].data;
967 180615 : target_buf->size = cq->msg_array[cq->read_index++].size;
968 180615 : if (cq->read_index == cq->max_size) {
969 2840 : cq->read_index = 0;
970 : }
971 :
972 180615 : --cq->msg_count;
973 :
974 180615 : if (cq->writers_waiting) ccol__cond_var_signal(cq->write_cond);
975 180615 : notify_one_sel_waiter(&cq->sel_write_waiters_head, &cq->sel_write_rotor);
976 180615 : }
977 :
978 : // Checks the arguments of every circular queue receive: Neither the queue nor
979 : // the buffer may be NULL.
980 185189 : static bool verify_recvfrom_cq_zc_params(ccircq *cq, cmessage *target_buf) {
981 185189 : if (!cq || !target_buf) {
982 : return false;
983 : }
984 :
985 : return true;
986 : }
987 :
988 : // Receives a message, blocking on read_cond while the queue is empty, for a
989 : // consumer that has nothing else to do.
990 41 : ccol_retval ccircq_recv(ccircq *cq, cmessage *target_buf) {
991 41 : if (!verify_recvfrom_cq_zc_params(cq, target_buf)) {
992 : return ccol_invalid_args;
993 : }
994 :
995 41 : ccol__mutex_lock(cq->mutex);
996 :
997 46 : while (cq->msg_count == 0) {
998 5 : ++cq->readers_waiting;
999 5 : ccol__cond_var_wait(cq->read_cond, cq->mutex);
1000 5 : --cq->readers_waiting;
1001 : }
1002 :
1003 41 : recvfrom_cq(cq, target_buf);
1004 :
1005 41 : ccol__mutex_unlock(cq->mutex);
1006 :
1007 41 : return ccol_success;
1008 : }
1009 :
1010 : // Receives a message or gives ccol_container_empty at once, for a consumer that
1011 : // must not block (an event loop callback, or after cselect()).
1012 175253 : ccol_retval ccircq_try_recv(ccircq *cq, cmessage *target_buf) {
1013 175253 : if (!verify_recvfrom_cq_zc_params(cq, target_buf)) {
1014 : return ccol_invalid_args;
1015 : }
1016 :
1017 175252 : ccol_retval result = ccol_container_empty;
1018 :
1019 175252 : ccol__mutex_lock(cq->mutex);
1020 :
1021 175341 : if (cq->msg_count > 0) {
1022 170692 : result = ccol_success;
1023 170692 : recvfrom_cq(cq, target_buf);
1024 : }
1025 :
1026 175341 : ccol__mutex_unlock(cq->mutex);
1027 :
1028 175341 : return result;
1029 : }
1030 :
1031 : #ifdef RUNNING_UNIT_TESTS
1032 : // Test-only flags of the forced wait error of ccircq_timed_recv.
1033 : static _Atomic bool g_circq_recv_force_condvar_wait_error = false;
1034 : static _Atomic bool g_circq_recv_force_condvar_wait_error_also_race = false;
1035 :
1036 : // Test-only: Arms the forced wait error of the next timed receive.
1037 1 : void ccircq__test_force_next_recv_condvar_wait_error(void) {
1038 1 : atomic_store(&g_circq_recv_force_condvar_wait_error, true);
1039 1 : }
1040 :
1041 : // Test-only: Arms the forced wait error together with an imitated send of a
1042 : // sentinel under the same mutex.
1043 1 : void ccircq__test_force_next_recv_condvar_wait_error_racing_ready(void) {
1044 1 : atomic_store(&g_circq_recv_force_condvar_wait_error, true);
1045 1 : atomic_store(&g_circq_recv_force_condvar_wait_error_also_race, true);
1046 1 : }
1047 : #endif
1048 :
1049 : // Receives a message, waiting at most timeout_us against one deadline, for a
1050 : // consumer that also has other work (0 is ccircq_try_recv()). As in the timed
1051 : // send, a failed wait looks at the queue again, and a message that arrived wins
1052 : // over the error or the timeout.
1053 9898 : ccol_retval ccircq_timed_recv(ccircq *cq, cmessage *target_buf,
1054 : uint64_t timeout_us) {
1055 9898 : if (timeout_us == 0) return ccircq_try_recv(cq, target_buf);
1056 9895 : if (!verify_recvfrom_cq_zc_params(cq, target_buf)) {
1057 : return ccol_invalid_args;
1058 : }
1059 :
1060 9895 : ccol__mutex_lock(cq->mutex);
1061 :
1062 9895 : if (cq->msg_count == 0) {
1063 373 : int retval;
1064 373 : struct timespec abs_time;
1065 373 : ccol_deadline_after_us(timeout_us, &abs_time);
1066 :
1067 731 : while (cq->msg_count == 0) {
1068 373 : ++cq->readers_waiting;
1069 : #ifdef RUNNING_UNIT_TESTS
1070 373 : if (atomic_load(&g_circq_recv_force_condvar_wait_error)) {
1071 2 : atomic_store(&g_circq_recv_force_condvar_wait_error, false);
1072 2 : retval = EINVAL;
1073 2 : if (atomic_load(&g_circq_recv_force_condvar_wait_error_also_race)) {
1074 1 : atomic_store(&g_circq_recv_force_condvar_wait_error_also_race, false);
1075 1 : cmessage sentinel = {.data = NULL, .size = 0};
1076 1 : sendto_cq(cq, &sentinel);
1077 : }
1078 : } else {
1079 371 : retval = ccol__cond_var_timedwait(cq->read_cond, cq->mutex, abs_time);
1080 : }
1081 : #else
1082 : retval = ccol__cond_var_timedwait(cq->read_cond, cq->mutex, abs_time);
1083 : #endif
1084 366 : --cq->readers_waiting;
1085 366 : if (retval) {
1086 8 : if (cq->msg_count > 0) break;
1087 7 : if (retval != ETIMEDOUT) {
1088 1 : ccol_store_wait_errno(retval);
1089 1 : ccol__mutex_unlock(cq->mutex);
1090 7 : return ccol_unexpected_failure;
1091 : }
1092 6 : ccol__mutex_unlock(cq->mutex);
1093 6 : return ccol_timed_out;
1094 : }
1095 : }
1096 : }
1097 :
1098 9881 : recvfrom_cq(cq, target_buf);
1099 :
1100 9881 : ccol__mutex_unlock(cq->mutex);
1101 :
1102 9881 : return ccol_success;
1103 : }
1104 :
1105 : // Turns sends off, so an owner can stop new work while it drains the queue.
1106 : // Under the mutex it wakes every blocked sender (which then gives
1107 : // ccol_not_permitted) and every write waiter.
1108 29 : ccol_retval ccircq_disable_sending(ccircq *cq) {
1109 29 : if (cq) {
1110 29 : ccol__mutex_lock(cq->mutex);
1111 29 : cq->writing_disabled = true;
1112 29 : ccol__cond_var_broadcast(cq->write_cond);
1113 29 : notify_all_sel_waiters(cq->sel_write_waiters_head);
1114 29 : ccol__mutex_unlock(cq->mutex);
1115 29 : return ccol_success;
1116 : }
1117 : return ccol_invalid_args;
1118 : }
1119 :
1120 : // Turns sends back on after ccircq_disable_sending(), and under the mutex
1121 : // wakes every blocked sender and every write waiter.
1122 81 : ccol_retval ccircq_enable_sending(ccircq *cq) {
1123 81 : if (cq) {
1124 81 : ccol__mutex_lock(cq->mutex);
1125 81 : cq->writing_disabled = false;
1126 81 : ccol__cond_var_broadcast(cq->write_cond);
1127 81 : notify_all_sel_waiters(cq->sel_write_waiters_head);
1128 81 : ccol__mutex_unlock(cq->mutex);
1129 81 : return ccol_success;
1130 : }
1131 : return ccol_invalid_args;
1132 : }
1133 :
1134 : // Gives the message count, read under the mutex, or ccol_invalid_size for
1135 : // NULL. The destroy uses it, and so can a caller that wants a snapshot.
1136 736 : size_t ccircq_msg_count(ccircq *cq) {
1137 736 : size_t result = ccol_invalid_size;
1138 :
1139 38 : if (cq) {
1140 736 : ccol__mutex_lock(cq->mutex);
1141 736 : result = cq->msg_count;
1142 736 : ccol__mutex_unlock(cq->mutex);
1143 : }
1144 :
1145 674 : return result;
1146 : }
1147 :
1148 : // Dynamic queue
1149 :
1150 : // A node of a dynamic queue's doubly-linked list.
1151 : typedef struct dllist_node {
1152 : struct dllist_node *prev;
1153 : cmessage msg;
1154 : struct dllist_node *next;
1155 : } dllist_node;
1156 :
1157 : // The dynamic queue. It's unbounded, so it has readers to wake but no blocked
1158 : // writer and no write_cond. The other fields mean what they mean in struct
1159 : // ccircq: Everything is guarded by mutex except the atomic dispatch_refs.
1160 : struct cdynmq {
1161 : ccol__mutex mutex;
1162 : ccol__cond_var read_cond;
1163 :
1164 : size_t readers_waiting;
1165 :
1166 : size_t msg_count;
1167 :
1168 : dllist_node *head;
1169 : dllist_node *tail;
1170 :
1171 : ccol_memmgmt_procs *m_procs;
1172 :
1173 : bool writing_disabled;
1174 :
1175 : ccol_sel_waiter *sel_read_waiters_head;
1176 : ccol_sel_waiter *sel_write_waiters_head;
1177 :
1178 : ccol_sel_waiter *sel_read_rotor;
1179 : ccol_sel_waiter *sel_write_rotor;
1180 : size_t detached_loop_regs;
1181 :
1182 : _Atomic size_t dispatch_refs;
1183 :
1184 : #if CCOL_FORK_SAFETY_REQUIRED
1185 : size_t registry_idx;
1186 : #endif
1187 : };
1188 :
1189 : // Appends msg in a new node, taking msg->data from the sender; sendto_dq()
1190 : // uses it. Gives ccol_not_enough_memory and leaves msg alone when the node
1191 : // can't be allocated. The caller holds the mutex.
1192 103282 : static ccol_retval append_msg_to_dq_tail(cdynmq *dq, cmessage *msg) {
1193 206564 : dllist_node *new_elem =
1194 103282 : (dllist_node *)ccol__mem_alloc(dq->m_procs, sizeof(dllist_node));
1195 103282 : if (!new_elem) {
1196 : return ccol_not_enough_memory;
1197 : }
1198 :
1199 103266 : new_elem->msg.data = msg->data;
1200 103266 : new_elem->msg.size = (msg->data == NULL) ? 0 : msg->size;
1201 103266 : msg->data = NULL;
1202 103266 : new_elem->next = NULL;
1203 :
1204 103266 : if (!dq->head) {
1205 : #ifdef RUNNING_UNIT_TESTS
1206 3162 : ccol__assert(!dq->tail);
1207 : #endif
1208 3162 : new_elem->prev = NULL;
1209 3162 : dq->head = new_elem;
1210 3162 : dq->tail = new_elem;
1211 : } else {
1212 : #ifdef RUNNING_UNIT_TESTS
1213 100104 : ccol__assert(dq->tail && !dq->tail->next);
1214 : #endif
1215 100104 : new_elem->prev = dq->tail;
1216 100104 : dq->tail->next = new_elem;
1217 100104 : dq->tail = new_elem;
1218 : }
1219 :
1220 : return ccol_success;
1221 : }
1222 :
1223 : // Moves the head message into target_buf and frees its node, or gives
1224 : // ccol_container_empty; recvfrom_dq() uses it. The caller holds the mutex.
1225 103061 : static ccol_retval remove_msg_from_dq_head(cdynmq *dq, cmessage *target_buf) {
1226 103061 : if (!dq->head) {
1227 : #ifdef RUNNING_UNIT_TESTS
1228 0 : ccol__assert(!dq->tail);
1229 : #endif
1230 : return ccol_container_empty;
1231 : }
1232 :
1233 : #ifdef RUNNING_UNIT_TESTS
1234 103061 : ccol__assert(!dq->head->prev);
1235 103061 : ccol__assert(dq->tail && !dq->tail->next);
1236 : #endif
1237 :
1238 103061 : dllist_node *node_to_be_freed = dq->head;
1239 :
1240 103061 : target_buf->data = dq->head->msg.data;
1241 103061 : target_buf->size = dq->head->msg.size;
1242 :
1243 103061 : dq->head = dq->head->next;
1244 103061 : if (dq->head) {
1245 99906 : dq->head->prev = NULL;
1246 : } else {
1247 3155 : dq->tail = NULL;
1248 : }
1249 :
1250 103061 : ccol__mem_free(dq->m_procs, node_to_be_freed);
1251 : return ccol_success;
1252 : }
1253 :
1254 : // Frees every node of a dynamic queue for its destroy, but not the messages'
1255 : // data, which the destroy has already asserted is gone.
1256 350 : static void destroy_dq_dllist(cdynmq *dq) {
1257 350 : dllist_node *node_to_be_freed = NULL;
1258 350 : while (dq->head) {
1259 0 : node_to_be_freed = dq->head;
1260 0 : dq->head = dq->head->next;
1261 0 : ccol__mem_free(dq->m_procs, node_to_be_freed);
1262 : }
1263 350 : dq->tail = NULL;
1264 350 : }
1265 :
1266 : // Creates a dynamic queue, the constructor behind cdynmq_create(): The struct,
1267 : // its mutex and a monotonic read_cond, empty and with sends on. Gives the
1268 : // queue, or NULL with *err_str set. Registering the mutex for fork safety is
1269 : // the last step, so its failure unwinds like any allocation failure.
1270 382 : cdynmq *cdynmq_create_mp(ccol_memmgmt_procs *mmgmt_procs, char **err_str) {
1271 382 : if (!ccol__verify_memmgmt_procs(mmgmt_procs, err_str)) {
1272 1 : return NULL;
1273 : }
1274 :
1275 381 : cdynmq *dq = (cdynmq *)ccol__mem_alloc(mmgmt_procs, sizeof(cdynmq));
1276 381 : if (!dq) {
1277 2 : if (err_str) {
1278 2 : *err_str = CCOL__ERR_STR("Failed to allocate memory for cdynmq");
1279 : }
1280 2 : return NULL;
1281 : }
1282 :
1283 379 : if (!ccol__populate_mem_mgmt_procs(dq, mmgmt_procs, err_str)) {
1284 2 : ccol__mem_free(mmgmt_procs, dq);
1285 2 : return NULL;
1286 : }
1287 :
1288 377 : if (ccol__mutex_init(dq->mutex) != 0) {
1289 0 : if (err_str) *err_str = CCOL__ERR_STR("Failed to initialize dq mutex");
1290 0 : ccol__mem_free(mmgmt_procs, dq->m_procs);
1291 0 : ccol__mem_free(mmgmt_procs, dq);
1292 0 : return NULL;
1293 : }
1294 377 : if (init_monotonic_cond_var(&dq->read_cond) != 0) {
1295 0 : if (err_str) *err_str = CCOL__ERR_STR("Failed to initialize dq read_cond");
1296 0 : ccol__mutex_destroy(dq->mutex);
1297 0 : ccol__mem_free(mmgmt_procs, dq->m_procs);
1298 0 : ccol__mem_free(mmgmt_procs, dq);
1299 0 : return NULL;
1300 : }
1301 377 : dq->msg_count = 0;
1302 377 : dq->head = NULL;
1303 377 : dq->tail = NULL;
1304 377 : dq->readers_waiting = 0;
1305 377 : dq->writing_disabled = false;
1306 377 : dq->sel_read_waiters_head = NULL;
1307 377 : dq->sel_write_waiters_head = NULL;
1308 377 : dq->sel_read_rotor = NULL;
1309 377 : dq->sel_write_rotor = NULL;
1310 377 : dq->detached_loop_regs = 0;
1311 377 : atomic_init(&dq->dispatch_refs, (size_t)0);
1312 :
1313 : #if CCOL_FORK_SAFETY_REQUIRED
1314 377 : if (!queue_mutex_registry_add(&dq->mutex, &dq->registry_idx)) {
1315 1 : if (err_str) {
1316 0 : *err_str =
1317 : CCOL__ERR_STR("Failed to register cdynmq's mutex for fork safety");
1318 : }
1319 1 : ccol__mutex_destroy(dq->mutex);
1320 1 : ccol__cond_var_destroy(dq->read_cond);
1321 1 : ccol__mem_free(mmgmt_procs, dq->m_procs);
1322 1 : ccol__mem_free(mmgmt_procs, dq);
1323 1 : return NULL;
1324 : }
1325 : #endif
1326 :
1327 376 : if (err_str) {
1328 226 : *err_str = NULL;
1329 : }
1330 :
1331 : return dq;
1332 : }
1333 :
1334 : // Destroys a dynamic queue for cdynmq_destroy(), with the checks of
1335 : // ccircq__destroy(): It asserts on a linked waiter or a detached registration,
1336 : // waits for running dispatches, then asserts on queued messages, and frees the
1337 : // nodes.
1338 354 : void cdynmq__destroy(cdynmq *dq) {
1339 354 : if (dq) {
1340 353 : ccol__mutex_lock(dq->mutex);
1341 1058 : bool has_sel_waiters = (dq->sel_read_waiters_head != NULL) ||
1342 353 : (dq->sel_write_waiters_head != NULL) ||
1343 352 : dq->detached_loop_regs != 0;
1344 353 : ccol__mutex_unlock(dq->mutex);
1345 353 : if (has_sel_waiters) {
1346 2 : ccol__assert(false);
1347 : }
1348 :
1349 351 : queue_wait_for_dispatch_refs(&dq->dispatch_refs, dq);
1350 :
1351 702 : if (cdynmq_msg_count(dq) > 0) {
1352 1 : ccol__assert(false);
1353 : }
1354 :
1355 : #if CCOL_FORK_SAFETY_REQUIRED
1356 350 : queue_mutex_registry_remove(&dq->mutex, &dq->registry_idx);
1357 : #endif
1358 :
1359 350 : ccol__mutex_destroy(dq->mutex);
1360 350 : ccol__cond_var_destroy(dq->read_cond);
1361 350 : destroy_dq_dllist(dq);
1362 :
1363 350 : if (dq->m_procs) {
1364 140 : ccol_free free_func = dq->m_procs->free;
1365 140 : free_func(dq->m_procs);
1366 140 : free_func(dq);
1367 : } else {
1368 210 : ccol__default_mem_free(dq);
1369 : }
1370 : }
1371 351 : }
1372 :
1373 : #ifdef RUNNING_UNIT_TESTS
1374 : // Test-only: The blocked reader count, read under the mutex.
1375 3 : size_t cdynmq__waiting_readers_for_tests(cdynmq *dq) {
1376 3 : ccol__mutex_lock(dq->mutex);
1377 3 : size_t n = dq->readers_waiting;
1378 3 : ccol__mutex_unlock(dq->mutex);
1379 3 : return n;
1380 : }
1381 : #endif
1382 :
1383 : // Appends msg, counts it and wakes one reader and one read waiter. Every send
1384 : // path of the dynamic queue ends here. Gives ccol_not_enough_memory, leaving
1385 : // msg alone, when the node can't be allocated. The caller holds the mutex.
1386 103282 : static ccol_retval sendto_dq(cdynmq *dq, cmessage *msg) {
1387 103282 : ccol_retval retval = append_msg_to_dq_tail(dq, msg);
1388 :
1389 103282 : if (retval == ccol_success) {
1390 103266 : ++dq->msg_count;
1391 103266 : if (dq->readers_waiting) ccol__cond_var_signal(dq->read_cond);
1392 103266 : notify_one_sel_waiter(&dq->sel_read_waiters_head, &dq->sel_read_rotor);
1393 : }
1394 :
1395 103282 : return retval;
1396 : }
1397 :
1398 : // Checks the arguments of every dynamic queue send, like
1399 : // verify_circq_send_zc_params().
1400 103283 : static bool verify_dynmq_send_zc_params(cdynmq *dq, cmessage *msg) {
1401 103283 : if (!dq || !msg || (msg->size == 0 && msg->data != NULL) ||
1402 103281 : (msg->data == NULL && msg->size != 0)) {
1403 : return false;
1404 : }
1405 :
1406 : return true;
1407 : }
1408 :
1409 : // Appends msg without blocking, the only send of an unbounded queue. Gives
1410 : // ccol_not_permitted when sends are off and ccol_container_full at
1411 : // ccol_max_elem_count messages.
1412 103245 : ccol_retval cdynmq_send(cdynmq *dq, cmessage *msg) {
1413 103245 : if (!verify_dynmq_send_zc_params(dq, msg)) {
1414 : return ccol_invalid_args;
1415 : }
1416 :
1417 103242 : ccol__mutex_lock(dq->mutex);
1418 :
1419 103271 : if (dq->writing_disabled) {
1420 28 : ccol__mutex_unlock(dq->mutex);
1421 28 : return ccol_not_permitted;
1422 : }
1423 :
1424 103243 : if (dq->msg_count == ccol_max_elem_count) {
1425 0 : ccol__mutex_unlock(dq->mutex);
1426 0 : return ccol_container_full;
1427 : }
1428 :
1429 103243 : ccol_retval result = sendto_dq(dq, msg);
1430 :
1431 103243 : ccol__mutex_unlock(dq->mutex);
1432 :
1433 103243 : return result;
1434 : }
1435 :
1436 : // Appends msg whether sends are on or off, so an owner that turned sends off
1437 : // can still queue its last control message (see internal/cqueueowner.h).
1438 38 : ccol_retval cdynmq_owner_send(cdynmq *dq, cmessage *msg) {
1439 38 : if (!verify_dynmq_send_zc_params(dq, msg)) return ccol_invalid_args;
1440 38 : ccol__mutex_lock(dq->mutex);
1441 76 : ccol_retval result = dq->msg_count == ccol_max_elem_count
1442 : ? ccol_container_full
1443 38 : : sendto_dq(dq, msg);
1444 38 : ccol__mutex_unlock(dq->mutex);
1445 38 : return result;
1446 : }
1447 :
1448 : // Takes the head message, counts it and wakes one write waiter. Every receive
1449 : // path of the dynamic queue ends here. The caller holds the mutex.
1450 103061 : static ccol_retval recvfrom_dq(cdynmq *dq, cmessage *target_buf) {
1451 103061 : ccol_retval retval = remove_msg_from_dq_head(dq, target_buf);
1452 :
1453 103060 : if (retval == ccol_success) {
1454 103060 : --dq->msg_count;
1455 103060 : notify_one_sel_waiter(&dq->sel_write_waiters_head, &dq->sel_write_rotor);
1456 : }
1457 :
1458 103060 : return retval;
1459 : }
1460 :
1461 : // Checks the arguments of every dynamic queue receive: Neither the queue nor
1462 : // the buffer may be NULL.
1463 104417 : static bool verify_recvfrom_dq_zc_params(cdynmq *dq, cmessage *target_buf) {
1464 104417 : if (!dq || !target_buf) {
1465 : return false;
1466 : }
1467 :
1468 : return true;
1469 : }
1470 :
1471 : // Receives the head message, blocking on read_cond while the queue is empty,
1472 : // for a consumer with nothing else to do.
1473 16 : ccol_retval cdynmq_recv(cdynmq *dq, cmessage *target_buf) {
1474 16 : if (!verify_recvfrom_dq_zc_params(dq, target_buf)) {
1475 : return ccol_invalid_args;
1476 : }
1477 :
1478 16 : ccol__mutex_lock(dq->mutex);
1479 :
1480 18 : while (dq->msg_count == 0) {
1481 2 : ++dq->readers_waiting;
1482 2 : ccol__cond_var_wait(dq->read_cond, dq->mutex);
1483 2 : --dq->readers_waiting;
1484 : }
1485 :
1486 16 : ccol_retval result = recvfrom_dq(dq, target_buf);
1487 :
1488 16 : ccol__mutex_unlock(dq->mutex);
1489 :
1490 16 : return result;
1491 : }
1492 :
1493 : // Receives the head message or gives ccol_container_empty at once, for a
1494 : // consumer that must not block.
1495 87472 : ccol_retval cdynmq_try_recv(cdynmq *dq, cmessage *target_buf) {
1496 87472 : if (!verify_recvfrom_dq_zc_params(dq, target_buf)) {
1497 : return ccol_invalid_args;
1498 : }
1499 :
1500 87471 : ccol_retval result = ccol_container_empty;
1501 :
1502 87471 : ccol__mutex_lock(dq->mutex);
1503 :
1504 87536 : if (dq->msg_count > 0) {
1505 86141 : result = recvfrom_dq(dq, target_buf);
1506 : }
1507 :
1508 87536 : ccol__mutex_unlock(dq->mutex);
1509 :
1510 87536 : return result;
1511 : }
1512 :
1513 : #ifdef RUNNING_UNIT_TESTS
1514 : // Test-only flags of the forced wait error of cdynmq_timed_recv.
1515 : static _Atomic bool g_dynmq_recv_force_condvar_wait_error = false;
1516 : static _Atomic bool g_dynmq_recv_force_condvar_wait_error_also_race = false;
1517 :
1518 : // Test-only: Arms the forced wait error of the next timed receive.
1519 1 : void cdynmq__test_force_next_recv_condvar_wait_error(void) {
1520 1 : atomic_store(&g_dynmq_recv_force_condvar_wait_error, true);
1521 1 : }
1522 :
1523 : // Test-only: Arms the forced wait error together with an imitated send of a
1524 : // sentinel under the same mutex.
1525 1 : void cdynmq__test_force_next_recv_condvar_wait_error_racing_ready(void) {
1526 1 : atomic_store(&g_dynmq_recv_force_condvar_wait_error, true);
1527 1 : atomic_store(&g_dynmq_recv_force_condvar_wait_error_also_race, true);
1528 1 : }
1529 : #endif
1530 :
1531 : // Receives the head message, waiting at most timeout_us against one deadline,
1532 : // for a consumer that also has other work (0 is cdynmq_try_recv()). As in
1533 : // ccircq_timed_recv(), a message that arrived wins over a failed wait.
1534 16932 : ccol_retval cdynmq_timed_recv(cdynmq *dq, cmessage *target_buf,
1535 : uint64_t timeout_us) {
1536 16932 : if (timeout_us == 0) return cdynmq_try_recv(dq, target_buf);
1537 16929 : if (!verify_recvfrom_dq_zc_params(dq, target_buf)) {
1538 : return ccol_invalid_args;
1539 : }
1540 :
1541 16929 : ccol__mutex_lock(dq->mutex);
1542 :
1543 16929 : if (dq->msg_count == 0) {
1544 730 : int retval;
1545 730 : struct timespec abs_time;
1546 730 : ccol_deadline_after_us(timeout_us, &abs_time);
1547 :
1548 1434 : while (dq->msg_count == 0) {
1549 730 : ++dq->readers_waiting;
1550 : #ifdef RUNNING_UNIT_TESTS
1551 730 : if (atomic_load(&g_dynmq_recv_force_condvar_wait_error)) {
1552 2 : atomic_store(&g_dynmq_recv_force_condvar_wait_error, false);
1553 2 : retval = EINVAL;
1554 2 : if (atomic_load(&g_dynmq_recv_force_condvar_wait_error_also_race)) {
1555 1 : atomic_store(&g_dynmq_recv_force_condvar_wait_error_also_race, false);
1556 1 : cmessage sentinel = {.data = NULL, .size = 0};
1557 1 : sendto_dq(dq, &sentinel);
1558 : }
1559 : } else {
1560 728 : retval = ccol__cond_var_timedwait(dq->read_cond, dq->mutex, abs_time);
1561 : }
1562 : #else
1563 : retval = ccol__cond_var_timedwait(dq->read_cond, dq->mutex, abs_time);
1564 : #endif
1565 714 : --dq->readers_waiting;
1566 714 : if (retval) {
1567 10 : if (dq->msg_count > 0) break;
1568 9 : if (retval != ETIMEDOUT) {
1569 1 : ccol_store_wait_errno(retval);
1570 1 : ccol__mutex_unlock(dq->mutex);
1571 9 : return ccol_unexpected_failure;
1572 : }
1573 8 : ccol__mutex_unlock(dq->mutex);
1574 8 : return ccol_timed_out;
1575 : }
1576 : }
1577 : }
1578 :
1579 16904 : ccol_retval result = recvfrom_dq(dq, target_buf);
1580 :
1581 16903 : ccol__mutex_unlock(dq->mutex);
1582 :
1583 16903 : return result;
1584 : }
1585 :
1586 : // Turns sends off, so an owner can stop new work, and under the mutex wakes
1587 : // every write waiter.
1588 33 : ccol_retval cdynmq_disable_sending(cdynmq *dq) {
1589 33 : if (dq) {
1590 33 : ccol__mutex_lock(dq->mutex);
1591 33 : dq->writing_disabled = true;
1592 33 : notify_all_sel_waiters(dq->sel_write_waiters_head);
1593 33 : ccol__mutex_unlock(dq->mutex);
1594 33 : return ccol_success;
1595 : }
1596 :
1597 : return ccol_invalid_args;
1598 : }
1599 :
1600 : // Turns sends back on after cdynmq_disable_sending() and wakes every write
1601 : // waiter.
1602 209 : ccol_retval cdynmq_enable_sending(cdynmq *dq) {
1603 209 : if (dq) {
1604 209 : ccol__mutex_lock(dq->mutex);
1605 209 : dq->writing_disabled = false;
1606 209 : notify_all_sel_waiters(dq->sel_write_waiters_head);
1607 209 : ccol__mutex_unlock(dq->mutex);
1608 209 : return ccol_success;
1609 : }
1610 :
1611 : return ccol_invalid_args;
1612 : }
1613 :
1614 : // Gives the message count, read under the mutex, or ccol_invalid_size for NULL.
1615 : // The destroy uses it, and so can a caller.
1616 382 : size_t cdynmq_msg_count(cdynmq *dq) {
1617 382 : size_t result = ccol_invalid_size;
1618 :
1619 31 : if (dq) {
1620 382 : ccol__mutex_lock(dq->mutex);
1621 382 : result = dq->msg_count;
1622 382 : ccol__mutex_unlock(dq->mutex);
1623 : }
1624 :
1625 351 : return result;
1626 : }
1627 :
1628 : // Channel
1629 :
1630 : // A channel: Two circular queues and the thread ID of the owner, which routes
1631 : // every call.
1632 : struct cchan {
1633 : ccol__thread_id owner_tid;
1634 : ccircq *owner_to_workers_cq;
1635 : ccircq *workers_to_owner_cq;
1636 : ccol_memmgmt_procs *m_procs;
1637 : };
1638 :
1639 : // Creates a channel for two-way traffic between an owner and its workers: Its
1640 : // two circular queues, and the calling thread recorded as the owner. Gives the
1641 : // channel, or NULL with *err_str set.
1642 32 : cchan *cchan_create_mp(size_t max_size, ccol_memmgmt_procs *mmgmt_procs,
1643 : char **err_str) {
1644 32 : if (!ccol__verify_memmgmt_procs(mmgmt_procs, err_str)) {
1645 1 : return NULL;
1646 : }
1647 :
1648 31 : cchan *ch = (cchan *)ccol__mem_alloc(mmgmt_procs, sizeof(cchan));
1649 31 : if (!ch) {
1650 0 : if (err_str) {
1651 0 : *err_str = CCOL__ERR_STR("Failed to allocate memory for cchan");
1652 : }
1653 0 : return NULL;
1654 : }
1655 :
1656 31 : if (!ccol__populate_mem_mgmt_procs(ch, mmgmt_procs, err_str)) {
1657 0 : ccol__mem_free(mmgmt_procs, ch);
1658 0 : return NULL;
1659 : }
1660 :
1661 31 : ch->owner_to_workers_cq = ccircq_create_mp(max_size, mmgmt_procs, err_str);
1662 31 : if (!ch->owner_to_workers_cq) {
1663 2 : ccol__mem_free(mmgmt_procs, ch->m_procs);
1664 2 : ccol__mem_free(mmgmt_procs, ch);
1665 2 : return NULL;
1666 : }
1667 :
1668 29 : ch->workers_to_owner_cq = ccircq_create_mp(max_size, mmgmt_procs, err_str);
1669 29 : if (!ch->workers_to_owner_cq) {
1670 0 : ccircq_destroy(ch->owner_to_workers_cq);
1671 0 : ccol__mem_free(mmgmt_procs, ch->m_procs);
1672 0 : ccol__mem_free(mmgmt_procs, ch);
1673 0 : return NULL;
1674 : }
1675 :
1676 29 : ch->owner_tid = ccol__get_thread_id();
1677 :
1678 29 : if (err_str) {
1679 2 : *err_str = NULL;
1680 : }
1681 :
1682 : return ch;
1683 : }
1684 :
1685 : // Destroys both queues of the channel, then the channel; cchan_destroy() calls
1686 : // it.
1687 29 : void cchan__destroy(cchan *ch) {
1688 29 : if (ch) {
1689 29 : ccircq_destroy(ch->owner_to_workers_cq);
1690 29 : ccircq_destroy(ch->workers_to_owner_cq);
1691 :
1692 28 : if (ch->m_procs) {
1693 2 : ccol_free free_func = ch->m_procs->free;
1694 2 : free_func(ch->m_procs);
1695 2 : free_func(ch);
1696 : } else {
1697 26 : ccol__default_mem_free(ch);
1698 : }
1699 : }
1700 28 : }
1701 :
1702 : // Sends on the caller's direction: The owner to owner_to_workers_cq, any other
1703 : // thread to workers_to_owner_cq. The thread ID comparison is all the routing.
1704 19 : ccol_retval cchan_send(cchan *ch, cmessage *msg) {
1705 19 : if (!ch) {
1706 : return ccol_invalid_args;
1707 : }
1708 :
1709 19 : if (ccol__get_thread_id() == ch->owner_tid) {
1710 10 : return ccircq_send(ch->owner_to_workers_cq, msg);
1711 : }
1712 :
1713 9 : return ccircq_send(ch->workers_to_owner_cq, msg);
1714 : }
1715 :
1716 : // ccircq_try_send() on the caller's direction, for a channel user that must not
1717 : // block.
1718 7 : ccol_retval cchan_try_send(cchan *ch, cmessage *msg) {
1719 7 : if (!ch) {
1720 : return ccol_invalid_args;
1721 : }
1722 :
1723 7 : if (ccol__get_thread_id() == ch->owner_tid) {
1724 4 : return ccircq_try_send(ch->owner_to_workers_cq, msg);
1725 : }
1726 :
1727 3 : return ccircq_try_send(ch->workers_to_owner_cq, msg);
1728 : }
1729 :
1730 : // ccircq_timed_send() on the caller's direction, for a channel user that may
1731 : // wait a while.
1732 7 : ccol_retval cchan_timed_send(cchan *ch, cmessage *msg, uint64_t timeout_us) {
1733 7 : if (!ch) {
1734 : return ccol_invalid_args;
1735 : }
1736 :
1737 7 : if (ccol__get_thread_id() == ch->owner_tid) {
1738 4 : return ccircq_timed_send(ch->owner_to_workers_cq, msg, timeout_us);
1739 : }
1740 :
1741 3 : return ccircq_timed_send(ch->workers_to_owner_cq, msg, timeout_us);
1742 : }
1743 :
1744 : // Receives on the caller's direction: The owner from workers_to_owner_cq, any
1745 : // other thread from owner_to_workers_cq.
1746 13 : ccol_retval cchan_recv(cchan *ch, cmessage *target_buf) {
1747 13 : if (!ch) {
1748 : return ccol_invalid_args;
1749 : }
1750 :
1751 13 : if (ccol__get_thread_id() == ch->owner_tid) {
1752 7 : return ccircq_recv(ch->workers_to_owner_cq, target_buf);
1753 : }
1754 :
1755 6 : return ccircq_recv(ch->owner_to_workers_cq, target_buf);
1756 : }
1757 :
1758 : // ccircq_try_recv() on the caller's direction, for a channel user that must not
1759 : // block.
1760 10 : ccol_retval cchan_try_recv(cchan *ch, cmessage *target_buf) {
1761 10 : if (!ch) {
1762 : return ccol_invalid_args;
1763 : }
1764 :
1765 10 : if (ccol__get_thread_id() == ch->owner_tid) {
1766 6 : return ccircq_try_recv(ch->workers_to_owner_cq, target_buf);
1767 : }
1768 :
1769 4 : return ccircq_try_recv(ch->owner_to_workers_cq, target_buf);
1770 : }
1771 :
1772 : // ccircq_timed_recv() on the caller's direction, for a channel user that may
1773 : // wait a while.
1774 5 : ccol_retval cchan_timed_recv(cchan *ch, cmessage *target_buf,
1775 : uint64_t timeout_us) {
1776 5 : if (!ch) {
1777 : return ccol_invalid_args;
1778 : }
1779 :
1780 5 : if (ccol__get_thread_id() == ch->owner_tid) {
1781 2 : return ccircq_timed_recv(ch->workers_to_owner_cq, target_buf, timeout_us);
1782 : }
1783 :
1784 3 : return ccircq_timed_recv(ch->owner_to_workers_cq, target_buf, timeout_us);
1785 : }
1786 :
1787 : // Turns sends off on direction d, so one side can stop new work. The direction
1788 : // is explicit here, since a caller may stop only one side.
1789 2 : ccol_retval cchan_disable_sending(cchan *ch, cchan_direction d) {
1790 2 : if (!ch) {
1791 : return ccol_invalid_args;
1792 : }
1793 :
1794 2 : if (d == cchan_owner_to_workers) {
1795 1 : return ccircq_disable_sending(ch->owner_to_workers_cq);
1796 1 : } else if (d == cchan_workers_to_owner) {
1797 1 : return ccircq_disable_sending(ch->workers_to_owner_cq);
1798 : }
1799 :
1800 : return ccol_invalid_args;
1801 : }
1802 :
1803 : // Turns sends back on for direction d.
1804 2 : ccol_retval cchan_enable_sending(cchan *ch, cchan_direction d) {
1805 2 : if (!ch) {
1806 : return ccol_invalid_args;
1807 : }
1808 :
1809 2 : if (d == cchan_owner_to_workers) {
1810 1 : return ccircq_enable_sending(ch->owner_to_workers_cq);
1811 1 : } else if (d == cchan_workers_to_owner) {
1812 1 : return ccircq_enable_sending(ch->workers_to_owner_cq);
1813 : }
1814 :
1815 : return ccol_invalid_args;
1816 : }
1817 :
1818 : // Gives the message count of direction d, for a snapshot, or ccol_invalid_size
1819 : // for a bad d.
1820 24 : size_t cchan_msg_count(cchan *ch, cchan_direction d) {
1821 24 : if (!ch) {
1822 : return ccol_invalid_size;
1823 : }
1824 :
1825 24 : if (d == cchan_owner_to_workers) {
1826 24 : return ccircq_msg_count(ch->owner_to_workers_cq);
1827 12 : } else if (d == cchan_workers_to_owner) {
1828 24 : return ccircq_msg_count(ch->workers_to_owner_cq);
1829 : }
1830 :
1831 : return ccol_invalid_size;
1832 : }
1833 :
1834 : // cselect
1835 :
1836 : // Splices node out of a waiter list; every path that takes a waiter off a
1837 : // queue uses it. head and rotor must be the pair of that list. A rotor that
1838 : // points at node moves to node->next first, since the node can be freed right
1839 : // after. The caller holds the queue's mutex and forwards the wake in the same
1840 : // critical section.
1841 7983 : static void sel_unlink_waiter_locked(ccol_sel_waiter *node,
1842 : ccol_sel_waiter **head,
1843 : ccol_sel_waiter **rotor) {
1844 61 : if (*rotor == node) *rotor = node->next;
1845 7983 : if (node->prev)
1846 595 : node->prev->next = node->next;
1847 : else
1848 7388 : *head = node->next;
1849 7983 : if (node->next) node->next->prev = node->prev;
1850 : }
1851 :
1852 : static void queue_sel_locate(cselectable *sel, ccol__mutex **out_mtx,
1853 : ccol_sel_waiter ***out_head,
1854 : ccol_sel_waiter ***out_rotor);
1855 : static bool queue_sel_is_ready(cselectable *sel);
1856 :
1857 : // Unlinks the waiter node of selectables[i] from its queue, taking the queue's
1858 : // mutex, drains the node's eventfd for reuse and marks the slot done
1859 : // (sel_mtx = NULL). When the queue is still ready the wake goes on to another
1860 : // waiter in the same critical section: A producer wakes exactly one waiter, and
1861 : // a waiter that leaves for another reason (deadline, another selectable won,
1862 : // an error) would otherwise use that wake up while a message sits in the
1863 : // queue. An fd selectable has nothing to unlink.
1864 7543 : static void deregister_sel_waiter(size_t i, ccol_sel_waiter *nodes,
1865 : cselectable *selectables) {
1866 7543 : if (selectables[i].type == cselectable_type_fd) return;
1867 :
1868 7543 : ccol__mutex *q_mtx;
1869 7543 : ccol_sel_waiter **head;
1870 7543 : ccol_sel_waiter **rotor;
1871 15086 : queue_sel_locate(&selectables[i], &q_mtx, &head, &rotor);
1872 :
1873 7543 : ccol__mutex_lock(*q_mtx);
1874 7551 : sel_unlink_waiter_locked(&nodes[i], head, rotor);
1875 7551 : if (queue_sel_is_ready(&selectables[i])) notify_one_sel_waiter(head, rotor);
1876 7551 : ccol__mutex_unlock(*q_mtx);
1877 :
1878 7551 : if (nodes[i].efd >= 0) {
1879 2465 : eventfd_drain(nodes[i].efd);
1880 : }
1881 7537 : nodes[i].sel_mtx = NULL;
1882 : }
1883 :
1884 : // Deregisters every node of a cselect_timed() call whose sel_mtx isn't NULL,
1885 : // on every way out of a pass.
1886 18212 : static void deregister_all_sel_waiters(size_t n, ccol_sel_waiter *nodes,
1887 : cselectable *selectables) {
1888 51919 : for (size_t i = 0; i < n; i++) {
1889 33731 : if (nodes[i].sel_mtx != NULL) {
1890 7545 : deregister_sel_waiter(i, nodes, selectables);
1891 : }
1892 : }
1893 18188 : }
1894 :
1895 : // Gives a selectable for the channel queue that the calling thread reads from
1896 : // or writes to: For cselect_read the owner watches workers_to_owner_cq and a
1897 : // worker owner_to_workers_cq, for cselect_write the other way round. A NULL ch
1898 : // gives a selectable with a NULL queue.
1899 18 : cselectable cchan_selectable(cchan *ch, cselect_dir dir) {
1900 18 : if (!ch) {
1901 0 : return (cselectable){
1902 : .type = cselectable_type_ccircq, .dir = dir, .cq = NULL};
1903 : }
1904 18 : bool is_owner = (ccol__get_thread_id() == ch->owner_tid);
1905 18 : ccircq *cq;
1906 18 : if (dir == cselect_read) {
1907 17 : cq = is_owner ? ch->workers_to_owner_cq : ch->owner_to_workers_cq;
1908 : } else {
1909 1 : cq = is_owner ? ch->owner_to_workers_cq : ch->workers_to_owner_cq;
1910 : }
1911 18 : return (cselectable){.type = cselectable_type_ccircq, .dir = dir, .cq = cq};
1912 : }
1913 :
1914 : // Gives nodes[i] an eventfd registered with epfd under its index, so a queue
1915 : // notify wakes the poll wait of a call with fds; once per call. Gives false
1916 : // when eventfd or the registration fails. The node must not be linked yet,
1917 : // since producers read efd.
1918 1951 : static bool sel_ensure_efd(size_t i, ccol_sel_waiter *nodes, int epfd) {
1919 1951 : if (nodes[i].efd >= 0) return true;
1920 1931 : nodes[i].efd = ccol_wakefd_create();
1921 1935 : if (nodes[i].efd < 0) return false;
1922 1935 : ccol_poll_event ev = {.data.u64 = (uint64_t)i, .events = CCOL_POLL_IN};
1923 1935 : if (ccol_poll_ctl(epfd, CCOL_POLL_CTL_ADD, nodes[i].efd, &ev, NULL) < 0) {
1924 0 : close(nodes[i].efd);
1925 0 : nodes[i].efd = -1;
1926 0 : return false;
1927 : }
1928 : return true;
1929 : }
1930 :
1931 : // Fills nodes[i] and prepends it to *head, so the queue's producers can wake
1932 : // it. cselect_timed() and ceventloop_add_queue() use it. The caller holds the
1933 : // queue's mutex.
1934 7988 : static void sel_link_waiter(size_t i, ccol_sel_waiter *nodes,
1935 : ccol__mutex *sel_mtx, ccol__cond_var *sel_cond,
1936 : bool *ready, ccol_sel_waiter **head) {
1937 7988 : nodes[i].sel_mtx = sel_mtx;
1938 7988 : nodes[i].sel_cond = sel_cond;
1939 7988 : nodes[i].ready = ready;
1940 7988 : nodes[i].fwd_hops = 0;
1941 7988 : nodes[i].prev = NULL;
1942 7988 : nodes[i].next = *head;
1943 1865 : if (*head) (*head)->prev = &nodes[i];
1944 7988 : *head = &nodes[i];
1945 : }
1946 :
1947 : // Checks the arguments of cselect_timed() before it allocates anything. Gives
1948 : // ccol_success or ccol_invalid_args. n must keep n * sizeof(ccol_sel_waiter)
1949 : // from overflowing (the waiter array is one plain malloc) and be at most
1950 : // INT_MAX, since the scan carries the match index in an int.
1951 10670 : static ccol_retval sel_validate_args(const size_t *ready_index, size_t n,
1952 : const cselectable *selectables) {
1953 10670 : if (!ready_index || n == 0 || !selectables) return ccol_invalid_args;
1954 10667 : if (n > SIZE_MAX / sizeof(ccol_sel_waiter)) return ccol_invalid_args;
1955 10666 : if (n > (size_t)INT_MAX) return ccol_invalid_args;
1956 32462 : for (size_t i = 0; i < n; i++) {
1957 21799 : if (selectables[i].type == cselectable_type_ccircq) {
1958 9080 : if (!selectables[i].cq) return ccol_invalid_args;
1959 12719 : } else if (selectables[i].type == cselectable_type_cdynmq) {
1960 6452 : if (!selectables[i].dq) return ccol_invalid_args;
1961 6267 : } else if (selectables[i].type == cselectable_type_fd) {
1962 6267 : if (selectables[i].fd < 0) return ccol_invalid_args;
1963 : } else {
1964 : return ccol_invalid_args;
1965 : }
1966 21797 : if (selectables[i].dir != cselect_read &&
1967 : selectables[i].dir != cselect_write)
1968 : return ccol_invalid_args;
1969 : }
1970 : return ccol_success;
1971 : }
1972 :
1973 : // Turns the timeout_us of cselect_timed() into a CLOCK_MONOTONIC deadline and
1974 : // gives true, or gives false for UINT64_MAX, which means no deadline.
1975 10666 : static bool sel_compute_deadline(uint64_t timeout_us,
1976 : struct timespec *deadline) {
1977 10666 : if (timeout_us == UINT64_MAX) return false;
1978 4446 : ccol_deadline_after_us(timeout_us, deadline);
1979 4446 : return true;
1980 : }
1981 :
1982 : // The interest bits of one direction of an fd selectable. Registration and
1983 : // the mapping of events back to members both use it, so they always agree.
1984 1928 : static uint32_t sel_fd_base_events(cselect_dir dir) {
1985 1928 : return (dir == cselect_read)
1986 : ? (uint32_t)(CCOL_POLL_IN | CCOL_POLL_RDHUP | CCOL_POLL_ERR |
1987 : CCOL_POLL_HUP)
1988 1928 : : (uint32_t)(CCOL_POLL_OUT | CCOL_POLL_ERR | CCOL_POLL_HUP);
1989 : }
1990 :
1991 : // Tag bit in the event data of an fd group's registration. The other bits hold
1992 : // the position of the group's first member in the sorted pairs, so an event
1993 : // leads to its group without a search. A queue eventfd's data is an index below
1994 : // n, and the position stays below INT_MAX, keeping bit 62 (reserved by the
1995 : // kqueue translation) clear.
1996 : #define SEL_FD_TAG ((uint64_t)1 << 63)
1997 :
1998 : // One fd selectable and its index in selectables[]. Sorted by fd, the
1999 : // selectables of one fd form a contiguous run.
2000 : typedef struct {
2001 : int fd;
2002 : size_t idx;
2003 : } sel_fd_pair;
2004 :
2005 : // What a cselect_timed() call with fd selectables keeps. pairs and pfds hold
2006 : // the fd selectables in the same order (Phase 1 polls them without any kernel
2007 : // state), and fd_ready one flag per selectable; the three share one block.
2008 : // Only a call that blocks builds the poll set, which sorts pairs and pfds by fd
2009 : // then index, and evs, which has room for every filter the set can report at
2010 : // once.
2011 : typedef struct {
2012 : sel_fd_pair *pairs;
2013 : struct pollfd *pfds;
2014 : size_t n_pairs;
2015 : ccol_poll_event *evs;
2016 : int ev_cap;
2017 : bool *fd_ready;
2018 : bool has_queues;
2019 : } sel_fd_state;
2020 :
2021 : // Frees what sel_fd_state_init() and sel_setup_epoll() allocated: The block of
2022 : // pairs, pfds and fd_ready, and the event buffer.
2023 5264 : static void sel_fd_state_free(sel_fd_state *fs) {
2024 5264 : free(fs->pairs);
2025 5264 : free(fs->evs);
2026 5263 : }
2027 :
2028 : // The calling thread's rotation state for the scan of cselect_timed(). Each
2029 : // call adds the 32-bit golden ratio (a Weyl sequence), so starts spread evenly
2030 : // over [0, n) even when a thread alternates between sets. Per thread, it writes
2031 : // no shared cache line.
2032 : static __thread uint32_t sel_rotation;
2033 :
2034 : // Gives the next start index in [0, n) for the scan of cselect_timed(), so
2035 : // ready selectables share the calls; 0 for a single selectable. Advances the
2036 : // thread's sel_rotation.
2037 10663 : static size_t sel_rotation_start(size_t n) {
2038 10663 : if (n < 2) return 0;
2039 8140 : sel_rotation += 0x9E3779B9u;
2040 8140 : return (size_t)(((uint64_t)sel_rotation * (uint64_t)n) >> 32);
2041 : }
2042 :
2043 : // Turns the events of the last poll wait into fs->fd_ready for
2044 : // sel_wait_epoll(): The flag of every fd selectable whose direction an event
2045 : // satisfies is set and the rest cleared. Each event is refined with the
2046 : // combined mask of its fd group; queue eventfd events and events that refine to
2047 : // nothing set no flag. Gives true when any flag is set.
2048 2461 : static bool sel_mark_fd_events(sel_fd_state *fs, size_t n,
2049 : cselectable *selectables, int n_ev) {
2050 2461 : memset(fs->fd_ready, 0, n * sizeof(bool));
2051 2461 : bool any = false;
2052 4922 : for (int e = 0; e < n_ev; e++) {
2053 2461 : ccol_poll_event *ev = &fs->evs[e];
2054 2461 : if (!(ev->data.u64 & SEL_FD_TAG)) continue;
2055 3 : size_t run = (size_t)(ev->data.u64 & ~SEL_FD_TAG);
2056 3 : int fd = fs->pairs[run].fd;
2057 3 : size_t end = run;
2058 3 : uint32_t combined = 0;
2059 6 : while (end < fs->n_pairs && fs->pairs[end].fd == fd) {
2060 3 : combined |= sel_fd_base_events(selectables[fs->pairs[end].idx].dir);
2061 3 : end++;
2062 : }
2063 : ccol_poll_refine(ev, fd, combined, NULL);
2064 6 : for (size_t j = run; j < end; j++) {
2065 3 : size_t idx = fs->pairs[j].idx;
2066 3 : if (sel_fd_base_events(selectables[idx].dir) & ev->events) {
2067 3 : fs->fd_ready[idx] = true;
2068 3 : any = true;
2069 : }
2070 : }
2071 : }
2072 2461 : return any;
2073 : }
2074 :
2075 : // qsort() order of the pairs, by fd and then by index, which groups the
2076 : // selectables of one fd for sel_setup_epoll().
2077 1 : static int sel_fd_pair_cmp(const void *a, const void *b) {
2078 1 : const sel_fd_pair *pa = (const sel_fd_pair *)a;
2079 1 : const sel_fd_pair *pb = (const sel_fd_pair *)b;
2080 1 : if (pa->fd != pb->fd) return (pa->fd < pb->fd) ? -1 : 1;
2081 1 : if (pa->idx != pb->idx) return (pa->idx < pb->idx) ? -1 : 1;
2082 : return 0;
2083 : }
2084 :
2085 : #ifdef RUNNING_UNIT_TESTS
2086 : // Test-only: The number of the cselect allocation that fails, 0 when none.
2087 : static _Atomic uint32_t g_sel_fail_alloc_at = 0;
2088 :
2089 : // Test-only: How many poll sets cselect_timed() created.
2090 : static _Atomic uint64_t g_sel_poll_sets_created = 0;
2091 :
2092 : // Test-only: Arms the failing allocation.
2093 10 : void cselect__test_fail_alloc(uint32_t index) {
2094 10 : atomic_store(&g_sel_fail_alloc_at, index);
2095 10 : }
2096 :
2097 : // Test-only: Reads the count of poll sets.
2098 12 : uint64_t cselect__test_poll_sets_created(void) {
2099 12 : return atomic_load(&g_sel_poll_sets_created);
2100 : }
2101 : #endif
2102 :
2103 : // malloc() for every allocation of cselect_timed(), so a test can make any one
2104 : // of them fail.
2105 17887 : static void *sel_malloc(size_t size) {
2106 : #ifdef RUNNING_UNIT_TESTS
2107 17887 : uint32_t at = atomic_load(&g_sel_fail_alloc_at);
2108 17887 : while (at != 0) {
2109 10 : if (atomic_compare_exchange_weak(&g_sel_fail_alloc_at, &at, at - 1)) {
2110 10 : if (at == 1) return NULL;
2111 : break;
2112 : }
2113 : }
2114 : #endif
2115 17883 : return malloc(size);
2116 : }
2117 :
2118 : // Fills *fs with the fd selectables in array order and allocates the block of
2119 : // pairs, pfds and fd_ready; cselect_timed() calls it for a set with fds. Free
2120 : // it with sel_fd_state_free() whatever the result. Gives ccol_success or
2121 : // ccol_not_enough_memory.
2122 5262 : static ccol_retval sel_fd_state_init(size_t n, cselectable *selectables,
2123 : sel_fd_state *fs) {
2124 5262 : fs->pairs = NULL;
2125 5262 : fs->pfds = NULL;
2126 5262 : fs->evs = NULL;
2127 5262 : fs->ev_cap = 0;
2128 5262 : fs->fd_ready = NULL;
2129 5262 : fs->n_pairs = 0;
2130 5262 : size_t n_fd = 0;
2131 15652 : for (size_t i = 0; i < n; i++) {
2132 10390 : if (selectables[i].type == cselectable_type_fd) n_fd++;
2133 : }
2134 5262 : fs->has_queues = n_fd < n;
2135 :
2136 5262 : _Static_assert(_Alignof(sel_fd_pair) % _Alignof(struct pollfd) == 0,
2137 : "the pollfd array must be aligned after the pairs");
2138 5262 : if (n_fd > SIZE_MAX / (sizeof(sel_fd_pair) + sizeof(struct pollfd)) ||
2139 5262 : n > SIZE_MAX - n_fd * (sizeof(sel_fd_pair) + sizeof(struct pollfd)))
2140 : return ccol_not_enough_memory;
2141 5262 : size_t pfds_off = n_fd * sizeof(sel_fd_pair);
2142 5262 : size_t ready_off = pfds_off + n_fd * sizeof(struct pollfd);
2143 5262 : unsigned char *block = sel_malloc(ready_off + n * sizeof(bool));
2144 5265 : if (!block) return ccol_not_enough_memory;
2145 5264 : fs->pairs = (sel_fd_pair *)(void *)block;
2146 5264 : fs->pfds = (struct pollfd *)(void *)(block + pfds_off);
2147 5264 : fs->fd_ready = (bool *)(void *)(block + ready_off);
2148 :
2149 5264 : size_t k = 0;
2150 15656 : for (size_t i = 0; i < n; i++) {
2151 10392 : if (selectables[i].type != cselectable_type_fd) continue;
2152 6265 : fs->pairs[k].fd = selectables[i].fd;
2153 6265 : fs->pairs[k].idx = i;
2154 6265 : fs->pfds[k].fd = selectables[i].fd;
2155 12530 : fs->pfds[k].events =
2156 6265 : (selectables[i].dir == cselect_read) ? POLLIN : POLLOUT;
2157 6265 : fs->pfds[k].revents = 0;
2158 6265 : k++;
2159 : }
2160 5264 : fs->n_pairs = k;
2161 5264 : return ccol_success;
2162 : }
2163 :
2164 : // Asks poll(2), without waiting, which fd selectables are ready and records it
2165 : // in fs->fd_ready. Phase 1 of cselect_timed() uses it, so a call answered at
2166 : // once needs no poll set. POLLIN counts for a read selectable, POLLOUT for a
2167 : // write one, and POLLERR or POLLHUP for both. A ready fd that is a regular file
2168 : // or a directory fails with EPERM (poll calls such a file always ready, epoll
2169 : // refuses it), and an fd that isn't open with EBADF. Gives 0, or -1 with errno
2170 : // set.
2171 9677 : static int sel_poll_fds(sel_fd_state *fs, size_t n, cselectable *selectables) {
2172 9678 : int r;
2173 9678 : do {
2174 9678 : r = poll(fs->pfds, (nfds_t)fs->n_pairs, 0);
2175 9584 : } while (r < 0 && errno == EINTR);
2176 9583 : if (r < 0) return -1;
2177 9583 : memset(fs->fd_ready, 0, n * sizeof(bool));
2178 9583 : if (r == 0) return 0;
2179 7189 : for (size_t k = 0; k < fs->n_pairs; k++) {
2180 4076 : short rev = fs->pfds[k].revents;
2181 4076 : if (rev == 0) continue;
2182 4075 : if (rev & POLLNVAL) {
2183 0 : errno = EBADF;
2184 2 : return -1;
2185 : }
2186 4075 : size_t idx = fs->pairs[k].idx;
2187 4075 : short want = (selectables[idx].dir == cselect_read) ? POLLIN : POLLOUT;
2188 4075 : if (!(rev & (want | POLLERR | POLLHUP))) continue;
2189 4075 : struct stat st;
2190 4075 : if (fstat(fs->pairs[k].fd, &st) != 0) return -1;
2191 4117 : if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode)) {
2192 2 : errno = EPERM;
2193 2 : return -1;
2194 : }
2195 4115 : fs->fd_ready[idx] = true;
2196 : }
2197 : return 0;
2198 : }
2199 :
2200 : // Builds what a call needs to block: The event buffer, a poll set with one
2201 : // level-triggered registration per fd (the selectables of one fd are combined
2202 : // into one registration with the OR of their masks, since a second ADD of the
2203 : // same fd fails), and an eventfd for each queue waiter. Grouping sorts the
2204 : // pairs, O(n log n), and rebuilds pfds in the same order. Every node must be
2205 : // unlinked here. Gives ccol_success, ccol_not_enough_memory for the buffer, or
2206 : // ccol_unexpected_failure; *epfd is then -1 or a set the caller closes.
2207 1962 : static ccol_retval sel_setup_epoll(size_t n, cselectable *selectables,
2208 : ccol_sel_waiter *nodes, sel_fd_state *fs,
2209 : int *epfd) {
2210 1962 : size_t ev_cap = n + fs->n_pairs;
2211 1962 : if (ev_cap > (size_t)INT_MAX) ev_cap = (size_t)INT_MAX;
2212 : if (ev_cap > SIZE_MAX / sizeof(ccol_poll_event))
2213 : return ccol_not_enough_memory;
2214 1962 : fs->evs = sel_malloc(ev_cap * sizeof(ccol_poll_event));
2215 1962 : if (!fs->evs) return ccol_not_enough_memory;
2216 1961 : fs->ev_cap = (int)ev_cap;
2217 :
2218 1961 : *epfd = ccol_poll_create();
2219 1960 : if (*epfd < 0) return ccol_unexpected_failure;
2220 : #ifdef RUNNING_UNIT_TESTS
2221 1960 : atomic_fetch_add(&g_sel_poll_sets_created, (uint64_t)1);
2222 : #endif
2223 :
2224 1960 : size_t n_pairs = fs->n_pairs;
2225 1960 : qsort(fs->pairs, n_pairs, sizeof(sel_fd_pair), sel_fd_pair_cmp);
2226 3892 : for (size_t k = 0; k < n_pairs; k++) {
2227 1932 : size_t idx = fs->pairs[k].idx;
2228 1932 : fs->pfds[k].fd = fs->pairs[k].fd;
2229 3864 : fs->pfds[k].events =
2230 1932 : (selectables[idx].dir == cselect_read) ? POLLIN : POLLOUT;
2231 1932 : fs->pfds[k].revents = 0;
2232 : }
2233 :
2234 3900 : for (size_t i = 0; i < n_pairs;) {
2235 1939 : int fd = fs->pairs[i].fd;
2236 1939 : uint32_t combined = 0;
2237 1939 : size_t j = i;
2238 3864 : while (j < n_pairs && fs->pairs[j].fd == fd) {
2239 1925 : combined |= sel_fd_base_events(selectables[fs->pairs[j].idx].dir);
2240 1925 : j++;
2241 : }
2242 :
2243 1939 : ccol_poll_event ev;
2244 1939 : ev.data.u64 = SEL_FD_TAG | (uint64_t)i;
2245 1939 : ev.events = combined;
2246 1939 : if (ccol_poll_ctl(*epfd, CCOL_POLL_CTL_ADD, fd, &ev, NULL) < 0)
2247 0 : return ccol_unexpected_failure;
2248 1961 : i = j;
2249 : }
2250 :
2251 5847 : for (size_t i = 0; i < n; i++) {
2252 5815 : if (selectables[i].type != cselectable_type_fd &&
2253 1929 : !sel_ensure_efd(i, nodes, *epfd))
2254 : return ccol_unexpected_failure;
2255 : }
2256 : return ccol_success;
2257 : }
2258 :
2259 : // Phase 1: Scans the selectables in rotation order from start and stops at the
2260 : // first ready one. With fds it first polls them once without waiting, and a
2261 : // ready fd competes like a ready queue. A queue is only peeked at, under its
2262 : // mutex: A ready one also forwards a wake to its next waiter (this caller
2263 : // consumes nothing and is about to leave), and one that isn't ready gets its
2264 : // node linked. Write readiness is room or sends off. Gives the found index, -1
2265 : // when nothing is ready and every queue node is linked, or -2 when the poll
2266 : // fails, before any node is linked. fs is NULL without fds.
2267 18204 : static int sel_phase1_scan_register(size_t n, cselectable *selectables,
2268 : ccol_sel_waiter *nodes, size_t start,
2269 : sel_fd_state *fs, ccol__mutex *sel_mtx,
2270 : ccol__cond_var *sel_cond, bool *ready) {
2271 18204 : bool has_fd_sels = fs != NULL;
2272 18204 : if (has_fd_sels && sel_poll_fds(fs, n, selectables) != 0) return -2;
2273 : int found = -1;
2274 : size_t i = start;
2275 41759 : for (size_t left = n; left != 0 && found < 0;
2276 23671 : left--, i = (i + 1 == n) ? 0 : i + 1) {
2277 23544 : if (selectables[i].type == cselectable_type_fd) {
2278 7608 : if (has_fd_sels && fs->fd_ready[i]) found = (int)i;
2279 7608 : continue;
2280 : }
2281 :
2282 15936 : if (selectables[i].type == cselectable_type_ccircq) {
2283 10810 : ccircq *cq = selectables[i].cq;
2284 10810 : ccol__mutex_lock(cq->mutex);
2285 :
2286 10862 : if (selectables[i].dir == cselect_read) {
2287 9848 : if (cq->msg_count > 0) {
2288 4057 : notify_one_sel_waiter(&cq->sel_read_waiters_head,
2289 : &cq->sel_read_rotor);
2290 4057 : ccol__mutex_unlock(cq->mutex);
2291 4055 : found = (int)i;
2292 : } else {
2293 5791 : sel_link_waiter(i, nodes, sel_mtx, sel_cond, ready,
2294 : &cq->sel_read_waiters_head);
2295 5791 : ccol__mutex_unlock(cq->mutex);
2296 : }
2297 : } else {
2298 1014 : if (cq->msg_count < cq->max_size || cq->writing_disabled) {
2299 1007 : notify_one_sel_waiter(&cq->sel_write_waiters_head,
2300 : &cq->sel_write_rotor);
2301 1007 : ccol__mutex_unlock(cq->mutex);
2302 1007 : found = (int)i;
2303 : } else {
2304 7 : sel_link_waiter(i, nodes, sel_mtx, sel_cond, ready,
2305 : &cq->sel_write_waiters_head);
2306 7 : ccol__mutex_unlock(cq->mutex);
2307 : }
2308 : }
2309 : } else {
2310 5126 : cdynmq *dq = selectables[i].dq;
2311 5126 : ccol__mutex_lock(dq->mutex);
2312 :
2313 5205 : if (selectables[i].dir == cselect_read) {
2314 5202 : if (dq->msg_count > 0) {
2315 3448 : notify_one_sel_waiter(&dq->sel_read_waiters_head,
2316 : &dq->sel_read_rotor);
2317 3448 : ccol__mutex_unlock(dq->mutex);
2318 3448 : found = (int)i;
2319 : } else {
2320 1754 : sel_link_waiter(i, nodes, sel_mtx, sel_cond, ready,
2321 : &dq->sel_read_waiters_head);
2322 1754 : ccol__mutex_unlock(dq->mutex);
2323 : }
2324 : } else {
2325 3 : if (dq->writing_disabled || dq->msg_count < ccol_max_elem_count) {
2326 3 : notify_one_sel_waiter(&dq->sel_write_waiters_head,
2327 : &dq->sel_write_rotor);
2328 3 : ccol__mutex_unlock(dq->mutex);
2329 3 : found = (int)i;
2330 : } else {
2331 0 : sel_link_waiter(i, nodes, sel_mtx, sel_cond, ready,
2332 : &dq->sel_write_waiters_head);
2333 0 : ccol__mutex_unlock(dq->mutex);
2334 : }
2335 : }
2336 : }
2337 : }
2338 : return found;
2339 : }
2340 :
2341 : // How a condition-variable wait of cselect_timed() ended.
2342 : typedef enum {
2343 : SEL_CONDVAR_READY,
2344 : SEL_CONDVAR_TIMED_OUT,
2345 : SEL_CONDVAR_FAILURE,
2346 : } sel_condvar_outcome;
2347 :
2348 : #ifdef RUNNING_UNIT_TESTS
2349 : // Test-only: Makes the next timed condition wait of sel_wait_condvar() give
2350 : // EINVAL without waiting (no correct deadline can cause that).
2351 : static _Atomic bool g_sel_force_condvar_wait_error = false;
2352 :
2353 : // Test-only: With the flag above, also sets *ready under the same mutex, as a
2354 : // producer whose notify lands just before the error.
2355 : static _Atomic bool g_sel_force_condvar_wait_error_also_marks_ready = false;
2356 :
2357 : // Test-only: How many of the next capped waits (INT_MAX ms) of sel_wait_epoll
2358 : // return 0 at once.
2359 : static _Atomic uint32_t g_sel_short_capped_waits = 0;
2360 :
2361 : // Test-only: Sets and reads the count of capped waits that end at once.
2362 2 : void cselect__test_short_next_capped_waits(uint32_t count) {
2363 2 : atomic_store(&g_sel_short_capped_waits, count);
2364 2 : }
2365 :
2366 2 : uint32_t cselect__test_short_capped_waits_left(void) {
2367 2 : return atomic_load(&g_sel_short_capped_waits);
2368 : }
2369 :
2370 : // Test-only: ccol_poll_wait() that ends an armed capped wait at once.
2371 2474 : static int sel_poll_wait_for_tests(int epfd, ccol_poll_event *evs, int cap,
2372 : int timeout_ms) {
2373 2474 : if (timeout_ms == INT_MAX) {
2374 5 : uint32_t left = atomic_load(&g_sel_short_capped_waits);
2375 5 : while (left > 0) {
2376 3 : if (atomic_compare_exchange_weak(&g_sel_short_capped_waits, &left,
2377 : left - 1))
2378 2493 : return 0;
2379 : }
2380 : }
2381 2471 : return ccol_poll_wait(epfd, evs, cap, timeout_ms);
2382 : }
2383 :
2384 : // Test-only: Arm the forced condition wait error, with or without the ready
2385 : // flag.
2386 1 : void cselect__test_force_next_condvar_wait_error(void) {
2387 1 : atomic_store(&g_sel_force_condvar_wait_error, true);
2388 1 : }
2389 :
2390 1 : void cselect__test_force_next_condvar_wait_error_racing_ready(void) {
2391 1 : atomic_store(&g_sel_force_condvar_wait_error, true);
2392 1 : atomic_store(&g_sel_force_condvar_wait_error_also_marks_ready, true);
2393 1 : }
2394 :
2395 : // Test-only: The armed delay between a timed-out condition wait and the
2396 : // deregister step, and how many times a thread entered it.
2397 : static _Atomic uint32_t g_sel_timed_out_deregister_delay_us = 0;
2398 : static _Atomic uint64_t g_sel_timed_out_deregister_delays = 0;
2399 :
2400 : // Test-only: Arms the delay and reads the entry count.
2401 2 : void cselect__test_delay_next_timed_out_deregister_us(uint32_t us) {
2402 2 : atomic_store(&g_sel_timed_out_deregister_delay_us, us);
2403 2 : }
2404 :
2405 473 : uint64_t cselect__test_timed_out_deregister_delay_count(void) {
2406 473 : return atomic_load(&g_sel_timed_out_deregister_delays);
2407 : }
2408 :
2409 : // Test-only: Takes the armed delay once and counts it.
2410 6 : static void sel_timed_out_deregister_test_delay(void) {
2411 6 : uint32_t us = atomic_exchange(&g_sel_timed_out_deregister_delay_us, 0u);
2412 6 : if (us == 0) return;
2413 1 : atomic_fetch_add(&g_sel_timed_out_deregister_delays, (uint64_t)1);
2414 1 : struct timespec ts = {.tv_sec = us / 1000000,
2415 1 : .tv_nsec = (long)(us % 1000000) * 1000L};
2416 1 : nanosleep(&ts, NULL);
2417 : }
2418 : #endif
2419 :
2420 : // Phase 2 of cselect_timed() without fds: Waits on sel_cond until a producer
2421 : // sets *ready or the deadline passes, and clears *ready before it returns. A
2422 : // wait with no deadline always gives SEL_CONDVAR_READY. With a deadline,
2423 : // ETIMEDOUT gives SEL_CONDVAR_TIMED_OUT and any other error
2424 : // SEL_CONDVAR_FAILURE, so the loop can't spin on an error; but a *ready that is
2425 : // set when either is seen wins, since the producer may have finished just
2426 : // before. Locks *sel_mtx.
2427 3140 : static sel_condvar_outcome sel_wait_condvar(ccol__mutex *sel_mtx,
2428 : ccol__cond_var *sel_cond,
2429 : bool *ready, bool has_deadline,
2430 : const struct timespec *deadline) {
2431 3140 : ccol__mutex_lock(*sel_mtx);
2432 3140 : if (has_deadline) {
2433 6218 : sel_condvar_outcome outcome = SEL_CONDVAR_READY;
2434 6218 : while (!*ready) {
2435 3096 : int wait_ret;
2436 : #ifdef RUNNING_UNIT_TESTS
2437 3096 : if (atomic_load(&g_sel_force_condvar_wait_error)) {
2438 2 : atomic_store(&g_sel_force_condvar_wait_error, false);
2439 2 : wait_ret = EINVAL;
2440 2 : if (atomic_load(&g_sel_force_condvar_wait_error_also_marks_ready)) {
2441 1 : atomic_store(&g_sel_force_condvar_wait_error_also_marks_ready, false);
2442 1 : *ready = true;
2443 : }
2444 : } else {
2445 3094 : wait_ret = ccol__cond_var_timedwait(*sel_cond, *sel_mtx, *deadline);
2446 : }
2447 : #else
2448 : wait_ret = ccol__cond_var_timedwait(*sel_cond, *sel_mtx, *deadline);
2449 : #endif
2450 3092 : if (wait_ret == ETIMEDOUT) {
2451 6 : if (!*ready) outcome = SEL_CONDVAR_TIMED_OUT;
2452 : break;
2453 : }
2454 3087 : if (wait_ret != 0) {
2455 2 : if (!*ready) outcome = SEL_CONDVAR_FAILURE;
2456 : break;
2457 : }
2458 : }
2459 3130 : *ready = false;
2460 3130 : ccol__mutex_unlock(*sel_mtx);
2461 3130 : return outcome;
2462 : }
2463 14 : while (!*ready) ccol__cond_var_wait(*sel_cond, *sel_mtx);
2464 7 : *ready = false;
2465 7 : ccol__mutex_unlock(*sel_mtx);
2466 7 : return SEL_CONDVAR_READY;
2467 : }
2468 :
2469 : // How an epoll wait of cselect_timed() ended.
2470 : typedef enum {
2471 : SEL_EPOLL_CONTINUE,
2472 : SEL_EPOLL_BREAK,
2473 : SEL_EPOLL_FAILURE,
2474 : } sel_epoll_outcome;
2475 :
2476 : // Phase 2 with fds: Waits on the poll set until something is ready or the
2477 : // deadline passes. The remaining time is recomputed before every wait, rounded
2478 : // up and capped at INT_MAX ms; a wait that returns nothing before the deadline
2479 : // waits again, and after it the call deregisters and gives ccol_timed_out. When
2480 : // only queue eventfds fired (or fd events that refine to nothing) it gives
2481 : // SEL_EPOLL_CONTINUE for Phase 3. Otherwise the ready fd first in rotation
2482 : // order from start wins: It deregisters, sets *ready_index and *out_retval and
2483 : // gives SEL_EPOLL_BREAK. A system error gives SEL_EPOLL_FAILURE with the nodes
2484 : // still linked.
2485 2482 : static sel_epoll_outcome sel_wait_epoll(
2486 : int epfd, bool has_deadline, const struct timespec *deadline, size_t n,
2487 : cselectable *selectables, ccol_sel_waiter *nodes, sel_fd_state *fs,
2488 : size_t start, size_t *ready_index, ccol_retval *out_retval) {
2489 2485 : int n_ready;
2490 2485 : int epoll_to;
2491 2485 : for (;;) {
2492 2485 : if (has_deadline) {
2493 2482 : epoll_to = ccol_deadline_remaining_ms_ceil(deadline);
2494 : } else {
2495 : epoll_to = -1;
2496 : }
2497 : #ifdef RUNNING_UNIT_TESTS
2498 2473 : n_ready = sel_poll_wait_for_tests(epfd, fs->evs, fs->ev_cap, epoll_to);
2499 : #else
2500 : n_ready = ccol_poll_wait(epfd, fs->evs, fs->ev_cap, epoll_to);
2501 : #endif
2502 2492 : if (n_ready < 0 && errno == EINTR) continue;
2503 2492 : if (n_ready == 0 && epoll_to != 0 &&
2504 26 : (!has_deadline || ccol_deadline_remaining_ms_ceil(deadline) > 0))
2505 3 : continue;
2506 2477 : break;
2507 : }
2508 :
2509 2477 : if (n_ready == 0) {
2510 23 : deregister_all_sel_waiters(n, nodes, selectables);
2511 23 : *out_retval = ccol_timed_out;
2512 23 : return SEL_EPOLL_BREAK;
2513 : }
2514 2454 : if (n_ready < 0) return SEL_EPOLL_FAILURE;
2515 :
2516 2454 : if (!sel_mark_fd_events(fs, n, selectables, n_ready))
2517 : return SEL_EPOLL_CONTINUE;
2518 3 : size_t match = n;
2519 3 : for (size_t step = 0; step < n; step++) {
2520 3 : size_t k = start + step;
2521 3 : if (k >= n) k -= n;
2522 3 : if (fs->fd_ready[k]) {
2523 : match = k;
2524 : break;
2525 : }
2526 : }
2527 3 : deregister_all_sel_waiters(n, nodes, selectables);
2528 :
2529 3 : *out_retval = ccol_success;
2530 3 : *ready_index = match;
2531 3 : return SEL_EPOLL_BREAK;
2532 : }
2533 :
2534 : // Waits until one of n selectables is ready or timeout_us passes (UINT64_MAX:
2535 : // no limit) and sets *ready_index; the caller then does the receive or send.
2536 : // Each iteration has three phases. Phase 1 scans in rotation order and links a
2537 : // waiter node into every queue that isn't ready (sel_phase1_scan_register). The
2538 : // first time a call with fds must block, it unlinks, builds the poll set and
2539 : // the queue eventfds and scans again, so no wake is lost. Phase 2 waits: On
2540 : // sel_cond without fds (a producer sets *ready under sel_mtx before it
2541 : // signals), on the poll set with fds, where queue notifies arrive as eventfd
2542 : // writes. Phase 3 unlinks every node, forwarding a wake from a queue that is
2543 : // still ready, drains the eventfds, clears *ready and goes back to Phase 1. The
2544 : // lock order is always a queue's mutex, then sel_mtx, and a producer can't
2545 : // unlink a node it's walking, since both need the queue's mutex. The poll set
2546 : // and eventfds are made at most once per call and closed at the end.
2547 10672 : ccol_retval cselect_timed(size_t *ready_index, size_t n,
2548 : cselectable *selectables, uint64_t timeout_us) {
2549 10672 : ccol_retval v = sel_validate_args(ready_index, n, selectables);
2550 10672 : if (v != ccol_success) return v;
2551 :
2552 24087 : bool has_fd_sels = false;
2553 24087 : for (size_t i = 0; i < n; i++) {
2554 18688 : if (selectables[i].type == cselectable_type_fd) {
2555 : has_fd_sels = true;
2556 : break;
2557 : }
2558 : }
2559 :
2560 10665 : ccol_sel_waiter *nodes = sel_malloc(n * sizeof(ccol_sel_waiter));
2561 10661 : if (!nodes) return ccol_not_enough_memory;
2562 32457 : for (size_t i = 0; i < n; i++) {
2563 21798 : nodes[i].sel_mtx = NULL;
2564 21798 : nodes[i].efd = -1;
2565 : }
2566 :
2567 10659 : ccol__mutex sel_mtx;
2568 10659 : ccol__cond_var sel_cond;
2569 10659 : bool ready = false;
2570 10659 : if (ccol__mutex_init(sel_mtx) != 0) {
2571 0 : free(nodes);
2572 0 : return ccol_unexpected_failure;
2573 : }
2574 10660 : if (init_monotonic_cond_var(&sel_cond) != 0) {
2575 0 : ccol__mutex_destroy(sel_mtx);
2576 0 : free(nodes);
2577 0 : return ccol_unexpected_failure;
2578 : }
2579 :
2580 10666 : bool has_deadline;
2581 10666 : struct timespec deadline = {0, 0};
2582 10666 : has_deadline = sel_compute_deadline(timeout_us, &deadline);
2583 :
2584 10664 : int epfd = -1;
2585 10664 : sel_fd_state fd_state;
2586 10664 : sel_fd_state *fs = NULL;
2587 10664 : if (has_fd_sels) {
2588 5264 : fs = &fd_state;
2589 5264 : if (sel_fd_state_init(n, selectables, fs) != ccol_success) {
2590 1 : sel_fd_state_free(fs);
2591 1 : free(nodes);
2592 1 : ccol__mutex_destroy(sel_mtx);
2593 1 : ccol__cond_var_destroy(sel_cond);
2594 1 : return ccol_not_enough_memory;
2595 : }
2596 : }
2597 10663 : ccol_retval failure = ccol_unexpected_failure;
2598 :
2599 10663 : size_t start = sel_rotation_start(n);
2600 :
2601 10663 : ccol_retval retval = ccol_success;
2602 :
2603 18208 : for (;;) {
2604 18208 : int found = sel_phase1_scan_register(n, selectables, nodes, start, fs,
2605 : &sel_mtx, &sel_cond, &ready);
2606 18218 : if (found == -2) goto cleanup_failure;
2607 18216 : if (found >= 0) {
2608 10627 : deregister_all_sel_waiters(n, nodes, selectables);
2609 10627 : *ready_index = (size_t)found;
2610 10627 : retval = ccol_success;
2611 10627 : break;
2612 : }
2613 :
2614 7589 : if (has_fd_sels && epfd < 0) {
2615 1961 : deregister_all_sel_waiters(n, nodes, selectables);
2616 1963 : if (has_deadline && ccol_deadline_remaining_ms_ceil(&deadline) == 0) {
2617 1 : retval = ccol_timed_out;
2618 1 : break;
2619 : }
2620 1961 : ccol__mutex_lock(sel_mtx);
2621 1960 : ready = false;
2622 1960 : ccol__mutex_unlock(sel_mtx);
2623 1962 : failure = sel_setup_epoll(n, selectables, nodes, fs, &epfd);
2624 1957 : if (failure != ccol_success) goto cleanup_failure;
2625 1956 : failure = ccol_unexpected_failure;
2626 1956 : continue;
2627 : }
2628 :
2629 5628 : if (!has_fd_sels) {
2630 3140 : sel_condvar_outcome outcome = sel_wait_condvar(
2631 : &sel_mtx, &sel_cond, &ready, has_deadline, &deadline);
2632 3134 : if (outcome == SEL_CONDVAR_TIMED_OUT) {
2633 : #ifdef RUNNING_UNIT_TESTS
2634 6 : sel_timed_out_deregister_test_delay();
2635 : #endif
2636 6 : deregister_all_sel_waiters(n, nodes, selectables);
2637 6 : retval = ccol_timed_out;
2638 6 : break;
2639 : }
2640 3128 : if (outcome == SEL_CONDVAR_FAILURE) goto cleanup_failure;
2641 : } else {
2642 2488 : sel_epoll_outcome outcome =
2643 2488 : sel_wait_epoll(epfd, has_deadline, &deadline, n, selectables, nodes,
2644 : fs, start, ready_index, &retval);
2645 2489 : if (outcome == SEL_EPOLL_BREAK) break;
2646 2463 : if (outcome == SEL_EPOLL_FAILURE) goto cleanup_failure;
2647 : }
2648 :
2649 5590 : deregister_all_sel_waiters(n, nodes, selectables);
2650 5566 : ccol__mutex_lock(sel_mtx);
2651 5591 : ready = false;
2652 5591 : ccol__mutex_unlock(sel_mtx);
2653 : }
2654 :
2655 32430 : for (size_t i = 0; i < n; i++) {
2656 21777 : if (nodes[i].efd >= 0) close(nodes[i].efd);
2657 : }
2658 10653 : if (epfd >= 0) close(epfd);
2659 10657 : if (fs) sel_fd_state_free(fs);
2660 10657 : ccol__mutex_destroy(sel_mtx);
2661 10658 : ccol__cond_var_destroy(sel_cond);
2662 10654 : free(nodes);
2663 10654 : return retval;
2664 :
2665 4 : cleanup_failure:
2666 4 : deregister_all_sel_waiters(n, nodes, selectables);
2667 9 : for (size_t i = 0; i < n; i++) {
2668 5 : if (nodes[i].efd >= 0) close(nodes[i].efd);
2669 : }
2670 4 : if (epfd >= 0) close(epfd);
2671 4 : if (fs) sel_fd_state_free(fs);
2672 4 : ccol__mutex_destroy(sel_mtx);
2673 4 : ccol__cond_var_destroy(sel_cond);
2674 4 : free(nodes);
2675 4 : return failure;
2676 : }
2677 :
2678 : // cselect_timed() with no time limit.
2679 6224 : ccol_retval cselect(size_t *ready_index, size_t n, cselectable *selectables) {
2680 6224 : return cselect_timed(ready_index, n, selectables, UINT64_MAX);
2681 : }
2682 :
2683 : // ceventloop
2684 :
2685 : typedef struct event_entry event_entry;
2686 :
2687 : // A registration. The public ceventloop_reg is an opaque handle resolved
2688 : // through the loop's reg_slots table, never a pointer to this struct.
2689 : typedef struct ceventloop_reg_s ceventloop_reg_s;
2690 : struct ceventloop_reg_s {
2691 : cselectable sel;
2692 : ceventloop_handlers handlers;
2693 : void *arg;
2694 : // 1 while registered, plus one for each callback that runs.
2695 : _Atomic int refcount;
2696 : _Atomic bool removed;
2697 :
2698 : // Set between ceventloop_pause and ceventloop_resume: The registration keeps
2699 : // its slot, count and generation but leaves the fd's interest mask, which
2700 : // every re-arm recomputes from live state. Always false for a queue
2701 : // registration.
2702 : _Atomic bool paused;
2703 :
2704 : // Set when this fd registration got an event no handler of it can take
2705 : // (usually a hang-up, which level-triggered epoll repeats), so it leaves the
2706 : // interest mask like a paused one. Collection sets it, modify and resume
2707 : // clear it, always under the stripe lock.
2708 : bool muted;
2709 :
2710 : event_entry *owning_entry;
2711 :
2712 : // The stripe of the entry, the generation and the public handle, all written
2713 : // once before the registration is wired. They're read from here and never
2714 : // through owning_entry, because a stale reg can outlive its entry: The two
2715 : // have separate deferred-free lists. A dispatch hands self_handle to every
2716 : // callback, so a callback can act on its registration before the add returns.
2717 : size_t stripe_idx;
2718 :
2719 : uint64_t generation;
2720 :
2721 : ceventloop_reg self_handle;
2722 :
2723 : // Index into loop->reg_slots, which ceventloop_remove invalidates.
2724 : uint32_t self_slot_idx;
2725 :
2726 : // Pins taken by ceventloop_reg_resolve and dropped by the unpin. The reclaim
2727 : // never frees a reg while it isn't zero, which covers a public call that is
2728 : // in the middle of using the reg.
2729 : _Atomic size_t pending_resolve_count;
2730 :
2731 : // For a queue registration: The persistent bridge eventfd, -1 for an fd. A
2732 : // queue wake is recorded under wait_mtx in wait_ready, which is true exactly
2733 : // while a wake is pending on bridge_efd; queue_reg_consume_wake clears both
2734 : // right before a dispatch, so one write covers every send up to it. Nothing
2735 : // waits on wait_cond. waiter_detached (under the queue's mutex) is set once
2736 : // the loop's shutdown unlinked waiter_node, so it isn't unlinked twice.
2737 : int bridge_efd;
2738 :
2739 : ccol__mutex wait_mtx;
2740 : ccol__cond_var wait_cond;
2741 : bool wait_ready;
2742 : ccol_sel_waiter waiter_node;
2743 : bool waiter_detached;
2744 :
2745 : // Links of the stripe's list of queue registrations, which the destroy walks
2746 : // to unlink every waiter node; an fd registration is reached through the fd
2747 : // table instead.
2748 : ceventloop_reg_s *loop_list_prev;
2749 : ceventloop_reg_s *loop_list_next;
2750 :
2751 : // Link in loop->pending_reg_frees once the refcount reached 0.
2752 : ceventloop_reg_s *pending_free_next;
2753 : };
2754 :
2755 : // What the event data of every poll registration of the loop points at. Up to
2756 : // two fd registrations (read and write) share one entry, because the kernel
2757 : // keys its interest list by fd alone; a queue registration has its own bridge
2758 : // eventfd and entry.
2759 : struct event_entry {
2760 : bool is_fd;
2761 : int fd;
2762 :
2763 : // The stripe whose lock guards as.* and whose index holds the entry. Set
2764 : // before the entry is published and never written again, so it's read without
2765 : // a lock; never derive it from as.reg, which the remove sets to NULL while a
2766 : // stale batch may still point at the entry.
2767 : size_t stripe_idx;
2768 :
2769 : // Held across the entry's whole dispatch (collection and callback), so one
2770 : // registration never runs concurrently with itself, and the read and write
2771 : // registrations of an fd never run at the same time. It's taken before a
2772 : // stripe lock and released before any other stripe lock, so it adds no cycle.
2773 : ccol__mutex dispatch_lock;
2774 :
2775 : // The identity token of ceventloop_reg_generation, made once per new entry.
2776 : uint64_t generation;
2777 :
2778 : // poller_batch_gen when the entry was deferred for freeing, and the flag set
2779 : // at that moment; the re-arm skips a removed entry, whose fd may be closed or
2780 : // reused.
2781 : uint64_t defer_gen;
2782 :
2783 : _Atomic bool removed;
2784 :
2785 : // Dispatch jobs that reference the entry (only with a dispatch pool). The
2786 : // reclaim doesn't free a deferred entry while it isn't zero, since a job can
2787 : // run long after the poller has moved on.
2788 : _Atomic size_t refcount;
2789 :
2790 : union {
2791 : struct {
2792 : ceventloop_reg_s *read_reg;
2793 : ceventloop_reg_s *write_reg;
2794 : } fd;
2795 : ceventloop_reg_s *reg;
2796 : } as;
2797 :
2798 : // Whether the fd is in the poll set right now. ERR and HUP are reported
2799 : // whatever the mask, so an fd whose live directions are all paused (or muted)
2800 : // is taken out with DEL, or it would be reported over and over; it's added
2801 : // back with ADD. armed_in is the IN bit of the last ADD or MOD, so a MOD that
2802 : // flips it carries CCOL_POLL_READ_MODE_CHANGE, and poll_info is the cache of
2803 : // cpoll.h. All three are kept under the stripe lock and are unused for a
2804 : // queue entry.
2805 : bool epoll_added;
2806 : bool armed_in;
2807 : ccol_poll_fdinfo poll_info;
2808 :
2809 : // Link in loop->pending_entry_frees once the entry is retired.
2810 : event_entry *pending_free_next;
2811 : };
2812 :
2813 : // One lock stripe of a loop's registry: A mutex, the fd index of its real fds
2814 : // and the list of its queue registrations. An fd (or a queue's bridge eventfd)
2815 : // belongs to one stripe for life, so no operation holds two stripe locks.
2816 : typedef struct ceventloop_stripe {
2817 : ccol__mutex lock;
2818 : chmap fd_index;
2819 : ceventloop_reg_s *queue_regs_head;
2820 : } ceventloop_stripe;
2821 :
2822 : // One slot of the process-wide loop table. A loop handle is the slot index in
2823 : // the top 32 bits and the generation in the bottom 32. The generation rises on
2824 : // every acquire, so a stale handle never names a later loop, and the destroy
2825 : // can report a double destroy instead of freeing twice.
2826 : typedef struct {
2827 : struct ceventloop__s *ptr;
2828 : uint32_t generation;
2829 : bool in_use;
2830 : } ceventloop_slot;
2831 :
2832 : // The process-wide table of loop slots. The lock is a read-write lock, since a
2833 : // resolve only reads and runs on every pause, resume, modify and remove, while
2834 : // only create and destroy write. slots only grows, so an index is permanent;
2835 : // free_indices is a LIFO of reusable indices. lost_indices counts released
2836 : // slots that the free list couldn't take for lack of memory; an acquire with an
2837 : // empty free list recovers one by a scan. release_deferred is set when the exit
2838 : // destructor found a live loop, and the destroy of the last loop releases the
2839 : // table.
2840 : static struct {
2841 : ccol__rw_lock rwlock;
2842 : ccol__once_flag once;
2843 : cvec slots;
2844 : cvec free_indices;
2845 : size_t lost_indices;
2846 : bool release_deferred;
2847 : } ceventloop_slot_table = {0};
2848 :
2849 : static void release_event_loop_slot_table_if_deferred_locked(void);
2850 :
2851 : // Gives how many slots the table holds, 0 once the exit destructor released
2852 : // it, so a resolve finds nothing and a create fails cleanly. The caller holds
2853 : // either side of the table lock.
2854 107203 : static inline size_t event_loop_slot_count_locked(void) {
2855 107202 : return ceventloop_slot_table.slots ? cvector_size(ceventloop_slot_table.slots)
2856 107203 : : 0;
2857 : }
2858 :
2859 : #if CCOL_FORK_SAFETY_REQUIRED
2860 : static void cthreadcomm_atfork_prepare(void);
2861 : static void cthreadcomm_atfork_release(void);
2862 : static void cthreadcomm_atfork_child_release(void);
2863 : #endif
2864 :
2865 : // Creates the table's lock and vectors on first use; the resolve, the acquire
2866 : // and the fork registration need them. A failure is fatal.
2867 51 : static void ceventloop_slot_table_init_globals(void) {
2868 51 : if (ccol__rw_lock_init(ceventloop_slot_table.rwlock) != 0)
2869 0 : ccol__fatal_err("ceventloop slot table: failed to initialize rwlock");
2870 51 : ceventloop_slot_table.slots = cvector_create(sizeof(ceventloop_slot), NULL);
2871 51 : if (!ceventloop_slot_table.slots)
2872 0 : ccol__fatal_err("ceventloop slot table: failed to allocate slots vector");
2873 51 : ceventloop_slot_table.free_indices = cvector_create(sizeof(uint32_t), NULL);
2874 51 : if (!ceventloop_slot_table.free_indices)
2875 0 : ccol__fatal_err(
2876 : "ceventloop slot table: failed to allocate free-index vector");
2877 51 : }
2878 :
2879 : // Registers the one merged set of fork handlers that covers the loop table and
2880 : // the queue mutex registry; two separate sets would deadlock. It first readies
2881 : // both structures, since a process may use only queues and the handlers walk
2882 : // both. Called once through g_cthreadcomm_atfork_once.
2883 45 : static void cthreadcomm_register_atfork_once(void) {
2884 : #if CCOL_FORK_SAFETY_REQUIRED
2885 45 : ccol__call_once(queue_mutex_registry.once, queue_mutex_registry_init_globals);
2886 45 : ccol__call_once(ceventloop_slot_table.once,
2887 : ceventloop_slot_table_init_globals);
2888 45 : ccol__at_fork(cthreadcomm_atfork_prepare, cthreadcomm_atfork_release,
2889 : cthreadcomm_atfork_child_release);
2890 : #endif
2891 45 : }
2892 :
2893 : #if defined(CCOL__ATFORK_AT_LOAD)
2894 : // Registers the fork handlers at load time where CCOL__ATFORK_AT_LOAD asks for
2895 : // that (see common.h).
2896 : __attribute__((constructor)) static void cthreadcomm_atfork_at_load(void) {
2897 : ccol__call_once(g_cthreadcomm_atfork_once, cthreadcomm_register_atfork_once);
2898 : }
2899 : #endif
2900 :
2901 : // Registers this module's fork handlers now, so that they run after the
2902 : // caller's prepare handler (prepare handlers run in reverse order). chttpserver
2903 : // calls it before it registers its own, which rules out a lock order inversion
2904 : // between the two sets. Declared in internal/catfork.h.
2905 39 : void cthreadcomm__ensure_atfork_registered_before_caller(void) {
2906 39 : ccol__call_once(g_cthreadcomm_atfork_once, cthreadcomm_register_atfork_once);
2907 39 : }
2908 :
2909 : // A loop. The registry lives in the stripes, each with its own lock; the other
2910 : // fields are described per group below.
2911 : struct ceventloop__s {
2912 : // The poll set the poller waits on, and the eventfd a shutdown writes once
2913 : // and nothing ever drains, so every wait sees it.
2914 : int epfd;
2915 : int shutdown_efd;
2916 :
2917 : // A wake descriptor that pings the poller between batches. ceventloop_remove
2918 : // pings it for a registration with on_removed, so the notice comes promptly
2919 : // on an idle loop. It's only for latency: The bounded retry timeout of the
2920 : // poller is what guarantees a pending reclaim runs.
2921 : int reclaim_wake_efd;
2922 :
2923 : // The one thread that waits on epfd, and the thread count the caller asked
2924 : // for. With one thread the poller also runs every callback and the reclaim.
2925 : ccol__thread_id poller_thread;
2926 : size_t num_reactor_threads;
2927 :
2928 : // NULL with one reactor thread, else num_reactor_threads - 1 workers that run
2929 : // the callbacks. The poller only collects readiness and submits jobs; the
2930 : // pool's queue is unbounded, so a submit never blocks it.
2931 : cthrpool dispatch_pool;
2932 :
2933 : // Guards only the one-shot shutdown coordination: shutdown_started, joined
2934 : // and joined_cv. destroy_claimed, under the write side of the loop table
2935 : // lock, says a destroy owns the teardown while the handle still resolves.
2936 : ccol__mutex shutdown_lock;
2937 : ccol__cond_var joined_cv;
2938 : bool shutdown_started;
2939 : bool joined;
2940 : bool destroy_claimed;
2941 : _Atomic bool shutting_down;
2942 :
2943 : // Lock-free stacks of retired entries and registrations waiting for the
2944 : // reclaim. Freeing at once would leave a stale batch, a running job or a
2945 : // caller with a freed pointer.
2946 : _Atomic(event_entry *) pending_entry_frees;
2947 :
2948 : _Atomic(ceventloop_reg_s *) pending_reg_frees;
2949 :
2950 : // The loop's own generation-tagged table for the public ceventloop_reg, the
2951 : // same design as the loop table. It's what lets a public call detect a
2952 : // removed or stale registration without touching memory that may be freed:
2953 : // remove frees the slot and bumps its generation at once, before the reg
2954 : // itself is reclaimed. Read-write, since every pause, resume and modify
2955 : // resolves through it. reg_lost_indices counts released slots the free list
2956 : // couldn't take, as in the loop table.
2957 : ccol__rw_lock reg_slot_rwlock;
2958 : cvec reg_slots;
2959 : cvec reg_free_indices;
2960 : size_t reg_lost_indices;
2961 :
2962 : // The reclaim epoch. The poller bumps it once between batches; a deferred
2963 : // item records it in defer_gen and is free of any batch once defer_gen <
2964 : // poller_batch_gen. 64 bits, so it never wraps.
2965 : _Atomic uint64_t poller_batch_gen;
2966 :
2967 : // Makes the generation of each new entry, starting at 1 (0 means none).
2968 : _Atomic uint64_t fd_generation_counter;
2969 :
2970 : size_t max_events_per_wait;
2971 :
2972 : // The poller's event buffer of max_events_per_wait entries, allocated before
2973 : // the thread starts so the thread has no step that can fail.
2974 : ccol_poll_event *poller_events;
2975 :
2976 : // The lock stripes of the registry.
2977 : ceventloop_stripe *stripes;
2978 : size_t num_stripes;
2979 :
2980 : // Round-robin cursor that gives each queue registration a stripe. A queue's
2981 : // entry is never looked up by another call, so any deterministic choice
2982 : // works.
2983 : _Atomic size_t next_queue_stripe;
2984 :
2985 : // Live registrations, for ceventloop_reg_count.
2986 : _Atomic size_t reg_count;
2987 :
2988 : ccol_memmgmt_procs *m_procs;
2989 :
2990 : // Pins of resolved loop pointers. Pin and unpin are bare atomics, so the hot
2991 : // calls take no global lock; the destroy polls until it reaches 0.
2992 : _Atomic size_t pending_resolve_count;
2993 :
2994 : // The loop's public handle, written once before the create returns. Callbacks
2995 : // get it as their loop argument, so a call back into the loop resolves like
2996 : // any other.
2997 : ceventloop self_handle;
2998 :
2999 : #if CCOL_FORK_SAFETY_REQUIRED
3000 : // Set by the child fork handler on every inherited loop. Then the shutdown
3001 : // neither joins the poller (this process never created it) nor writes
3002 : // shutdown_efd (shared with the parent's poller).
3003 : _Atomic bool foreign_since_fork;
3004 : #endif
3005 :
3006 : #ifdef RUNNING_UNIT_TESTS
3007 : // Test-only counts of finished poller waits (to spot a busy spin) and of
3008 : // entries the reclaim freed.
3009 : _Atomic uint64_t poller_iterations_for_tests;
3010 : _Atomic uint64_t entries_reclaimed_for_tests;
3011 : #endif
3012 : };
3013 :
3014 : #if CCOL_FORK_SAFETY_REQUIRED
3015 : // The prepare handler of fork(). fork() copies only the calling thread, so a
3016 : // lock that another thread holds would stay locked for ever in the child; this
3017 : // takes every lock of the module first, so fork() happens when nobody holds
3018 : // one. The order matches every nesting in this file: The queue registry mutex
3019 : // and the loop table lock (write side), then for each live loop its
3020 : // shutdown_lock, reg_slot_rwlock (write side) and stripe locks, then every
3021 : // queue mutex once, then every queue registration's wait_mtx. Entry dispatch
3022 : // locks are left out, since taking one under a stripe lock reverses the order
3023 : // the dispatch uses; a child never dispatches an inherited loop anyway. Only
3024 : // slots with in_use are walked, which covers a loop whose destroy is still
3025 : // draining.
3026 385 : static void cthreadcomm_atfork_prepare(void) {
3027 : #ifdef RUNNING_UNIT_TESTS
3028 385 : ccol__atfork_order_record(ccol__atfork_module_cthreadcomm);
3029 : #endif
3030 385 : ccol__mutex_lock(queue_mutex_registry.mutex);
3031 385 : ccol__rw_lock_wrlock(ceventloop_slot_table.rwlock);
3032 :
3033 385 : size_t n_loops = event_loop_slot_count_locked();
3034 :
3035 716 : for (size_t i = 0; i < n_loops; i++) {
3036 331 : ceventloop_slot *slot =
3037 331 : (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, i);
3038 331 : if (!slot->in_use) continue;
3039 80 : struct ceventloop__s *loop = slot->ptr;
3040 80 : ccol__mutex_lock(loop->shutdown_lock);
3041 80 : ccol__rw_lock_wrlock(loop->reg_slot_rwlock);
3042 236 : for (size_t s = 0; s < loop->num_stripes; s++) {
3043 156 : ccol__mutex_lock(loop->stripes[s].lock);
3044 : }
3045 : }
3046 :
3047 770 : size_t n_addrs =
3048 385 : queue_mutex_registry.addrs ? cvector_size(queue_mutex_registry.addrs) : 0;
3049 387 : for (size_t k = 0; k < n_addrs; k++) {
3050 2 : ccol__mutex *m = ((queue_mutex_registry_entry *)cvector_at(
3051 : queue_mutex_registry.addrs, k))
3052 : ->mutex;
3053 2 : ccol__mutex_lock(*m);
3054 : }
3055 :
3056 716 : for (size_t i = 0; i < n_loops; i++) {
3057 331 : ceventloop_slot *slot =
3058 331 : (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, i);
3059 331 : if (!slot->in_use) continue;
3060 80 : struct ceventloop__s *loop = slot->ptr;
3061 236 : for (size_t s = 0; s < loop->num_stripes; s++) {
3062 157 : for (ceventloop_reg_s *reg = loop->stripes[s].queue_regs_head; reg;
3063 1 : reg = reg->loop_list_next) {
3064 1 : ccol__mutex_lock(reg->wait_mtx);
3065 : }
3066 : }
3067 : }
3068 385 : }
3069 :
3070 : // Releases what the prepare handler took, in reverse phases, in the parent
3071 : // (is_child false) or the child. Nothing could change the walked structures in
3072 : // between, since every lock a change needs is held. The two rwlocks are
3073 : // re-initialised in the child instead of unlocked, because a glibc rwlock
3074 : // unlocks a writer only for the thread ID that locked it and the child's
3075 : // thread has a new ID. In the child every live loop also becomes
3076 : // foreign_since_fork, its pending_resolve_count goes back to 0 (a vanished
3077 : // thread may have left a pin), and its epfd is replaced by a new empty set, so
3078 : // the child's epoll_ctl calls don't edit the parent's live set. A failed
3079 : // replacement keeps the shared set.
3080 385 : static void cthreadcomm_atfork_release_impl(bool is_child) {
3081 385 : size_t n_loops = event_loop_slot_count_locked();
3082 :
3083 716 : for (size_t i = 0; i < n_loops; i++) {
3084 331 : ceventloop_slot *slot =
3085 331 : (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, i);
3086 331 : if (!slot->in_use) continue;
3087 80 : struct ceventloop__s *loop = slot->ptr;
3088 :
3089 80 : if (is_child) {
3090 0 : atomic_store(&loop->foreign_since_fork, true);
3091 0 : atomic_store(&loop->pending_resolve_count, (size_t)0);
3092 :
3093 0 : int old_epfd = loop->epfd;
3094 0 : int new_epfd = ccol_poll_create();
3095 0 : if (new_epfd >= 0) {
3096 0 : loop->epfd = new_epfd;
3097 0 : close(old_epfd);
3098 : }
3099 : }
3100 :
3101 236 : for (size_t s = 0; s < loop->num_stripes; s++) {
3102 157 : for (ceventloop_reg_s *reg = loop->stripes[s].queue_regs_head; reg;
3103 1 : reg = reg->loop_list_next) {
3104 1 : ccol__mutex_unlock(reg->wait_mtx);
3105 : }
3106 : }
3107 : }
3108 :
3109 770 : size_t n_addrs =
3110 385 : queue_mutex_registry.addrs ? cvector_size(queue_mutex_registry.addrs) : 0;
3111 387 : for (size_t k = 0; k < n_addrs; k++) {
3112 2 : ccol__mutex *m = ((queue_mutex_registry_entry *)cvector_at(
3113 : queue_mutex_registry.addrs, k))
3114 : ->mutex;
3115 2 : ccol__mutex_unlock(*m);
3116 : }
3117 :
3118 716 : for (size_t i = 0; i < n_loops; i++) {
3119 331 : ceventloop_slot *slot =
3120 331 : (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, i);
3121 331 : if (!slot->in_use) continue;
3122 80 : struct ceventloop__s *loop = slot->ptr;
3123 236 : for (size_t s = 0; s < loop->num_stripes; s++) {
3124 156 : ccol__mutex_unlock(loop->stripes[s].lock);
3125 : }
3126 80 : if (is_child) {
3127 0 : if (ccol__rw_lock_reinit_in_child(loop->reg_slot_rwlock) != 0)
3128 0 : ccol__fatal_err(
3129 : "ceventloop atfork release: failed to reinit reg_slot_rwlock");
3130 : } else {
3131 80 : ccol__rw_lock_unlock(loop->reg_slot_rwlock);
3132 : }
3133 80 : ccol__mutex_unlock(loop->shutdown_lock);
3134 : }
3135 :
3136 385 : if (is_child) {
3137 0 : if (ccol__rw_lock_reinit_in_child(ceventloop_slot_table.rwlock) != 0)
3138 0 : ccol__fatal_err(
3139 : "ceventloop atfork release: failed to reinit "
3140 : "ceventloop_slot_table "
3141 : "rwlock");
3142 : } else {
3143 385 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
3144 : }
3145 385 : ccol__mutex_unlock(queue_mutex_registry.mutex);
3146 385 : }
3147 :
3148 : // The parent fork handler: Releases every lock the prepare handler took.
3149 385 : static void cthreadcomm_atfork_release(void) {
3150 385 : cthreadcomm_atfork_release_impl(false);
3151 385 : }
3152 :
3153 : // The child fork handler: Releases the locks and detaches every inherited loop
3154 : // from the parent (see cthreadcomm_atfork_release_impl). It runs before fork()
3155 : // returns, so before any code of the child can reach these loops.
3156 0 : static void cthreadcomm_atfork_child_release(void) {
3157 0 : cthreadcomm_atfork_release_impl(true);
3158 0 : }
3159 : #endif
3160 :
3161 : // Resolves a loop handle and pins the loop against a concurrent destroy. Every
3162 : // public call that takes a ceventloop starts here, so a stale handle is
3163 : // detected before anything is touched. Gives NULL for 0, garbage, a free slot
3164 : // or a wrong generation. On success the caller calls ceventloop_resolve_unpin()
3165 : // once when it's done. Takes the read side of the loop table lock; the pin is a
3166 : // bare atomic increment, safe because the destroy releases the slot only under
3167 : // the write side.
3168 66568 : static struct ceventloop__s *ceventloop_resolve(ceventloop h) {
3169 66568 : ccol__call_once(ceventloop_slot_table.once,
3170 : ceventloop_slot_table_init_globals);
3171 66567 : ccol__call_once(g_cthreadcomm_atfork_once, cthreadcomm_register_atfork_once);
3172 66570 : if (h == 0) return NULL;
3173 66567 : uint32_t idx = (uint32_t)(h >> 32);
3174 66567 : uint32_t gen = (uint32_t)(h & 0xFFFFFFFFu);
3175 66567 : ccol__rw_lock_rdlock(ceventloop_slot_table.rwlock);
3176 66564 : struct ceventloop__s *raw = NULL;
3177 133123 : if (idx < event_loop_slot_count_locked()) {
3178 66560 : ceventloop_slot *slot =
3179 66560 : (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, idx);
3180 66557 : if (slot->in_use && slot->generation == gen) raw = slot->ptr;
3181 : }
3182 66559 : if (raw) atomic_fetch_add(&raw->pending_resolve_count, 1);
3183 66557 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
3184 66557 : return raw;
3185 : }
3186 :
3187 : // Drops the pin of ceventloop_resolve(). A bare atomic decrement: The destroy
3188 : // polls the count, so there's no waiter to signal.
3189 66568 : static void ceventloop_resolve_unpin(struct ceventloop__s *raw) {
3190 66568 : atomic_fetch_sub(&raw->pending_resolve_count, 1);
3191 2 : }
3192 :
3193 : #ifdef RUNNING_UNIT_TESTS
3194 : // Test-only: Makes the next push onto the loop free list fail as without
3195 : // memory, to reach the lost-index recovery.
3196 : static _Atomic bool g_fail_next_loop_free_index_push = false;
3197 :
3198 : // Test-only: Arms the failing free list push.
3199 4 : void ceventloop__force_next_free_index_push_failure_for_tests(void) {
3200 4 : atomic_store(&g_fail_next_loop_free_index_push, true);
3201 4 : }
3202 : #endif
3203 :
3204 : // Puts idx back on the loop free list for reuse by a later create. A push that
3205 : // can't allocate counts the index in lost_indices instead of stranding it. The
3206 : // caller holds the write lock.
3207 39357 : static void ceventloop_free_index_release_locked(uint32_t idx) {
3208 : #ifdef RUNNING_UNIT_TESTS
3209 39357 : if (atomic_exchange(&g_fail_next_loop_free_index_push, false)) {
3210 4 : ceventloop_slot_table.lost_indices++;
3211 4 : return;
3212 : }
3213 : #endif
3214 39353 : if (cvector_push_back(ceventloop_slot_table.free_indices, &idx) !=
3215 : ccol_success)
3216 0 : ceventloop_slot_table.lost_indices++;
3217 : }
3218 :
3219 : // Finds a slot that a failed free list push stranded, so an acquire reuses it
3220 : // instead of growing the table. With the free list empty, a slot with no ptr
3221 : // and not in use can only be such a slot (a destroy keeps ptr until its last
3222 : // step). It zeroes the count when it finds none, so the scan doesn't repeat.
3223 : // Gives the index in *out_idx. Out of line, since only a non-zero count reaches
3224 : // it. The caller holds the write lock.
3225 4 : static __attribute__((noinline)) bool ceventloop_reclaim_lost_index_locked(
3226 : uint32_t *out_idx) {
3227 4 : size_t slot_count = cvector_size(ceventloop_slot_table.slots);
3228 5 : for (size_t i = 0; i < slot_count; i++) {
3229 5 : ceventloop_slot *slot =
3230 5 : (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, i);
3231 5 : if (slot->ptr == NULL && !slot->in_use) {
3232 4 : *out_idx = (uint32_t)i;
3233 4 : ceventloop_slot_table.lost_indices--;
3234 4 : return true;
3235 : }
3236 : }
3237 0 : ceventloop_slot_table.lost_indices = 0;
3238 0 : return false;
3239 : }
3240 :
3241 : // Gives loop a slot of the process-wide table and gives its handle, or 0 when
3242 : // no slot can be allocated or the exit destructor released the table.
3243 : // ceventloop_create_mp calls it as its last step. It reuses a free index, then
3244 : // a lost one, and grows the table only after that; the generation rises on
3245 : // every acquire. Takes the write lock.
3246 39379 : static ceventloop ceventloop_handle_slot_acquire(struct ceventloop__s *loop) {
3247 39379 : ccol__call_once(ceventloop_slot_table.once,
3248 : ceventloop_slot_table_init_globals);
3249 39379 : ccol__call_once(g_cthreadcomm_atfork_once, cthreadcomm_register_atfork_once);
3250 39379 : ccol__rw_lock_wrlock(ceventloop_slot_table.rwlock);
3251 39379 : if (!ceventloop_slot_table.slots) {
3252 0 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
3253 0 : return 0;
3254 : }
3255 39379 : uint32_t idx;
3256 39379 : ceventloop_slot *slot;
3257 39379 : if (cvector_size(ceventloop_slot_table.free_indices) > 0) {
3258 39325 : cvector_pop_back(ceventloop_slot_table.free_indices, &idx);
3259 39325 : slot = (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, idx);
3260 58 : } else if (ceventloop_slot_table.lost_indices > 0 &&
3261 4 : ceventloop_reclaim_lost_index_locked(&idx)) {
3262 4 : slot = (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, idx);
3263 : } else {
3264 50 : ceventloop_slot fresh = {0};
3265 50 : if (cvector_push_back(ceventloop_slot_table.slots, &fresh) !=
3266 : ccol_success) {
3267 0 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
3268 0 : return 0;
3269 : }
3270 50 : idx = (uint32_t)cvector_size(ceventloop_slot_table.slots) - 1;
3271 50 : slot = (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, idx);
3272 : }
3273 39379 : slot->generation++;
3274 39379 : if (slot->generation == 0) slot->generation++;
3275 39379 : slot->ptr = loop;
3276 39379 : slot->in_use = true;
3277 39379 : ceventloop h = ((ceventloop)idx << 32) | (ceventloop)slot->generation;
3278 39379 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
3279 39379 : return h;
3280 : }
3281 :
3282 : // Maps an fd to its lock stripe, so every call for one fd takes the same
3283 : // stripe lock. Knuth's multiplicative hash reduced from its high bits, which
3284 : // depend on every bit of the fd (the low bits would cluster like
3285 : // fd % num_stripes). Only fds use it; queue registrations go round-robin.
3286 46743 : static size_t stripe_index(size_t num_stripes, int fd) {
3287 46743 : uint32_t h = (uint32_t)fd * 2654435761u;
3288 : #if SIZE_MAX > UINT32_MAX
3289 0 : if (num_stripes > UINT32_MAX) return (size_t)h;
3290 : #endif
3291 46743 : return (size_t)(((uint64_t)h * (uint64_t)num_stripes) >> 32);
3292 : }
3293 :
3294 : // stripe_index() for the stripe count of loop.
3295 45793 : static size_t stripe_index_for_fd(struct ceventloop__s *loop, int fd) {
3296 92024 : return stripe_index(loop->num_stripes, fd);
3297 : }
3298 :
3299 : #ifdef RUNNING_UNIT_TESTS
3300 : // Test-only: Exposes stripe_index().
3301 950 : size_t ceventloop__test_stripe_index(size_t num_stripes, int fd) {
3302 950 : return stripe_index(num_stripes, fd);
3303 : }
3304 : #endif
3305 :
3306 : // Finds the entry of fd in one stripe's fd index, or NULL, for the add,
3307 : // modify and remove paths. The pointer is read with memcpy as a second line of
3308 : // defence, like the other chmap users. The caller holds the stripe lock.
3309 45791 : static event_entry *fd_registry_find(ceventloop_stripe *stripe, int fd) {
3310 45791 : cmap_pair key_pair = {.ptr = &fd, .size = sizeof(fd)};
3311 45791 : cmap_pair val_pair;
3312 45791 : if (chashmap_get_elem_ref(stripe->fd_index, &key_pair, &val_pair) !=
3313 : ccol_success) {
3314 : return NULL;
3315 : }
3316 3562 : event_entry *entry;
3317 3562 : memcpy(&entry, val_pair.ptr, sizeof(entry));
3318 3562 : return entry;
3319 : }
3320 :
3321 : // Inserts fd -> entry into the stripe's index when ceventloop_add_fd() makes a
3322 : // new entry, after a find said fd is absent. Gives false when the map can't
3323 : // grow. The caller holds the stripe lock.
3324 42225 : static bool fd_registry_insert(ceventloop_stripe *stripe, int fd,
3325 : event_entry *entry) {
3326 42225 : cmap_pair key_pair = {.ptr = &fd, .size = sizeof(fd)};
3327 42225 : cmap_pair val_pair = {.ptr = &entry, .size = sizeof(entry)};
3328 42225 : return chashmap_insert_elem(stripe->fd_index, &key_pair, &val_pair) ==
3329 : ccol_success;
3330 : }
3331 :
3332 : // Removes fd from the stripe's index when its last registration goes (or a new
3333 : // entry's publish fails). The caller holds the stripe lock.
3334 3580 : static void fd_registry_remove(ceventloop_stripe *stripe, int fd) {
3335 3580 : cmap_pair key_pair = {.ptr = &fd, .size = sizeof(fd)};
3336 3580 : chashmap_remove_elem(stripe->fd_index, &key_pair);
3337 : }
3338 :
3339 : // Links and unlinks a queue registration in its stripe's list, which the
3340 : // destroy and the fork handlers walk. The caller holds the stripe lock.
3341 436 : static void loop_queue_list_add(ceventloop_stripe *stripe,
3342 : ceventloop_reg_s *reg) {
3343 436 : reg->loop_list_prev = NULL;
3344 436 : reg->loop_list_next = stripe->queue_regs_head;
3345 68 : if (stripe->queue_regs_head) stripe->queue_regs_head->loop_list_prev = reg;
3346 436 : stripe->queue_regs_head = reg;
3347 436 : }
3348 :
3349 388 : static void loop_queue_list_remove(ceventloop_stripe *stripe,
3350 : ceventloop_reg_s *reg) {
3351 388 : if (reg->loop_list_prev)
3352 47 : reg->loop_list_prev->loop_list_next = reg->loop_list_next;
3353 : else
3354 341 : stripe->queue_regs_head = reg->loop_list_next;
3355 388 : if (reg->loop_list_next)
3356 9 : reg->loop_list_next->loop_list_prev = reg->loop_list_prev;
3357 : }
3358 :
3359 : // Gives the mutex of the queue sel names and the head and rotor of the waiter
3360 : // list for its direction. The registration, deregistration and dispatch paths
3361 : // use it so they share one idea of which list a selectable lives on. sel is a
3362 : // ccircq or cdynmq; a channel selectable is already a ccircq.
3363 40599 : static void queue_sel_locate(cselectable *sel, ccol__mutex **out_mtx,
3364 : ccol_sel_waiter ***out_head,
3365 : ccol_sel_waiter ***out_rotor) {
3366 7543 : if (sel->type == cselectable_type_ccircq) {
3367 27459 : ccircq *cq = sel->cq;
3368 27459 : *out_mtx = &cq->mutex;
3369 44488 : *out_head = (sel->dir == cselect_read) ? &cq->sel_read_waiters_head
3370 17029 : : &cq->sel_write_waiters_head;
3371 21242 : *out_rotor =
3372 6217 : (sel->dir == cselect_read) ? &cq->sel_read_rotor : &cq->sel_write_rotor;
3373 : } else {
3374 13140 : cdynmq *dq = sel->dq;
3375 13140 : *out_mtx = &dq->mutex;
3376 20636 : *out_head = (sel->dir == cselect_read) ? &dq->sel_read_waiters_head
3377 7496 : : &dq->sel_write_waiters_head;
3378 11337 : *out_rotor =
3379 1803 : (sel->dir == cselect_read) ? &dq->sel_read_rotor : &dq->sel_write_rotor;
3380 : }
3381 : }
3382 :
3383 : // Give the queue a queue selectable names and that queue's dispatch reference
3384 : // counter, for the dispatch mark and the destroy wait.
3385 16074 : static void *queue_sel_queue(cselectable *sel) {
3386 16074 : return (sel->type == cselectable_type_ccircq) ? (void *)sel->cq
3387 16074 : : (void *)sel->dq;
3388 : }
3389 :
3390 32148 : static _Atomic size_t *queue_sel_dispatch_refs(cselectable *sel) {
3391 53008 : return (sel->type == cselectable_type_ccircq) ? &sel->cq->dispatch_refs
3392 32148 : : &sel->dq->dispatch_refs;
3393 : }
3394 :
3395 : // Gives the detached registration count of the queue sel names, which the
3396 : // loop shutdown raises and the remove lowers. The caller holds the queue's
3397 : // mutex.
3398 92 : static size_t *queue_sel_detached_count(cselectable *sel) {
3399 183 : return (sel->type == cselectable_type_ccircq) ? &sel->cq->detached_loop_regs
3400 92 : : &sel->dq->detached_loop_regs;
3401 : }
3402 :
3403 : // Claims a dispatch reference on the queue sel names, so its destroy waits for
3404 : // this callback. The caller holds the stripe lock under which it just found the
3405 : // registration not removed, and the remove sets that flag under the same lock,
3406 : // so once the remove returns no reference can be claimed. Only a dispatch about
3407 : // to run its callback claims one (on a pool worker, when the job starts): A
3408 : // queued job holding one could make a destroy on a worker wait for a job stuck
3409 : // behind that same worker.
3410 16074 : static void queue_dispatch_ref_acquire(cselectable *sel) {
3411 32148 : atomic_fetch_add(queue_sel_dispatch_refs(sel), (size_t)1);
3412 : }
3413 :
3414 : // Gives the message count of the queue sel names, for the progress snapshot of
3415 : // a dispatch. The caller holds the queue's mutex.
3416 29728 : static size_t queue_sel_msg_count(cselectable *sel) {
3417 48588 : return (sel->type == cselectable_type_ccircq) ? sel->cq->msg_count
3418 29728 : : sel->dq->msg_count;
3419 : }
3420 :
3421 : // Consumes a queue registration's outstanding wake right before its dispatch
3422 : // runs: It clears wait_ready, takes the hop count into *hops and drains the
3423 : // bridge eventfd in one critical section under wait_mtx. notify_waiter() works
3424 : // under the same mutex, so a notify lands either before (its message is there
3425 : // for the callback) or after (it writes again). When queue_count isn't NULL it
3426 : // also snapshots the message count under the queue's mutex, taking wait_mtx
3427 : // before it lets the queue go, so the cascade step can tell whether the
3428 : // callback moved a message. The caller holds the stripe lock.
3429 16074 : static void queue_reg_consume_wake(ceventloop_reg_s *reg, size_t *queue_count,
3430 : uint32_t *hops) {
3431 16074 : if (queue_count) {
3432 16074 : ccol__mutex *q_mtx;
3433 16074 : ccol_sel_waiter **q_head;
3434 16074 : ccol_sel_waiter **q_rotor;
3435 16074 : queue_sel_locate(®->sel, &q_mtx, &q_head, &q_rotor);
3436 16074 : ccol__mutex_lock(*q_mtx);
3437 16074 : *queue_count = queue_sel_msg_count(®->sel);
3438 16074 : ccol__mutex_lock(reg->wait_mtx);
3439 16074 : ccol__mutex_unlock(*q_mtx);
3440 : } else {
3441 0 : ccol__mutex_lock(reg->wait_mtx);
3442 : }
3443 16074 : reg->wait_ready = false;
3444 16074 : if (hops) *hops = reg->waiter_node.fwd_hops;
3445 16074 : reg->waiter_node.fwd_hops = 0;
3446 16074 : eventfd_drain(reg->bridge_efd);
3447 16074 : ccol__mutex_unlock(reg->wait_mtx);
3448 16074 : }
3449 :
3450 : // Drops a dispatch reference once a queue callback and its cascade step are
3451 : // done. Nothing may touch the queue after it, since a waiting destroy can go on
3452 : // at once.
3453 16074 : static void queue_dispatch_ref_release(cselectable *sel) {
3454 32148 : atomic_fetch_sub(queue_sel_dispatch_refs(sel), (size_t)1);
3455 16074 : }
3456 :
3457 : // One slot of a loop's registration table, behind a public ceventloop_reg. The
3458 : // generation rises on every acquire and skips 0.
3459 : typedef struct {
3460 : ceventloop_reg_s *ptr;
3461 : uint32_t generation;
3462 : bool in_use;
3463 : } ceventloop_reg_slot;
3464 :
3465 : #ifdef RUNNING_UNIT_TESTS
3466 : // Test-only: Makes the next registration slot acquire fail, which the shared
3467 : // allocator can't do in isolation.
3468 : static _Atomic bool g_force_next_reg_slot_acquire_failure = false;
3469 :
3470 : // Test-only: The loop's registration count when the forced failure fired. A 0
3471 : // proves the slot is taken before the registration is wired.
3472 : static _Atomic size_t g_forced_slot_acquire_failure_reg_count_snapshot = 0;
3473 :
3474 : // Test-only: Arms the forced slot failure.
3475 2 : void ceventloop__test_force_next_reg_slot_acquire_failure(void) {
3476 2 : atomic_store(&g_force_next_reg_slot_acquire_failure, true);
3477 2 : }
3478 :
3479 : // Test-only: Reads the snapshot.
3480 1 : size_t ceventloop__test_last_forced_slot_acquire_failure_reg_count(void) {
3481 1 : return atomic_load(&g_forced_slot_acquire_failure_reg_count_snapshot);
3482 : }
3483 :
3484 : // Test-only hook that ceventloop_add calls once the registration is live. No
3485 : // initializer, since Clang 11 refuses one on an atomic function pointer.
3486 : static void (*_Atomic g_evl_add_before_return_hook)(void);
3487 :
3488 : // Test-only: Installs the hook, NULL to remove it.
3489 2 : void ceventloop__test_set_add_before_return_hook(void (*hook)(void)) {
3490 2 : atomic_store(&g_evl_add_before_return_hook, hook);
3491 2 : }
3492 :
3493 : // Test-only: Resolves the loop once, write-locks its reg_slot_rwlock and gives
3494 : // the pinned loop, so a test can hold the lock across a fork(). The unlock
3495 : // takes that pointer, since resolving again could deadlock against a fork that
3496 : // holds the table lock while it waits for this one.
3497 1 : void *ceventloop__test_wrlock_reg_slot_for_tests(ceventloop loop) {
3498 1 : struct ceventloop__s *raw = ceventloop_resolve(loop);
3499 1 : if (!raw) return NULL;
3500 1 : ccol__rw_lock_wrlock(raw->reg_slot_rwlock);
3501 1 : return raw;
3502 : }
3503 :
3504 : // Test-only: Unlocks what the call above locked and drops its pin.
3505 1 : void ceventloop__test_wrunlock_reg_slot_for_tests(void *resolved_loop) {
3506 1 : struct ceventloop__s *raw = (struct ceventloop__s *)resolved_loop;
3507 1 : if (!raw) return;
3508 1 : ccol__rw_lock_unlock(raw->reg_slot_rwlock);
3509 1 : ceventloop_resolve_unpin(raw);
3510 : }
3511 : #endif
3512 :
3513 : #ifdef RUNNING_UNIT_TESTS
3514 : // Test-only: Makes the next registration free list push fail.
3515 : static _Atomic bool g_fail_next_reg_free_index_push = false;
3516 :
3517 : // Test-only: Arms the failing push.
3518 8 : void ceventloop__force_next_reg_free_index_push_failure_for_tests(void) {
3519 8 : atomic_store(&g_fail_next_reg_free_index_push, true);
3520 8 : }
3521 :
3522 : // Test-only: How many registration slots the loop has ever allocated.
3523 2 : size_t ceventloop__reg_slot_count_for_tests(ceventloop loop) {
3524 2 : struct ceventloop__s *raw = ceventloop_resolve(loop);
3525 2 : if (!raw) return 0;
3526 2 : ccol__rw_lock_rdlock(raw->reg_slot_rwlock);
3527 2 : size_t n = cvector_size(raw->reg_slots);
3528 2 : ccol__rw_lock_unlock(raw->reg_slot_rwlock);
3529 2 : ceventloop_resolve_unpin(raw);
3530 2 : return n;
3531 : }
3532 : #endif
3533 :
3534 : // Finds a registration slot that a failed free list push stranded, so the
3535 : // acquire reuses it instead of growing the table; it works like the loop table
3536 : // version. Gives the index in *out_idx. The caller holds the write side of
3537 : // reg_slot_rwlock.
3538 8 : static __attribute__((noinline)) bool ceventloop_reg_reclaim_lost_index_locked(
3539 : struct ceventloop__s *loop, uint32_t *out_idx) {
3540 8 : size_t slot_count = cvector_size(loop->reg_slots);
3541 8 : for (size_t i = 0; i < slot_count; i++) {
3542 8 : ceventloop_reg_slot *slot =
3543 8 : (ceventloop_reg_slot *)cvector_at(loop->reg_slots, i);
3544 8 : if (slot->ptr == NULL && !slot->in_use) {
3545 8 : *out_idx = (uint32_t)i;
3546 8 : loop->reg_lost_indices--;
3547 8 : return true;
3548 : }
3549 : }
3550 0 : loop->reg_lost_indices = 0;
3551 0 : return false;
3552 : }
3553 :
3554 : // Gives reg a slot of the loop's registration table and gives the public
3555 : // handle, or 0 when no slot can be allocated. ceventloop_add calls it before it
3556 : // wires reg into any registry, so a failure has nothing to unwind. It reuses a
3557 : // free index, then a lost one, then grows the table, and sets
3558 : // reg->self_slot_idx and reg->self_handle. Takes the write side of
3559 : // reg_slot_rwlock, since a growth can move the table under a reader.
3560 46227 : static ceventloop_reg ceventloop_reg_slot_acquire(struct ceventloop__s *loop,
3561 : ceventloop_reg_s *reg) {
3562 : #ifdef RUNNING_UNIT_TESTS
3563 46227 : if (atomic_load(&g_force_next_reg_slot_acquire_failure)) {
3564 2 : atomic_store(&g_force_next_reg_slot_acquire_failure, false);
3565 2 : atomic_store(&g_forced_slot_acquire_failure_reg_count_snapshot,
3566 : atomic_load(&loop->reg_count));
3567 2 : return 0;
3568 : }
3569 : #endif
3570 46225 : ccol__rw_lock_wrlock(loop->reg_slot_rwlock);
3571 46231 : uint32_t idx;
3572 46231 : ceventloop_reg_slot *slot;
3573 46231 : if (cvector_size(loop->reg_free_indices) > 0) {
3574 6105 : cvector_pop_back(loop->reg_free_indices, &idx);
3575 6105 : slot = (ceventloop_reg_slot *)cvector_at(loop->reg_slots, idx);
3576 40134 : } else if (loop->reg_lost_indices > 0 &&
3577 8 : ceventloop_reg_reclaim_lost_index_locked(loop, &idx)) {
3578 8 : slot = (ceventloop_reg_slot *)cvector_at(loop->reg_slots, idx);
3579 : } else {
3580 40118 : ceventloop_reg_slot fresh = {0};
3581 40118 : if (cvector_push_back(loop->reg_slots, &fresh) != ccol_success) {
3582 0 : ccol__rw_lock_unlock(loop->reg_slot_rwlock);
3583 0 : return 0;
3584 : }
3585 40118 : idx = (uint32_t)cvector_size(loop->reg_slots) - 1;
3586 40118 : slot = (ceventloop_reg_slot *)cvector_at(loop->reg_slots, idx);
3587 : }
3588 46231 : slot->generation++;
3589 46231 : if (slot->generation == 0) slot->generation++;
3590 46231 : slot->ptr = reg;
3591 46231 : slot->in_use = true;
3592 46231 : reg->self_slot_idx = idx;
3593 46231 : ceventloop_reg h =
3594 46231 : ((ceventloop_reg)idx << 32) | (ceventloop_reg)slot->generation;
3595 46231 : reg->self_handle = h;
3596 46231 : ccol__rw_lock_unlock(loop->reg_slot_rwlock);
3597 46231 : return h;
3598 : }
3599 :
3600 : // Resolves a registration handle of loop and pins the registration against a
3601 : // concurrent free, the per-loop twin of ceventloop_resolve(). Every public call
3602 : // that takes a ceventloop_reg uses it, so a removed or stale handle gives NULL
3603 : // without a dereference. On success the caller calls
3604 : // ceventloop_reg_resolve_unpin() once. Takes the read side of reg_slot_rwlock,
3605 : // so resolves run in parallel; the pin happens under it, and the remove frees
3606 : // the slot only under the write side.
3607 17209 : static ceventloop_reg_s *ceventloop_reg_resolve(struct ceventloop__s *loop,
3608 : ceventloop_reg h) {
3609 17209 : if (h == 0) return NULL;
3610 17207 : uint32_t idx = (uint32_t)(h >> 32);
3611 17207 : uint32_t gen = (uint32_t)(h & 0xFFFFFFFFu);
3612 17207 : ccol__rw_lock_rdlock(loop->reg_slot_rwlock);
3613 17206 : ceventloop_reg_s *raw = NULL;
3614 17206 : if (idx < cvector_size(loop->reg_slots)) {
3615 17205 : ceventloop_reg_slot *slot =
3616 17205 : (ceventloop_reg_slot *)cvector_at(loop->reg_slots, idx);
3617 17202 : if (slot->in_use && slot->generation == gen) raw = slot->ptr;
3618 : }
3619 15891 : if (raw) atomic_fetch_add(&raw->pending_resolve_count, 1);
3620 17201 : ccol__rw_lock_unlock(loop->reg_slot_rwlock);
3621 17201 : return raw;
3622 : }
3623 :
3624 : #ifdef RUNNING_UNIT_TESTS
3625 : // Test-only: The armed sleep of the next unpin, between its read of removed
3626 : // and its decrement, which lets a test land a remove inside that window.
3627 : static _Atomic uint32_t g_delay_next_reg_resolve_unpin_ms = 0;
3628 :
3629 : // Test-only: Arms the unpin delay.
3630 2 : void ceventloop__test_delay_next_reg_resolve_unpin_ms(uint32_t ms) {
3631 2 : atomic_store(&g_delay_next_reg_resolve_unpin_ms, ms);
3632 2 : }
3633 :
3634 : // Test-only: true once an unpin has taken the armed delay (it's taken after the
3635 : // read of removed, with the pin still held).
3636 2 : bool ceventloop__test_reg_resolve_unpin_delay_taken_for_tests(void) {
3637 2 : return atomic_load(&g_delay_next_reg_resolve_unpin_ms) == 0u;
3638 : }
3639 : #endif
3640 :
3641 : // Drops the pin of ceventloop_reg_resolve(). When the registration is removed,
3642 : // has an on_removed and this was the last pin, it pings the poller so the
3643 : // notice comes quickly. removed is read before the decrement, while the pin
3644 : // still makes raw safe; a remove that lands in between makes that read stale,
3645 : // and the bounded reclaim retry then covers the missed ping. Reading after the
3646 : // decrement would be a use-after-free.
3647 15902 : static void ceventloop_reg_resolve_unpin(struct ceventloop__s *loop,
3648 : ceventloop_reg_s *raw) {
3649 31804 : bool maybe_needs_wake =
3650 15902 : atomic_load(&raw->removed) && raw->handlers.on_removed;
3651 :
3652 : #ifdef RUNNING_UNIT_TESTS
3653 15902 : uint32_t delay_ms = atomic_exchange(&g_delay_next_reg_resolve_unpin_ms, 0u);
3654 15902 : if (delay_ms > 0) {
3655 1 : struct timespec ts = {.tv_sec = delay_ms / 1000,
3656 1 : .tv_nsec = (long)(delay_ms % 1000) * 1000000L};
3657 1 : nanosleep(&ts, NULL);
3658 : }
3659 : #endif
3660 :
3661 15902 : int prev = atomic_fetch_sub(&raw->pending_resolve_count, 1);
3662 :
3663 15902 : if (prev == 1 && maybe_needs_wake) eventfd_notify(loop->reclaim_wake_efd);
3664 15902 : }
3665 :
3666 : // Frees reg's slot (not in use, ptr NULL) so every later resolve of its handle
3667 : // fails at once, and puts the index on the free list; a push that can't
3668 : // allocate counts it in reg_lost_indices. ceventloop_remove calls it the moment
3669 : // it removes reg, well before the struct itself is reclaimed; the two have
3670 : // separate lifetimes, so the index can be reused at once. Takes the write side
3671 : // of reg_slot_rwlock.
3672 7533 : static void ceventloop_reg_slot_release(struct ceventloop__s *loop,
3673 : ceventloop_reg_s *reg) {
3674 7533 : ccol__rw_lock_wrlock(loop->reg_slot_rwlock);
3675 7534 : ceventloop_reg_slot *slot =
3676 7534 : (ceventloop_reg_slot *)cvector_at(loop->reg_slots, reg->self_slot_idx);
3677 7534 : slot->in_use = false;
3678 7534 : slot->ptr = NULL;
3679 : #ifdef RUNNING_UNIT_TESTS
3680 7534 : if (atomic_exchange(&g_fail_next_reg_free_index_push, false)) {
3681 8 : loop->reg_lost_indices++;
3682 8 : ccol__rw_lock_unlock(loop->reg_slot_rwlock);
3683 8 : return;
3684 : }
3685 : #endif
3686 7526 : if (cvector_push_back(loop->reg_free_indices, ®->self_slot_idx) !=
3687 : ccol_success) {
3688 0 : loop->reg_lost_indices++;
3689 : }
3690 7526 : ccol__rw_lock_unlock(loop->reg_slot_rwlock);
3691 : }
3692 :
3693 : #ifdef RUNNING_UNIT_TESTS
3694 : // Test-only: Makes the next wait mutex init of a queue registration fail.
3695 : static _Atomic bool g_fail_next_reg_sync_init = false;
3696 :
3697 : // Test-only: Arms the failing init.
3698 1 : void ceventloop__test_fail_next_reg_sync_init(void) {
3699 1 : atomic_store(&g_fail_next_reg_sync_init, true);
3700 1 : }
3701 : #endif
3702 :
3703 : // Allocates and fills a registration for ceventloop_add. A queue registration
3704 : // also gets its wait_mtx and wait_cond here, before anything else can fail, so
3705 : // ceventloop_reg_free can always destroy them. Gives NULL with *rv_out set to
3706 : // ccol_not_enough_memory or, when an init fails (reg is then freed directly),
3707 : // ccol_unexpected_failure.
3708 46229 : static ceventloop_reg_s *ceventloop_reg_create(struct ceventloop__s *loop,
3709 : cselectable sel,
3710 : ceventloop_handlers handlers,
3711 : void *arg, ccol_retval *rv_out) {
3712 92463 : ceventloop_reg_s *reg =
3713 46229 : ccol__mem_calloc(loop->m_procs, 1, sizeof(ceventloop_reg_s));
3714 46234 : if (!reg) {
3715 2 : *rv_out = ccol_not_enough_memory;
3716 2 : return NULL;
3717 : }
3718 46232 : reg->sel = sel;
3719 46232 : reg->handlers = handlers;
3720 46232 : reg->arg = arg;
3721 46232 : atomic_init(®->refcount, 1);
3722 46232 : atomic_init(®->removed, false);
3723 46232 : atomic_init(®->paused, false);
3724 46232 : atomic_init(®->pending_resolve_count, (size_t)0);
3725 46232 : reg->bridge_efd = -1;
3726 46232 : if (sel.type != cselectable_type_fd) {
3727 439 : bool mutex_failed;
3728 : #ifdef RUNNING_UNIT_TESTS
3729 439 : if (atomic_exchange(&g_fail_next_reg_sync_init, false))
3730 : mutex_failed = true;
3731 : else
3732 : #endif
3733 438 : mutex_failed = ccol__mutex_init(reg->wait_mtx) != 0;
3734 438 : if (mutex_failed) {
3735 1 : ccol__mem_free(loop->m_procs, reg);
3736 1 : *rv_out = ccol_unexpected_failure;
3737 1 : return NULL;
3738 : }
3739 438 : if (ccol__cond_var_init(reg->wait_cond) != 0) {
3740 0 : ccol__mutex_destroy(reg->wait_mtx);
3741 0 : ccol__mem_free(loop->m_procs, reg);
3742 0 : *rv_out = ccol_unexpected_failure;
3743 0 : return NULL;
3744 : }
3745 : }
3746 : return reg;
3747 : }
3748 :
3749 : // Frees a registration: It calls on_removed when the registration was ever
3750 : // wired (owning_entry set), so the notice comes exactly once for every real
3751 : // registration, then destroys wait_mtx and wait_cond and closes the bridge
3752 : // eventfd of a queue registration. It's the only place that tears those down,
3753 : // for the reclaim, the destroy and a failed add, so nothing is destroyed twice.
3754 : // No lock of this module is held, so on_removed may take any lock of yours.
3755 46189 : static void ceventloop_reg_free(struct ceventloop__s *loop,
3756 : ceventloop_reg_s *reg) {
3757 46189 : if (reg->owning_entry && reg->handlers.on_removed)
3758 1296 : reg->handlers.on_removed(reg->arg);
3759 :
3760 46189 : if (reg->sel.type != cselectable_type_fd) {
3761 433 : ccol__mutex_destroy(reg->wait_mtx);
3762 433 : ccol__cond_var_destroy(reg->wait_cond);
3763 433 : if (reg->bridge_efd >= 0) close(reg->bridge_efd);
3764 : }
3765 46189 : ccol__mem_free(loop->m_procs, reg);
3766 46189 : }
3767 :
3768 : // Gives the interest bits one direction of an fd entry adds to the combined
3769 : // mask, 0 for no registration or a paused or muted one. IN and OUT come only
3770 : // from a real on_readable or on_writable, because readiness that nothing
3771 : // consumes would make level-triggered epoll spin (an error-only registration on
3772 : // a healthy socket would). ERR and HUP always go in, and a read direction adds
3773 : // RDHUP, the only bit that reports a plain TCP close to a registration with no
3774 : // reader.
3775 923152 : static uint32_t fd_reg_interest_bits(ceventloop_reg_s *reg, cselect_dir dir) {
3776 923152 : if (!reg || atomic_load(®->paused) || reg->muted) return 0;
3777 483581 : uint32_t bits = (uint32_t)(CCOL_POLL_ERR | CCOL_POLL_HUP);
3778 483581 : if (dir == cselect_read) {
3779 442057 : bits |= (uint32_t)CCOL_POLL_RDHUP;
3780 442057 : if (reg->handlers.on_readable) bits |= (uint32_t)CCOL_POLL_IN;
3781 41524 : } else if (reg->handlers.on_writable) {
3782 37817 : bits |= (uint32_t)CCOL_POLL_OUT;
3783 : }
3784 : return bits;
3785 : }
3786 :
3787 : static size_t ceventloop_entry_alloc_size(const struct ceventloop__s *loop);
3788 :
3789 : // Registers reg's direction of an fd in stripe idx, for ceventloop_add. A new
3790 : // fd gets a new entry (with a new generation) and an ADD; a second direction
3791 : // joins the existing entry and the combined mask is applied with MOD, or ADD
3792 : // when the entry was taken out of the set (epoll_added false). The mask is
3793 : // one-shot only with a dispatch pool, where the pool re-arms after each job;
3794 : // with one thread nothing re-arms, so one-shot would lose every later event. A
3795 : // new entry goes into the fd index before epoll_ctl publishes it, because once
3796 : // published only the deferred reclaim may free it. Gives ccol_not_permitted
3797 : // when the direction is taken, ccol_not_enough_memory, or
3798 : // ccol_unexpected_failure. On success it sets owning_entry, stripe_idx and
3799 : // generation of reg. The caller holds the stripe lock.
3800 45792 : static ccol_retval ceventloop_add_fd(struct ceventloop__s *loop, size_t idx,
3801 : ceventloop_reg_s *reg) {
3802 45792 : ceventloop_stripe *stripe = &loop->stripes[idx];
3803 45792 : int fd = reg->sel.fd;
3804 45792 : event_entry *entry = fd_registry_find(stripe, fd);
3805 45785 : bool new_entry = (entry == NULL);
3806 :
3807 45785 : if (new_entry) {
3808 84452 : entry =
3809 84448 : ccol__mem_calloc(loop->m_procs, 1, ceventloop_entry_alloc_size(loop));
3810 42228 : if (!entry) return ccol_not_enough_memory;
3811 42227 : entry->is_fd = true;
3812 42227 : entry->fd = fd;
3813 42227 : entry->stripe_idx = idx;
3814 42227 : entry->as.fd.read_reg = NULL;
3815 42227 : entry->as.fd.write_reg = NULL;
3816 42227 : if (ccol__mutex_init(entry->dispatch_lock) != 0) {
3817 0 : ccol__mem_free(loop->m_procs, entry);
3818 0 : return ccol_unexpected_failure;
3819 : }
3820 42228 : atomic_init(&entry->removed, false);
3821 42228 : atomic_init(&entry->refcount, (size_t)0);
3822 42228 : entry->generation = atomic_fetch_add(&loop->fd_generation_counter, 1) + 1;
3823 : }
3824 :
3825 91578 : ceventloop_reg_s **slot = (reg->sel.dir == cselect_read)
3826 : ? &entry->as.fd.read_reg
3827 45789 : : &entry->as.fd.write_reg;
3828 45789 : if (*slot != NULL) {
3829 2 : if (new_entry) {
3830 0 : ccol__mutex_destroy(entry->dispatch_lock);
3831 0 : ccol__mem_free(loop->m_procs, entry);
3832 : }
3833 2 : return ccol_not_permitted;
3834 : }
3835 45787 : *slot = reg;
3836 :
3837 45787 : uint32_t mask = loop->dispatch_pool ? CCOL_POLL_ONESHOT : 0;
3838 45787 : mask |= fd_reg_interest_bits(entry->as.fd.read_reg, cselect_read);
3839 45785 : mask |= fd_reg_interest_bits(entry->as.fd.write_reg, cselect_write);
3840 :
3841 45784 : ccol_poll_event ev;
3842 45784 : ev.data.ptr = entry;
3843 45784 : ev.events = mask;
3844 88006 : if (new_entry && !fd_registry_insert(stripe, fd, entry)) {
3845 1 : *slot = NULL;
3846 1 : ccol__mutex_destroy(entry->dispatch_lock);
3847 1 : ccol__mem_free(loop->m_procs, entry);
3848 1 : return ccol_not_enough_memory;
3849 : }
3850 :
3851 45780 : int ctl_op = entry->epoll_added ? CCOL_POLL_CTL_MOD : CCOL_POLL_CTL_ADD;
3852 45780 : bool want_in = (mask & CCOL_POLL_IN) != 0;
3853 45780 : if (ctl_op == CCOL_POLL_CTL_MOD && want_in != entry->armed_in)
3854 : ev.events |= CCOL_POLL_READ_MODE_CHANGE;
3855 45780 : if (ccol_poll_ctl(loop->epfd, ctl_op, fd, &ev, &entry->poll_info) < 0) {
3856 1 : *slot = NULL;
3857 1 : if (new_entry) {
3858 1 : fd_registry_remove(stripe, fd);
3859 1 : ccol__mutex_destroy(entry->dispatch_lock);
3860 1 : ccol__mem_free(loop->m_procs, entry);
3861 : }
3862 1 : return ccol_unexpected_failure;
3863 : }
3864 45787 : entry->epoll_added = true;
3865 45787 : entry->armed_in = want_in;
3866 :
3867 45787 : reg->owning_entry = entry;
3868 45787 : reg->stripe_idx = idx;
3869 45787 : reg->generation = entry->generation;
3870 45787 : return ccol_success;
3871 : }
3872 :
3873 : // Says whether the queue sel names is ready for sel's direction: A message
3874 : // for read, room or sends off for write. It's the one definition of ready for a
3875 : // queue, used by the add, the cascade and the deregister paths so they never
3876 : // disagree. The caller holds the queue's mutex.
3877 24489 : static bool queue_sel_is_ready(cselectable *sel) {
3878 24489 : if (sel->type == cselectable_type_ccircq) {
3879 16993 : ccircq *cq = sel->cq;
3880 16993 : return (sel->dir == cselect_read)
3881 14346 : ? cq->msg_count > 0
3882 19618 : : (cq->msg_count < cq->max_size || cq->writing_disabled);
3883 : }
3884 7496 : cdynmq *dq = sel->dq;
3885 7496 : return (sel->dir == cselect_read)
3886 6867 : ? dq->msg_count > 0
3887 8125 : : (dq->writing_disabled || dq->msg_count < ccol_max_elem_count);
3888 : }
3889 :
3890 : // Wires a queue registration for ceventloop_add: It creates the bridge
3891 : // eventfd, adds it to the poll set and links the registration's waiter node
3892 : // into the queue's list for good, so every send, receive and state change of
3893 : // the queue wakes it. A queue that is already ready gets a wake through
3894 : // notify_waiter() at once, since the eventfd rings only on later notifies. On
3895 : // failure it closes only the eventfd; ceventloop_reg_free owns the rest. The
3896 : // caller holds the stripe lock, and this takes the queue's mutex.
3897 436 : static ccol_retval ceventloop_add_queue(struct ceventloop__s *loop,
3898 : event_entry *entry,
3899 : ceventloop_reg_s *reg) {
3900 436 : reg->bridge_efd = ccol_wakefd_create();
3901 436 : if (reg->bridge_efd < 0) {
3902 : return ccol_unexpected_failure;
3903 : }
3904 436 : reg->waiter_node.efd = reg->bridge_efd;
3905 :
3906 436 : ccol_poll_event ev;
3907 436 : ev.data.ptr = entry;
3908 436 : ev.events = CCOL_POLL_IN | (loop->dispatch_pool ? CCOL_POLL_ONESHOT : 0);
3909 436 : if (ccol_poll_ctl(loop->epfd, CCOL_POLL_CTL_ADD, reg->bridge_efd, &ev, NULL) <
3910 : 0) {
3911 0 : close(reg->bridge_efd);
3912 0 : reg->bridge_efd = -1;
3913 0 : reg->waiter_node.efd = -1;
3914 0 : return ccol_unexpected_failure;
3915 : }
3916 :
3917 436 : ccol__mutex *q_mtx;
3918 436 : ccol_sel_waiter **q_head;
3919 436 : ccol_sel_waiter **q_rotor;
3920 436 : queue_sel_locate(®->sel, &q_mtx, &q_head, &q_rotor);
3921 436 : (void)q_rotor;
3922 :
3923 436 : ccol__mutex_lock(*q_mtx);
3924 436 : sel_link_waiter(0, ®->waiter_node, ®->wait_mtx, ®->wait_cond,
3925 : ®->wait_ready, q_head);
3926 436 : bool already_ready = queue_sel_is_ready(®->sel);
3927 436 : if (already_ready) notify_waiter(®->waiter_node);
3928 436 : ccol__mutex_unlock(*q_mtx);
3929 :
3930 436 : return ccol_success;
3931 : }
3932 :
3933 : #ifdef RUNNING_UNIT_TESTS
3934 : // Test-only: The armed delay of the next cascade step and the counts of steps
3935 : // begun and finished.
3936 : static _Atomic uint32_t g_queue_cascade_test_delay_us = 0;
3937 : static _Atomic uint64_t g_queue_cascade_begun_for_tests = 0;
3938 : static _Atomic uint64_t g_queue_cascade_finished_for_tests = 0;
3939 : #endif
3940 :
3941 : // Decides who hears about the queue after reg's callback returned, since a
3942 : // registration stays linked and one eventfd write covers a whole burst. When
3943 : // the queue isn't ready, nobody is woken. When reg's dispatch moved a
3944 : // message (the count changed in its direction since queue_count_before), reg is
3945 : // woken again and its successor gets a forwarded wake, so a backlog drains and
3946 : // reaches the other listeners. When it moved nothing, the wake goes to the
3947 : // successor (or the head) with wake_hops + 1, and stops once the hops reach the
3948 : // list length, so listeners that all decline don't wake each other for ever. A
3949 : // modify that changed the direction counts as no progress. The stripe lock is
3950 : // held across the removed check and the queue's mutex: A removed registration
3951 : // may name a queue that's already destroyed, and the remove sets the flag under
3952 : // the same lock, while a live one keeps the queue destroy asserting. The caller
3953 : // holds the entry's dispatch lock and the collection's refcount.
3954 16074 : static void ceventloop_queue_cascade_notify_next(struct ceventloop__s *loop,
3955 : ceventloop_reg_s *reg,
3956 : cselect_dir dispatched_dir,
3957 : size_t queue_count_before,
3958 : uint32_t wake_hops) {
3959 16074 : ceventloop_stripe *stripe = &loop->stripes[reg->stripe_idx];
3960 16074 : ccol__mutex_lock(stripe->lock);
3961 :
3962 : #ifdef RUNNING_UNIT_TESTS
3963 16074 : atomic_fetch_add(&g_queue_cascade_begun_for_tests, (uint64_t)1);
3964 : {
3965 16074 : uint32_t cascade_delay_us =
3966 16074 : atomic_exchange(&g_queue_cascade_test_delay_us, 0u);
3967 16074 : if (cascade_delay_us > 0) {
3968 1 : struct timespec cascade_ts = {
3969 1 : .tv_sec = cascade_delay_us / 1000000,
3970 1 : .tv_nsec = (long)(cascade_delay_us % 1000000) * 1000L};
3971 1 : nanosleep(&cascade_ts, NULL);
3972 : }
3973 : }
3974 : #endif
3975 :
3976 16074 : if (!atomic_load(®->removed)) {
3977 16069 : ccol__mutex *q_mtx;
3978 16069 : ccol_sel_waiter **q_head;
3979 16069 : ccol_sel_waiter **q_rotor;
3980 16069 : queue_sel_locate(®->sel, &q_mtx, &q_head, &q_rotor);
3981 16069 : (void)q_rotor;
3982 :
3983 16069 : ccol__mutex_lock(*q_mtx);
3984 16069 : if (queue_sel_is_ready(®->sel)) {
3985 13654 : ccol_sel_waiter *self = ®->waiter_node;
3986 13654 : bool moved = false;
3987 13654 : if (reg->sel.dir == dispatched_dir) {
3988 13654 : size_t count_now = queue_sel_msg_count(®->sel);
3989 13654 : moved = (dispatched_dir == cselect_read)
3990 : ? count_now < queue_count_before
3991 13654 : : count_now > queue_count_before;
3992 : }
3993 13654 : if (moved) {
3994 11774 : notify_waiter(self);
3995 11774 : if (self->next) notify_waiter_forwarded(self->next, 1u);
3996 1880 : } else if (wake_hops < UINT32_MAX) {
3997 1880 : uint32_t next_hops = wake_hops + 1u;
3998 1880 : ccol_sel_waiter *target = self->next ? self->next : *q_head;
3999 2805 : if (target != self && sel_list_longer_than(*q_head, next_hops))
4000 165 : notify_waiter_forwarded(target, next_hops);
4001 : }
4002 : }
4003 16069 : ccol__mutex_unlock(*q_mtx);
4004 : }
4005 :
4006 : #ifdef RUNNING_UNIT_TESTS
4007 16074 : atomic_fetch_add(&g_queue_cascade_finished_for_tests, (uint64_t)1);
4008 : #endif
4009 16074 : ccol__mutex_unlock(stripe->lock);
4010 16074 : }
4011 :
4012 : #ifdef RUNNING_UNIT_TESTS
4013 : // Test-only: Arms the cascade delay.
4014 2 : void ceventloop__test_delay_next_queue_cascade_us(uint32_t us) {
4015 2 : atomic_store(&g_queue_cascade_test_delay_us, us);
4016 2 : }
4017 :
4018 : // Test-only: Reads the counts of cascade steps begun and finished.
4019 3 : void ceventloop__test_queue_cascade_counts(uint64_t *begun,
4020 : uint64_t *finished) {
4021 3 : if (begun) *begun = atomic_load(&g_queue_cascade_begun_for_tests);
4022 3 : if (finished) *finished = atomic_load(&g_queue_cascade_finished_for_tests);
4023 3 : }
4024 : #endif
4025 :
4026 : // Checks the selectable that ceventloop_add got: A known type and direction,
4027 : // an fd of at least 0 or a non-NULL queue. Gives ccol_success or
4028 : // ccol_invalid_args.
4029 46234 : static ccol_retval ceventloop_validate_add_args(struct ceventloop__s *loop,
4030 : cselectable *sel) {
4031 46234 : if (!loop) return ccol_invalid_args;
4032 46234 : if (sel->dir != cselect_read && sel->dir != cselect_write)
4033 : return ccol_invalid_args;
4034 :
4035 46234 : if (sel->type == cselectable_type_fd) {
4036 45794 : if (sel->fd < 0) return ccol_invalid_args;
4037 440 : } else if (sel->type == cselectable_type_ccircq) {
4038 390 : if (!sel->cq) return ccol_invalid_args;
4039 50 : } else if (sel->type == cselectable_type_cdynmq) {
4040 50 : if (!sel->dq) return ccol_invalid_args;
4041 : } else {
4042 : return ccol_invalid_args;
4043 : }
4044 : return ccol_success;
4045 : }
4046 :
4047 : // Registers sel with the loop and gives the new handle, or CEVENTLOOP_REG_NULL
4048 : // with *err_str naming the failure class. It resolves the loop, builds the
4049 : // registration, takes its handle slot first and only then wires it into the
4050 : // fd or queue registry under the stripe lock: Once wired it can be dispatched,
4051 : // and a failure reported after that point could let the caller free an arg that
4052 : // a callback is about to use. That order also matches the fork prepare handler
4053 : // (reg_slot_rwlock before stripe locks). An fd's stripe comes from the fd, a
4054 : // queue's from the round-robin cursor. A loop that has started to shut down
4055 : // refuses the add, checked under the stripe lock that the shutdown's detach
4056 : // walk also takes. A failure releases the slot and frees reg directly, since
4057 : // nothing could have seen it. Raises reg_count on success.
4058 46236 : ceventloop_reg ceventloop_add(ceventloop loop, cselectable sel,
4059 : ceventloop_handlers handlers, void *arg,
4060 : char **err_str) {
4061 46236 : struct ceventloop__s *raw = ceventloop_resolve(loop);
4062 46230 : if (!raw) {
4063 0 : if (err_str) *err_str = CCOL__ERR_STR("Invalid or stale ceventloop handle");
4064 0 : return CEVENTLOOP_REG_NULL;
4065 : }
4066 :
4067 46230 : ccol_retval validate = ceventloop_validate_add_args(raw, &sel);
4068 46230 : if (validate != ccol_success) {
4069 0 : if (err_str)
4070 0 : *err_str = CCOL__ERR_STR("Invalid arguments to ceventloop_add");
4071 0 : ceventloop_resolve_unpin(raw);
4072 0 : return CEVENTLOOP_REG_NULL;
4073 : }
4074 :
4075 46230 : ccol_retval create_rv = ccol_success;
4076 46230 : ceventloop_reg_s *reg =
4077 46230 : ceventloop_reg_create(raw, sel, handlers, arg, &create_rv);
4078 46229 : if (!reg) {
4079 3 : if (err_str)
4080 3 : *err_str =
4081 3 : create_rv == ccol_not_enough_memory
4082 : ? CCOL__ERR_STR(
4083 : "ceventloop_add: failed to allocate the registration")
4084 3 : : CCOL__ERR_STR(
4085 : "ceventloop_add: a system call failed (the "
4086 : "initialisation of a mutex or a condition variable)");
4087 3 : ceventloop_resolve_unpin(raw);
4088 3 : return CEVENTLOOP_REG_NULL;
4089 : }
4090 :
4091 46226 : ceventloop_reg h = ceventloop_reg_slot_acquire(raw, reg);
4092 46233 : if (h == 0) {
4093 2 : if (err_str)
4094 2 : *err_str = CCOL__ERR_STR(
4095 : "ceventloop_add: failed to allocate the registration handle "
4096 : "slot");
4097 2 : ceventloop_reg_free(raw, reg);
4098 2 : ceventloop_resolve_unpin(raw);
4099 2 : return CEVENTLOOP_REG_NULL;
4100 : }
4101 :
4102 92462 : size_t idx =
4103 46231 : (sel.type == cselectable_type_fd)
4104 45793 : ? stripe_index_for_fd(raw, sel.fd)
4105 46231 : : (atomic_fetch_add(&raw->next_queue_stripe, 1) % raw->num_stripes);
4106 46231 : ceventloop_stripe *stripe = &raw->stripes[idx];
4107 :
4108 46231 : ccol__mutex_lock(stripe->lock);
4109 :
4110 46230 : bool shut_down = atomic_load(&raw->shutting_down);
4111 46230 : ccol_retval rv;
4112 46230 : if (shut_down) {
4113 : rv = ccol_not_permitted;
4114 46229 : } else if (sel.type == cselectable_type_fd) {
4115 45792 : rv = ceventloop_add_fd(raw, idx, reg);
4116 : } else {
4117 874 : event_entry *entry =
4118 874 : ccol__mem_calloc(raw->m_procs, 1, ceventloop_entry_alloc_size(raw));
4119 437 : if (!entry) {
4120 : rv = ccol_not_enough_memory;
4121 : } else {
4122 436 : entry->is_fd = false;
4123 436 : entry->fd = -1;
4124 436 : entry->stripe_idx = idx;
4125 436 : entry->as.reg = reg;
4126 436 : if (ccol__mutex_init(entry->dispatch_lock) != 0) {
4127 0 : ccol__mem_free(raw->m_procs, entry);
4128 : rv = ccol_unexpected_failure;
4129 : } else {
4130 436 : atomic_init(&entry->removed, false);
4131 436 : atomic_init(&entry->refcount, (size_t)0);
4132 436 : entry->generation =
4133 436 : atomic_fetch_add(&raw->fd_generation_counter, 1) + 1;
4134 436 : rv = ceventloop_add_queue(raw, entry, reg);
4135 436 : if (rv == ccol_success) {
4136 436 : reg->owning_entry = entry;
4137 436 : reg->stripe_idx = idx;
4138 436 : reg->generation = entry->generation;
4139 504 : loop_queue_list_add(stripe, reg);
4140 : } else {
4141 0 : ccol__mutex_destroy(entry->dispatch_lock);
4142 0 : ccol__mem_free(raw->m_procs, entry);
4143 : }
4144 : }
4145 : }
4146 : }
4147 :
4148 46228 : if (rv == ccol_success) atomic_fetch_add(&raw->reg_count, 1);
4149 :
4150 46230 : ccol__mutex_unlock(stripe->lock);
4151 :
4152 46231 : if (rv != ccol_success) {
4153 8 : if (err_str) {
4154 8 : if (shut_down)
4155 2 : *err_str = CCOL__ERR_STR("ceventloop_add: the loop is shut down");
4156 6 : else if (rv == ccol_not_permitted)
4157 2 : *err_str = CCOL__ERR_STR(
4158 : "ceventloop_add: direction already in use on this fd");
4159 4 : else if (rv == ccol_not_enough_memory)
4160 3 : *err_str = CCOL__ERR_STR(
4161 : "ceventloop_add: failed to allocate the registration");
4162 : else
4163 1 : *err_str = CCOL__ERR_STR(
4164 : "ceventloop_add: a system call failed (epoll_ctl, eventfd "
4165 : "or a mutex initialisation)");
4166 : }
4167 8 : ceventloop_reg_slot_release(raw, reg);
4168 8 : ceventloop_reg_free(raw, reg);
4169 8 : ceventloop_resolve_unpin(raw);
4170 8 : return CEVENTLOOP_REG_NULL;
4171 : }
4172 :
4173 : #ifdef RUNNING_UNIT_TESTS
4174 46223 : void (*add_hook)(void) = atomic_load(&g_evl_add_before_return_hook);
4175 46223 : if (add_hook) add_hook();
4176 : #endif
4177 46223 : ceventloop_resolve_unpin(raw);
4178 46223 : if (err_str) *err_str = NULL;
4179 : return h;
4180 : }
4181 :
4182 : // Gives the generation of the fd behind reg, for the caller's own bookkeeping
4183 : // across fd reuse, or 0 when the loop or reg doesn't resolve. It resolves and
4184 : // pins both handles for the read.
4185 1509 : uint64_t ceventloop_reg_generation(ceventloop loop, ceventloop_reg reg) {
4186 1509 : struct ceventloop__s *raw = ceventloop_resolve(loop);
4187 1509 : if (!raw) return 0;
4188 1508 : ceventloop_reg_s *raw_reg = ceventloop_reg_resolve(raw, reg);
4189 1510 : if (!raw_reg) {
4190 267 : ceventloop_resolve_unpin(raw);
4191 267 : return 0;
4192 : }
4193 1243 : uint64_t gen = raw_reg->generation;
4194 1243 : ceventloop_reg_resolve_unpin(raw, raw_reg);
4195 1239 : ceventloop_resolve_unpin(raw);
4196 1239 : return gen;
4197 : }
4198 :
4199 : // Applies the poll interest an entry wants right now, computed from live state
4200 : // (each direction's registration, paused and muted included), never from a
4201 : // snapshot. Modify, a partial remove, pause, resume and the one-shot re-arm
4202 : // after a pool dispatch all use it, so whichever runs last under the stripe
4203 : // lock applies the current answer and none can replay a stale mask. When no fd
4204 : // direction wants real interest the fd is taken out with DEL (ERR and HUP can't
4205 : // be masked, and a paused fd in error would spin the poller) and added back
4206 : // with ADD later. A removed entry, whose fd may be closed or reused, and a
4207 : // queue entry whose registration is gone are left alone. The caller holds the
4208 : // stripe lock.
4209 28224 : static void ceventloop_rearm_entry_locked(struct ceventloop__s *loop,
4210 : event_entry *entry) {
4211 28224 : if (atomic_load(&entry->removed)) return;
4212 :
4213 27337 : ccol_poll_event ev;
4214 27337 : ev.data.ptr = entry;
4215 :
4216 27337 : if (entry->is_fd) {
4217 19469 : uint32_t mask = loop->dispatch_pool ? CCOL_POLL_ONESHOT : 0;
4218 19469 : mask |= fd_reg_interest_bits(entry->as.fd.read_reg, cselect_read);
4219 19471 : mask |= fd_reg_interest_bits(entry->as.fd.write_reg, cselect_write);
4220 :
4221 19470 : bool wants_interest = (mask & ~(uint32_t)CCOL_POLL_ONESHOT) != 0;
4222 19470 : if (wants_interest) {
4223 18500 : ev.events = mask;
4224 18500 : int op = entry->epoll_added ? CCOL_POLL_CTL_MOD : CCOL_POLL_CTL_ADD;
4225 18500 : bool want_in = (mask & CCOL_POLL_IN) != 0;
4226 18500 : if (op == CCOL_POLL_CTL_MOD && want_in != entry->armed_in)
4227 : ev.events |= CCOL_POLL_READ_MODE_CHANGE;
4228 18500 : if (ccol_poll_ctl(loop->epfd, op, entry->fd, &ev, &entry->poll_info) ==
4229 : 0) {
4230 18510 : entry->epoll_added = true;
4231 18510 : entry->armed_in = want_in;
4232 : }
4233 970 : } else if (entry->epoll_added) {
4234 942 : ccol_poll_ctl(loop->epfd, CCOL_POLL_CTL_DEL, entry->fd, NULL,
4235 : &entry->poll_info);
4236 942 : entry->epoll_added = false;
4237 : }
4238 7868 : } else if (entry->as.reg) {
4239 7868 : ev.events = CCOL_POLL_IN | (loop->dispatch_pool ? CCOL_POLL_ONESHOT : 0);
4240 7868 : ccol_poll_ctl(loop->epfd, CCOL_POLL_CTL_MOD, entry->as.reg->bridge_efd, &ev,
4241 : NULL);
4242 : }
4243 : }
4244 :
4245 : // Changes the direction of an fd registration, for a caller whose interest
4246 : // changes over time (a connecting socket that then reads). It resolves and pins
4247 : // the loop and the registration, then under the stripe lock checks that reg
4248 : // isn't removed (which makes owning_entry safe), moves reg to the other slot of
4249 : // its entry, clears muted and re-arms the entry. The same direction only
4250 : // unmutes and re-arms. Callbacks get a snapshot of reg->sel taken under the
4251 : // stripe lock, so the write here never races one. Gives ccol_success,
4252 : // ccol_invalid_args (bad handle, removed or queue registration, bad new_dir) or
4253 : // ccol_not_permitted when the other slot is taken.
4254 5280 : ccol_retval ceventloop_modify(ceventloop loop, ceventloop_reg reg_h,
4255 : cselect_dir new_dir) {
4256 5280 : struct ceventloop__s *raw = ceventloop_resolve(loop);
4257 5280 : if (!raw) return ccol_invalid_args;
4258 5280 : if (new_dir != cselect_read && new_dir != cselect_write) {
4259 0 : ceventloop_resolve_unpin(raw);
4260 0 : return ccol_invalid_args;
4261 : }
4262 :
4263 5280 : ceventloop_reg_s *reg = ceventloop_reg_resolve(raw, reg_h);
4264 5279 : if (!reg) {
4265 243 : ceventloop_resolve_unpin(raw);
4266 243 : return ccol_invalid_args;
4267 : }
4268 :
4269 5036 : if (reg->sel.type != cselectable_type_fd) {
4270 2 : ceventloop_reg_resolve_unpin(raw, reg);
4271 2 : ceventloop_resolve_unpin(raw);
4272 2 : return ccol_invalid_args;
4273 : }
4274 :
4275 5034 : ceventloop_stripe *stripe = &raw->stripes[reg->stripe_idx];
4276 5034 : ccol__mutex_lock(stripe->lock);
4277 :
4278 5034 : if (atomic_load(®->removed)) {
4279 23 : ccol__mutex_unlock(stripe->lock);
4280 23 : ceventloop_reg_resolve_unpin(raw, reg);
4281 23 : ceventloop_resolve_unpin(raw);
4282 23 : return ccol_invalid_args;
4283 : }
4284 :
4285 5011 : if (reg->sel.dir == new_dir) {
4286 3586 : if (reg->muted) {
4287 2 : reg->muted = false;
4288 2 : ceventloop_rearm_entry_locked(raw, reg->owning_entry);
4289 : }
4290 3586 : ccol__mutex_unlock(stripe->lock);
4291 3586 : ceventloop_reg_resolve_unpin(raw, reg);
4292 3586 : ceventloop_resolve_unpin(raw);
4293 3586 : return ccol_success;
4294 : }
4295 :
4296 1425 : event_entry *entry = reg->owning_entry;
4297 2850 : ceventloop_reg_s **target_slot = (new_dir == cselect_read)
4298 : ? &entry->as.fd.read_reg
4299 1425 : : &entry->as.fd.write_reg;
4300 1425 : if (*target_slot != NULL) {
4301 1 : ccol__mutex_unlock(stripe->lock);
4302 1 : ceventloop_reg_resolve_unpin(raw, reg);
4303 1 : ceventloop_resolve_unpin(raw);
4304 1 : return ccol_not_permitted;
4305 : }
4306 :
4307 2848 : ceventloop_reg_s **current_slot = (reg->sel.dir == cselect_read)
4308 : ? &entry->as.fd.read_reg
4309 1424 : : &entry->as.fd.write_reg;
4310 1424 : *current_slot = NULL;
4311 1424 : *target_slot = reg;
4312 1424 : reg->sel.dir = new_dir;
4313 1424 : reg->muted = false;
4314 :
4315 1424 : ceventloop_rearm_entry_locked(raw, entry);
4316 :
4317 1425 : ccol__mutex_unlock(stripe->lock);
4318 1425 : ceventloop_reg_resolve_unpin(raw, reg);
4319 1425 : ceventloop_resolve_unpin(raw);
4320 1425 : return ccol_success;
4321 : }
4322 :
4323 : // Shared checks of pause and resume: reg must be an fd registration that isn't
4324 : // removed (confirmed under the stripe lock before owning_entry is read; a
4325 : // queue's bridge eventfd has no use for a pause). Gives ccol_success and the
4326 : // entry in *out_entry, or ccol_invalid_args.
4327 2069 : static ccol_retval ceventloop_pause_resume_validate_locked(
4328 : struct ceventloop__s *loop, ceventloop_reg_s *reg,
4329 : event_entry **out_entry) {
4330 2069 : (void)loop;
4331 2069 : if (reg->sel.type != cselectable_type_fd) return ccol_invalid_args;
4332 2067 : if (atomic_load(®->removed)) return ccol_invalid_args;
4333 2052 : *out_entry = reg->owning_entry;
4334 2052 : return ccol_success;
4335 : }
4336 :
4337 : // Stops event delivery for an fd registration while keeping it whole, the
4338 : // cheap form of remove plus add for a connection that leaves the reactor for a
4339 : // while. Under the stripe lock it sets paused and re-arms the entry without it.
4340 : // A paused registration stays paused and succeeds. Gives ccol_success or
4341 : // ccol_invalid_args.
4342 1281 : ccol_retval ceventloop_pause(ceventloop loop, ceventloop_reg reg_h) {
4343 1281 : struct ceventloop__s *raw = ceventloop_resolve(loop);
4344 1281 : if (!raw) return ccol_invalid_args;
4345 :
4346 1279 : ceventloop_reg_s *reg = ceventloop_reg_resolve(raw, reg_h);
4347 1279 : if (!reg) {
4348 260 : ceventloop_resolve_unpin(raw);
4349 260 : return ccol_invalid_args;
4350 : }
4351 :
4352 1019 : ceventloop_stripe *stripe = &raw->stripes[reg->stripe_idx];
4353 1019 : ccol__mutex_lock(stripe->lock);
4354 :
4355 1019 : event_entry *entry = NULL;
4356 1019 : ccol_retval rv = ceventloop_pause_resume_validate_locked(raw, reg, &entry);
4357 1019 : if (rv != ccol_success) {
4358 10 : ccol__mutex_unlock(stripe->lock);
4359 10 : ceventloop_reg_resolve_unpin(raw, reg);
4360 10 : ceventloop_resolve_unpin(raw);
4361 10 : return rv;
4362 : }
4363 :
4364 1009 : if (!atomic_load(®->paused)) {
4365 934 : atomic_store(®->paused, true);
4366 934 : ceventloop_rearm_entry_locked(raw, entry);
4367 : }
4368 :
4369 1009 : ccol__mutex_unlock(stripe->lock);
4370 1009 : ceventloop_reg_resolve_unpin(raw, reg);
4371 1009 : ceventloop_resolve_unpin(raw);
4372 1009 : return ccol_success;
4373 : }
4374 :
4375 : // Starts event delivery again for a paused (or muted) fd registration, by
4376 : // clearing both flags under the stripe lock and re-arming the entry. Resuming
4377 : // anything else succeeds and does nothing, so a caller racing its own pause and
4378 : // resume against a remove needn't tell the cases apart. Gives ccol_success or
4379 : // ccol_invalid_args.
4380 1319 : ccol_retval ceventloop_resume(ceventloop loop, ceventloop_reg reg_h) {
4381 1319 : struct ceventloop__s *raw = ceventloop_resolve(loop);
4382 1319 : if (!raw) return ccol_invalid_args;
4383 :
4384 1318 : ceventloop_reg_s *reg = ceventloop_reg_resolve(raw, reg_h);
4385 1318 : if (!reg) {
4386 268 : ceventloop_resolve_unpin(raw);
4387 268 : return ccol_invalid_args;
4388 : }
4389 :
4390 1050 : ceventloop_stripe *stripe = &raw->stripes[reg->stripe_idx];
4391 1050 : ccol__mutex_lock(stripe->lock);
4392 :
4393 1050 : event_entry *entry = NULL;
4394 1050 : ccol_retval rv = ceventloop_pause_resume_validate_locked(raw, reg, &entry);
4395 1050 : if (rv != ccol_success) {
4396 7 : ccol__mutex_unlock(stripe->lock);
4397 7 : ceventloop_reg_resolve_unpin(raw, reg);
4398 7 : ceventloop_resolve_unpin(raw);
4399 7 : return rv;
4400 : }
4401 :
4402 1043 : if (atomic_load(®->paused) || reg->muted) {
4403 817 : atomic_store(®->paused, false);
4404 817 : reg->muted = false;
4405 817 : ceventloop_rearm_entry_locked(raw, entry);
4406 : }
4407 :
4408 1043 : ccol__mutex_unlock(stripe->lock);
4409 1043 : ceventloop_reg_resolve_unpin(raw, reg);
4410 1043 : ceventloop_resolve_unpin(raw);
4411 1043 : return ccol_success;
4412 : }
4413 :
4414 : // Pushes a retired entry onto the loop's lock-free list of entries waiting for
4415 : // the reclaim. Entries come from every stripe, so no stripe lock can guard the
4416 : // list. There's no ABA problem, since the reclaim only ever takes the whole
4417 : // list at once.
4418 4809 : static void ceventloop_push_entry_free_node(struct ceventloop__s *loop,
4419 : event_entry *entry) {
4420 4809 : event_entry *old_head = atomic_load(&loop->pending_entry_frees);
4421 4810 : do {
4422 4810 : entry->pending_free_next = old_head;
4423 4810 : } while (!atomic_compare_exchange_weak(&loop->pending_entry_frees, &old_head,
4424 : entry));
4425 : }
4426 :
4427 : // Retires an entry that ceventloop_remove fully unregistered: Marks it removed,
4428 : // stamps defer_gen and queues it for the reclaim. It can't be freed at once,
4429 : // because a batch the poller already fetched, or a running pool job, can still
4430 : // point at it.
4431 3967 : static void ceventloop_defer_entry_free(struct ceventloop__s *loop,
4432 : event_entry *entry) {
4433 3967 : atomic_store(&entry->removed, true);
4434 3967 : entry->defer_gen = atomic_load(&loop->poller_batch_gen);
4435 3967 : ceventloop_push_entry_free_node(loop, entry);
4436 3967 : }
4437 :
4438 : // Pushes a registration onto the loop's lock-free list waiting for the reclaim.
4439 7592 : static void ceventloop_push_reg_free_node(struct ceventloop__s *loop,
4440 : ceventloop_reg_s *reg) {
4441 7592 : ceventloop_reg_s *old_head = atomic_load(&loop->pending_reg_frees);
4442 7593 : do {
4443 7593 : reg->pending_free_next = old_head;
4444 : } while (
4445 7593 : !atomic_compare_exchange_weak(&loop->pending_reg_frees, &old_head, reg));
4446 : }
4447 :
4448 : // Queues a registration whose refcount reached 0 for the reclaim, which waits
4449 : // until no public call still holds a resolve pin on it.
4450 7526 : static void ceventloop_defer_reg_free(struct ceventloop__s *loop,
4451 : ceventloop_reg_s *reg) {
4452 16407 : ceventloop_push_reg_free_node(loop, reg);
4453 : }
4454 :
4455 : // Frees every deferred entry and registration that is safe to free and keeps
4456 : // the rest. The poller calls it between batches after it advanced
4457 : // poller_batch_gen. An entry is safe once defer_gen < poller_batch_gen (no
4458 : // batch in flight can name it) and its refcount is 0 (no pool job uses it); a
4459 : // registration once its pending_resolve_count is 0, since its slot was released
4460 : // at the remove. Each list is taken whole with one exchange and the rest pushed
4461 : // back without a new stamp, so a busy loop can't starve an item. Gives true
4462 : // when something stays pending, which makes the poller use a bounded wait: The
4463 : // ping from the last unpin may not come.
4464 288139 : static bool ceventloop_reclaim_pending_frees(struct ceventloop__s *loop) {
4465 288139 : uint64_t reached = atomic_load(&loop->poller_batch_gen);
4466 :
4467 288139 : event_entry *e = atomic_exchange(&loop->pending_entry_frees, NULL);
4468 288139 : event_entry *e_keep = NULL;
4469 292680 : while (e) {
4470 4541 : event_entry *next = e->pending_free_next;
4471 4541 : if (e->defer_gen < reached && atomic_load(&e->refcount) == 0) {
4472 3699 : ccol__mutex_destroy(e->dispatch_lock);
4473 3699 : ccol__mem_free(loop->m_procs, e);
4474 : #ifdef RUNNING_UNIT_TESTS
4475 3699 : atomic_fetch_add_explicit(&loop->entries_reclaimed_for_tests, (uint64_t)1,
4476 : memory_order_relaxed);
4477 : #endif
4478 : } else {
4479 842 : e->pending_free_next = e_keep;
4480 842 : e_keep = e;
4481 : }
4482 : e = next;
4483 : }
4484 288139 : bool entries_still_pending = (e_keep != NULL);
4485 288139 : while (e_keep) {
4486 842 : event_entry *next = e_keep->pending_free_next;
4487 288981 : ceventloop_push_entry_free_node(loop, e_keep);
4488 : e_keep = next;
4489 : }
4490 :
4491 288139 : ceventloop_reg_s *r = atomic_exchange(&loop->pending_reg_frees, NULL);
4492 288139 : ceventloop_reg_s *r_keep = NULL;
4493 295457 : while (r) {
4494 7318 : ceventloop_reg_s *next = r->pending_free_next;
4495 7318 : if (atomic_load(&r->pending_resolve_count) == 0) {
4496 7252 : ceventloop_reg_free(loop, r);
4497 : } else {
4498 66 : r->pending_free_next = r_keep;
4499 66 : r_keep = r;
4500 : }
4501 : r = next;
4502 : }
4503 288139 : bool regs_still_pending = (r_keep != NULL);
4504 288139 : while (r_keep) {
4505 66 : ceventloop_reg_s *next = r_keep->pending_free_next;
4506 288205 : ceventloop_push_reg_free_node(loop, r_keep);
4507 : r_keep = next;
4508 : }
4509 :
4510 288139 : return entries_still_pending || regs_still_pending;
4511 : }
4512 :
4513 : // Frees every deferred entry and registration with no check, for the destroy
4514 : // once every loop thread is joined and nothing can point at them.
4515 39357 : static void ceventloop_free_all_pending(struct ceventloop__s *loop) {
4516 39357 : event_entry *e = atomic_exchange(&loop->pending_entry_frees, NULL);
4517 39594 : while (e) {
4518 237 : event_entry *next = e->pending_free_next;
4519 237 : ccol__mutex_destroy(e->dispatch_lock);
4520 237 : ccol__mem_free(loop->m_procs, e);
4521 : e = next;
4522 : }
4523 39357 : ceventloop_reg_s *r = atomic_exchange(&loop->pending_reg_frees, NULL);
4524 39601 : while (r) {
4525 243 : ceventloop_reg_s *next = r->pending_free_next;
4526 243 : ceventloop_reg_free(loop, r);
4527 243 : r = next;
4528 : }
4529 39358 : }
4530 :
4531 : // Phase 1 of a remove: Unlinks reg from the registry and marks it removed,
4532 : // under the stripe lock, without touching the refcount. For an fd it clears
4533 : // reg's slot and either retires the entry (DEL when still added, out of the
4534 : // index, deferred) or re-arms it for the other direction. For a queue the
4535 : // splice of the waiter node, the removed store and the hand-on of a pending
4536 : // wake happen in one critical section of the queue's mutex: Split in two, a
4537 : // cascade step could read a frozen next pointer of a node whose successor
4538 : // another remove already reclaimed. A node a shutdown already detached only
4539 : // lowers the queue's detached count. Then the bridge eventfd leaves the set and
4540 : // entry->as.reg becomes NULL before the entry is deferred, so a stale batch
4541 : // reads NULL. Gives true when this call did the removal, false when an earlier
4542 : // one had.
4543 7546 : static bool ceventloop_remove_unlink(struct ceventloop__s *raw,
4544 : ceventloop_reg_s *reg) {
4545 7546 : ceventloop_stripe *stripe = &raw->stripes[reg->stripe_idx];
4546 7546 : ccol__mutex_lock(stripe->lock);
4547 :
4548 7548 : if (atomic_load(®->removed)) {
4549 27 : ccol__mutex_unlock(stripe->lock);
4550 27 : return false;
4551 : }
4552 :
4553 7521 : event_entry *entry = reg->owning_entry;
4554 :
4555 7521 : if (reg->sel.type == cselectable_type_fd) {
4556 14268 : ceventloop_reg_s **slot = (reg->sel.dir == cselect_read)
4557 : ? &entry->as.fd.read_reg
4558 7134 : : &entry->as.fd.write_reg;
4559 7134 : *slot = NULL;
4560 7134 : if (entry->as.fd.read_reg == NULL && entry->as.fd.write_reg == NULL) {
4561 3574 : if (entry->epoll_added)
4562 3451 : ccol_poll_ctl(raw->epfd, CCOL_POLL_CTL_DEL, entry->fd, NULL,
4563 : &entry->poll_info);
4564 3579 : fd_registry_remove(stripe, entry->fd);
4565 3579 : ceventloop_defer_entry_free(raw, entry);
4566 : } else {
4567 3560 : ceventloop_rearm_entry_locked(raw, entry);
4568 : }
4569 : } else {
4570 387 : ccol__mutex *q_mtx;
4571 387 : ccol_sel_waiter **q_head;
4572 387 : ccol_sel_waiter **q_rotor;
4573 387 : queue_sel_locate(®->sel, &q_mtx, &q_head, &q_rotor);
4574 :
4575 387 : ccol__mutex_lock(*q_mtx);
4576 387 : bool linked = !reg->waiter_detached;
4577 387 : if (linked)
4578 385 : sel_unlink_waiter_locked(®->waiter_node, q_head, q_rotor);
4579 : else
4580 4 : (*queue_sel_detached_count(®->sel))--;
4581 387 : atomic_store(®->removed, true);
4582 387 : if (linked && queue_sel_is_ready(®->sel))
4583 53 : notify_one_sel_waiter(q_head, q_rotor);
4584 387 : ccol__mutex_unlock(*q_mtx);
4585 :
4586 388 : ccol_poll_ctl(raw->epfd, CCOL_POLL_CTL_DEL, reg->bridge_efd, NULL, NULL);
4587 388 : loop_queue_list_remove(stripe, reg);
4588 388 : entry->as.reg = NULL;
4589 388 : ceventloop_defer_entry_free(raw, entry);
4590 : }
4591 :
4592 7526 : if (reg->sel.type == cselectable_type_fd) {
4593 7138 : atomic_store(®->removed, true);
4594 : }
4595 :
4596 7526 : ccol__mutex_unlock(stripe->lock);
4597 7526 : return true;
4598 : }
4599 :
4600 : // Phase 2 of a remove, after the slot release: Lowers reg_count, drops the
4601 : // registration's own reference (deferring it when that was the last), and
4602 : // always pings the poller. Only the poller reclaims, and nothing else wakes it
4603 : // on an idle loop, so without the ping deferred entries would keep bridge
4604 : // eventfds open and an add and remove cycle would leak descriptors.
4605 7526 : static void ceventloop_remove_finish(struct ceventloop__s *raw,
4606 : ceventloop_reg_s *reg) {
4607 7526 : atomic_fetch_sub(&raw->reg_count, 1);
4608 :
4609 7526 : int prev = atomic_fetch_sub(®->refcount, 1);
4610 7526 : if (prev == 1) ceventloop_defer_reg_free(raw, reg);
4611 :
4612 7526 : eventfd_notify(raw->reclaim_wake_efd);
4613 7525 : }
4614 :
4615 : // Removes a registration. It resolves and pins the loop and the registration,
4616 : // unlinks it, releases its handle slot (before the registration can be
4617 : // reclaimed, so no resolve can find a reclaimable reg) and finishes the remove;
4618 : // a call that finds it already removed does neither. The pin it still holds
4619 : // keeps reg from being freed until the unpin. Gives ccol_success, or
4620 : // ccol_invalid_args when a handle doesn't resolve.
4621 7824 : ccol_retval ceventloop_remove(ceventloop loop, ceventloop_reg reg_h) {
4622 7824 : struct ceventloop__s *raw = ceventloop_resolve(loop);
4623 7821 : if (!raw) return ccol_invalid_args;
4624 7821 : ceventloop_reg_s *reg = ceventloop_reg_resolve(raw, reg_h);
4625 7822 : if (!reg) {
4626 274 : ceventloop_resolve_unpin(raw);
4627 274 : return ccol_invalid_args;
4628 : }
4629 :
4630 7548 : if (ceventloop_remove_unlink(raw, reg)) {
4631 7525 : ceventloop_reg_slot_release(raw, reg);
4632 7526 : ceventloop_remove_finish(raw, reg);
4633 : }
4634 :
4635 7552 : ceventloop_reg_resolve_unpin(raw, reg);
4636 7553 : ceventloop_resolve_unpin(raw);
4637 7553 : return ccol_success;
4638 : }
4639 :
4640 : // Gives the number of live registrations, or ccol_invalid_size for a bad
4641 : // handle.
4642 51 : size_t ceventloop_reg_count(ceventloop loop) {
4643 51 : struct ceventloop__s *raw = ceventloop_resolve(loop);
4644 51 : if (!raw) return ccol_invalid_size;
4645 50 : size_t n = atomic_load(&raw->reg_count);
4646 50 : ceventloop_resolve_unpin(raw);
4647 50 : return n;
4648 : }
4649 :
4650 : // One registration collected for dispatch under the stripe lock and acted on
4651 : // after it. sel_snapshot is a copy of reg->sel taken under that lock, so a
4652 : // callback never reads reg->sel while ceventloop_modify writes it.
4653 : // queue_count_before and wake_hops, for queue items, are the message count and
4654 : // hop count taken when the wake was consumed, for the cascade step.
4655 : typedef struct dispatch_item {
4656 : ceventloop_reg_s *reg;
4657 : bool is_error;
4658 : bool is_readable;
4659 : bool is_writable;
4660 : cselectable sel_snapshot;
4661 : size_t queue_count_before;
4662 : uint32_t wake_hops;
4663 : } dispatch_item;
4664 :
4665 : static void ccol_fd_reg_mute_locked(struct ceventloop__s *loop,
4666 : event_entry *entry, ceventloop_reg_s *reg);
4667 :
4668 : // What one fd event means for one registration, decided the same way on both
4669 : // dispatch paths.
4670 : typedef enum {
4671 : FD_TAKE_NONE,
4672 : FD_TAKE_DIRECTION,
4673 : FD_TAKE_ERROR,
4674 : } fd_take;
4675 :
4676 : static fd_take ccol_fd_reg_takes_condition(struct ceventloop__s *loop,
4677 : event_entry *entry,
4678 : ceventloop_reg_s *reg,
4679 : bool is_write_direction);
4680 :
4681 : // Decides whether an event on one direction of an fd entry goes to reg, and to
4682 : // which handler, so both dispatch paths route events the same way. A removed
4683 : // registration gets nothing. A ready direction with its own handler takes the
4684 : // event even when the fd also has an error, so data that arrived first isn't
4685 : // lost; anything else goes to ccol_fd_reg_takes_condition(). The caller holds
4686 : // the stripe lock.
4687 789668 : static inline fd_take ccol_fd_reg_takes_event(struct ceventloop__s *loop,
4688 : event_entry *entry,
4689 : ceventloop_reg_s *reg,
4690 : bool is_err, bool direction_ready,
4691 : bool is_write_direction) {
4692 789668 : if (!reg || atomic_load(®->removed) || !(is_err || direction_ready))
4693 389735 : return FD_TAKE_NONE;
4694 794176 : if (direction_ready &&
4695 21308 : (is_write_direction ? reg->handlers.on_writable != NULL
4696 372935 : : reg->handlers.on_readable != NULL))
4697 : return FD_TAKE_DIRECTION;
4698 10399 : return ccol_fd_reg_takes_condition(loop, entry, reg, is_write_direction);
4699 : }
4700 :
4701 : // The rest of the routing rule, for an error, a hang-up or a ready direction
4702 : // without a handler: on_error when there is one, else the direction's handler
4703 : // (its own read or write reports the condition and clears a socket error, as in
4704 : // libevent and libuv). When neither exists reg is muted, since the condition
4705 : // may stay true and repeat on every wait. Out of line and cold, so plain
4706 : // readiness keeps the short inlined path. The caller holds the stripe lock.
4707 : static __attribute__((noinline, cold)) fd_take
4708 10399 : ccol_fd_reg_takes_condition(struct ceventloop__s *loop, event_entry *entry,
4709 : ceventloop_reg_s *reg, bool is_write_direction) {
4710 10399 : if (reg->handlers.on_error) return FD_TAKE_ERROR;
4711 700 : if (is_write_direction ? reg->handlers.on_writable != NULL
4712 349 : : reg->handlers.on_readable != NULL)
4713 : return FD_TAKE_DIRECTION;
4714 10 : ccol_fd_reg_mute_locked(loop, entry, reg);
4715 10 : return FD_TAKE_NONE;
4716 : }
4717 :
4718 : // Mutes reg and re-arms its entry from live state, which takes reg out of the
4719 : // mask while a sibling direction with handlers stays armed. A pool event that
4720 : // arrives before the sibling's job finishes is dropped by the in-flight check,
4721 : // and the job's re-arm applies the live state again. The caller holds the
4722 : // stripe lock.
4723 10 : static __attribute__((noinline, cold)) void ccol_fd_reg_mute_locked(
4724 : struct ceventloop__s *loop, event_entry *entry, ceventloop_reg_s *reg) {
4725 10 : reg->muted = true;
4726 10 : ceventloop_rearm_entry_locked(loop, entry);
4727 10 : }
4728 :
4729 : // Fills a dispatch item for one direction of an fd entry from the routing
4730 : // decision take, so both dispatch paths build items the same way. A ready
4731 : // direction with a handler gives a readable or writable item; anything else is
4732 : // an error item. With fd_reg_interest_bits() never arming IN for a registration
4733 : // without a reader, IN there means the peer hung up. The selectable is copied
4734 : // into the item.
4735 399923 : static inline void ccol_fd_item_fill(dispatch_item *item, ceventloop_reg_s *reg,
4736 : fd_take take, bool is_write_direction) {
4737 399923 : bool dispatch_on_direction = (take == FD_TAKE_DIRECTION);
4738 399923 : item->reg = reg;
4739 399923 : item->is_readable = !is_write_direction && dispatch_on_direction;
4740 399923 : item->is_writable = is_write_direction && dispatch_on_direction;
4741 399923 : item->is_error = !dispatch_on_direction;
4742 399923 : item->sel_snapshot = reg->sel;
4743 : }
4744 :
4745 : // Calls the callback an item asks for, with the registration's own handle.
4746 : // Both dispatch paths use it. It checks removed and paused again right before
4747 : // the call, because the collection check is not enough: A remove or pause can
4748 : // finish between collection and this call (a long wait on the pool path), and
4749 : // the remover may already have freed arg.
4750 415980 : static void ceventloop_run_callback(ceventloop loop, dispatch_item *item) {
4751 415980 : ceventloop_reg_s *reg = item->reg;
4752 415980 : if (atomic_load(®->removed)) return;
4753 415971 : if (atomic_load(®->paused)) return;
4754 415635 : if (item->is_error) {
4755 10047 : if (reg->handlers.on_error)
4756 10047 : reg->handlers.on_error(loop, reg->self_handle, &item->sel_snapshot,
4757 : reg->arg);
4758 405588 : } else if (item->is_readable) {
4759 381073 : if (reg->handlers.on_readable)
4760 381073 : reg->handlers.on_readable(loop, reg->self_handle, &item->sel_snapshot,
4761 : reg->arg);
4762 24515 : } else if (item->is_writable) {
4763 24516 : if (reg->handlers.on_writable)
4764 24516 : reg->handlers.on_writable(loop, reg->self_handle, &item->sel_snapshot,
4765 : reg->arg);
4766 : }
4767 : }
4768 :
4769 : // Drops the reference a collection took on reg. When it was the last one and
4770 : // reg is removed, it defers reg and pings the poller, since on a worker this
4771 : // may be the call that makes reg reclaimable and the poller wouldn't know.
4772 : // Nothing is read off reg after the defer: No resolve pin holds it, so the
4773 : // poller may free it at once.
4774 415996 : static void ceventloop_release_after_dispatch(struct ceventloop__s *loop,
4775 : ceventloop_reg_s *reg) {
4776 415996 : int prev = atomic_fetch_sub(®->refcount, 1);
4777 415996 : if (prev == 1 && atomic_load(®->removed)) {
4778 1355 : ceventloop_defer_reg_free(loop, reg);
4779 1355 : eventfd_notify(loop->reclaim_wake_efd);
4780 : }
4781 415996 : }
4782 :
4783 : // Runs a queue item's callback with the thread marked as dispatching that
4784 : // queue, so a destroy of the queue from the callback is a fatal error instead
4785 : // of waiting for itself. The mark is cleared afterwards.
4786 16074 : static void queue_dispatch_run_callback(struct ceventloop__s *loop,
4787 : dispatch_item *item) {
4788 32148 : bool fell_back = queue_dispatch_mark(queue_sel_queue(&item->sel_snapshot));
4789 16074 : ceventloop_run_callback(loop->self_handle, item);
4790 16074 : queue_dispatch_unmark(fell_back);
4791 16074 : }
4792 :
4793 : // Dispatches one event on a loop with a single reactor thread, where the
4794 : // poller collects and runs callbacks itself. A NULL entry is the shutdown
4795 : // eventfd, which is never drained so every wait keeps seeing it. Otherwise it
4796 : // holds the entry's dispatch lock for the whole dispatch and the stripe lock
4797 : // only for the collection: It refines an fd event (safe there, since the fd is
4798 : // open while the entry isn't removed), routes it per direction through the
4799 : // shared rule, or consumes a queue registration's wake and claims its dispatch
4800 : // reference. Each collected registration gets a refcount; callbacks run with no
4801 : // stripe lock held, and a queue callback is followed by the cascade step and
4802 : // the release of the queue reference.
4803 427967 : static void ceventloop_handle_event(struct ceventloop__s *loop,
4804 : ccol_poll_event *ev) {
4805 427967 : event_entry *entry = (event_entry *)ev->data.ptr;
4806 :
4807 427967 : if (entry == NULL) {
4808 38540 : return;
4809 : }
4810 :
4811 389427 : ccol__mutex_lock(entry->dispatch_lock);
4812 :
4813 389427 : dispatch_item items[2];
4814 389427 : size_t n_items = 0;
4815 :
4816 389427 : ceventloop_stripe *stripe = &loop->stripes[entry->stripe_idx];
4817 389427 : ccol__mutex_lock(stripe->lock);
4818 389427 : if (entry->is_fd && !atomic_load(&entry->removed))
4819 762108 : ccol_poll_refine(
4820 : ev, entry->fd,
4821 381054 : fd_reg_interest_bits(entry->as.fd.read_reg, cselect_read) |
4822 381054 : fd_reg_interest_bits(entry->as.fd.write_reg, cselect_write),
4823 : &entry->poll_info);
4824 :
4825 389427 : if (entry->is_fd) {
4826 381219 : bool is_err = (ev->events & (CCOL_POLL_ERR | CCOL_POLL_HUP)) != 0;
4827 381219 : bool is_in = (ev->events & (CCOL_POLL_IN | CCOL_POLL_RDHUP)) != 0;
4828 381219 : bool is_out = (ev->events & CCOL_POLL_OUT) != 0;
4829 :
4830 381219 : ceventloop_reg_s *r = entry->as.fd.read_reg;
4831 381219 : fd_take r_take =
4832 381219 : ccol_fd_reg_takes_event(loop, entry, r, is_err, is_in, false);
4833 381219 : if (r_take != FD_TAKE_NONE) {
4834 367426 : atomic_fetch_add(&r->refcount, 1);
4835 367426 : ccol_fd_item_fill(&items[n_items], r, r_take, false);
4836 367426 : n_items++;
4837 : }
4838 381219 : ceventloop_reg_s *w = entry->as.fd.write_reg;
4839 381219 : fd_take w_take =
4840 381219 : ccol_fd_reg_takes_event(loop, entry, w, is_err, is_out, true);
4841 381219 : if (w_take != FD_TAKE_NONE) {
4842 18064 : atomic_fetch_add(&w->refcount, 1);
4843 18064 : ccol_fd_item_fill(&items[n_items], w, w_take, true);
4844 18064 : n_items++;
4845 : }
4846 : } else {
4847 8208 : ceventloop_reg_s *r = entry->as.reg;
4848 8208 : if (r && atomic_load(&r->removed)) {
4849 0 : queue_reg_consume_wake(r, NULL, NULL);
4850 8206 : } else if (r) {
4851 8206 : queue_reg_consume_wake(r, &items[n_items].queue_count_before,
4852 : &items[n_items].wake_hops);
4853 8206 : atomic_fetch_add(&r->refcount, 1);
4854 8206 : queue_dispatch_ref_acquire(&r->sel);
4855 8206 : items[n_items].reg = r;
4856 8206 : items[n_items].is_error = false;
4857 8206 : items[n_items].is_readable = (r->sel.dir == cselect_read);
4858 8206 : items[n_items].is_writable = (r->sel.dir == cselect_write);
4859 8206 : items[n_items].sel_snapshot = r->sel;
4860 8206 : n_items++;
4861 : }
4862 : }
4863 :
4864 389427 : ccol__mutex_unlock(stripe->lock);
4865 :
4866 783120 : for (size_t i = 0; i < n_items; i++) {
4867 393696 : if (entry->is_fd) {
4868 385490 : ceventloop_run_callback(loop->self_handle, &items[i]);
4869 : } else {
4870 8206 : queue_dispatch_run_callback(loop, &items[i]);
4871 8206 : ceventloop_queue_cascade_notify_next(
4872 : loop, items[i].reg, items[i].sel_snapshot.dir,
4873 : items[i].queue_count_before, items[i].wake_hops);
4874 16412 : queue_dispatch_ref_release(&items[i].sel_snapshot);
4875 : }
4876 393693 : ceventloop_release_after_dispatch(loop, items[i].reg);
4877 : }
4878 :
4879 389424 : ccol__mutex_unlock(entry->dispatch_lock);
4880 : }
4881 :
4882 : // One collected batch of up to two items for one entry, run as one pool job
4883 : // under one hold of the entry's dispatch lock, with the ordering of the single
4884 : // thread path. Each entry owns exactly one job as the tail of its allocation;
4885 : // the poller drops events for an entry with a job in flight, so a dispatch
4886 : // allocates nothing.
4887 : typedef struct dispatch_job {
4888 : struct ceventloop__s *loop;
4889 : event_entry *entry;
4890 : dispatch_item items[2];
4891 : size_t n_items;
4892 : } dispatch_job;
4893 :
4894 : // The layout of one entry allocation in a loop with a dispatch pool.
4895 : typedef struct event_entry_with_job {
4896 : event_entry entry;
4897 : dispatch_job job;
4898 : } event_entry_with_job;
4899 :
4900 : // Gives the size of one entry allocation of loop: With a dispatch pool the
4901 : // entry carries its job.
4902 42661 : static size_t ceventloop_entry_alloc_size(const struct ceventloop__s *loop) {
4903 42661 : return loop->dispatch_pool ? sizeof(event_entry_with_job)
4904 42661 : : sizeof(event_entry);
4905 : }
4906 :
4907 : // Gives the job storage of an entry of a loop with a dispatch pool, which the
4908 : // poller fills and a worker runs.
4909 21497 : static inline dispatch_job *ceventloop_entry_job(event_entry *entry) {
4910 21497 : return &((event_entry_with_job *)entry)->job;
4911 : }
4912 :
4913 : static void ceventloop_dispatch_job_fn(void *arg);
4914 :
4915 : // The thread-specific key that marks a loop's poller (for its whole life) and
4916 : // a dispatch worker running one of its jobs. Only the self-call guards of
4917 : // shutdown and destroy read it. One key covers every loop, since a pool's
4918 : // workers belong to one loop. live and the deletion work as for the queue
4919 : // dispatch marker; ceventloop_create_mp refuses to build a loop while live is
4920 : // false.
4921 : static struct {
4922 : ccol__thread_ls_key key;
4923 : ccol__once_flag once;
4924 : atomic_bool live;
4925 : } ceventloop_job_key_bundle = {.once = CCOL__ONCE_INIT};
4926 :
4927 : // Creates the job key once and records whether that worked.
4928 47 : static void ceventloop_init_job_key(void) {
4929 47 : if (ccol__thread_ls_key_create(ceventloop_job_key_bundle.key, NULL) == 0)
4930 46 : atomic_store(&ceventloop_job_key_bundle.live, true);
4931 47 : }
4932 :
4933 : // The job mark of a thread whose key store failed, as
4934 : // queue_dispatch_mark_fallback.
4935 : static __thread const void *ceventloop_job_mark_fallback;
4936 :
4937 : // Marks the calling thread as loop's poller or one of its dispatch workers, for
4938 : // the self-call guards. Gives true when the fallback copy holds the mark; pass
4939 : // that to ceventloop_job_unmark().
4940 60856 : static bool ceventloop_job_mark(struct ceventloop__s *loop) {
4941 60852 : if (cthreadcomm_mark_set(ceventloop_job_key_bundle.key, loop) == 0)
4942 : return false;
4943 4 : ceventloop_job_mark_fallback = loop;
4944 4 : return true;
4945 : }
4946 :
4947 : // Clears what ceventloop_job_mark() set, when a job or the poller thread ends,
4948 : // so no later work on the thread carries the mark.
4949 60837 : static void ceventloop_job_unmark(bool fell_back) {
4950 60837 : if (fell_back)
4951 4 : ceventloop_job_mark_fallback = NULL;
4952 : else
4953 60833 : (void)ccol__thread_ls_set(ceventloop_job_key_bundle.key, NULL);
4954 : }
4955 :
4956 : // Says whether the calling thread is loop's poller or runs one of its dispatch
4957 : // jobs. The self-call guards of shutdown and destroy ask it, because such a
4958 : // call would join or free the thread it runs on.
4959 120634 : static bool ceventloop_job_marked(const struct ceventloop__s *loop) {
4960 120634 : ccol__call_once(ceventloop_job_key_bundle.once, ceventloop_init_job_key);
4961 120634 : return ccol__thread_ls_get(ceventloop_job_key_bundle.key) ==
4962 120634 : (const void *)loop ||
4963 118121 : ceventloop_job_mark_fallback == (const void *)loop;
4964 : }
4965 :
4966 : // The poller's half of a dispatch on a loop with a dispatch pool: Collects an
4967 : // entry's items under the stripe lock (no dispatch lock; there's one poller)
4968 : // and submits the entry's own job to the pool. An event for an entry whose job
4969 : // is still queued or running is dropped, because a callback that calls modify
4970 : // can re-arm the fd before it frees state that a second job would read; the
4971 : // running job's own re-arm reflects the live state. A queue's wake isn't
4972 : // consumed here and no queue reference is claimed; the job does both when it
4973 : // runs. On a successful collect the entry's refcount goes up. A failed submit
4974 : // releases the item references, re-arms the entry (the one-shot event is spent)
4975 : // and gives true, so the poller backs off.
4976 23612 : static bool ceventloop_poller_collect(struct ceventloop__s *loop,
4977 : ccol_poll_event *ev) {
4978 23612 : event_entry *entry = (event_entry *)ev->data.ptr;
4979 23612 : if (entry == NULL) return false;
4980 :
4981 23154 : ceventloop_stripe *stripe = &loop->stripes[entry->stripe_idx];
4982 23154 : ccol__mutex_lock(stripe->lock);
4983 23154 : if (entry->is_fd && !atomic_load(&entry->removed))
4984 30542 : ccol_poll_refine(
4985 : ev, entry->fd,
4986 15271 : fd_reg_interest_bits(entry->as.fd.read_reg, cselect_read) |
4987 15271 : fd_reg_interest_bits(entry->as.fd.write_reg, cselect_write),
4988 : &entry->poll_info);
4989 :
4990 23154 : if (atomic_load(&entry->refcount) > 0) {
4991 1657 : ccol__mutex_unlock(stripe->lock);
4992 1657 : return false;
4993 : }
4994 :
4995 21497 : dispatch_job *job = ceventloop_entry_job(entry);
4996 21497 : job->loop = loop;
4997 21497 : job->entry = entry;
4998 21497 : job->n_items = 0;
4999 :
5000 21497 : if (entry->is_fd) {
5001 13615 : bool is_err = (ev->events & (CCOL_POLL_ERR | CCOL_POLL_HUP)) != 0;
5002 13615 : bool is_in = (ev->events & (CCOL_POLL_IN | CCOL_POLL_RDHUP)) != 0;
5003 13615 : bool is_out = (ev->events & CCOL_POLL_OUT) != 0;
5004 :
5005 13615 : ceventloop_reg_s *r = entry->as.fd.read_reg;
5006 13615 : fd_take r_take =
5007 13615 : ccol_fd_reg_takes_event(loop, entry, r, is_err, is_in, false);
5008 13615 : if (r_take != FD_TAKE_NONE) {
5009 8291 : atomic_fetch_add(&r->refcount, 1);
5010 8291 : ccol_fd_item_fill(&job->items[job->n_items], r, r_take, false);
5011 8291 : job->n_items++;
5012 : }
5013 13615 : ceventloop_reg_s *w = entry->as.fd.write_reg;
5014 13615 : fd_take w_take =
5015 13615 : ccol_fd_reg_takes_event(loop, entry, w, is_err, is_out, true);
5016 13615 : if (w_take != FD_TAKE_NONE) {
5017 6142 : atomic_fetch_add(&w->refcount, 1);
5018 6142 : ccol_fd_item_fill(&job->items[job->n_items], w, w_take, true);
5019 6142 : job->n_items++;
5020 : }
5021 : } else {
5022 7882 : ceventloop_reg_s *r = entry->as.reg;
5023 7882 : if (r && !atomic_load(&r->removed)) {
5024 7882 : atomic_fetch_add(&r->refcount, 1);
5025 7882 : dispatch_item *item = &job->items[job->n_items];
5026 7882 : item->reg = r;
5027 7882 : item->is_error = false;
5028 7882 : item->is_readable = (r->sel.dir == cselect_read);
5029 7882 : item->is_writable = (r->sel.dir == cselect_write);
5030 7882 : item->sel_snapshot = r->sel;
5031 7882 : job->n_items++;
5032 : }
5033 : }
5034 :
5035 21497 : if (job->n_items == 0) {
5036 5 : ccol__mutex_unlock(stripe->lock);
5037 5 : return false;
5038 : }
5039 :
5040 21492 : atomic_fetch_add(&entry->refcount, 1);
5041 21492 : ccol__mutex_unlock(stripe->lock);
5042 :
5043 21492 : ccol_retval rv = cthrpool_submit(loop->dispatch_pool,
5044 : ceventloop_dispatch_job_fn, job, NULL);
5045 21492 : if (rv != ccol_success) {
5046 24 : for (size_t i = 0; i < job->n_items; i++)
5047 12 : ceventloop_release_after_dispatch(loop, job->items[i].reg);
5048 12 : ccol__mutex_lock(stripe->lock);
5049 12 : ceventloop_rearm_entry_locked(loop, entry);
5050 12 : atomic_fetch_sub(&entry->refcount, 1);
5051 12 : ccol__mutex_unlock(stripe->lock);
5052 12 : return true;
5053 : }
5054 : return false;
5055 : }
5056 :
5057 : // The pool task that runs one entry's job on a dispatch worker, marked as a
5058 : // worker of the loop. It holds the entry's dispatch lock across the callbacks.
5059 : // For a queue item it checks under the stripe lock that the registration isn't
5060 : // removed, and only then claims the queue reference and consumes the wake (the
5061 : // queue of a removed registration may be gone); after the callback come the
5062 : // cascade step and the release. Then it re-arms the entry and drops its
5063 : // refcount together under the stripe lock, re-arm first: A reclaim needs the
5064 : // refcount at 0, and the poller must never see the re-arm without the drop, or
5065 : // it would discard a new event that one-shot has already spent.
5066 21475 : static void ceventloop_dispatch_job_fn(void *arg) {
5067 21475 : dispatch_job *job = (dispatch_job *)arg;
5068 21475 : struct ceventloop__s *loop = job->loop;
5069 21475 : event_entry *entry = job->entry;
5070 :
5071 21475 : ccol__call_once(ceventloop_job_key_bundle.once, ceventloop_init_job_key);
5072 21477 : bool fell_back = ceventloop_job_mark(loop);
5073 :
5074 21473 : ceventloop_stripe *stripe = &loop->stripes[entry->stripe_idx];
5075 :
5076 21473 : ccol__mutex_lock(entry->dispatch_lock);
5077 43763 : for (size_t i = 0; i < job->n_items; i++) {
5078 22299 : dispatch_item *item = &job->items[i];
5079 22299 : if (entry->is_fd) {
5080 14418 : ceventloop_run_callback(loop->self_handle, item);
5081 : } else {
5082 7881 : ccol__mutex_lock(stripe->lock);
5083 7882 : bool live = !atomic_load(&item->reg->removed);
5084 7882 : if (live) {
5085 7868 : queue_dispatch_ref_acquire(&item->sel_snapshot);
5086 7868 : queue_reg_consume_wake(item->reg, &item->queue_count_before,
5087 : &item->wake_hops);
5088 : }
5089 7882 : ccol__mutex_unlock(stripe->lock);
5090 7882 : if (live) {
5091 7868 : queue_dispatch_run_callback(loop, item);
5092 7868 : ceventloop_queue_cascade_notify_next(
5093 : loop, item->reg, item->sel_snapshot.dir, item->queue_count_before,
5094 : item->wake_hops);
5095 15736 : queue_dispatch_ref_release(&item->sel_snapshot);
5096 : }
5097 : }
5098 22293 : ceventloop_release_after_dispatch(loop, item->reg);
5099 : }
5100 21467 : ccol__mutex_unlock(entry->dispatch_lock);
5101 :
5102 21470 : ccol__mutex_lock(stripe->lock);
5103 21469 : ceventloop_rearm_entry_locked(loop, entry);
5104 21475 : atomic_fetch_sub(&entry->refcount, 1);
5105 21475 : ccol__mutex_unlock(stripe->lock);
5106 :
5107 21476 : ceventloop_job_unmark(fell_back);
5108 21476 : }
5109 :
5110 : // The poller's wait limit while a reclaim is pending: The guarantee that the
5111 : // reclaim runs, since a ping can be missed. 50 ms costs one wake and one list
5112 : // scan per interval, only while something is pending.
5113 : #define CEVENTLOOP_RECLAIM_RETRY_MS 50
5114 :
5115 : // The first and the longest pause of ceventloop_dispatch_backoff().
5116 : #define CEVENTLOOP_DISPATCH_BACKOFF_MIN_MS 1
5117 : #define CEVENTLOOP_DISPATCH_BACKOFF_MAX_MS 64
5118 :
5119 : // Pauses the poller after a batch with a failed submit, since the re-armed fd
5120 : // reports again at once and a lasting allocation failure would spin it. The
5121 : // pause in *backoff_ms doubles per failed batch up to the maximum, and the
5122 : // caller resets it after a good batch. It waits on shutdown_efd, so a shutdown
5123 : // ends it at once.
5124 12 : static __attribute__((noinline, cold)) void ceventloop_dispatch_backoff(
5125 : struct ceventloop__s *loop, int *backoff_ms) {
5126 24 : *backoff_ms =
5127 12 : *backoff_ms == 0 ? CEVENTLOOP_DISPATCH_BACKOFF_MIN_MS : *backoff_ms * 2;
5128 12 : if (*backoff_ms > CEVENTLOOP_DISPATCH_BACKOFF_MAX_MS)
5129 5 : *backoff_ms = CEVENTLOOP_DISPATCH_BACKOFF_MAX_MS;
5130 12 : struct pollfd pfd = {.fd = loop->shutdown_efd, .events = POLLIN};
5131 12 : (void)poll(&pfd, 1, *backoff_ms);
5132 12 : }
5133 :
5134 : // The poller thread of a loop. It's marked as the loop's poller for its whole
5135 : // life (callbacks and on_removed run here, and the guards go by that mark, not
5136 : // by thread ID, since a joined thread's ID gets reused). Each pass, until
5137 : // shutting_down, it bumps poller_batch_gen and reclaims what that makes safe,
5138 : // then waits, with CEVENTLOOP_RECLAIM_RETRY_MS as the limit while something is
5139 : // still pending. The reclaim ping is only drained. Every other event is
5140 : // dispatched inline with one thread or collected for the pool, and a batch with
5141 : // a failed submit backs off.
5142 39379 : static void *ceventloop_thread_fn(void *arg) {
5143 39379 : struct ceventloop__s *loop = (struct ceventloop__s *)arg;
5144 39379 : ccol_poll_event *events = loop->poller_events;
5145 39379 : int backoff_ms = 0;
5146 :
5147 78758 : bool fell_back = ceventloop_job_mark(loop);
5148 :
5149 327500 : for (;;) {
5150 327500 : if (atomic_load(&loop->shutting_down)) break;
5151 :
5152 288139 : atomic_fetch_add(&loop->poller_batch_gen, (uint64_t)1);
5153 288139 : bool reclaim_still_pending = ceventloop_reclaim_pending_frees(loop);
5154 :
5155 576278 : int wait_timeout_ms =
5156 288139 : reclaim_still_pending ? CEVENTLOOP_RECLAIM_RETRY_MS : -1;
5157 288139 : int n = ccol_poll_wait(loop->epfd, events, (int)loop->max_events_per_wait,
5158 : wait_timeout_ms);
5159 : #ifdef RUNNING_UNIT_TESTS
5160 288124 : atomic_fetch_add(&loop->poller_iterations_for_tests, (uint64_t)1);
5161 : #endif
5162 288124 : if (n < 0) {
5163 0 : if (errno == EINTR) continue;
5164 : break;
5165 : }
5166 : bool dispatch_failed = false;
5167 746685 : for (int i = 0; i < n; i++) {
5168 458564 : if (events[i].data.ptr == &loop->reclaim_wake_efd) {
5169 6985 : eventfd_drain(loop->reclaim_wake_efd);
5170 6985 : continue;
5171 : }
5172 451579 : if (loop->dispatch_pool) {
5173 23612 : dispatch_failed |= ceventloop_poller_collect(loop, &events[i]);
5174 : } else {
5175 427967 : ceventloop_handle_event(loop, &events[i]);
5176 : }
5177 : }
5178 288121 : if (__builtin_expect(dispatch_failed, 0))
5179 12 : ceventloop_dispatch_backoff(loop, &backoff_ms);
5180 : else
5181 288109 : backoff_ms = 0;
5182 : }
5183 :
5184 39361 : ceventloop_job_unmark(fell_back);
5185 39361 : return NULL;
5186 : }
5187 :
5188 : // Destroys the first created stripes (map and mutex) and frees the array, to
5189 : // roll back a failed ceventloop_create_mp. It frees through mmgmt_procs, since
5190 : // loop->m_procs may not be filled in yet.
5191 15 : static void destroy_stripes(struct ceventloop__s *loop,
5192 : ccol_memmgmt_procs *mmgmt_procs, size_t created) {
5193 33 : for (size_t i = 0; i < created; i++) {
5194 18 : chmap_destroy(loop->stripes[i].fd_index);
5195 18 : ccol__mutex_destroy(loop->stripes[i].lock);
5196 : }
5197 15 : ccol__mem_free(mmgmt_procs, loop->stripes);
5198 15 : }
5199 :
5200 : static void ceventloop_teardown_raw(struct ceventloop__s *loop);
5201 :
5202 : // Creates a loop with its poll set, shutdown and reclaim eventfds, locks,
5203 : // registration table, stripes, the poller's event buffer, the dispatch pool
5204 : // (with more than one thread; its queue is unbounded so the poller never
5205 : // blocks) and the poller thread, and gives its handle, or CEVENTLOOP_NULL with
5206 : // *err_str set. max_events_per_wait must fit an int and its buffer size must
5207 : // not overflow, or the poller's first wait would fail and the handle would
5208 : // never dispatch. A process without the two thread-specific keys a dispatch
5209 : // sets gets no loop. Everything that can fail runs before the thread starts.
5210 : // The handle slot is taken last; when that fails the running threads are
5211 : // stopped through ceventloop_teardown_raw().
5212 39414 : ceventloop ceventloop_create_mp(size_t max_events_per_wait,
5213 : size_t num_lock_stripes,
5214 : size_t num_reactor_threads,
5215 : ccol_memmgmt_procs *mmgmt_procs,
5216 : char **err_str) {
5217 39414 : if (max_events_per_wait == 0) {
5218 0 : if (err_str)
5219 0 : *err_str = CCOL__ERR_STR("max_events_per_wait must be positive");
5220 0 : return CEVENTLOOP_NULL;
5221 : }
5222 39414 : if (max_events_per_wait > (size_t)INT_MAX) {
5223 2 : if (err_str)
5224 2 : *err_str = CCOL__ERR_STR("max_events_per_wait must not exceed INT_MAX");
5225 2 : return CEVENTLOOP_NULL;
5226 : }
5227 39412 : if (max_events_per_wait > SIZE_MAX / sizeof(ccol_poll_event)) {
5228 : if (err_str)
5229 : *err_str = CCOL__ERR_STR(
5230 : "max_events_per_wait is too large: max_events_per_wait * "
5231 : "sizeof(ccol_poll_event) would overflow size_t");
5232 : return CEVENTLOOP_NULL;
5233 : }
5234 39412 : if (num_lock_stripes == 0) {
5235 1 : if (err_str) *err_str = CCOL__ERR_STR("num_lock_stripes must be positive");
5236 1 : return CEVENTLOOP_NULL;
5237 : }
5238 39411 : if (num_reactor_threads == 0) {
5239 0 : if (err_str)
5240 0 : *err_str = CCOL__ERR_STR("num_reactor_threads must be positive");
5241 0 : return CEVENTLOOP_NULL;
5242 : }
5243 39411 : if (!ccol__verify_memmgmt_procs(mmgmt_procs, err_str)) {
5244 0 : return CEVENTLOOP_NULL;
5245 : }
5246 :
5247 39411 : ccol__call_once(ceventloop_job_key_bundle.once, ceventloop_init_job_key);
5248 78819 : if (!atomic_load(&ceventloop_job_key_bundle.live) ||
5249 39408 : !queue_dispatch_marker_available()) {
5250 3 : if (err_str)
5251 3 : *err_str =
5252 : CCOL__ERR_STR("failed to create a thread-local key of ceventloop");
5253 3 : return CEVENTLOOP_NULL;
5254 : }
5255 :
5256 39408 : struct ceventloop__s *loop = (struct ceventloop__s *)ccol__mem_alloc(
5257 : mmgmt_procs, sizeof(struct ceventloop__s));
5258 39408 : if (!loop) {
5259 2 : if (err_str)
5260 2 : *err_str = CCOL__ERR_STR("Failed to allocate memory for ceventloop");
5261 2 : return CEVENTLOOP_NULL;
5262 : }
5263 :
5264 39406 : if (!ccol__populate_mem_mgmt_procs(loop, mmgmt_procs, err_str)) {
5265 2 : ccol__mem_free(mmgmt_procs, loop);
5266 2 : return CEVENTLOOP_NULL;
5267 : }
5268 :
5269 39404 : loop->epfd = ccol_poll_create();
5270 39404 : if (loop->epfd < 0) {
5271 0 : if (err_str) *err_str = CCOL__ERR_STR("epoll_create1 failed");
5272 0 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5273 0 : ccol__mem_free(mmgmt_procs, loop);
5274 0 : return CEVENTLOOP_NULL;
5275 : }
5276 :
5277 39404 : loop->shutdown_efd = ccol_wakefd_create();
5278 39404 : if (loop->shutdown_efd < 0) {
5279 0 : if (err_str) *err_str = CCOL__ERR_STR("eventfd failed");
5280 0 : close(loop->epfd);
5281 0 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5282 0 : ccol__mem_free(mmgmt_procs, loop);
5283 0 : return CEVENTLOOP_NULL;
5284 : }
5285 :
5286 39404 : ccol_poll_event ev;
5287 39404 : ev.data.ptr = NULL;
5288 39404 : ev.events = CCOL_POLL_IN;
5289 39404 : if (ccol_poll_ctl(loop->epfd, CCOL_POLL_CTL_ADD, loop->shutdown_efd, &ev,
5290 : NULL) < 0) {
5291 0 : if (err_str)
5292 0 : *err_str = CCOL__ERR_STR("epoll_ctl failed registering shutdown eventfd");
5293 0 : close(loop->shutdown_efd);
5294 0 : close(loop->epfd);
5295 0 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5296 0 : ccol__mem_free(mmgmt_procs, loop);
5297 0 : return CEVENTLOOP_NULL;
5298 : }
5299 :
5300 39404 : loop->reclaim_wake_efd = ccol_wakefd_create();
5301 39404 : if (loop->reclaim_wake_efd < 0) {
5302 0 : if (err_str) *err_str = CCOL__ERR_STR("eventfd failed");
5303 0 : close(loop->shutdown_efd);
5304 0 : close(loop->epfd);
5305 0 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5306 0 : ccol__mem_free(mmgmt_procs, loop);
5307 0 : return CEVENTLOOP_NULL;
5308 : }
5309 :
5310 39404 : ev.data.ptr = &loop->reclaim_wake_efd;
5311 39404 : ev.events = CCOL_POLL_IN;
5312 39404 : if (ccol_poll_ctl(loop->epfd, CCOL_POLL_CTL_ADD, loop->reclaim_wake_efd, &ev,
5313 : NULL) < 0) {
5314 0 : if (err_str)
5315 0 : *err_str =
5316 : CCOL__ERR_STR("epoll_ctl failed registering reclaim-wake eventfd");
5317 0 : close(loop->reclaim_wake_efd);
5318 0 : close(loop->shutdown_efd);
5319 0 : close(loop->epfd);
5320 0 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5321 0 : ccol__mem_free(mmgmt_procs, loop);
5322 0 : return CEVENTLOOP_NULL;
5323 : }
5324 :
5325 39404 : if (ccol__mutex_init(loop->shutdown_lock) != 0) {
5326 0 : if (err_str) *err_str = CCOL__ERR_STR("Failed to initialize shutdown_lock");
5327 0 : close(loop->reclaim_wake_efd);
5328 0 : close(loop->shutdown_efd);
5329 0 : close(loop->epfd);
5330 0 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5331 0 : ccol__mem_free(mmgmt_procs, loop);
5332 0 : return CEVENTLOOP_NULL;
5333 : }
5334 39404 : if (ccol__cond_var_init(loop->joined_cv) != 0) {
5335 0 : if (err_str) *err_str = CCOL__ERR_STR("Failed to initialize joined_cv");
5336 0 : ccol__mutex_destroy(loop->shutdown_lock);
5337 0 : close(loop->reclaim_wake_efd);
5338 0 : close(loop->shutdown_efd);
5339 0 : close(loop->epfd);
5340 0 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5341 0 : ccol__mem_free(mmgmt_procs, loop);
5342 0 : return CEVENTLOOP_NULL;
5343 : }
5344 39404 : if (ccol__rw_lock_init(loop->reg_slot_rwlock) != 0) {
5345 0 : if (err_str)
5346 0 : *err_str = CCOL__ERR_STR("Failed to initialize reg_slot_rwlock");
5347 0 : ccol__cond_var_destroy(loop->joined_cv);
5348 0 : ccol__mutex_destroy(loop->shutdown_lock);
5349 0 : close(loop->reclaim_wake_efd);
5350 0 : close(loop->shutdown_efd);
5351 0 : close(loop->epfd);
5352 0 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5353 0 : ccol__mem_free(mmgmt_procs, loop);
5354 0 : return CEVENTLOOP_NULL;
5355 : }
5356 78808 : loop->reg_slots =
5357 39404 : cvector_create_full(sizeof(ceventloop_reg_slot), mmgmt_procs, NULL);
5358 39404 : if (!loop->reg_slots) {
5359 4 : if (err_str) *err_str = CCOL__ERR_STR("Failed to allocate reg slot array");
5360 4 : ccol__rw_lock_destroy(loop->reg_slot_rwlock);
5361 4 : ccol__cond_var_destroy(loop->joined_cv);
5362 4 : ccol__mutex_destroy(loop->shutdown_lock);
5363 4 : close(loop->reclaim_wake_efd);
5364 4 : close(loop->shutdown_efd);
5365 4 : close(loop->epfd);
5366 4 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5367 4 : ccol__mem_free(mmgmt_procs, loop);
5368 4 : return CEVENTLOOP_NULL;
5369 : }
5370 39400 : loop->reg_lost_indices = 0;
5371 78800 : loop->reg_free_indices =
5372 39400 : cvector_create_full(sizeof(uint32_t), mmgmt_procs, NULL);
5373 39400 : if (!loop->reg_free_indices) {
5374 4 : if (err_str)
5375 4 : *err_str = CCOL__ERR_STR("Failed to allocate reg free-index array");
5376 4 : cvector__destroy(loop->reg_slots);
5377 4 : ccol__rw_lock_destroy(loop->reg_slot_rwlock);
5378 4 : ccol__cond_var_destroy(loop->joined_cv);
5379 4 : ccol__mutex_destroy(loop->shutdown_lock);
5380 4 : close(loop->reclaim_wake_efd);
5381 4 : close(loop->shutdown_efd);
5382 4 : close(loop->epfd);
5383 4 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5384 4 : ccol__mem_free(mmgmt_procs, loop);
5385 4 : return CEVENTLOOP_NULL;
5386 : }
5387 39396 : loop->shutdown_started = false;
5388 39396 : loop->joined = false;
5389 39396 : loop->destroy_claimed = false;
5390 39396 : atomic_init(&loop->shutting_down, false);
5391 39396 : loop->max_events_per_wait = max_events_per_wait;
5392 39396 : atomic_init(&loop->pending_entry_frees, NULL);
5393 39396 : atomic_init(&loop->pending_reg_frees, NULL);
5394 39396 : atomic_init(&loop->poller_batch_gen, (uint64_t)0);
5395 39396 : atomic_init(&loop->fd_generation_counter, (uint64_t)0);
5396 39396 : atomic_init(&loop->next_queue_stripe, (size_t)0);
5397 39396 : atomic_init(&loop->reg_count, (size_t)0);
5398 : #ifdef RUNNING_UNIT_TESTS
5399 39396 : atomic_init(&loop->poller_iterations_for_tests, (uint64_t)0);
5400 39396 : atomic_init(&loop->entries_reclaimed_for_tests, (uint64_t)0);
5401 : #endif
5402 39396 : loop->num_stripes = num_lock_stripes;
5403 39396 : loop->num_reactor_threads = num_reactor_threads;
5404 39396 : loop->dispatch_pool = CTHRPOOL_NULL;
5405 :
5406 39396 : loop->stripes = ccol__mem_calloc(mmgmt_procs, num_lock_stripes,
5407 : sizeof(ceventloop_stripe));
5408 39396 : if (!loop->stripes) {
5409 2 : if (err_str)
5410 2 : *err_str = CCOL__ERR_STR("Failed to allocate lock stripe array");
5411 2 : cvector_destroy(loop->reg_free_indices);
5412 2 : cvector_destroy(loop->reg_slots);
5413 2 : ccol__rw_lock_destroy(loop->reg_slot_rwlock);
5414 2 : ccol__cond_var_destroy(loop->joined_cv);
5415 2 : ccol__mutex_destroy(loop->shutdown_lock);
5416 2 : close(loop->reclaim_wake_efd);
5417 2 : close(loop->shutdown_efd);
5418 2 : close(loop->epfd);
5419 2 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5420 2 : ccol__mem_free(mmgmt_procs, loop);
5421 2 : return CEVENTLOOP_NULL;
5422 : }
5423 :
5424 : size_t stripes_created = 0;
5425 80406 : for (; stripes_created < num_lock_stripes; stripes_created++) {
5426 41020 : char *stripe_err = NULL;
5427 41020 : loop->stripes[stripes_created].fd_index = chashmap_create_full(
5428 : CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE, ccol_int, ccol_pointer,
5429 : mmgmt_procs, NULL, NULL, &stripe_err);
5430 41020 : if (!loop->stripes[stripes_created].fd_index) {
5431 8 : if (err_str)
5432 8 : *err_str = stripe_err ? stripe_err
5433 8 : : CCOL__ERR_STR("Failed to create fd registry");
5434 8 : destroy_stripes(loop, mmgmt_procs, stripes_created);
5435 8 : cvector_destroy(loop->reg_free_indices);
5436 8 : cvector_destroy(loop->reg_slots);
5437 8 : ccol__rw_lock_destroy(loop->reg_slot_rwlock);
5438 8 : ccol__cond_var_destroy(loop->joined_cv);
5439 8 : ccol__mutex_destroy(loop->shutdown_lock);
5440 8 : close(loop->reclaim_wake_efd);
5441 8 : close(loop->shutdown_efd);
5442 8 : close(loop->epfd);
5443 8 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5444 8 : ccol__mem_free(mmgmt_procs, loop);
5445 8 : return CEVENTLOOP_NULL;
5446 : }
5447 41012 : if (ccol__mutex_init(loop->stripes[stripes_created].lock) != 0) {
5448 0 : if (err_str) *err_str = CCOL__ERR_STR("Failed to initialize stripe lock");
5449 0 : chmap_destroy(loop->stripes[stripes_created].fd_index);
5450 0 : destroy_stripes(loop, mmgmt_procs, stripes_created);
5451 0 : cvector_destroy(loop->reg_free_indices);
5452 0 : cvector_destroy(loop->reg_slots);
5453 0 : ccol__rw_lock_destroy(loop->reg_slot_rwlock);
5454 0 : ccol__cond_var_destroy(loop->joined_cv);
5455 0 : ccol__mutex_destroy(loop->shutdown_lock);
5456 0 : close(loop->reclaim_wake_efd);
5457 0 : close(loop->shutdown_efd);
5458 0 : close(loop->epfd);
5459 0 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5460 0 : ccol__mem_free(mmgmt_procs, loop);
5461 0 : return CEVENTLOOP_NULL;
5462 : }
5463 41012 : loop->stripes[stripes_created].queue_regs_head = NULL;
5464 : }
5465 :
5466 39386 : loop->poller_events = ccol__mem_alloc(
5467 : mmgmt_procs, max_events_per_wait * sizeof(ccol_poll_event));
5468 39386 : if (!loop->poller_events) {
5469 4 : if (err_str)
5470 4 : *err_str = CCOL__ERR_STR("Failed to allocate the epoll_wait buffer");
5471 4 : destroy_stripes(loop, mmgmt_procs, num_lock_stripes);
5472 4 : cvector_destroy(loop->reg_free_indices);
5473 4 : cvector_destroy(loop->reg_slots);
5474 4 : ccol__rw_lock_destroy(loop->reg_slot_rwlock);
5475 4 : ccol__cond_var_destroy(loop->joined_cv);
5476 4 : ccol__mutex_destroy(loop->shutdown_lock);
5477 4 : close(loop->reclaim_wake_efd);
5478 4 : close(loop->shutdown_efd);
5479 4 : close(loop->epfd);
5480 4 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5481 4 : ccol__mem_free(mmgmt_procs, loop);
5482 4 : return CEVENTLOOP_NULL;
5483 : }
5484 :
5485 39382 : if (num_reactor_threads > 1) {
5486 503 : char *pool_err = NULL;
5487 1006 : loop->dispatch_pool =
5488 503 : cthrpool_create_mp(num_reactor_threads - 1, 0, mmgmt_procs, &pool_err);
5489 503 : if (!loop->dispatch_pool) {
5490 3 : if (err_str)
5491 3 : *err_str = pool_err ? pool_err
5492 3 : : CCOL__ERR_STR("Failed to create dispatch pool");
5493 3 : ccol__mem_free(mmgmt_procs, loop->poller_events);
5494 3 : destroy_stripes(loop, mmgmt_procs, num_lock_stripes);
5495 3 : cvector_destroy(loop->reg_free_indices);
5496 3 : cvector_destroy(loop->reg_slots);
5497 3 : ccol__rw_lock_destroy(loop->reg_slot_rwlock);
5498 3 : ccol__cond_var_destroy(loop->joined_cv);
5499 3 : ccol__mutex_destroy(loop->shutdown_lock);
5500 3 : close(loop->reclaim_wake_efd);
5501 3 : close(loop->shutdown_efd);
5502 3 : close(loop->epfd);
5503 3 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5504 3 : ccol__mem_free(mmgmt_procs, loop);
5505 3 : return CEVENTLOOP_NULL;
5506 : }
5507 : }
5508 :
5509 39379 : if (ccol__thread_create(loop->poller_thread, ceventloop_thread_fn, loop) !=
5510 : 0) {
5511 0 : if (err_str) *err_str = CCOL__ERR_STR("pthread_create failed");
5512 0 : if (loop->dispatch_pool) cthrpool__destroy(loop->dispatch_pool);
5513 0 : ccol__mem_free(mmgmt_procs, loop->poller_events);
5514 0 : destroy_stripes(loop, mmgmt_procs, num_lock_stripes);
5515 0 : cvector_destroy(loop->reg_free_indices);
5516 0 : cvector_destroy(loop->reg_slots);
5517 0 : ccol__rw_lock_destroy(loop->reg_slot_rwlock);
5518 0 : ccol__cond_var_destroy(loop->joined_cv);
5519 0 : ccol__mutex_destroy(loop->shutdown_lock);
5520 0 : close(loop->reclaim_wake_efd);
5521 0 : close(loop->shutdown_efd);
5522 0 : close(loop->epfd);
5523 0 : ccol__mem_free(mmgmt_procs, loop->m_procs);
5524 0 : ccol__mem_free(mmgmt_procs, loop);
5525 0 : return CEVENTLOOP_NULL;
5526 : }
5527 :
5528 39379 : atomic_init(&loop->pending_resolve_count, (size_t)0);
5529 : #if CCOL_FORK_SAFETY_REQUIRED
5530 39379 : atomic_init(&loop->foreign_since_fork, false);
5531 : #endif
5532 :
5533 39379 : ceventloop h = ceventloop_handle_slot_acquire(loop);
5534 39379 : if (h == 0) {
5535 0 : if (err_str)
5536 0 : *err_str = CCOL__ERR_STR("Failed to allocate ceventloop handle slot");
5537 0 : ceventloop_teardown_raw(loop);
5538 0 : return CEVENTLOOP_NULL;
5539 : }
5540 39379 : loop->self_handle = h;
5541 :
5542 39379 : if (err_str) *err_str = NULL;
5543 : return h;
5544 : }
5545 :
5546 : // Unlinks the waiter node of every queue registration of loop once nothing in
5547 : // it dispatches, so the shut-down loop doesn't keep taking wakes the queue's
5548 : // other listeners need. A wake moves on when the queue is ready, as on a
5549 : // remove, and the queue counts the registration as detached. Takes each stripe
5550 : // lock, then each queue's mutex.
5551 39358 : static void ceventloop_detach_queue_regs(struct ceventloop__s *loop) {
5552 80286 : for (size_t i = 0; i < loop->num_stripes; i++) {
5553 40928 : ceventloop_stripe *stripe = &loop->stripes[i];
5554 40928 : ccol__mutex_lock(stripe->lock);
5555 40975 : for (ceventloop_reg_s *reg = stripe->queue_regs_head; reg;
5556 47 : reg = reg->loop_list_next) {
5557 47 : ccol__mutex *q_mtx;
5558 47 : ccol_sel_waiter **q_head;
5559 47 : ccol_sel_waiter **q_rotor;
5560 47 : queue_sel_locate(®->sel, &q_mtx, &q_head, &q_rotor);
5561 47 : ccol__mutex_lock(*q_mtx);
5562 47 : if (!reg->waiter_detached && !atomic_load(®->removed)) {
5563 47 : sel_unlink_waiter_locked(®->waiter_node, q_head, q_rotor);
5564 47 : reg->waiter_detached = true;
5565 47 : (*queue_sel_detached_count(®->sel))++;
5566 47 : if (queue_sel_is_ready(®->sel))
5567 3 : notify_one_sel_waiter(q_head, q_rotor);
5568 : }
5569 47 : ccol__mutex_unlock(*q_mtx);
5570 : }
5571 40928 : ccol__mutex_unlock(stripe->lock);
5572 : }
5573 39358 : }
5574 :
5575 : // Stops a resolved loop: The shutdown and teardown paths use it. A call from
5576 : // the loop's poller or one of its dispatch workers gives ccol_not_permitted,
5577 : // since it would join itself. The first caller (under shutdown_lock) sets
5578 : // shutting_down, writes shutdown_efd, which nothing drains, so the poller
5579 : // always sees it, and joins the poller; an inherited loop skips both, since its
5580 : // poller doesn't exist here and the eventfd is the parent's. Then it drains the
5581 : // pool (no submit can come once the poller is joined), detaches the queue
5582 : // registrations and wakes the other callers, who wait on joined_cv.
5583 81267 : static ccol_retval ceventloop_shutdown_internal(struct ceventloop__s *loop) {
5584 81267 : if (ceventloop_job_marked(loop)) return ccol_not_permitted;
5585 :
5586 78756 : ccol__mutex_lock(loop->shutdown_lock);
5587 78756 : bool is_leader = !loop->shutdown_started;
5588 78756 : loop->shutdown_started = true;
5589 78756 : ccol__mutex_unlock(loop->shutdown_lock);
5590 :
5591 78756 : if (is_leader) {
5592 39363 : atomic_store(&loop->shutting_down, true);
5593 :
5594 : #if CCOL_FORK_SAFETY_REQUIRED
5595 39363 : bool is_foreign = atomic_load(&loop->foreign_since_fork);
5596 : #else
5597 : bool is_foreign = false;
5598 : #endif
5599 39363 : if (is_foreign) {
5600 : } else {
5601 39362 : eventfd_notify(loop->shutdown_efd);
5602 :
5603 39362 : ccol__thread_join(loop->poller_thread);
5604 : }
5605 :
5606 39362 : if (loop->dispatch_pool) {
5607 491 : cthrpool_shutdown_drain(loop->dispatch_pool);
5608 : }
5609 :
5610 39359 : if (!is_foreign) ceventloop_detach_queue_regs(loop);
5611 :
5612 39359 : ccol__mutex_lock(loop->shutdown_lock);
5613 39359 : loop->joined = true;
5614 39359 : ccol__cond_var_broadcast(loop->joined_cv);
5615 39359 : ccol__mutex_unlock(loop->shutdown_lock);
5616 : } else {
5617 39393 : ccol__mutex_lock(loop->shutdown_lock);
5618 39393 : while (!loop->joined) {
5619 0 : ccol__cond_var_wait(loop->joined_cv, loop->shutdown_lock);
5620 : }
5621 39393 : ccol__mutex_unlock(loop->shutdown_lock);
5622 : }
5623 :
5624 : return ccol_success;
5625 : }
5626 :
5627 : // Stops the loop's threads and drains its dispatches. It resolves and pins the
5628 : // loop for the call. Gives ccol_success, ccol_invalid_args for a bad handle, or
5629 : // ccol_not_permitted from one of the loop's own threads.
5630 2549 : ccol_retval ceventloop_shutdown(ceventloop loop) {
5631 2549 : struct ceventloop__s *raw = ceventloop_resolve(loop);
5632 2549 : if (!raw) return ccol_invalid_args;
5633 2549 : ccol_retval rv = ceventloop_shutdown_internal(raw);
5634 2549 : ceventloop_resolve_unpin(raw);
5635 2549 : return rv;
5636 : }
5637 :
5638 : // Shuts a loop down (if that hasn't happened) and frees everything it owns:
5639 : // the deferred items, every registration left in the stripes (each with its
5640 : // on_removed), the stripes, the pool, the tables, the locks and the
5641 : // descriptors. The destroy uses it after its pin wait, and the create's
5642 : // rollback; no caller can resolve the loop by then and every loop thread is
5643 : // joined, so no lock is needed. The fd index is walked without allocating, so a
5644 : // destroy short of memory still frees everything. A queue registration still
5645 : // linked to its queue is unlinked and hands on its wake, since the queue may
5646 : // have other listeners; a registration is freed before its entry, because the
5647 : // free reads owning_entry.
5648 39357 : static void ceventloop_teardown_raw(struct ceventloop__s *loop) {
5649 39357 : ceventloop_shutdown_internal(loop);
5650 :
5651 39357 : ceventloop_free_all_pending(loop);
5652 39357 : ccol__mem_free(loop->m_procs, loop->poller_events);
5653 :
5654 80285 : for (size_t i = 0; i < loop->num_stripes; i++) {
5655 40928 : ceventloop_stripe *stripe = &loop->stripes[i];
5656 :
5657 40928 : ccol_chmap_walk walk = {0};
5658 40928 : const void *key_bytes;
5659 40928 : const void *val_bytes;
5660 40928 : while (
5661 79568 : ccol_chmap_walk_next(stripe->fd_index, &walk, &key_bytes, &val_bytes)) {
5662 38640 : event_entry *entry;
5663 38640 : memcpy(&entry, val_bytes, sizeof(entry));
5664 38640 : if (entry->as.fd.read_reg)
5665 38640 : ceventloop_reg_free(loop, entry->as.fd.read_reg);
5666 38640 : if (entry->as.fd.write_reg)
5667 1 : ceventloop_reg_free(loop, entry->as.fd.write_reg);
5668 38640 : ccol__mutex_destroy(entry->dispatch_lock);
5669 38640 : ccol__mem_free(loop->m_procs, entry);
5670 : }
5671 40928 : chmap_destroy(stripe->fd_index);
5672 :
5673 40928 : ceventloop_reg_s *reg = stripe->queue_regs_head;
5674 40971 : while (reg) {
5675 43 : ceventloop_reg_s *next = reg->loop_list_next;
5676 43 : ccol__mutex *q_mtx;
5677 43 : ccol_sel_waiter **q_head;
5678 43 : ccol_sel_waiter **q_rotor;
5679 43 : queue_sel_locate(®->sel, &q_mtx, &q_head, &q_rotor);
5680 43 : ccol__mutex_lock(*q_mtx);
5681 43 : if (!reg->waiter_detached) {
5682 0 : sel_unlink_waiter_locked(®->waiter_node, q_head, q_rotor);
5683 0 : if (queue_sel_is_ready(®->sel))
5684 0 : notify_one_sel_waiter(q_head, q_rotor);
5685 : } else {
5686 86 : (*queue_sel_detached_count(®->sel))--;
5687 : }
5688 43 : ccol__mutex_unlock(*q_mtx);
5689 43 : event_entry *owning = reg->owning_entry;
5690 43 : ceventloop_reg_free(loop, reg);
5691 43 : ccol__mutex_destroy(owning->dispatch_lock);
5692 43 : ccol__mem_free(loop->m_procs, owning);
5693 : reg = next;
5694 : }
5695 :
5696 40928 : ccol__mutex_destroy(stripe->lock);
5697 : }
5698 39357 : ccol__mem_free(loop->m_procs, loop->stripes);
5699 39357 : if (loop->dispatch_pool) cthrpool__destroy(loop->dispatch_pool);
5700 :
5701 39357 : cvector_destroy(loop->reg_free_indices);
5702 39357 : cvector_destroy(loop->reg_slots);
5703 39357 : ccol__rw_lock_destroy(loop->reg_slot_rwlock);
5704 39357 : ccol__cond_var_destroy(loop->joined_cv);
5705 39357 : ccol__mutex_destroy(loop->shutdown_lock);
5706 39357 : close(loop->reclaim_wake_efd);
5707 39357 : close(loop->shutdown_efd);
5708 39357 : close(loop->epfd);
5709 :
5710 39357 : if (loop->m_procs) {
5711 20 : ccol_free free_func = loop->m_procs->free;
5712 20 : free_func(loop->m_procs);
5713 20 : free_func(loop);
5714 : } else {
5715 39337 : ccol__default_mem_free(loop);
5716 : }
5717 39357 : }
5718 :
5719 : // Destroys a loop. Under the write lock of the loop table it finds the slot and
5720 : // claims the teardown (destroy_claimed), so a second destroy, racing or later,
5721 : // or a stale handle, is a fatal error; so is a call from the loop's own thread,
5722 : // which would free the frame it runs in. The handle still resolves during the
5723 : // shutdown, so callbacks can remove their registrations while it drains. Then
5724 : // the slot stops resolving, it waits for every pin to drop, tears the loop
5725 : // down, and finally clears the slot, bumps its generation, frees the index and
5726 : // does a release of the table that the exit destructor deferred. The slot is
5727 : // always fetched by index again after an unlock, since a create can move the
5728 : // array.
5729 39365 : void ceventloop__destroy(ceventloop loop) {
5730 39365 : if (!loop) return;
5731 :
5732 39365 : ccol__call_once(ceventloop_slot_table.once,
5733 : ceventloop_slot_table_init_globals);
5734 39365 : ccol__call_once(g_cthreadcomm_atfork_once, cthreadcomm_register_atfork_once);
5735 39365 : uint32_t idx = (uint32_t)(loop >> 32);
5736 39365 : uint32_t gen = (uint32_t)(loop & 0xFFFFFFFFu);
5737 39365 : ccol__rw_lock_wrlock(ceventloop_slot_table.rwlock);
5738 39365 : struct ceventloop__s *raw = NULL;
5739 78730 : if (idx < event_loop_slot_count_locked()) {
5740 39365 : ceventloop_slot *s =
5741 39365 : (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, idx);
5742 39365 : if (s->in_use && s->generation == gen && !s->ptr->destroy_claimed)
5743 : raw = s->ptr;
5744 : }
5745 39363 : if (!raw) {
5746 2 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
5747 2 : ccol__fatal_err(
5748 : "ceventloop_destroy: handle is stale or already destroyed "
5749 : "(double-destroy / use-after-destroy of a ceventloop handle)");
5750 : }
5751 :
5752 39363 : bool is_self_call = ceventloop_job_marked(raw);
5753 39363 : if (is_self_call) {
5754 2 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
5755 2 : ccol__fatal_err(
5756 : "ceventloop_destroy: called from within a callback running on "
5757 : "this "
5758 : "loop's own reactor/dispatch thread (self-destroy hazard); defer "
5759 : "destruction to another thread, or to after the callback returns, "
5760 : "instead");
5761 : }
5762 :
5763 39361 : raw->destroy_claimed = true;
5764 39361 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
5765 :
5766 39361 : ceventloop_shutdown_internal(raw);
5767 :
5768 39357 : ccol__rw_lock_wrlock(ceventloop_slot_table.rwlock);
5769 39357 : ((ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, idx))->in_use =
5770 : false;
5771 39357 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
5772 :
5773 40655 : while (atomic_load(&raw->pending_resolve_count) > 0) {
5774 1298 : struct timespec ts = {.tv_sec = 0, .tv_nsec = 100000};
5775 1298 : nanosleep(&ts, NULL);
5776 : }
5777 :
5778 39357 : ceventloop_teardown_raw(raw);
5779 :
5780 39357 : ccol__rw_lock_wrlock(ceventloop_slot_table.rwlock);
5781 39357 : ceventloop_slot *slot2 =
5782 39357 : (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, idx);
5783 39357 : slot2->ptr = NULL;
5784 39357 : slot2->generation++;
5785 39357 : ceventloop_free_index_release_locked(idx);
5786 39357 : release_event_loop_slot_table_if_deferred_locked();
5787 39357 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
5788 : }
5789 :
5790 : #ifdef RUNNING_UNIT_TESTS
5791 : // Test-only: How many jobs wait in or run on the loop's dispatch pool.
5792 418 : size_t ceventloop__dispatch_pool_pending_count_for_tests(ceventloop loop) {
5793 418 : struct ceventloop__s *raw = ceventloop_resolve(loop);
5794 418 : if (!raw || !raw->dispatch_pool) {
5795 0 : if (raw) ceventloop_resolve_unpin(raw);
5796 0 : return 0;
5797 : }
5798 418 : size_t n = cthrpool_pending_count(raw->dispatch_pool);
5799 418 : ceventloop_resolve_unpin(raw);
5800 418 : return n;
5801 : }
5802 :
5803 : // Test-only: The poller's thread ID, so a test can prove the guards don't
5804 : // recognise the poller by its ID.
5805 2 : ccol__thread_id ceventloop__poller_thread_for_tests(ceventloop loop) {
5806 2 : struct ceventloop__s *raw = ceventloop_resolve(loop);
5807 2 : ccol__thread_id id;
5808 2 : memset(&id, 0, sizeof(id));
5809 2 : if (!raw) return id;
5810 2 : id = raw->poller_thread;
5811 2 : ceventloop_resolve_unpin(raw);
5812 2 : return id;
5813 : }
5814 :
5815 : // Test-only: Whether the calling thread carries loop's job mark.
5816 4 : bool ceventloop__test_runs_on_loop_thread(ceventloop loop) {
5817 4 : struct ceventloop__s *raw = ceventloop_resolve(loop);
5818 4 : if (!raw) return false;
5819 4 : bool marked = ceventloop_job_marked(raw);
5820 4 : ceventloop_resolve_unpin(raw);
5821 4 : return marked;
5822 : }
5823 :
5824 : // Test-only: How many waits the poller has finished, to spot a busy spin.
5825 73 : uint64_t ceventloop__poller_iterations_for_tests(ceventloop loop) {
5826 73 : struct ceventloop__s *raw = ceventloop_resolve(loop);
5827 73 : if (!raw) return 0;
5828 73 : uint64_t n = atomic_load(&raw->poller_iterations_for_tests);
5829 73 : ceventloop_resolve_unpin(raw);
5830 73 : return n;
5831 : }
5832 :
5833 : // Test-only: How many entries the reclaim has freed.
5834 21 : uint64_t ceventloop__entries_reclaimed_for_tests(ceventloop loop) {
5835 21 : struct ceventloop__s *raw = ceventloop_resolve(loop);
5836 21 : if (!raw) return 0;
5837 21 : uint64_t n = atomic_load_explicit(&raw->entries_reclaimed_for_tests,
5838 : memory_order_relaxed);
5839 21 : ceventloop_resolve_unpin(raw);
5840 21 : return n;
5841 : }
5842 :
5843 : // Test-only: Sets poller_batch_gen, so a test can check a deferred free across
5844 : // a 32-bit boundary.
5845 1 : void ceventloop__set_poller_batch_gen_for_tests(ceventloop loop,
5846 : uint64_t value) {
5847 1 : struct ceventloop__s *raw = ceventloop_resolve(loop);
5848 1 : if (!raw) return;
5849 1 : atomic_store(&raw->poller_batch_gen, value);
5850 1 : ceventloop_resolve_unpin(raw);
5851 : }
5852 :
5853 : // Test-only: Resolves a handle without a pin, so a test has no unpin to forget
5854 : // (a forgotten one would hang every later destroy).
5855 401 : struct ceventloop__s *ceventloop__resolve_for_tests(ceventloop h) {
5856 401 : ccol__call_once(ceventloop_slot_table.once,
5857 : ceventloop_slot_table_init_globals);
5858 401 : ccol__call_once(g_cthreadcomm_atfork_once, cthreadcomm_register_atfork_once);
5859 401 : if (h == 0) return NULL;
5860 401 : uint32_t idx = (uint32_t)(h >> 32);
5861 401 : uint32_t gen = (uint32_t)(h & 0xFFFFFFFFu);
5862 401 : ccol__rw_lock_rdlock(ceventloop_slot_table.rwlock);
5863 401 : struct ceventloop__s *raw = NULL;
5864 802 : if (idx < event_loop_slot_count_locked()) {
5865 401 : ceventloop_slot *slot =
5866 401 : (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, idx);
5867 401 : if (slot->in_use && slot->generation == gen) raw = slot->ptr;
5868 : }
5869 401 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
5870 401 : return raw;
5871 : }
5872 :
5873 : // Test-only: How many slots the loop table holds, freed ones included.
5874 4 : size_t ceventloop__slot_table_capacity_for_tests(void) {
5875 4 : ccol__call_once(ceventloop_slot_table.once,
5876 : ceventloop_slot_table_init_globals);
5877 4 : ccol__call_once(g_cthreadcomm_atfork_once, cthreadcomm_register_atfork_once);
5878 4 : ccol__rw_lock_rdlock(ceventloop_slot_table.rwlock);
5879 4 : size_t n = event_loop_slot_count_locked();
5880 4 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
5881 4 : return n;
5882 : }
5883 :
5884 : // Test-only: Holds a real pin on h until the test sets *release, after setting
5885 : // *pinned, so a test can prove a destroy waits for pins.
5886 1 : bool ceventloop__resolve_pin_until_for_tests(ceventloop h, atomic_int *pinned,
5887 : atomic_int *release) {
5888 1 : struct ceventloop__s *raw = ceventloop_resolve(h);
5889 1 : if (!raw) return false;
5890 1 : atomic_store(pinned, 1);
5891 1 : struct timespec ts = {.tv_sec = 0, .tv_nsec = 1000000};
5892 191 : while (!atomic_load(release)) nanosleep(&ts, NULL);
5893 1 : ceventloop_resolve_unpin(raw);
5894 1 : return true;
5895 : }
5896 :
5897 : // Test-only: Write-locks and unlocks the loop table directly, so a thread other
5898 : // than the forking one can hold it across a fork(). The lock registers the fork
5899 : // handlers first, as every library path does.
5900 1 : void ceventloop__test_wrlock_slot_table_for_tests(void) {
5901 1 : ccol__call_once(ceventloop_slot_table.once,
5902 : ceventloop_slot_table_init_globals);
5903 1 : ccol__call_once(g_cthreadcomm_atfork_once, cthreadcomm_register_atfork_once);
5904 1 : ccol__rw_lock_wrlock(ceventloop_slot_table.rwlock);
5905 1 : }
5906 :
5907 1 : void ceventloop__test_wrunlock_slot_table_for_tests(void) {
5908 1 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
5909 1 : }
5910 : #endif
5911 :
5912 : // Says whether any slot still names a loop, for the exit destructor and the
5913 : // deferred release. It tests ptr, not in_use, since a destroy clears in_use
5914 : // before its teardown ends. The caller holds the write lock.
5915 99 : static bool event_loop_any_slot_live_locked(void) {
5916 99 : size_t slot_count = event_loop_slot_count_locked();
5917 135 : for (size_t i = 0; i < slot_count; i++) {
5918 40 : ceventloop_slot *slot =
5919 40 : (ceventloop_slot *)cvector_at(ceventloop_slot_table.slots, i);
5920 40 : if (slot->ptr != NULL) return true;
5921 : }
5922 : return false;
5923 : }
5924 :
5925 : // Frees the table's vectors (setting them to NULL, so a later call sees the
5926 : // release) and deletes the two thread-specific keys, since no loop can exist
5927 : // any more. The rwlock stays, since a destroy may hold it here.
5928 95 : static void release_event_loop_slot_table_locked(void) {
5929 95 : cvector_destroy(ceventloop_slot_table.slots);
5930 95 : cvector_destroy(ceventloop_slot_table.free_indices);
5931 95 : ceventloop_slot_table.release_deferred = false;
5932 95 : if (atomic_exchange(&ceventloop_job_key_bundle.live, false))
5933 35 : ccol__thread_ls_key_delete(ceventloop_job_key_bundle.key);
5934 95 : if (atomic_exchange(&queue_dispatch_marker_bundle.live, false))
5935 35 : ccol__thread_ls_key_delete(queue_dispatch_marker_bundle.key);
5936 95 : }
5937 :
5938 : // Does the release the exit destructor deferred once no slot names a loop.
5939 : // The destroy of the last loop calls it; out of line, so the destroy keeps its
5940 : // shape. The caller holds the write lock.
5941 : static __attribute__((noinline)) void
5942 39357 : release_event_loop_slot_table_if_deferred_locked(void) {
5943 39358 : if (ceventloop_slot_table.release_deferred &&
5944 1 : !event_loop_any_slot_live_locked()) {
5945 1 : release_event_loop_slot_table_locked();
5946 : }
5947 39357 : }
5948 :
5949 : // Frees the loop table at process exit, so valgrind doesn't report it. A live
5950 : // loop (another destructor may still own one) defers the release to the
5951 : // destroy of the last loop. It runs for every program that links the library,
5952 : // so it readies the table through its once first.
5953 98 : __attribute__((destructor)) static void cleanup_event_loop_slot_table(void) {
5954 98 : ccol__call_once(ceventloop_slot_table.once,
5955 : ceventloop_slot_table_init_globals);
5956 98 : if (!ceventloop_slot_table.slots) return;
5957 98 : ccol__rw_lock_wrlock(ceventloop_slot_table.rwlock);
5958 98 : if (event_loop_any_slot_live_locked()) {
5959 4 : ceventloop_slot_table.release_deferred = true;
5960 4 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
5961 4 : return;
5962 : }
5963 94 : release_event_loop_slot_table_locked();
5964 94 : ccol__rw_lock_unlock(ceventloop_slot_table.rwlock);
5965 : }
|