LCOV - code coverage report
Current view: top level - src - cthreadpool.c (source / functions) Coverage Total Hit
Test: c_collections 2.0.0 Lines: 96.2 % 938 902
Test Date: 2026-11-15 18:57:05 Functions: 98.7 % 78 77
Legend: Lines: hit not hit

            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 <cthreadpool.h>
      26              : #include <cvector.h>
      27              : #include <errno.h>
      28              : #include <internal/catfork.h>
      29              : #include <internal/cdeadline.h>
      30              : #include <internal/cpintable.h>
      31              : #include <internal/test_helpers/common.h>
      32              : #include <internal/test_helpers/cthreadpool.h>
      33              : #include <limits.h>
      34              : #include <stdatomic.h>
      35              : #include <stdint.h>
      36              : #include <stdlib.h>
      37              : #include <string.h>
      38              : 
      39              : // Initializes cond so that its timed waits measure deadlines on
      40              : // CLOCK_MONOTONIC. not_full is the one condition that a timed submit waits on,
      41              : // and its deadline comes from CLOCK_MONOTONIC too; a step of CLOCK_REALTIME
      42              : // would otherwise stretch the wait. Gives 0 or the first failing pthread
      43              : // status.
      44         2379 : static int cthrpool_init_monotonic_cond_var(ccol__cond_var *cond) {
      45         2379 :   ccol__cond_var_attr attr;
      46         2379 :   int rv = ccol__cond_var_attr_init(attr);
      47         2379 :   if (rv != 0) return rv;
      48         2379 :   rv = ccol__cond_var_attr_setclock(attr, CLOCK_MONOTONIC);
      49         2379 :   if (rv == 0) rv = ccol__cond_var_init_ca(*cond, attr);
      50         2379 :   ccol__cond_var_attr_destroy(attr);
      51         2379 :   return rv;
      52              : }
      53              : 
      54              : // One slot of the handle table. A cthrpool is (slot index << 32) | generation;
      55              : // the generation goes up on every reuse, so a stale handle never names a later
      56              : // pool and cthrpool__destroy can report a double destroy. ptr is NULL while the
      57              : // slot is free.
      58              : //
      59              : // torn_down is true from the moment a destroy clears in_use until the teardown
      60              : // is about to make ptr->mu unsafe to touch (destroyed, or freed on the
      61              : // foreign_since_fork path). The workers aren't joined yet in that window, so
      62              : // the fork handlers must still lock ptr->mu. It's never true together with
      63              : // in_use, and it's cleared under the table's write lock.
      64              : typedef struct {
      65              :   cthread_pool *ptr;
      66              :   uint32_t generation;
      67              :   bool in_use;
      68              : #if CCOL_FORK_SAFETY_REQUIRED
      69              :   bool torn_down;
      70              : #endif
      71              : } cthrpool_slot;
      72              : 
      73              : // The handle table. Only create, destroy, the fork handlers and test helpers
      74              : // take its rwlock; every other call resolves through the lock-free pin table.
      75              : // slots only grows, so an index stays valid for good; free_indices is a LIFO of
      76              : // released indices.
      77              : //
      78              : // lost_indices counts released slots whose index couldn't go back on the free
      79              : // list (the push failed to allocate). An acquire that finds the list empty
      80              : // scans for one of them. release_deferred is set when the exit destructor finds
      81              : // a pool still live; the destroy that releases the last slot then frees the
      82              : // table. Both fields are used only under the write lock.
      83              : static struct {
      84              :   ccol__rw_lock rwlock;
      85              :   ccol__once_flag once;
      86              :   cvec slots;
      87              :   cvec free_indices;
      88              :   size_t lost_indices;
      89              :   bool release_deferred;
      90              : } cthrpool_slot_table = {0};
      91              : 
      92              : #if CCOL_FORK_SAFETY_REQUIRED
      93              : static void cthrpool_atfork_prepare(void);
      94              : static void cthrpool_atfork_release(void);
      95              : static void cthrpool_atfork_child_release(void);
      96              : #endif
      97              : 
      98              : // Creates the handle table and registers the fork handlers; runs once on first
      99              : // use. The handlers are defined below struct cthread_pool, because they lock
     100              : // the mu of every live pool.
     101          103 : static void cthrpool_slot_table_init_globals(void) {
     102          103 :   if (ccol__rw_lock_init(cthrpool_slot_table.rwlock) != 0)
     103            0 :     ccol__fatal_err("cthrpool slot table: failed to initialize rwlock");
     104          103 :   cthrpool_slot_table.slots = cvector_create(sizeof(cthrpool_slot), NULL);
     105          103 :   if (!cthrpool_slot_table.slots)
     106            0 :     ccol__fatal_err("cthrpool slot table: failed to allocate slots vector");
     107          103 :   cthrpool_slot_table.free_indices = cvector_create(sizeof(uint32_t), NULL);
     108          103 :   if (!cthrpool_slot_table.free_indices)
     109            0 :     ccol__fatal_err(
     110              :         "cthrpool slot table: failed to allocate free-index vector");
     111              : #if CCOL_FORK_SAFETY_REQUIRED
     112          103 :   ccol__at_fork(cthrpool_atfork_prepare, cthrpool_atfork_release,
     113              :                 cthrpool_atfork_child_release);
     114              : #endif
     115          103 : }
     116              : 
     117              : #if defined(CCOL__ATFORK_AT_LOAD)
     118              : // Registers the fork handlers at load time, on systems where a lazy
     119              : // registration from a thread is unsafe; see CCOL__ATFORK_AT_LOAD in
     120              : // common.h.
     121              : __attribute__((constructor)) static void cthrpool_atfork_at_load(void) {
     122              :   ccol__call_once(cthrpool_slot_table.once, cthrpool_slot_table_init_globals);
     123              : }
     124              : #endif
     125              : 
     126              : // Makes this module register its fork handlers now. Other modules of the
     127              : // library (chttpserver, for one) call it through internal/catfork.h before
     128              : // their own registration: pthread_atfork runs prepare handlers in reverse
     129              : // order, so their prepare handler then runs before ours, which avoids a lock
     130              : // order inversion between the two.
     131           39 : void cthrpool__ensure_atfork_registered_before_caller(void) {
     132           39 :   ccol__call_once(cthrpool_slot_table.once, cthrpool_slot_table_init_globals);
     133           39 : }
     134              : 
     135              : // One queued task. A callback task sets fn and on_complete, a future task sets
     136              : // fn_future and future; fn and fn_future share a union so the call needs no
     137              : // cast. next links the queue and the free list.
     138              : typedef struct cthrpool_task {
     139              :   union {
     140              :     void (*fn)(void *);
     141              :     void *(*fn_future)(void *);
     142              :   };
     143              :   void *arg;
     144              :   void (*on_complete)(void *, bool);
     145              :   cthrpool_future *future;
     146              :   struct cthrpool_task *next;
     147              : } cthrpool_task;
     148              : 
     149              : // A future, always allocated with plain malloc so its lifetime doesn't depend
     150              : // on any pool allocator. A submit gives it two references (caller and task),
     151              : // and every cthrpool_future_get in progress holds one more. The last reference
     152              : // out frees it.
     153              : struct cthrpool_future {
     154              :   ccol__mutex mu;
     155              :   ccol__cond_var cv;
     156              :   void *result;
     157              :   bool done;
     158              :   bool cancelled;
     159              :   int refcount;
     160              : };
     161              : 
     162              : // The hot half of the handle table: Handle to pointer, plus the pin that keeps
     163              : // a pool alive during a call. A resolve writes nothing that another thread
     164              : // reads, so submits from many threads don't contend on it.
     165              : static ccol_pintable cthrpool_pintable;
     166              : 
     167              : // One worker thread. The worker sets exited as its last write to the pool.
     168              : typedef struct cthrpool_worker_slot {
     169              :   ccol__thread_id id;
     170              :   atomic_bool exited;
     171              : } cthrpool_worker_slot;
     172              : 
     173              : // The pool. The queue and the free list of task nodes are intrusive lists, and
     174              : // mu guards everything here. queue_size, shutdown_drain and shutdown_immediate
     175              : // are written under mu with relaxed __atomic stores, because the refusal hint
     176              : // of a future try submit reads them without the lock.
     177              : //
     178              : // The free list keeps every node the recent traffic needed, up to
     179              : // task_free_list_cap (max(num_threads * 4, CTHRPOOL_TASK_FREE_LIST_CEILING)),
     180              : // so a deep queue doesn't cost an allocation per task. Its trim runs only at
     181              : // idle points (task_free_list_ran_dry, idle_points_since_trim), never on the
     182              : // submit or dequeue path, which would put another shared line in every critical
     183              : // section. The teardown must free the nodes on it.
     184              : //
     185              : // shutdown_complete is set, and shutdown_cv broadcast, once the call that does
     186              : // the shutdown has joined every worker; later shutdown calls wait for it.
     187              : // foreign_since_fork is set only by the child fork handler, for every pool
     188              : // inherited across fork(): Its workers don't exist in this process, so nothing
     189              : // may join them. shutdown_cv and the trim fields sit last, away from the lines
     190              : // that the submit and dequeue paths read.
     191              : struct cthread_pool {
     192              :   cthrpool_task *head;
     193              :   cthrpool_task *tail;
     194              :   size_t queue_size;
     195              :   size_t queue_cap;
     196              : 
     197              :   cthrpool_task *task_free_list;
     198              :   size_t task_free_list_size;
     199              :   size_t task_free_list_cap;
     200              : 
     201              :   ccol__mutex mu;
     202              :   ccol__cond_var not_empty;
     203              :   ccol__cond_var not_full;
     204              :   ccol__cond_var idle_cv;
     205              : 
     206              :   size_t active_count;
     207              : 
     208              :   bool shutdown_drain;
     209              :   bool shutdown_immediate;
     210              :   bool shutdown_started;
     211              :   bool shutdown_complete;
     212              : 
     213              :   cthrpool_worker_slot *threads;
     214              :   size_t num_threads;
     215              : 
     216              :   ccol_memmgmt_procs *m_procs;
     217              : 
     218              :   cthrpool self_handle;
     219              : 
     220              : #if CCOL_FORK_SAFETY_REQUIRED
     221              :   _Atomic bool foreign_since_fork;
     222              : #endif
     223              : 
     224              :   bool task_free_list_ran_dry;
     225              :   uint32_t idle_points_since_trim;
     226              : 
     227              :   ccol__cond_var shutdown_cv;
     228              : };
     229              : 
     230              : // cthrpool_lock_mu(p) locks the mu of pool p; every lock of a pool's mu goes
     231              : // through it. A test build also counts the locks each thread takes in
     232              : // cthrpool_mu_locks_taken, so a test can count the critical sections of one
     233              : // call; elsewhere it's the plain lock.
     234              : #ifdef RUNNING_UNIT_TESTS
     235              : static __thread unsigned long cthrpool_mu_locks_taken;
     236              : #define cthrpool_lock_mu(p) \
     237              :   (cthrpool_mu_locks_taken++, (void)ccol__mutex_lock((p)->mu))
     238              : #else
     239              : #define cthrpool_lock_mu(p) ccol__mutex_lock((p)->mu)
     240              : #endif
     241              : 
     242              : #if CCOL_FORK_SAFETY_REQUIRED
     243              : // The fork prepare handler: Takes the table's write lock and the mu of every
     244              : // slot that is in_use or torn_down, so the fork happens while no other thread
     245              : // holds any of them. fork() copies only the calling thread, so a lock another
     246              : // thread holds at that moment would stay locked in the child for good. A
     247              : // torn_down pool still has workers that can hold its mu. The default mutex type
     248              : // tracks no owner, so the release handlers may unlock from any thread, but a
     249              : // glibc rwlock checks the writer's thread ID, which differs in the child, so
     250              : // the child reinitializes it. Futures aren't covered: They have no registry to
     251              : // walk, and each of their critical sections is a few instructions long.
     252          362 : static void cthrpool_atfork_prepare(void) {
     253              : #ifdef RUNNING_UNIT_TESTS
     254          362 :   ccol__atfork_order_record(ccol__atfork_module_cthreadpool);
     255              : #endif
     256          362 :   ccol__rw_lock_wrlock(cthrpool_slot_table.rwlock);
     257              : 
     258          724 :   size_t n =
     259          362 :       cthrpool_slot_table.slots ? cvector_size(cthrpool_slot_table.slots) : 0;
     260         1307 :   for (size_t i = 0; i < n; i++) {
     261          945 :     cthrpool_slot *slot =
     262          945 :         (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, i);
     263          945 :     if (!slot->in_use && !slot->torn_down) continue;
     264          225 :     ccol__mutex_lock(slot->ptr->mu);
     265              :   }
     266          362 : }
     267              : 
     268              : // Releases every lock that cthrpool_atfork_prepare took; is_child says which
     269              : // side of the fork runs it. In the child it also marks every in_use pool
     270              : // foreign_since_fork (its workers don't exist here), resets its pins (a parent
     271              : // thread that was inside a resolve can never unpin, and the destroy would wait
     272              : // for ever) and reinitializes its condition variables and the table's rwlock.
     273              : // A torn_down pool only needs its mu unlocked.
     274          362 : static void cthrpool_atfork_release_impl(bool is_child) {
     275          724 :   size_t n =
     276          362 :       cthrpool_slot_table.slots ? cvector_size(cthrpool_slot_table.slots) : 0;
     277         1307 :   for (size_t i = 0; i < n; i++) {
     278          945 :     cthrpool_slot *slot =
     279          945 :         (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, i);
     280          945 :     if (!slot->in_use && !slot->torn_down) continue;
     281          225 :     cthread_pool *pool = slot->ptr;
     282              : 
     283          225 :     if (slot->in_use && is_child) {
     284            0 :       atomic_store(&pool->foreign_since_fork, true);
     285            0 :       ccol_pintable_reset_for(&cthrpool_pintable, pool->self_handle);
     286              : 
     287            0 :       if (ccol__cond_var_init(pool->not_empty) != 0)
     288            0 :         ccol__fatal_err("cthrpool atfork release: failed to reinit not_empty");
     289            0 :       if (cthrpool_init_monotonic_cond_var(&pool->not_full) != 0)
     290            0 :         ccol__fatal_err("cthrpool atfork release: failed to reinit not_full");
     291            0 :       if (ccol__cond_var_init(pool->idle_cv) != 0)
     292            0 :         ccol__fatal_err("cthrpool atfork release: failed to reinit idle_cv");
     293            0 :       if (ccol__cond_var_init(pool->shutdown_cv) != 0)
     294            0 :         ccol__fatal_err(
     295              :             "cthrpool atfork release: failed to reinit shutdown_cv");
     296              :     }
     297              : 
     298          225 :     ccol__mutex_unlock(pool->mu);
     299              :   }
     300              : 
     301          362 :   if (is_child) {
     302            0 :     if (ccol__rw_lock_reinit_in_child(cthrpool_slot_table.rwlock) != 0)
     303            0 :       ccol__fatal_err(
     304              :           "cthrpool atfork release: failed to reinit slot table rwlock");
     305              :   } else {
     306          362 :     ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
     307              :   }
     308          362 : }
     309              : 
     310              : // The parent's fork handler: Releases what cthrpool_atfork_prepare took.
     311          362 : static void cthrpool_atfork_release(void) {
     312          362 :   cthrpool_atfork_release_impl(false);
     313          362 : }
     314              : 
     315              : // The child's fork handler: Releases what cthrpool_atfork_prepare took and
     316              : // marks the inherited pools. It runs before fork() returns in the child, so
     317              : // before any code there can reach the shutdown or destroy of an inherited
     318              : // pool.
     319            0 : static void cthrpool_atfork_child_release(void) {
     320            0 :   cthrpool_atfork_release_impl(true);
     321            0 : }
     322              : #endif
     323              : 
     324              : static bool cthrpool_any_slot_live_locked(void);
     325              : static void cthrpool_release_slot_table_locked(void);
     326              : static void cthrpool_release_slot_table_if_deferred_locked(void);
     327              : 
     328              : // Waits until every caller that resolved pool before its slot was retired has
     329              : // unpinned, so the teardown never frees memory a caller still uses. It polls
     330              : // with a growing sleep because an unpin sends no wakeup, and it has no bound,
     331              : // since giving up would free memory in use. A pool whose handle was never
     332              : // published (failed create) has no slot to wait on.
     333         2341 : static void cthrpool_wait_for_pins(cthread_pool *pool) {
     334         2341 :   if (pool->self_handle == 0) return;
     335         2332 :   uint32_t idx = (uint32_t)(pool->self_handle >> 32);
     336         2332 :   long delay_ns = 1000;
     337         2332 :   while (ccol_pintable_pins(&cthrpool_pintable, idx) > 0) {
     338            0 :     struct timespec ts = {.tv_sec = 0, .tv_nsec = delay_ns};
     339            0 :     nanosleep(&ts, NULL);
     340            0 :     if (delay_ns < 1000000L) delay_ns *= 2;
     341              :   }
     342              : }
     343              : 
     344              : // Resolves h to its pool and pins it, so a concurrent destroy waits until the
     345              : // caller is done with it. Every public call on a pool starts here. Gives NULL
     346              : // for 0, garbage, a free slot or a reused one. On success the caller must call
     347              : // cthrpool_resolve_unpin() exactly once. It takes no lock and makes no shared
     348              : // write, since every submit runs it.
     349       157880 : static cthread_pool *cthrpool_resolve(cthrpool h) {
     350       157880 :   return (cthread_pool *)ccol_pintable_pin(&cthrpool_pintable, h);
     351              : }
     352              : 
     353              : // Drops the pin that cthrpool_resolve took, when a public call is done with the
     354              : // pool. It touches nothing else: The pool can be freed right after, so nothing
     355              : // may read raw once the pin is gone.
     356       157874 : static void cthrpool_resolve_unpin(cthread_pool *raw) {
     357       157874 :   ccol_pintable_unpin(&cthrpool_pintable, raw->self_handle);
     358       105899 : }
     359              : 
     360              : #ifdef RUNNING_UNIT_TESTS
     361              : // Test only: The next free list push fails like an allocation.
     362              : static _Atomic bool g_cthrpool_fail_next_free_index_push = false;
     363              : 
     364              : // Arms g_cthrpool_fail_next_free_index_push, so a test reaches the
     365              : // recovery of a lost slot index.
     366           10 : void cthrpool__force_next_free_index_push_failure_for_tests(void) {
     367           10 :   atomic_store(&g_cthrpool_fail_next_free_index_push, true);
     368           10 : }
     369              : #endif
     370              : 
     371              : // Puts idx back on the free list for the next create to reuse; the destroy and
     372              : // a failed acquire call it with the write lock held. A failed push is counted
     373              : // in lost_indices instead of stranding the slot for good.
     374         2341 : static void cthrpool_free_index_release_locked(uint32_t idx) {
     375              : #ifdef RUNNING_UNIT_TESTS
     376         2341 :   if (atomic_exchange(&g_cthrpool_fail_next_free_index_push, false)) {
     377           10 :     cthrpool_slot_table.lost_indices++;
     378           10 :     return;
     379              :   }
     380              : #endif
     381         2331 :   if (cvector_push_back(cthrpool_slot_table.free_indices, &idx) != ccol_success)
     382            0 :     cthrpool_slot_table.lost_indices++;
     383              : }
     384              : 
     385              : // Finds a released slot that no free list entry names (ptr NULL and not in_use)
     386              : // and puts its index in *out_idx, so a slot lost to a failed push gets reused
     387              : // instead of the table growing. The acquire calls it with the write lock held
     388              : // after finding the free list empty, which makes that state mean lost rather
     389              : // than free. A scan that finds nothing clears lost_indices.
     390           10 : static __attribute__((noinline)) bool cthrpool_reclaim_lost_index_locked(
     391              :     uint32_t *out_idx) {
     392           10 :   size_t slot_count = cvector_size(cthrpool_slot_table.slots);
     393           11 :   for (size_t i = 0; i < slot_count; i++) {
     394           11 :     cthrpool_slot *slot =
     395           11 :         (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, i);
     396           11 :     if (slot->ptr == NULL && !slot->in_use) {
     397           10 :       *out_idx = (uint32_t)i;
     398           10 :       cthrpool_slot_table.lost_indices--;
     399           10 :       return true;
     400              :     }
     401              :   }
     402            0 :   cthrpool_slot_table.lost_indices = 0;
     403            0 :   return false;
     404              : }
     405              : 
     406              : // Gives pool a slot (a free one, a lost one or a new one), publishes it in the
     407              : // pin table and gives the handle; it's the last step of cthrpool_create_mp.
     408              : // Gives 0 when the table was released at unload, is full or can't grow.
     409              : // Generation 0 is skipped because handle 0 is CTHRPOOL_NULL. self_handle is
     410              : // written before the publish so a resolver finds it. A failed publish puts the
     411              : // slot back with both flags clear. Takes the write lock.
     412         2370 : static cthrpool cthrpool_handle_slot_acquire(cthread_pool *pool) {
     413         2370 :   ccol__call_once(cthrpool_slot_table.once, cthrpool_slot_table_init_globals);
     414         2370 :   ccol__rw_lock_wrlock(cthrpool_slot_table.rwlock);
     415         2370 :   if (!cthrpool_slot_table.slots) {
     416            0 :     ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
     417            0 :     return 0;
     418              :   }
     419         2370 :   uint32_t idx;
     420         2370 :   cthrpool_slot *slot;
     421         2370 :   if (cvector_size(cthrpool_slot_table.free_indices) > 0) {
     422         2258 :     cvector_pop_back(cthrpool_slot_table.free_indices, &idx);
     423         2258 :     slot = (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, idx);
     424          122 :   } else if (cthrpool_slot_table.lost_indices > 0 &&
     425           10 :              cthrpool_reclaim_lost_index_locked(&idx)) {
     426           10 :     slot = (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, idx);
     427              :   } else {
     428          102 :     if (cvector_size(cthrpool_slot_table.slots) >= CCOL_PIN_MAX_SLOTS) {
     429            0 :       ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
     430            0 :       return 0;
     431              :     }
     432          102 :     cthrpool_slot fresh = {0};
     433          102 :     if (cvector_push_back(cthrpool_slot_table.slots, &fresh) != ccol_success) {
     434            0 :       ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
     435            0 :       return 0;
     436              :     }
     437          102 :     idx = (uint32_t)cvector_size(cthrpool_slot_table.slots) - 1;
     438          102 :     slot = (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, idx);
     439              :   }
     440         2370 :   slot->generation++;
     441         2370 :   if (slot->generation == 0) slot->generation++;
     442         2370 :   cthrpool h = ((cthrpool)idx << 32) | (cthrpool)slot->generation;
     443              : 
     444         2370 :   pool->self_handle = h;
     445              : 
     446         2370 :   if (!ccol_pintable_publish(&cthrpool_pintable, idx, slot->generation, pool)) {
     447            9 :     pool->self_handle = 0;
     448            9 :     slot->ptr = NULL;
     449              : #if CCOL_FORK_SAFETY_REQUIRED
     450            9 :     slot->torn_down = false;
     451              : #endif
     452            9 :     cthrpool_free_index_release_locked(idx);
     453            9 :     ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
     454            9 :     return 0;
     455              :   }
     456              : 
     457         2361 :   slot->ptr = pool;
     458         2361 :   slot->in_use = true;
     459              : #if CCOL_FORK_SAFETY_REQUIRED
     460         2361 :   slot->torn_down = false;
     461              : #endif
     462         2361 :   ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
     463         2361 :   return h;
     464              : }
     465              : 
     466              : // The thread-specific key that tells a worker which pool it serves. Each worker
     467              : // sets it once at start and never again, because a worker belongs to one pool
     468              : // for its whole life. It lets a task that waits on, shuts down or destroys its
     469              : // own pool be recognised: The join of the shutdown would otherwise get EDEADLK
     470              : // on the calling worker and carry on, and a destroy would free the pool under
     471              : // that worker. live tells whether the key was created.
     472              : static struct {
     473              :   ccol__thread_ls_key key;
     474              :   ccol__once_flag once;
     475              :   atomic_bool live;
     476              : } cthrpool_worker_key_bundle = {.once = CCOL__ONCE_INIT};
     477              : 
     478              : // Creates the worker key and sets live on success; the once of
     479              : // cthrpool_worker_key_bundle runs it on first need.
     480           42 : static void cthrpool_init_worker_key(void) {
     481           42 :   if (ccol__thread_ls_key_create(cthrpool_worker_key_bundle.key, NULL) == 0)
     482           41 :     atomic_store(&cthrpool_worker_key_bundle.live, true);
     483           42 : }
     484              : 
     485              : // Tells whether the worker key exists, creating it on the first call, so a
     486              : // create can refuse a pool whose workers couldn't mark themselves. Every other
     487              : // use of the key comes from a pool, and a pool exists only after this said
     488              : // true.
     489         2397 : static bool cthrpool_worker_key_available(void) {
     490         2397 :   ccol__call_once(cthrpool_worker_key_bundle.once, cthrpool_init_worker_key);
     491         2397 :   return atomic_load(&cthrpool_worker_key_bundle.live);
     492              : }
     493              : 
     494              : // One pool whose discarded tasks the calling thread is completing. The frames
     495              : // live on the stack of cthrpool_discard_tasks; they form a stack because an
     496              : // on_complete callback there can shut down a second pool, whose discards then
     497              : // run nested.
     498              : typedef struct cthrpool_discard_frame {
     499              :   cthread_pool *pool;
     500              :   struct cthrpool_discard_frame *prev;
     501              : } cthrpool_discard_frame;
     502              : 
     503              : // The innermost discard frame of the calling thread, or NULL.
     504              : static __thread cthrpool_discard_frame *cthrpool_discarding_top = NULL;
     505              : 
     506              : // Tells whether the calling thread is a worker of pool, so a wait, shutdown,
     507              : // destroy or full-queue submit can refuse to wait for itself. That covers the
     508              : // pool's tasks and on_complete callbacks and the ran == false callbacks that
     509              : // this thread runs for pool (cthrpool_discarding_top). A thread with another
     510              : // pool's mark isn't one. A worker whose pthread_setspecific failed has no mark,
     511              : // so a thread without one is compared with the worker IDs, which are written
     512              : // before the handle is published. Exited workers are skipped, because glibc
     513              : // gives a joined thread's ID to the next thread that starts, and an inherited
     514              : // pool has no workers here. Every caller is a cold path.
     515         7311 : static bool cthrpool_is_self_call(cthread_pool *pool) {
     516         7316 :   for (const cthrpool_discard_frame *f = cthrpool_discarding_top; f;
     517            5 :        f = f->prev)
     518           14 :     if (f->pool == pool) return true;
     519         7302 :   ccol__call_once(cthrpool_worker_key_bundle.once, cthrpool_init_worker_key);
     520         7302 :   void *mark = ccol__thread_ls_get(cthrpool_worker_key_bundle.key);
     521         7302 :   if (mark == (void *)pool) return true;
     522         7291 :   if (mark != NULL) return false;
     523              : #if CCOL_FORK_SAFETY_REQUIRED
     524         7290 :   if (atomic_load(&pool->foreign_since_fork)) return false;
     525              : #endif
     526         7278 :   ccol__thread_id me = ccol__get_thread_id();
     527        45485 :   for (size_t i = 0; i < pool->num_threads; i++) {
     528        38208 :     if (ccol__thread_id_equal(pool->threads[i].id, me) &&
     529            2 :         !atomic_load_explicit(&pool->threads[i].exited, memory_order_acquire))
     530              :       return true;
     531              :   }
     532              :   return false;
     533              : }
     534              : 
     535              : // Frees the pool struct and the procs copy it owns, through the copy's own free
     536              : // function; the last step of a teardown or a failed create.
     537         2353 : static void pool_free_self(cthread_pool *pool) {
     538         2353 :   ccol_memmgmt_procs *mp = pool->m_procs;
     539         2353 :   if (mp) {
     540          172 :     ccol_free free_fn = mp->free;
     541          172 :     free_fn(pool);
     542          172 :     free_fn(mp);
     543              :   } else {
     544         2181 :     free(pool);
     545              :   }
     546         2353 : }
     547              : 
     548              : // The cap on the task free list of a pool with few workers, in nodes (at most
     549              : // 1.25 MiB on LP64, and only after that many tasks were in flight at once).
     550              : #define CTHRPOOL_TASK_FREE_LIST_CEILING ((size_t)32768)
     551              : 
     552              : // How many idle points a trim waits for. A pool that keeps up with its producer
     553              : // goes idle between most tasks, and trimming each time would free nodes that
     554              : // the next burst allocates again.
     555              : #define CTHRPOOL_TASK_FREE_LIST_TRIM_IDLE_POINTS ((uint32_t)256)
     556              : 
     557              : // CTHRPOOL_TRIM_WINDOW() evaluates to the number of idle points between trims.
     558              : // A test build reads it from g_cthrpool_trim_window, so a test can shorten it
     559              : // through cthrpool__set_task_free_list_window_for_tests.
     560              : #ifdef RUNNING_UNIT_TESTS
     561              : static _Atomic uint32_t g_cthrpool_trim_window =
     562              :     CTHRPOOL_TASK_FREE_LIST_TRIM_IDLE_POINTS;
     563              : #define CTHRPOOL_TRIM_WINDOW() atomic_load(&g_cthrpool_trim_window)
     564              : // Sets g_cthrpool_trim_window, so a test reaches a trim with a few tasks; 0
     565              : // restores the shipped value.
     566            4 : void cthrpool__set_task_free_list_window_for_tests(uint32_t idle_points) {
     567            4 :   atomic_store(
     568              :       &g_cthrpool_trim_window,
     569              :       idle_points ? idle_points : CTHRPOOL_TASK_FREE_LIST_TRIM_IDLE_POINTS);
     570            4 : }
     571              : #else
     572              : #define CTHRPOOL_TRIM_WINDOW() CTHRPOOL_TASK_FREE_LIST_TRIM_IDLE_POINTS
     573              : #endif
     574              : 
     575              : // Trims the task free list at an idle point and unlocks pool->mu, which the
     576              : // caller holds (nothing is queued or running). At every trim window it gives
     577              : // half of what the list holds above num_threads * 4 back to the allocator,
     578              : // unless the list ran dry since the last trim. Nodes are unlinked under the
     579              : // lock and freed after it, since a custom free function may be slow. Out of
     580              : // line so the worker's completion path keeps its shape.
     581        17989 : static __attribute__((noinline)) void cthrpool_idle_unlock_and_trim(
     582              :     cthread_pool *pool) {
     583        17989 :   if (++pool->idle_points_since_trim < CTHRPOOL_TRIM_WINDOW()) {
     584        17938 :     ccol__mutex_unlock(pool->mu);
     585        17938 :     return;
     586              :   }
     587           51 :   pool->idle_points_since_trim = 0;
     588           51 :   bool ran_dry = pool->task_free_list_ran_dry;
     589           51 :   pool->task_free_list_ran_dry = false;
     590           51 :   size_t keep_min = pool->num_threads * 4;
     591           51 :   size_t size = pool->task_free_list_size;
     592           51 :   size_t excess = size > keep_min ? size - keep_min : 0;
     593           51 :   size_t to_free = ran_dry ? 0 : (excess + 1) / 2;
     594            4 :   cthrpool_task *freed = NULL;
     595            4 :   if (to_free > 0) {
     596            4 :     freed = pool->task_free_list;
     597            4 :     cthrpool_task *last = freed;
     598            9 :     for (size_t i = 1; i < to_free; i++) last = last->next;
     599            4 :     pool->task_free_list = last->next;
     600            4 :     last->next = NULL;
     601            4 :     pool->task_free_list_size -= to_free;
     602              :   }
     603           51 :   ccol__mutex_unlock(pool->mu);
     604           60 :   while (freed) {
     605            9 :     cthrpool_task *next = freed->next;
     606            9 :     ccol__mem_free(pool->m_procs, freed);
     607              :     freed = next;
     608              :   }
     609              : }
     610              : 
     611              : // Pushes a finished task's node onto the free list while it's under its cap, so
     612              : // the next submit doesn't allocate. The caller holds pool->mu. Gives false when
     613              : // the caller must free task itself, which it does only after unlocking.
     614              : // Separate from task_free so the worker can fold this into the critical section
     615              : // of its active_count decrement.
     616        99949 : static bool task_release_locked(cthread_pool *pool, cthrpool_task *task) {
     617        99949 :   bool recycled = pool->task_free_list_size < pool->task_free_list_cap;
     618        99949 :   if (recycled) {
     619        99848 :     task->next = pool->task_free_list;
     620        99848 :     pool->task_free_list = task;
     621        99848 :     pool->task_free_list_size++;
     622              :   }
     623        99949 :   return recycled;
     624              : }
     625              : 
     626              : // Recycles a task node onto the free list, or frees it when the list is full;
     627              : // the discard path uses it for nodes no worker ran. Takes pool->mu.
     628           52 : static void task_free(cthread_pool *pool, cthrpool_task *task) {
     629           52 :   cthrpool_lock_mu(pool);
     630           52 :   bool recycled = task_release_locked(pool, task);
     631           52 :   ccol__mutex_unlock(pool->mu);
     632              : 
     633           52 :   if (!recycled) ccol__mem_free(pool->m_procs, task);
     634           52 : }
     635              : 
     636              : // Frees every node on the free list, so a teardown leaks none of the recycled
     637              : // nodes. It's called once no submit and no worker can touch the pool any more,
     638              : // so it takes no lock.
     639         2341 : static void drain_task_free_list(cthread_pool *pool) {
     640         2341 :   cthrpool_task *t = pool->task_free_list;
     641         2341 :   pool->task_free_list = NULL;
     642         2341 :   pool->task_free_list_size = 0;
     643        38121 :   while (t) {
     644        35780 :     cthrpool_task *next = t->next;
     645        35780 :     ccol__mem_free(pool->m_procs, t);
     646              :     t = next;
     647              :   }
     648         2341 : }
     649              : 
     650              : // Appends task to the queue for the workers to take; the caller holds
     651              : // pool->mu.
     652       100017 : static void enqueue(cthread_pool *pool, cthrpool_task *task) {
     653       100017 :   task->next = NULL;
     654       100017 :   if (pool->tail) {
     655        75680 :     pool->tail->next = task;
     656              :   } else {
     657        24337 :     pool->head = task;
     658              :   }
     659       100017 :   pool->tail = task;
     660       100017 :   __atomic_store_n(&pool->queue_size, pool->queue_size + 1, __ATOMIC_RELAXED);
     661       100017 : }
     662              : 
     663              : // Takes the head of a non-empty queue for a worker to run; the caller holds
     664              : // pool->mu.
     665        99904 : static cthrpool_task *dequeue(cthread_pool *pool) {
     666        99904 :   cthrpool_task *task = pool->head;
     667        99904 :   pool->head = task->next;
     668        24299 :   if (!pool->head) pool->tail = NULL;
     669        99904 :   __atomic_store_n(&pool->queue_size, pool->queue_size - 1, __ATOMIC_RELAXED);
     670        99904 :   return task;
     671              : }
     672              : 
     673              : // Test hooks that force a future allocation, a primitive init or a worker's
     674              : // thread create to fail. cthrpool_armed_fault holds the armed step, and
     675              : // cthrpool_worker_create_fault one more than the index of the failing worker
     676              : // (0 when nothing is armed).
     677              : #ifdef RUNNING_UNIT_TESTS
     678              : atomic_bool cthrpool__fail_next_future_alloc_for_tests;
     679              : atomic_long cthrpool__live_futures_for_tests;
     680              : 
     681              : static atomic_int cthrpool_armed_fault;
     682              : static atomic_size_t cthrpool_worker_create_fault;
     683              : 
     684              : // Arms cthrpool_armed_fault, so a test reaches the error path of one
     685              : // creation step.
     686           22 : void cthrpool__arm_fault_for_tests(cthrpool__fault step) {
     687           22 :   atomic_store(&cthrpool_armed_fault, (int)step);
     688           22 : }
     689              : 
     690              : // Arms cthrpool_worker_create_fault, so a test reaches a failed worker start;
     691              : // SIZE_MAX wraps it to 0, which disarms.
     692            2 : void cthrpool__fail_worker_create_at_for_tests(size_t index) {
     693            2 :   atomic_store(&cthrpool_worker_create_fault, index + 1);
     694            2 : }
     695              : 
     696              : // Tells whether the armed fault is step, and disarms it if so, so the forced
     697              : // failure hits exactly one thread once.
     698        14879 : static bool cthrpool_fault_fires(cthrpool__fault step) {
     699        14879 :   int expected = (int)step;
     700        14879 :   return atomic_compare_exchange_strong(&cthrpool_armed_fault, &expected,
     701              :                                         (int)CTHRPOOL__FAULT_NONE);
     702              : }
     703              : 
     704              : // Tells whether the armed worker index is index, and disarms it if so.
     705         6351 : static bool cthrpool_worker_create_fault_fires(size_t index) {
     706         6351 :   size_t expected = index + 1;
     707         6351 :   return atomic_compare_exchange_strong(&cthrpool_worker_create_fault,
     708              :                                         &expected, 0);
     709              : }
     710              : 
     711              : // CTHRPOOL_FAULT(step) and CTHRPOOL_WORKER_CREATE_FAULT(index) evaluate to true
     712              : // when a test armed a forced failure of that creation step or worker start, so
     713              : // the error paths can be tested. Without the test hooks they are constant
     714              : // false.
     715              : #define CTHRPOOL_FAULT(step) cthrpool_fault_fires(step)
     716              : #define CTHRPOOL_WORKER_CREATE_FAULT(index) \
     717              :   cthrpool_worker_create_fault_fires(index)
     718              : #else
     719              : #define CTHRPOOL_FAULT(step) false
     720              : #define CTHRPOOL_WORKER_CREATE_FAULT(index) false
     721              : #endif
     722              : 
     723              : // Allocated future blocks, partly built ones included.
     724              : #ifdef RUNNING_UNIT_TESTS
     725              : atomic_long cthrpool__future_blocks_for_tests;
     726              : #endif
     727              : 
     728              : // Allocates a zeroed future block, or gives NULL (also when a test fault
     729              : // fires). Every block goes back through future_block_free(), so a test build
     730              : // can count them.
     731          995 : static inline cthrpool_future *future_block_alloc(void) {
     732          995 :   if (CTHRPOOL_FAULT(CTHRPOOL__FAULT_FUTURE_ALLOC)) return NULL;
     733          993 :   cthrpool_future *f = (cthrpool_future *)calloc(1, sizeof(cthrpool_future));
     734              : #ifdef RUNNING_UNIT_TESTS
     735          993 :   if (f)
     736          993 :     atomic_fetch_add_explicit(&cthrpool__future_blocks_for_tests, 1,
     737              :                               memory_order_relaxed);
     738              : #endif
     739              :   return f;
     740              : }
     741              : 
     742              : // Frees a future block and counts it in a test build; the partner of
     743              : // future_block_alloc().
     744          986 : static inline void future_block_free(cthrpool_future *f) {
     745              : #ifdef RUNNING_UNIT_TESTS
     746          986 :   atomic_fetch_sub_explicit(&cthrpool__future_blocks_for_tests, 1,
     747              :                             memory_order_relaxed);
     748              : #endif
     749          986 :   free(f);
     750          959 : }
     751              : 
     752              : // Frees f when remaining is 0. It's the shared tail of every site that drops a
     753              : // future reference: Each decrements the count under f->mu, unlocks, and then
     754              : // calls this, and whichever thread sees 0 frees it.
     755         2897 : static void future_destroy_if_unreferenced(cthrpool_future *f, int remaining) {
     756         2897 :   if (remaining == 0) {
     757              : #ifdef RUNNING_UNIT_TESTS
     758          959 :     atomic_fetch_sub_explicit(&cthrpool__live_futures_for_tests, 1,
     759              :                               memory_order_relaxed);
     760              : #endif
     761          959 :     ccol__mutex_destroy(f->mu);
     762          959 :     ccol__cond_var_destroy(f->cv);
     763          959 :     future_block_free(f);
     764              :   }
     765         2897 : }
     766              : 
     767              : // Drops one reference of f and frees it on the last one; cthrpool_future_free
     768              : // uses it. Locks f->mu itself, so the caller must not hold it.
     769          959 : static void future_deref(cthrpool_future *f) {
     770          959 :   ccol__mutex_lock(f->mu);
     771          959 :   int remaining = --f->refcount;
     772          959 :   ccol__mutex_unlock(f->mu);
     773          959 :   future_destroy_if_unreferenced(f, remaining);
     774          959 : }
     775              : 
     776              : // Marks f done and cancelled, wakes every waiter and drops the task's
     777              : // reference. A shutdown uses it for the futures of discarded tasks.
     778            7 : static void future_cancel(cthrpool_future *f) {
     779            7 :   ccol__mutex_lock(f->mu);
     780            7 :   f->cancelled = true;
     781            7 :   f->done = true;
     782            7 :   ccol__cond_var_broadcast(f->cv);
     783            7 :   int remaining = --f->refcount;
     784            7 :   ccol__mutex_unlock(f->mu);
     785            7 :   future_destroy_if_unreferenced(f, remaining);
     786            7 : }
     787              : 
     788              : // Takes the whole queue in one step, so an immediate shutdown or the teardown
     789              : // of an inherited pool can discard it; the caller holds pool->mu. The list must
     790              : // be discarded only after the unlock, because future->mu never nests under
     791              : // pool->mu.
     792           46 : static cthrpool_task *steal_queue(cthread_pool *pool) {
     793           46 :   cthrpool_task *list = pool->head;
     794           46 :   pool->head = NULL;
     795           46 :   pool->tail = NULL;
     796           46 :   __atomic_store_n(&pool->queue_size, 0, __ATOMIC_RELAXED);
     797           46 :   return list;
     798              : }
     799              : 
     800              : // Completes every task of a stolen list that no worker ran, so every accepted
     801              : // task still gets exactly one completion: Futures are cancelled and callback
     802              : // tasks get on_complete(arg, false). The caller doesn't hold pool->mu. While
     803              : // the callbacks run, a frame on cthrpool_discarding_top makes this thread a
     804              : // worker of pool, so a wait or shutdown of pool from a callback is a no-op and
     805              : // a destroy is fatal. recycle says whether nodes may go back on the free list
     806              : // or straight to m_procs (a pool nobody can submit to).
     807           46 : static void cthrpool_discard_tasks(cthread_pool *pool, cthrpool_task *list,
     808              :                                    bool recycle) {
     809           46 :   cthrpool_discard_frame frame = {pool, cthrpool_discarding_top};
     810           46 :   cthrpool_discarding_top = &frame;
     811           99 :   for (cthrpool_task *t = list; t;) {
     812           53 :     cthrpool_task *next = t->next;
     813           53 :     if (t->future)
     814            7 :       future_cancel(t->future);
     815           46 :     else if (t->on_complete)
     816           35 :       t->on_complete(t->arg, false);
     817           53 :     if (recycle)
     818           52 :       task_free(pool, t);
     819              :     else
     820            1 :       ccol__mem_free(pool->m_procs, t);
     821              :     t = next;
     822              :   }
     823           46 :   cthrpool_discarding_top = frame.prev;
     824           46 : }
     825              : 
     826              : // Computes the CLOCK_MONOTONIC deadline of a timed submit, timeout_us from now.
     827              : // It saturates instead of wrapping into the past. False when clock_gettime
     828              : // fails.
     829        12042 : static bool make_abs_deadline(uint64_t timeout_us, struct timespec *abs_out) {
     830        12042 :   return ccol_deadline_after_us(timeout_us, abs_out);
     831              : }
     832              : 
     833              : // Test hooks: Skip the worker mark, count running workers, and delay a worker's
     834              : // exit.
     835              : #ifdef RUNNING_UNIT_TESTS
     836              : atomic_bool cthrpool__skip_worker_mark_for_tests;
     837              : 
     838              : atomic_long cthrpool__running_workers_for_tests;
     839              : atomic_uint cthrpool__worker_exit_delay_us_for_tests;
     840              : #endif
     841              : 
     842              : // The body of one worker of pool (arg). It sets its key mark first (a failure
     843              : // is tolerated, since cthrpool_is_self_call falls back to the worker IDs), then
     844              : // takes tasks under pool->mu until an immediate shutdown, or a drain with an
     845              : // empty queue. A taken task signals not_full on a bounded queue. The node
     846              : // release goes in the same critical section as the active_count decrement, and
     847              : // the last task of an idle pool broadcasts idle_cv and may trim the free list.
     848              : // Marking its slot exited is the worker's last write to the pool.
     849         6349 : static void *worker_thread_fn(void *arg) {
     850         6349 :   cthread_pool *pool = (cthread_pool *)arg;
     851              : 
     852         6349 :   ccol__call_once(cthrpool_worker_key_bundle.once, cthrpool_init_worker_key);
     853              : #ifdef RUNNING_UNIT_TESTS
     854         6349 :   if (!atomic_load(&cthrpool__skip_worker_mark_for_tests))
     855              : #endif
     856         6347 :     if (atomic_load(&cthrpool_worker_key_bundle.live))
     857         6348 :       (void)ccol__thread_ls_set(cthrpool_worker_key_bundle.key, (void *)pool);
     858              : 
     859       106146 :   for (;;) {
     860       106146 :     cthrpool_lock_mu(pool);
     861              : 
     862       140010 :     while (pool->queue_size == 0 && !pool->shutdown_immediate &&
     863        40136 :            !pool->shutdown_drain) {
     864        33963 :       ccol__cond_var_wait(pool->not_empty, pool->mu);
     865              :     }
     866              : 
     867       106147 :     if (pool->shutdown_immediate ||
     868       106077 :         (pool->shutdown_drain && pool->queue_size == 0)) {
     869         6243 :       ccol__mutex_unlock(pool->mu);
     870         6229 :       break;
     871              :     }
     872              : 
     873        99904 :     cthrpool_task *task = dequeue(pool);
     874        99904 :     pool->active_count++;
     875              : 
     876        99904 :     if (pool->queue_cap > 0) {
     877        19777 :       ccol__cond_var_signal(pool->not_full);
     878              :     }
     879              : 
     880        99904 :     ccol__mutex_unlock(pool->mu);
     881              : 
     882        99826 :     if (task->future) {
     883           34 :       void *result = task->fn_future(task->arg);
     884           34 :       ccol__mutex_lock(task->future->mu);
     885           34 :       task->future->result = result;
     886           34 :       task->future->done = true;
     887           34 :       ccol__cond_var_broadcast(task->future->cv);
     888           34 :       int remaining = --task->future->refcount;
     889           34 :       ccol__mutex_unlock(task->future->mu);
     890           34 :       future_destroy_if_unreferenced(task->future, remaining);
     891              :     } else {
     892        99792 :       task->fn(task->arg);
     893        99776 :       if (task->on_complete) {
     894           19 :         task->on_complete(task->arg, true);
     895              :       }
     896              :     }
     897              : 
     898        99809 :     cthrpool_lock_mu(pool);
     899        99897 :     bool recycled = task_release_locked(pool, task);
     900        99897 :     pool->active_count--;
     901        99897 :     if (pool->active_count == 0 && pool->queue_size == 0) {
     902        17989 :       ccol__cond_var_broadcast(pool->idle_cv);
     903        17989 :       cthrpool_idle_unlock_and_trim(pool);
     904              :     } else {
     905        81908 :       ccol__mutex_unlock(pool->mu);
     906              :     }
     907        99797 :     if (!recycled) ccol__mem_free(pool->m_procs, task);
     908              :   }
     909              : 
     910         6229 :   ccol__thread_id me = ccol__get_thread_id();
     911        13864 :   for (size_t i = 0; i < pool->num_threads; i++) {
     912        13867 :     if (ccol__thread_id_equal(pool->threads[i].id, me)) {
     913         6232 :       atomic_store_explicit(&pool->threads[i].exited, true,
     914              :                             memory_order_release);
     915         6232 :       break;
     916              :     }
     917              :   }
     918              : #ifdef RUNNING_UNIT_TESTS
     919         6229 :   unsigned delay_us = atomic_load(&cthrpool__worker_exit_delay_us_for_tests);
     920         6229 :   if (delay_us) {
     921            3 :     struct timespec ts = {(time_t)(delay_us / 1000000u),
     922            3 :                           (long)(delay_us % 1000000u) * 1000L};
     923            3 :     nanosleep(&ts, NULL);
     924              :   }
     925         6229 :   atomic_fetch_sub(&cthrpool__running_workers_for_tests, 1);
     926              : #endif
     927         6229 :   return NULL;
     928              : }
     929              : 
     930              : // The idx that cthrpool_teardown_raw gets for a pool that never got a slot (the
     931              : // rollback of a failed create). No caller ever saw its handle, so there is no
     932              : // torn_down state to keep.
     933              : #define CTHRPOOL_TEARDOWN_NO_SLOT ((uint32_t)-1)
     934              : 
     935              : static void cthrpool_teardown_raw(cthread_pool *pool, uint32_t idx);
     936              : 
     937              : // Creates a pool of num_threads workers with the given queue capacity (0 for
     938              : // unbounded) and allocator, and gives its handle, or CTHRPOOL_NULL with
     939              : // *err_str set. It builds the pool, starts every worker and only then takes a
     940              : // slot, so an acquire failure has no published handle to worry about; that
     941              : // rollback must stop the running workers, which cthrpool_teardown_raw does. A
     942              : // failed thread create shuts down and joins the workers that did start. Needs
     943              : // the worker key (cthrpool_worker_key_bundle).
     944         2400 : cthrpool cthrpool_create_mp(size_t num_threads, size_t queue_capacity,
     945              :                             ccol_memmgmt_procs *mprocs, char **err_str) {
     946         2400 :   if (num_threads == 0) {
     947            1 :     if (err_str) *err_str = CCOL__ERR_STR("num_threads must be >= 1");
     948            1 :     return CTHRPOOL_NULL;
     949              :   }
     950         2399 :   if (queue_capacity == ccol_invalid_size) {
     951            2 :     if (err_str)
     952            2 :       *err_str = CCOL__ERR_STR(
     953              :           "queue_capacity is ccol_invalid_size; pass 0 for an unbounded queue");
     954            2 :     return CTHRPOOL_NULL;
     955              :   }
     956              : 
     957         2397 :   if (!ccol__verify_memmgmt_procs(mprocs, err_str)) return CTHRPOOL_NULL;
     958              : 
     959         2397 :   if (!cthrpool_worker_key_available()) {
     960            3 :     if (err_str)
     961            3 :       *err_str = CCOL__ERR_STR(
     962              :           "the thread-local worker key is not available: it could not be "
     963              :           "created, or the library already released it at unload");
     964            3 :     return CTHRPOOL_NULL;
     965              :   }
     966              : 
     967         2394 :   cthread_pool *pool =
     968          184 :       (cthread_pool *)(mprocs ? mprocs->calloc(1, sizeof(*pool))
     969         2210 :                               : calloc(1, sizeof(*pool)));
     970         2394 :   if (!pool) {
     971            6 :     if (err_str) *err_str = CCOL__ERR_STR("failed to allocate pool struct");
     972            6 :     return CTHRPOOL_NULL;
     973              :   }
     974              : 
     975         2388 :   if (mprocs) {
     976          178 :     pool->m_procs = (ccol_memmgmt_procs *)mprocs->malloc(sizeof(*mprocs));
     977          178 :     if (!pool->m_procs) {
     978            6 :       mprocs->free(pool);
     979            6 :       if (err_str) *err_str = CCOL__ERR_STR("failed to allocate m_procs copy");
     980            6 :       return CTHRPOOL_NULL;
     981              :     }
     982          172 :     memcpy(pool->m_procs, mprocs, sizeof(*mprocs));
     983              :   }
     984              : 
     985         2382 :   pool->queue_cap = queue_capacity;
     986              : 
     987         4763 :   if (CTHRPOOL_FAULT(CTHRPOOL__FAULT_POOL_MUTEX) ||
     988         2381 :       ccol__mutex_init(pool->mu) != 0) {
     989            1 :     if (err_str) *err_str = CCOL__ERR_STR("mutex init failed");
     990            1 :     pool_free_self(pool);
     991            1 :     return CTHRPOOL_NULL;
     992              :   }
     993         4761 :   if (CTHRPOOL_FAULT(CTHRPOOL__FAULT_POOL_NOT_EMPTY) ||
     994         2380 :       ccol__cond_var_init(pool->not_empty) != 0) {
     995            1 :     if (err_str) *err_str = CCOL__ERR_STR("cond_var init failed");
     996            1 :     ccol__mutex_destroy(pool->mu);
     997            1 :     pool_free_self(pool);
     998            1 :     return CTHRPOOL_NULL;
     999              :   }
    1000         4759 :   if (CTHRPOOL_FAULT(CTHRPOOL__FAULT_POOL_NOT_FULL) ||
    1001         2379 :       cthrpool_init_monotonic_cond_var(&pool->not_full) != 0) {
    1002            1 :     if (err_str) *err_str = CCOL__ERR_STR("cond_var init failed");
    1003            1 :     ccol__mutex_destroy(pool->mu);
    1004            1 :     ccol__cond_var_destroy(pool->not_empty);
    1005            1 :     pool_free_self(pool);
    1006            1 :     return CTHRPOOL_NULL;
    1007              :   }
    1008         4757 :   if (CTHRPOOL_FAULT(CTHRPOOL__FAULT_POOL_IDLE_CV) ||
    1009         2378 :       ccol__cond_var_init(pool->idle_cv) != 0) {
    1010            1 :     if (err_str) *err_str = CCOL__ERR_STR("cond_var init failed");
    1011            1 :     ccol__mutex_destroy(pool->mu);
    1012            1 :     ccol__cond_var_destroy(pool->not_empty);
    1013            1 :     ccol__cond_var_destroy(pool->not_full);
    1014            1 :     pool_free_self(pool);
    1015            1 :     return CTHRPOOL_NULL;
    1016              :   }
    1017         4755 :   if (CTHRPOOL_FAULT(CTHRPOOL__FAULT_POOL_SHUTDOWN_CV) ||
    1018         2377 :       ccol__cond_var_init(pool->shutdown_cv) != 0) {
    1019            1 :     if (err_str) *err_str = CCOL__ERR_STR("cond_var init failed");
    1020            1 :     ccol__mutex_destroy(pool->mu);
    1021            1 :     ccol__cond_var_destroy(pool->not_empty);
    1022            1 :     ccol__cond_var_destroy(pool->not_full);
    1023            1 :     ccol__cond_var_destroy(pool->idle_cv);
    1024            1 :     pool_free_self(pool);
    1025            1 :     return CTHRPOOL_NULL;
    1026              :   }
    1027              : 
    1028              : #if CCOL_FORK_SAFETY_REQUIRED
    1029         2377 :   atomic_init(&pool->foreign_since_fork, false);
    1030              : #endif
    1031              : 
    1032         2377 :   pool->threads = (cthrpool_worker_slot *)ccol__mem_calloc(
    1033              :       pool->m_procs, num_threads, sizeof(cthrpool_worker_slot));
    1034         2377 :   if (!pool->threads) {
    1035            6 :     if (err_str) *err_str = CCOL__ERR_STR("failed to allocate threads array");
    1036            6 :     ccol__mutex_destroy(pool->mu);
    1037            6 :     ccol__cond_var_destroy(pool->not_empty);
    1038            6 :     ccol__cond_var_destroy(pool->not_full);
    1039            6 :     ccol__cond_var_destroy(pool->idle_cv);
    1040            6 :     ccol__cond_var_destroy(pool->shutdown_cv);
    1041            6 :     pool_free_self(pool);
    1042            6 :     return CTHRPOOL_NULL;
    1043              :   }
    1044              : 
    1045         2371 :   pool->num_threads = num_threads;
    1046         2371 :   pool->task_free_list_cap = num_threads * 4 > CTHRPOOL_TASK_FREE_LIST_CEILING
    1047              :                                  ? num_threads * 4
    1048         2371 :                                  : CTHRPOOL_TASK_FREE_LIST_CEILING;
    1049              : 
    1050         8721 :   for (size_t i = 0; i < num_threads; i++) {
    1051        12701 :     if (CTHRPOOL_WORKER_CREATE_FAULT(i) ||
    1052         6350 :         ccol__thread_create(pool->threads[i].id, worker_thread_fn, pool) != 0) {
    1053            1 :       cthrpool_lock_mu(pool);
    1054            1 :       __atomic_store_n(&pool->shutdown_drain, true, __ATOMIC_RELAXED);
    1055            1 :       pool->shutdown_started = true;
    1056            1 :       ccol__cond_var_broadcast(pool->not_empty);
    1057            1 :       ccol__mutex_unlock(pool->mu);
    1058            4 :       for (size_t j = 0; j < i; j++) {
    1059            3 :         ccol__thread_join(pool->threads[j].id);
    1060              :       }
    1061            1 :       if (err_str) *err_str = CCOL__ERR_STR("pthread_create failed");
    1062            1 :       ccol__mem_free(pool->m_procs, pool->threads);
    1063            1 :       ccol__mutex_destroy(pool->mu);
    1064            1 :       ccol__cond_var_destroy(pool->not_empty);
    1065            1 :       ccol__cond_var_destroy(pool->not_full);
    1066            1 :       ccol__cond_var_destroy(pool->idle_cv);
    1067            1 :       ccol__cond_var_destroy(pool->shutdown_cv);
    1068            1 :       pool_free_self(pool);
    1069            1 :       return CTHRPOOL_NULL;
    1070              :     }
    1071              : #ifdef RUNNING_UNIT_TESTS
    1072         6350 :     atomic_fetch_add(&cthrpool__running_workers_for_tests, 1);
    1073              : #endif
    1074              :   }
    1075              : 
    1076         2370 :   cthrpool h = cthrpool_handle_slot_acquire(pool);
    1077         2370 :   if (h == 0) {
    1078            9 :     if (err_str)
    1079            1 :       *err_str = CCOL__ERR_STR("failed to allocate cthrpool handle slot");
    1080            9 :     cthrpool_teardown_raw(pool, CTHRPOOL_TEARDOWN_NO_SLOT);
    1081            9 :     return CTHRPOOL_NULL;
    1082              :   }
    1083              : 
    1084              :   return h;
    1085              : }
    1086              : 
    1087              : // Test hooks: Make the next timed wait for room report ETIMEDOUT after a real
    1088              : // wake, and record what the last timed wait of each thread did.
    1089              : #ifdef RUNNING_UNIT_TESTS
    1090              : atomic_bool cthrpool__timeout_after_wake_for_tests;
    1091              : atomic_bool cthrpool__timeout_after_wake_waiting_for_tests;
    1092              : 
    1093              : static __thread cthrpool__timed_wait_record cthrpool_timed_wait_record;
    1094              : #endif
    1095              : 
    1096              : // Checks for a shutdown and waits for room in the queue, for every submit. The
    1097              : // caller holds pool->mu; on ccol_success it's still held and the queue has
    1098              : // room, on any other result it's released. block is 0 for try, 1 to wait and 2
    1099              : // to wait until abs_deadline. A waiting submit from one of pool's own workers
    1100              : // gives ccol_container_full instead of waiting, since only the workers can free
    1101              : // a slot and all of them could end up waiting here. After a failed timed wait
    1102              : // the queue state decides, not the return code: The wait may have consumed a
    1103              : // dequeue's signal as its deadline passed. Always inlined, since each submit
    1104              : // passes a constant block.
    1105              : static inline __attribute__((always_inline)) ccol_retval
    1106       140588 : submit_wait_for_room_locked(cthread_pool *pool, int block,
    1107              :                             const struct timespec *abs_deadline) {
    1108       140588 :   if (pool->shutdown_drain || pool->shutdown_immediate) {
    1109           15 :     ccol__mutex_unlock(pool->mu);
    1110           15 :     return ccol_not_permitted;
    1111              :   }
    1112              : 
    1113       140573 :   if (pool->queue_cap > 0) {
    1114        28190 :     while (pool->queue_size >= pool->queue_cap && !pool->shutdown_drain &&
    1115         8020 :            !pool->shutdown_immediate) {
    1116            6 :       if (block == 0) {
    1117         4473 :         ccol__mutex_unlock(pool->mu);
    1118         4473 :         return ccol_container_full;
    1119         3547 :       } else if (cthrpool_is_self_call(pool)) {
    1120            6 :         ccol__mutex_unlock(pool->mu);
    1121            6 :         return ccol_container_full;
    1122            4 :       } else if (block == 1) {
    1123         1786 :         ccol__cond_var_wait(pool->not_full, pool->mu);
    1124              :       } else {
    1125         1755 :         int rc;
    1126              : #ifdef RUNNING_UNIT_TESTS
    1127         1755 :         if (!cthrpool_timed_wait_record.waited) {
    1128           13 :           cthrpool_timed_wait_record.waited = true;
    1129           13 :           cthrpool_timed_wait_record.deadline = *abs_deadline;
    1130           13 :           clock_gettime(CLOCK_MONOTONIC,
    1131              :                         &cthrpool_timed_wait_record.wait_started);
    1132              :         }
    1133         1755 :         if (atomic_exchange(&cthrpool__timeout_after_wake_for_tests, false)) {
    1134            2 :           atomic_store(&cthrpool__timeout_after_wake_waiting_for_tests, true);
    1135            2 :           ccol__cond_var_wait(pool->not_full, pool->mu);
    1136            2 :           rc = ETIMEDOUT;
    1137              :         } else
    1138              : #endif
    1139         1753 :           rc =
    1140         1753 :               ccol__cond_var_timedwait(pool->not_full, pool->mu, *abs_deadline);
    1141         1755 :         if (rc != 0 && pool->queue_size >= pool->queue_cap &&
    1142            6 :             !pool->shutdown_drain && !pool->shutdown_immediate) {
    1143              : #ifdef RUNNING_UNIT_TESTS
    1144            6 :           cthrpool_timed_wait_record.timed_out = rc == ETIMEDOUT;
    1145            6 :           clock_gettime(CLOCK_MONOTONIC,
    1146              :                         &cthrpool_timed_wait_record.wait_ended);
    1147              : #endif
    1148            6 :           ccol__mutex_unlock(pool->mu);
    1149            6 :           return rc == ETIMEDOUT ? ccol_timed_out : ccol_unexpected_failure;
    1150              :         }
    1151              :       }
    1152              :     }
    1153        12243 :     if (pool->shutdown_drain || pool->shutdown_immediate) {
    1154            2 :       ccol__mutex_unlock(pool->mu);
    1155            2 :       return ccol_not_permitted;
    1156              :     }
    1157              :   }
    1158              : 
    1159              :   return ccol_success;
    1160              : }
    1161              : 
    1162              : // Takes a node from the free list and enqueues the task in one pool->mu
    1163              : // critical section. When the list is empty it allocates outside the lock and
    1164              : // runs the checks again. A submitter that leaves after an allocation failure
    1165              : // passes the not_full signal on, since it may have used up the one meant for
    1166              : // another waiter. not_empty is signalled on every enqueue: Skipping it when no
    1167              : // worker seems to wait makes a burst drain on fewer threads. A callback task
    1168              : // passes fn and on_complete, a future task fn_future and future (allocated by
    1169              : // the caller); the NULLs are constants, so each instantiation holds only its
    1170              : // own code.
    1171              : static inline __attribute__((always_inline)) ccol_retval
    1172       104512 : submit_pop_and_enqueue_body(cthread_pool *pool, void (*fn)(void *),
    1173              :                             void *(*fn_future)(void *), void *arg,
    1174              :                             void (*on_complete)(void *, bool),
    1175              :                             cthrpool_future *future, int block,
    1176              :                             const struct timespec *abs_deadline) {
    1177       104512 :   cthrpool_task *spare = NULL;
    1178       104512 :   cthrpool_lock_mu(pool);
    1179       176637 :   for (;;) {
    1180       140588 :     ccol_retval r = submit_wait_for_room_locked(pool, block, abs_deadline);
    1181       136086 :     if (r != ccol_success) {
    1182         4501 :       if (spare) ccol__mem_free(pool->m_procs, spare);
    1183              :       return r;
    1184              :     }
    1185       136086 :     cthrpool_task *task = pool->task_free_list;
    1186       136086 :     if (task) {
    1187        64092 :       pool->task_free_list = task->next;
    1188        64092 :       if (--pool->task_free_list_size == 0) pool->task_free_list_ran_dry = true;
    1189              :     } else {
    1190        71994 :       pool->task_free_list_ran_dry = true;
    1191        71994 :       task = spare;
    1192        71994 :       spare = NULL;
    1193              :     }
    1194        86384 :     if (!task) {
    1195        36069 :       ccol__mutex_unlock(pool->mu);
    1196        36068 :       spare = (cthrpool_task *)ccol__mem_calloc(pool->m_procs, 1,
    1197              :                                                 sizeof(cthrpool_task));
    1198        36068 :       if (!spare) {
    1199           20 :         cthrpool_lock_mu(pool);
    1200           20 :         ccol__cond_var_signal(pool->not_full);
    1201           20 :         ccol__mutex_unlock(pool->mu);
    1202           20 :         return ccol_not_enough_memory;
    1203              :       }
    1204        36048 :       cthrpool_lock_mu(pool);
    1205        36049 :       continue;
    1206              :     }
    1207       100017 :     memset(task, 0, sizeof(*task));
    1208           40 :     if (future) {
    1209           40 :       task->fn_future = fn_future;
    1210           40 :       task->arg = arg;
    1211           40 :       task->future = future;
    1212              :     } else {
    1213        99977 :       task->fn = fn;
    1214        99977 :       task->arg = arg;
    1215            0 :       task->on_complete = on_complete;
    1216              :     }
    1217       100017 :     enqueue(pool, task);
    1218       100017 :     ccol__cond_var_signal(pool->not_empty);
    1219       100017 :     ccol__mutex_unlock(pool->mu);
    1220        99998 :     if (spare) ccol__mem_free(pool->m_procs, spare);
    1221              :     return ccol_success;
    1222              :   }
    1223              : }
    1224              : 
    1225              : // Queues a callback task. Always inlined so each plain submit holds the whole
    1226              : // path with no extra call.
    1227              : static inline __attribute__((always_inline)) ccol_retval
    1228       104449 : submit_pop_and_enqueue(cthread_pool *pool, void (*fn)(void *), void *arg,
    1229              :                        void (*on_complete)(void *, bool), int block,
    1230              :                        const struct timespec *abs_deadline) {
    1231       208908 :   return submit_pop_and_enqueue_body(pool, fn, NULL, arg, on_complete, NULL,
    1232              :                                      block, abs_deadline);
    1233              : }
    1234              : 
    1235              : // Queues a future task. future must not be NULL; on failure the queue doesn't
    1236              : // hold it and the caller keeps both its references.
    1237           63 : static ccol_retval submit_future_pop_and_enqueue(
    1238              :     cthread_pool *pool, void *(*fn_future)(void *), void *arg,
    1239              :     cthrpool_future *future, int block, const struct timespec *abs_deadline) {
    1240           63 :   return submit_pop_and_enqueue_body(pool, NULL, fn_future, arg, NULL, future,
    1241              :                                      block, abs_deadline);
    1242              : }
    1243              : 
    1244              : // Queues a callback task for the three plain submits: Resolves pool, checks fn,
    1245              : // computes the deadline for block == 2 (after those checks and before any node
    1246              : // is taken), submits and unpins.
    1247       104480 : static inline __attribute__((always_inline)) ccol_retval submit_generic(
    1248              :     cthrpool pool, void (*fn)(void *), void *arg,
    1249              :     void (*on_complete)(void *, bool), int block, uint64_t timeout_us) {
    1250       208956 :   cthread_pool *raw = cthrpool_resolve(pool);
    1251       104476 :   if (!raw) return ccol_invalid_args;
    1252       104472 :   if (!fn) {
    1253           25 :     cthrpool_resolve_unpin(raw);
    1254           25 :     return ccol_invalid_args;
    1255              :   }
    1256              : 
    1257       104447 :   struct timespec deadline;
    1258       104447 :   const struct timespec *abs_deadline = NULL;
    1259       104447 :   if (block == 2) {
    1260        12024 :     if (!make_abs_deadline(timeout_us, &deadline)) {
    1261            0 :       cthrpool_resolve_unpin(raw);
    1262            0 :       return ccol_unexpected_failure;
    1263              :     }
    1264              :     abs_deadline = &deadline;
    1265              :   }
    1266       104449 :   ccol_retval r =
    1267       104459 :       submit_pop_and_enqueue(raw, fn, arg, on_complete, block, abs_deadline);
    1268       104459 :   cthrpool_resolve_unpin(raw);
    1269       104459 :   return r;
    1270              : }
    1271              : 
    1272              : // Queues fn(arg) with on_complete, waiting for room on a full bounded queue;
    1273              : // the public blocking submit.
    1274        73718 : ccol_retval cthrpool_submit(cthrpool pool, void (*fn)(void *), void *arg,
    1275              :                             void (*on_complete)(void *, bool)) {
    1276        73718 :   return submit_generic(pool, fn, arg, on_complete, 1, 0);
    1277              : }
    1278              : 
    1279              : // Queues fn(arg) with on_complete, or gives ccol_container_full at once on a
    1280              : // full bounded queue; the public submit that never blocks.
    1281        18740 : ccol_retval cthrpool_try_submit(cthrpool pool, void (*fn)(void *), void *arg,
    1282              :                                 void (*on_complete)(void *, bool)) {
    1283        18740 :   return submit_generic(pool, fn, arg, on_complete, 0, 0);
    1284              : }
    1285              : 
    1286              : // Queues fn(arg) with on_complete, waiting at most timeout_us for room; the
    1287              : // public timed submit. A timeout of 0 goes to cthrpool_try_submit() before any
    1288              : // resolve, so that path pays for one resolve only.
    1289        12026 : ccol_retval cthrpool_timed_submit(cthrpool pool, void (*fn)(void *), void *arg,
    1290              :                                   void (*on_complete)(void *, bool),
    1291              :                                   uint64_t timeout_us) {
    1292        12026 :   if (timeout_us == 0) return cthrpool_try_submit(pool, fn, arg, on_complete);
    1293        24051 :   return submit_generic(pool, fn, arg, on_complete, 2, timeout_us);
    1294              : }
    1295              : 
    1296              : // Allocates a submit's future with a refcount of 2 (caller and task), or gives
    1297              : // NULL. A submit calls it before taking the pool lock, so the critical section
    1298              : // allocates nothing.
    1299           69 : static cthrpool_future *submit_future_alloc(void) {
    1300              : #ifdef RUNNING_UNIT_TESTS
    1301           69 :   if (atomic_exchange(&cthrpool__fail_next_future_alloc_for_tests, false))
    1302              :     return NULL;
    1303              : #endif
    1304           66 :   cthrpool_future *f = future_block_alloc();
    1305           66 :   if (!f) return NULL;
    1306          129 :   if (CTHRPOOL_FAULT(CTHRPOOL__FAULT_FUTURE_MUTEX) ||
    1307           64 :       ccol__mutex_init(f->mu) != 0) {
    1308            1 :     future_block_free(f);
    1309            1 :     return NULL;
    1310              :   }
    1311          127 :   if (CTHRPOOL_FAULT(CTHRPOOL__FAULT_FUTURE_CV) ||
    1312           63 :       ccol__cond_var_init(f->cv) != 0) {
    1313            1 :     ccol__mutex_destroy(f->mu);
    1314            1 :     future_block_free(f);
    1315            1 :     return NULL;
    1316              :   }
    1317           63 :   f->refcount = 2;
    1318              : #ifdef RUNNING_UNIT_TESTS
    1319           63 :   atomic_fetch_add_explicit(&cthrpool__live_futures_for_tests, 1,
    1320              :                             memory_order_relaxed);
    1321              : #endif
    1322           63 :   return f;
    1323              : }
    1324              : 
    1325              : // Frees a future that no queue ever held, when its submit failed after
    1326              : // allocating it.
    1327           23 : static void submit_future_discard(cthrpool_future *f) {
    1328              : #ifdef RUNNING_UNIT_TESTS
    1329           23 :   atomic_fetch_sub_explicit(&cthrpool__live_futures_for_tests, 1,
    1330              :                             memory_order_relaxed);
    1331              : #endif
    1332           23 :   ccol__mutex_destroy(f->mu);
    1333           23 :   ccol__cond_var_destroy(f->cv);
    1334           23 :   future_block_free(f);
    1335           23 : }
    1336              : 
    1337              : // Predicts what a future try submit would get, from the pool state read without
    1338              : // the lock: ccol_not_permitted after a shutdown started, ccol_container_full
    1339              : // while a bounded queue is full, else ccol_success. A refused try then neither
    1340              : // allocates nor locks. ccol_success is only a hint; the critical section checks
    1341              : // again under the lock.
    1342           19 : static ccol_retval submit_future_refusal_hint(cthread_pool *pool) {
    1343           19 :   if (__atomic_load_n(&pool->shutdown_drain, __ATOMIC_RELAXED) ||
    1344           14 :       __atomic_load_n(&pool->shutdown_immediate, __ATOMIC_RELAXED))
    1345            7 :     return ccol_not_permitted;
    1346           12 :   size_t cap = pool->queue_cap;
    1347           12 :   if (cap > 0 && __atomic_load_n(&pool->queue_size, __ATOMIC_RELAXED) >= cap)
    1348              :     return ccol_container_full;
    1349              :   return ccol_success;
    1350              : }
    1351              : 
    1352              : // Queues a future task for the three future submits (block as in
    1353              : // submit_generic) and puts the future in *out. It sets *out to NULL first, so
    1354              : // every failure path leaves it NULL; every caller has already checked that out
    1355              : // isn't NULL. A try asks the refusal hint before it allocates the future.
    1356           95 : static ccol_retval submit_future_generic(cthrpool pool, void *(*fn)(void *),
    1357              :                                          void *arg, int block,
    1358              :                                          uint64_t timeout_us,
    1359              :                                          cthrpool_future **out) {
    1360           95 :   *out = NULL;
    1361              : 
    1362           95 :   cthread_pool *raw = cthrpool_resolve(pool);
    1363           95 :   if (!raw) return ccol_invalid_args;
    1364           89 :   if (!fn) {
    1365            7 :     cthrpool_resolve_unpin(raw);
    1366            7 :     return ccol_invalid_args;
    1367              :   }
    1368              : 
    1369           82 :   struct timespec deadline;
    1370           82 :   const struct timespec *abs_deadline = NULL;
    1371           82 :   if (block == 2) {
    1372           18 :     if (!make_abs_deadline(timeout_us, &deadline)) {
    1373            0 :       cthrpool_resolve_unpin(raw);
    1374            0 :       return ccol_unexpected_failure;
    1375              :     }
    1376              :     abs_deadline = &deadline;
    1377           64 :   } else if (block == 0) {
    1378           19 :     ccol_retval hint = submit_future_refusal_hint(raw);
    1379           19 :     if (hint != ccol_success) {
    1380           13 :       cthrpool_resolve_unpin(raw);
    1381           13 :       return hint;
    1382              :     }
    1383              :   }
    1384              : 
    1385           69 :   cthrpool_future *f = submit_future_alloc();
    1386           69 :   if (!f) {
    1387            6 :     cthrpool_resolve_unpin(raw);
    1388            6 :     return ccol_not_enough_memory;
    1389              :   }
    1390              : 
    1391           63 :   ccol_retval r =
    1392           63 :       submit_future_pop_and_enqueue(raw, fn, arg, f, block, abs_deadline);
    1393           63 :   if (r != ccol_success)
    1394           23 :     submit_future_discard(f);
    1395              :   else
    1396           40 :     *out = f;
    1397           63 :   cthrpool_resolve_unpin(raw);
    1398           63 :   return r;
    1399              : }
    1400              : 
    1401              : // Queues fn(arg) and gives its future, waiting for room on a full bounded
    1402              : // queue; the public blocking future submit. NULL on failure, with the code in
    1403              : // *rv_out when rv_out isn't NULL.
    1404           48 : cthrpool_future *cthrpool_submit_future(cthrpool pool, void *(*fn)(void *),
    1405              :                                         void *arg, ccol_retval *rv_out) {
    1406           48 :   cthrpool_future *f;
    1407           48 :   ccol_retval r = submit_future_generic(pool, fn, arg, 1, 0, &f);
    1408           48 :   if (rv_out) *rv_out = r;
    1409           48 :   return f;
    1410              : }
    1411              : 
    1412              : // Queues fn(arg) and puts its future in *out, or fails at once on a full
    1413              : // bounded queue; the public future submit that never blocks.
    1414           20 : ccol_retval cthrpool_try_submit_future(cthrpool pool, void *(*fn)(void *),
    1415              :                                        void *arg, cthrpool_future **out) {
    1416           20 :   if (!out) return ccol_invalid_args;
    1417           19 :   return submit_future_generic(pool, fn, arg, 0, 0, out);
    1418              : }
    1419              : 
    1420              : // Queues fn(arg) and puts its future in *out, waiting at most timeout_us for
    1421              : // room; the public timed future submit. A timeout of 0 is a try.
    1422           29 : ccol_retval cthrpool_timed_submit_future(cthrpool pool, void *(*fn)(void *),
    1423              :                                          void *arg, uint64_t timeout_us,
    1424              :                                          cthrpool_future **out) {
    1425           29 :   if (!out) return ccol_invalid_args;
    1426           28 :   if (timeout_us == 0) return submit_future_generic(pool, fn, arg, 0, 0, out);
    1427           22 :   return submit_future_generic(pool, fn, arg, 2, timeout_us, out);
    1428              : }
    1429              : 
    1430              : // Blocks until f is done and gives its result (NULL when cancelled), so the
    1431              : // caller can collect what the task computed. Each waiter holds its own
    1432              : // reference for the whole call, taken and dropped under f->mu. Without it the
    1433              : // other references can go while the thread waits (the completion broadcast
    1434              : // wakes every waiter at once) and the future would be freed under it.
    1435          982 : void *cthrpool_future_get(cthrpool_future *f) {
    1436          982 :   if (!f) return NULL;
    1437          982 :   ccol__mutex_lock(f->mu);
    1438          982 :   f->refcount++;
    1439         1895 :   while (!f->done) {
    1440          918 :     ccol__cond_var_wait(f->cv, f->mu);
    1441              :   }
    1442          977 :   void *result = f->result;
    1443          977 :   int remaining = --f->refcount;
    1444          977 :   ccol__mutex_unlock(f->mu);
    1445          976 :   future_destroy_if_unreferenced(f, remaining);
    1446          976 :   return result;
    1447              : }
    1448              : 
    1449              : // Tells whether f is done (finished or cancelled), read under f->mu, for a
    1450              : // caller that polls instead of blocking.
    1451           70 : bool cthrpool_future_done(cthrpool_future *f) {
    1452           70 :   if (!f) return false;
    1453           70 :   ccol__mutex_lock(f->mu);
    1454           70 :   bool done = f->done;
    1455           70 :   ccol__mutex_unlock(f->mu);
    1456           70 :   return done;
    1457              : }
    1458              : 
    1459              : // Tells whether f was cancelled, read under f->mu, so a caller can tell a
    1460              : // cancelled task from one that returned NULL.
    1461            9 : bool cthrpool_future_cancelled(cthrpool_future *f) {
    1462            9 :   if (!f) return false;
    1463            9 :   ccol__mutex_lock(f->mu);
    1464            9 :   bool cancelled = f->cancelled;
    1465            9 :   ccol__mutex_unlock(f->mu);
    1466            9 :   return cancelled;
    1467              : }
    1468              : 
    1469              : // Drops the caller's reference of f, which is how a caller releases a future;
    1470              : // the last reference frees it.
    1471          959 : void cthrpool_future_free(cthrpool_future *f) {
    1472          959 :   if (!f) return;
    1473          959 :   future_deref(f);
    1474              : }
    1475              : 
    1476              : // Creates a future with no pool behind it, for a producer that isn't a
    1477              : // cthrpool worker. It starts with two references, one for the caller and one
    1478              : // for the producer. Gives NULL with *err_str set on failure.
    1479          929 : cthrpool_future *cthrpool_future_create_detached(char **err_str) {
    1480          929 :   cthrpool_future *f = future_block_alloc();
    1481          929 :   if (!f) {
    1482            1 :     if (err_str) *err_str = CCOL__ERR_STR("failed to allocate future");
    1483            1 :     return NULL;
    1484              :   }
    1485         1855 :   if (CTHRPOOL_FAULT(CTHRPOOL__FAULT_FUTURE_MUTEX) ||
    1486          927 :       ccol__mutex_init(f->mu) != 0) {
    1487            1 :     future_block_free(f);
    1488            1 :     if (err_str) *err_str = CCOL__ERR_STR("future mutex init failed");
    1489            1 :     return NULL;
    1490              :   }
    1491         1853 :   if (CTHRPOOL_FAULT(CTHRPOOL__FAULT_FUTURE_CV) ||
    1492          926 :       ccol__cond_var_init(f->cv) != 0) {
    1493            1 :     ccol__mutex_destroy(f->mu);
    1494            1 :     future_block_free(f);
    1495            1 :     if (err_str) *err_str = CCOL__ERR_STR("future cond_var init failed");
    1496            1 :     return NULL;
    1497              :   }
    1498          926 :   f->refcount = 2;
    1499              : #ifdef RUNNING_UNIT_TESTS
    1500          926 :   atomic_fetch_add_explicit(&cthrpool__live_futures_for_tests, 1,
    1501              :                             memory_order_relaxed);
    1502              : #endif
    1503          926 :   return f;
    1504              : }
    1505              : 
    1506              : // Stores result in a detached future, wakes every waiter and drops the
    1507              : // producer's reference; it's how an outside producer completes such a future.
    1508              : // ccol_not_permitted when f is already done.
    1509          922 : ccol_retval cthrpool_future_fulfill(cthrpool_future *f, void *result) {
    1510          922 :   if (!f) return ccol_invalid_args;
    1511          921 :   ccol__mutex_lock(f->mu);
    1512          921 :   if (f->done) {
    1513            1 :     ccol__mutex_unlock(f->mu);
    1514            1 :     return ccol_not_permitted;
    1515              :   }
    1516          920 :   f->result = result;
    1517          920 :   f->done = true;
    1518          920 :   ccol__cond_var_broadcast(f->cv);
    1519          920 :   int remaining = --f->refcount;
    1520          920 :   ccol__mutex_unlock(f->mu);
    1521          919 :   future_destroy_if_unreferenced(f, remaining);
    1522          919 :   return ccol_success;
    1523              : }
    1524              : 
    1525              : // Blocks until pool has nothing queued and nothing running, so a caller can
    1526              : // wait for a batch without shutting down; it waits on idle_cv under mu. A
    1527              : // self-call returns at once, since the calling task counts as active until it
    1528              : // returns. A pool inherited across fork() counts as idle, because no thread
    1529              : // here can ever finish its work.
    1530          121 : void cthrpool_wait(cthrpool pool) {
    1531          121 :   cthread_pool *raw = cthrpool_resolve(pool);
    1532          121 :   if (!raw) return;
    1533          121 :   if (cthrpool_is_self_call(raw)) {
    1534            3 :     cthrpool_resolve_unpin(raw);
    1535            3 :     return;
    1536              :   }
    1537          118 :   cthrpool_lock_mu(raw);
    1538              : #if CCOL_FORK_SAFETY_REQUIRED
    1539          118 :   if (!atomic_load(&raw->foreign_since_fork)) {
    1540          214 :     while (raw->active_count > 0 || raw->queue_size > 0) {
    1541           99 :       ccol__cond_var_wait(raw->idle_cv, raw->mu);
    1542              :     }
    1543              :   }
    1544              : #else
    1545              :   while (raw->active_count > 0 || raw->queue_size > 0) {
    1546              :     ccol__cond_var_wait(raw->idle_cv, raw->mu);
    1547              :   }
    1548              : #endif
    1549          116 :   ccol__mutex_unlock(raw->mu);
    1550          116 :   cthrpool_resolve_unpin(raw);
    1551              : }
    1552              : 
    1553              : // Sets shutdown_complete and wakes every shutdown call waiting for it, so a
    1554              : // second shutdown call returns only once no worker is alive. The call that did
    1555              : // the shutdown runs it last, after joining every worker.
    1556         2340 : static void cthrpool_mark_shutdown_complete(cthread_pool *pool) {
    1557         2340 :   cthrpool_lock_mu(pool);
    1558         2340 :   pool->shutdown_complete = true;
    1559         2340 :   ccol__cond_var_broadcast(pool->shutdown_cv);
    1560         2340 :   ccol__mutex_unlock(pool->mu);
    1561         2340 : }
    1562              : 
    1563              : // Runs a drain shutdown of pool and returns once every worker is joined; shared
    1564              : // by cthrpool_shutdown_drain and cthrpool_teardown_raw. When another call
    1565              : // already owns the shutdown it waits for shutdown_complete, because
    1566              : // shutdown_started is set long before the workers are joined; the owner is
    1567              : // never this thread, so that can't deadlock. Otherwise it sets the drain flag,
    1568              : // wakes idle workers and blocked submitters, and joins every worker, except for
    1569              : // a pool inherited across fork(), whose threads this process can't join.
    1570         3592 : static void cthrpool_shutdown_drain_internal(cthread_pool *pool) {
    1571         3592 :   cthrpool_lock_mu(pool);
    1572         3592 :   if (pool->shutdown_started) {
    1573         1302 :     while (!pool->shutdown_complete) {
    1574           15 :       ccol__cond_var_wait(pool->shutdown_cv, pool->mu);
    1575              :     }
    1576         1287 :     ccol__mutex_unlock(pool->mu);
    1577         1287 :     return;
    1578              :   }
    1579         2305 :   __atomic_store_n(&pool->shutdown_drain, true, __ATOMIC_RELAXED);
    1580         2305 :   pool->shutdown_started = true;
    1581         2305 :   ccol__cond_var_broadcast(pool->not_empty);
    1582         2303 :   ccol__cond_var_broadcast(pool->not_full);
    1583         2303 :   ccol__mutex_unlock(pool->mu);
    1584              : 
    1585              : #if CCOL_FORK_SAFETY_REQUIRED
    1586         2303 :   if (!atomic_load(&pool->foreign_since_fork)) {
    1587         8470 :     for (size_t i = 0; i < pool->num_threads; i++) {
    1588         6173 :       ccol__thread_join(pool->threads[i].id);
    1589              :     }
    1590              :   }
    1591              : #else
    1592              :   for (size_t i = 0; i < pool->num_threads; i++) {
    1593              :     ccol__thread_join(pool->threads[i].id);
    1594              :   }
    1595              : #endif
    1596              : 
    1597         2302 :   cthrpool_mark_shutdown_complete(pool);
    1598              : }
    1599              : 
    1600              : // Runs every queued task, then stops and joins the workers; the public graceful
    1601              : // shutdown. A self-call is a full no-op and leaves every flag alone: The worker
    1602              : // can't join itself, and a shutdown_started set here would stop a later
    1603              : // shutdown from outside from ever joining that worker.
    1604         1259 : void cthrpool_shutdown_drain(cthrpool pool) {
    1605         1259 :   cthread_pool *raw = cthrpool_resolve(pool);
    1606         1259 :   if (!raw) return;
    1607         1259 :   if (cthrpool_is_self_call(raw)) {
    1608            3 :     cthrpool_resolve_unpin(raw);
    1609            3 :     return;
    1610              :   }
    1611         1256 :   cthrpool_shutdown_drain_internal(raw);
    1612         1254 :   cthrpool_resolve_unpin(raw);
    1613              : }
    1614              : 
    1615              : // Runs an immediate shutdown of pool and returns once every worker is joined.
    1616              : // It steals the queue and completes the discarded tasks with mu unlocked, wakes
    1617              : // workers and submitters, broadcasts idle_cv when nothing is active (no task is
    1618              : // left to do it), and joins the workers. When a drain owns the shutdown it
    1619              : // escalates it the same way and then waits for shutdown_complete instead.
    1620           41 : static void cthrpool_shutdown_immediate_internal(cthread_pool *pool) {
    1621           41 :   cthrpool_lock_mu(pool);
    1622           41 :   if (pool->shutdown_started) {
    1623            3 :     if (!pool->shutdown_immediate) {
    1624            2 :       __atomic_store_n(&pool->shutdown_immediate, true, __ATOMIC_RELAXED);
    1625            2 :       cthrpool_task *escalated = steal_queue(pool);
    1626            2 :       ccol__mutex_unlock(pool->mu);
    1627            2 :       cthrpool_discard_tasks(pool, escalated, true);
    1628            2 :       cthrpool_lock_mu(pool);
    1629            2 :       ccol__cond_var_broadcast(pool->not_empty);
    1630            2 :       ccol__cond_var_broadcast(pool->not_full);
    1631            2 :       if (pool->active_count == 0) {
    1632            0 :         ccol__cond_var_broadcast(pool->idle_cv);
    1633              :       }
    1634              :     }
    1635            5 :     while (!pool->shutdown_complete) {
    1636            2 :       ccol__cond_var_wait(pool->shutdown_cv, pool->mu);
    1637              :     }
    1638            3 :     ccol__mutex_unlock(pool->mu);
    1639            3 :     return;
    1640              :   }
    1641           38 :   __atomic_store_n(&pool->shutdown_immediate, true, __ATOMIC_RELAXED);
    1642           38 :   pool->shutdown_started = true;
    1643              : 
    1644           38 :   cthrpool_task *discarded = steal_queue(pool);
    1645           38 :   ccol__mutex_unlock(pool->mu);
    1646           38 :   cthrpool_discard_tasks(pool, discarded, true);
    1647           38 :   cthrpool_lock_mu(pool);
    1648              : 
    1649           38 :   ccol__cond_var_broadcast(pool->not_empty);
    1650           38 :   ccol__cond_var_broadcast(pool->not_full);
    1651           38 :   if (pool->active_count == 0) {
    1652           31 :     ccol__cond_var_broadcast(pool->idle_cv);
    1653              :   }
    1654           38 :   ccol__mutex_unlock(pool->mu);
    1655              : 
    1656              : #if CCOL_FORK_SAFETY_REQUIRED
    1657           38 :   if (!atomic_load(&pool->foreign_since_fork)) {
    1658          106 :     for (size_t i = 0; i < pool->num_threads; i++) {
    1659           68 :       ccol__thread_join(pool->threads[i].id);
    1660              :     }
    1661              :   }
    1662              : #else
    1663              :   for (size_t i = 0; i < pool->num_threads; i++) {
    1664              :     ccol__thread_join(pool->threads[i].id);
    1665              :   }
    1666              : #endif
    1667              : 
    1668           38 :   cthrpool_mark_shutdown_complete(pool);
    1669              : }
    1670              : 
    1671              : // Discards the queue and stops the workers after their current task; the public
    1672              : // fast shutdown. A self-call is a no-op, as in cthrpool_shutdown_drain.
    1673           44 : void cthrpool_shutdown_immediate(cthrpool pool) {
    1674           44 :   cthread_pool *raw = cthrpool_resolve(pool);
    1675           44 :   if (!raw) return;
    1676           44 :   if (cthrpool_is_self_call(raw)) {
    1677            3 :     cthrpool_resolve_unpin(raw);
    1678            3 :     return;
    1679              :   }
    1680           41 :   cthrpool_shutdown_immediate_internal(raw);
    1681           41 :   cthrpool_resolve_unpin(raw);
    1682              : }
    1683              : 
    1684              : // Gives the number of queued tasks, read under mu, for monitoring; 0 for a bad
    1685              : // handle.
    1686        51819 : size_t cthrpool_pending_count(cthrpool pool) {
    1687        51819 :   cthread_pool *raw = cthrpool_resolve(pool);
    1688        51819 :   if (!raw) return 0;
    1689        51819 :   cthrpool_lock_mu(raw);
    1690        51819 :   size_t n = raw->queue_size;
    1691        51819 :   ccol__mutex_unlock(raw->mu);
    1692        51819 :   cthrpool_resolve_unpin(raw);
    1693        51819 :   return n;
    1694              : }
    1695              : 
    1696              : // Gives the number of running tasks, read under mu, for monitoring; 0 for a bad
    1697              : // handle.
    1698           62 : size_t cthrpool_active_count(cthrpool pool) {
    1699           62 :   cthread_pool *raw = cthrpool_resolve(pool);
    1700           62 :   if (!raw) return 0;
    1701           62 :   cthrpool_lock_mu(raw);
    1702           62 :   size_t n = raw->active_count;
    1703           62 :   ccol__mutex_unlock(raw->mu);
    1704           62 :   cthrpool_resolve_unpin(raw);
    1705           62 :   return n;
    1706              : }
    1707              : 
    1708              : #if CCOL_FORK_SAFETY_REQUIRED
    1709              : // Clears torn_down of slot idx under the write lock, so the fork handler stops
    1710              : // locking the pool's mu just before the teardown makes it unsafe to touch.
    1711              : // No-op for CTHRPOOL_TEARDOWN_NO_SLOT.
    1712         2341 : static void cthrpool_teardown_clear_torn_down(uint32_t idx) {
    1713         2341 :   if (idx == CTHRPOOL_TEARDOWN_NO_SLOT) return;
    1714         2332 :   ccol__rw_lock_wrlock(cthrpool_slot_table.rwlock);
    1715         2332 :   cthrpool_slot *slot =
    1716         2332 :       (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, idx);
    1717         2332 :   slot->torn_down = false;
    1718         2332 :   ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    1719              : }
    1720              : #endif
    1721              : 
    1722              : // Stops pool and frees it; idx is its slot, or CTHRPOOL_TEARDOWN_NO_SLOT.
    1723              : // Shared by cthrpool__destroy and the rollback of a failed create. It runs a
    1724              : // drain shutdown before it waits for pins, because only the shutdown's
    1725              : // broadcast releases a pinned submitter blocked on a full queue; then it frees
    1726              : // the free list, the thread array and the primitives, and clears torn_down
    1727              : // before mu goes. The drain is idempotent under its own lock, so it's always
    1728              : // called.
    1729              : //
    1730              : // A pool inherited across fork() is handled apart: Its primitives may be in use
    1731              : // by parent threads that don't exist here (destroying a condition variable
    1732              : // would hang on its waiter count), so only this process's private memory is
    1733              : // freed. The pin wait still runs, for resolves by other threads of this
    1734              : // process.
    1735         2342 : static void cthrpool_teardown_raw(cthread_pool *pool, uint32_t idx) {
    1736              : #if !CCOL_FORK_SAFETY_REQUIRED
    1737              :   (void)idx;
    1738              : #endif
    1739              : #if CCOL_FORK_SAFETY_REQUIRED
    1740         2342 :   if (atomic_load(&pool->foreign_since_fork)) {
    1741            6 :     cthrpool_wait_for_pins(pool);
    1742            6 :     cthrpool_lock_mu(pool);
    1743            6 :     cthrpool_task *discarded = steal_queue(pool);
    1744            6 :     ccol__mutex_unlock(pool->mu);
    1745            6 :     cthrpool_discard_tasks(pool, discarded, false);
    1746            6 :     drain_task_free_list(pool);
    1747              : 
    1748            6 :     ccol__mem_free(pool->m_procs, pool->threads);
    1749            6 :     cthrpool_teardown_clear_torn_down(idx);
    1750            6 :     pool_free_self(pool);
    1751            6 :     return;
    1752              :   }
    1753              : #endif
    1754              : 
    1755         2336 :   cthrpool_shutdown_drain_internal(pool);
    1756              : 
    1757         2335 :   cthrpool_wait_for_pins(pool);
    1758              : 
    1759         2335 :   drain_task_free_list(pool);
    1760              : 
    1761         2335 :   ccol__mem_free(pool->m_procs, pool->threads);
    1762              : 
    1763              : #if CCOL_FORK_SAFETY_REQUIRED
    1764         2335 :   cthrpool_teardown_clear_torn_down(idx);
    1765              : #endif
    1766         2335 :   ccol__mutex_destroy(pool->mu);
    1767         2335 :   ccol__cond_var_destroy(pool->not_empty);
    1768         2335 :   ccol__cond_var_destroy(pool->not_full);
    1769         2335 :   ccol__cond_var_destroy(pool->idle_cv);
    1770         2335 :   ccol__cond_var_destroy(pool->shutdown_cv);
    1771              : 
    1772         2335 :   pool_free_self(pool);
    1773              : }
    1774              : 
    1775              : // Destroys the pool behind a live handle and releases its slot; CTHRPOOL_NULL
    1776              : // is a no-op. It looks the handle up and retires it in one write lock section,
    1777              : // so a second destroy (concurrent or later) fails the lookup and ends in
    1778              : // ccol__fatal_err, and so does a self-call. torn_down keeps the fork handler
    1779              : // locking the pool's mu until the teardown clears it. The slot is released
    1780              : // last, fetched again by index because a concurrent acquire can move the slots
    1781              : // vector, and its generation is raised so the old handle never matches again.
    1782              : // The destroy that frees the last slot also does a release that the exit
    1783              : // destructor deferred.
    1784         2339 : void cthrpool__destroy(cthrpool pool) {
    1785         2339 :   if (!pool) return;
    1786              : 
    1787         2339 :   ccol__call_once(cthrpool_slot_table.once, cthrpool_slot_table_init_globals);
    1788         2339 :   uint32_t idx = (uint32_t)(pool >> 32);
    1789         2339 :   uint32_t gen = (uint32_t)(pool & 0xFFFFFFFFu);
    1790         2339 :   ccol__rw_lock_wrlock(cthrpool_slot_table.rwlock);
    1791         2339 :   cthrpool_slot *slot = NULL;
    1792         2339 :   cthread_pool *raw = NULL;
    1793         4677 :   if (cthrpool_slot_table.slots &&
    1794         2338 :       idx < cvector_size(cthrpool_slot_table.slots)) {
    1795         2338 :     cthrpool_slot *s =
    1796         2338 :         (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, idx);
    1797         2338 :     if (s->in_use && s->generation == gen) {
    1798         2336 :       slot = s;
    1799         2336 :       raw = s->ptr;
    1800              :     }
    1801              :   }
    1802         2336 :   if (!raw) {
    1803            3 :     ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    1804            3 :     ccol__fatal_err(
    1805              :         "cthrpool_destroy: handle is stale or already destroyed "
    1806              :         "(double-destroy / use-after-destroy of a cthrpool handle)");
    1807              :   }
    1808         2336 :   if (cthrpool_is_self_call(raw)) {
    1809            3 :     ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    1810            3 :     ccol__fatal_err(
    1811              :         "cthrpool_destroy: called from within a task (or its on_complete "
    1812              :         "callback) running on this very pool's own worker thread; "
    1813              :         "destroying it here would free the pool out from under that "
    1814              :         "still-executing worker");
    1815              :   }
    1816         2333 :   slot->in_use = false;
    1817         2333 :   ccol_pintable_retire(&cthrpool_pintable, idx);
    1818              : #if CCOL_FORK_SAFETY_REQUIRED
    1819         2333 :   slot->torn_down = true;
    1820              : #endif
    1821         2333 :   ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    1822              : 
    1823         2333 :   cthrpool_teardown_raw(raw, idx);
    1824              : 
    1825         2332 :   ccol__rw_lock_wrlock(cthrpool_slot_table.rwlock);
    1826         2332 :   cthrpool_slot *slot2 =
    1827         2332 :       (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, idx);
    1828         2332 :   slot2->ptr = NULL;
    1829         2332 :   slot2->generation++;
    1830         2332 :   cthrpool_free_index_release_locked(idx);
    1831         2332 :   cthrpool_release_slot_table_if_deferred_locked();
    1832         2332 :   ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    1833              : }
    1834              : 
    1835              : #ifdef RUNNING_UNIT_TESTS
    1836              : // Gives the pool behind h for the test accessors, looked up under the read lock
    1837              : // with no pin, so there's no unpin to forget.
    1838           19 : cthread_pool *cthrpool__resolve_for_tests(cthrpool h) {
    1839           19 :   ccol__call_once(cthrpool_slot_table.once, cthrpool_slot_table_init_globals);
    1840           19 :   if (h == 0) return NULL;
    1841           19 :   uint32_t idx = (uint32_t)(h >> 32);
    1842           19 :   uint32_t gen = (uint32_t)(h & 0xFFFFFFFFu);
    1843           19 :   ccol__rw_lock_rdlock(cthrpool_slot_table.rwlock);
    1844           19 :   cthread_pool *raw = NULL;
    1845           19 :   if (idx < cvector_size(cthrpool_slot_table.slots)) {
    1846           19 :     cthrpool_slot *slot =
    1847           19 :         (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, idx);
    1848           19 :     if (slot->in_use && slot->generation == gen) raw = slot->ptr;
    1849              :   }
    1850           19 :   ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    1851           19 :   return raw;
    1852              : }
    1853              : 
    1854              : // Gives the number of indices on the free list, so a test can see that no slot
    1855              : // is lost.
    1856            3 : size_t cthrpool__free_index_count_for_tests(void) {
    1857            3 :   ccol__call_once(cthrpool_slot_table.once, cthrpool_slot_table_init_globals);
    1858            3 :   ccol__rw_lock_rdlock(cthrpool_slot_table.rwlock);
    1859            3 :   size_t n = cvector_size(cthrpool_slot_table.free_indices);
    1860            3 :   ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    1861            3 :   return n;
    1862              : }
    1863              : 
    1864              : // Copies pool's shutdown flags out, read under mu, so a test can order two
    1865              : // shutdown calls.
    1866           11 : void cthrpool__shutdown_state_for_tests(struct cthread_pool *pool,
    1867              :                                         bool *started, bool *immediate,
    1868              :                                         bool *complete) {
    1869           11 :   cthrpool_lock_mu(pool);
    1870           11 :   if (started) *started = pool->shutdown_started;
    1871           11 :   if (immediate) *immediate = pool->shutdown_immediate;
    1872           11 :   if (complete) *complete = pool->shutdown_complete;
    1873           11 :   ccol__mutex_unlock(pool->mu);
    1874           11 : }
    1875              : 
    1876              : // Answers cthrpool_is_self_call() for pool on the calling thread, so a test can
    1877              : // check it from a callback.
    1878            4 : bool cthrpool__is_self_call_for_tests(struct cthread_pool *pool) {
    1879            4 :   return cthrpool_is_self_call(pool);
    1880              : }
    1881              : 
    1882              : // Gives the number of slots in the table, free ones included, so a test can see
    1883              : // that slots are reused.
    1884            6 : size_t cthrpool__slot_table_capacity_for_tests(void) {
    1885            6 :   ccol__call_once(cthrpool_slot_table.once, cthrpool_slot_table_init_globals);
    1886            6 :   ccol__rw_lock_rdlock(cthrpool_slot_table.rwlock);
    1887            6 :   size_t n = cvector_size(cthrpool_slot_table.slots);
    1888            6 :   ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    1889            6 :   return n;
    1890              : }
    1891              : 
    1892              : // Gives the free list size, read under mu, so a test can check the recycling.
    1893           12 : size_t cthrpool__task_free_list_size_for_tests(cthread_pool *pool) {
    1894           12 :   cthrpool_lock_mu(pool);
    1895           12 :   size_t n = pool->task_free_list_size;
    1896           12 :   ccol__mutex_unlock(pool->mu);
    1897           12 :   return n;
    1898              : }
    1899              : 
    1900              : // Gives the free list cap, read under mu, so a test can check the bound.
    1901            1 : size_t cthrpool__task_free_list_cap_for_tests(cthread_pool *pool) {
    1902            1 :   cthrpool_lock_mu(pool);
    1903            1 :   size_t n = pool->task_free_list_cap;
    1904            1 :   ccol__mutex_unlock(pool->mu);
    1905            1 :   return n;
    1906              : }
    1907              : 
    1908              : // Gives the number of pins on pool's slot, read with no lock, so a test can see
    1909              : // a concurrent resolve.
    1910            2 : size_t cthrpool__pending_resolve_count_for_tests(cthread_pool *pool) {
    1911            2 :   return ccol_pintable_pins_for(&cthrpool_pintable, pool->self_handle);
    1912              : }
    1913              : 
    1914              : // Waits on not_full until abs, ignoring wakes, and gives the final status, so a
    1915              : // test can tell which clock not_full uses.
    1916            2 : int cthrpool__timedwait_not_full_for_tests(cthread_pool *pool,
    1917              :                                            const struct timespec *abs) {
    1918            2 :   cthrpool_lock_mu(pool);
    1919            2 :   int rc = 0;
    1920            2 :   do {
    1921            2 :     rc = ccol__cond_var_timedwait(pool->not_full, pool->mu, *abs);
    1922            2 :   } while (rc == 0);
    1923            2 :   ccol__mutex_unlock(pool->mu);
    1924            2 :   return rc;
    1925              : }
    1926              : 
    1927              : // Gives the calling thread's count of pool locks, so a test can count the
    1928              : // critical sections of one call.
    1929           20 : unsigned long cthrpool__mu_locks_for_tests(void) {
    1930           20 :   return cthrpool_mu_locks_taken;
    1931              : }
    1932              : 
    1933              : // Gives the calling thread's timed wait record and clears it, so a test can
    1934              : // check what a timed submit waited for.
    1935           16 : cthrpool__timed_wait_record cthrpool__timed_wait_record_for_tests(void) {
    1936           16 :   cthrpool__timed_wait_record r = cthrpool_timed_wait_record;
    1937           16 :   memset(&cthrpool_timed_wait_record, 0, sizeof(cthrpool_timed_wait_record));
    1938           16 :   return r;
    1939              : }
    1940              : 
    1941              : // Gives f's refcount, read under its mutex, so a test can wait until a waiter
    1942              : // holds its reference; -1 for NULL.
    1943            4 : int cthrpool__future_refcount_for_tests(cthrpool_future *f) {
    1944            4 :   if (!f) return -1;
    1945            4 :   ccol__mutex_lock(f->mu);
    1946            4 :   int refcount = f->refcount;
    1947            4 :   ccol__mutex_unlock(f->mu);
    1948            4 :   return refcount;
    1949              : }
    1950              : 
    1951              : // Takes the write side of the table lock, so a test can hold it while another
    1952              : // thread forks.
    1953            1 : void cthrpool_test_wrlock_slot_table_for_tests(void) {
    1954            1 :   ccol__call_once(cthrpool_slot_table.once, cthrpool_slot_table_init_globals);
    1955            1 :   ccol__rw_lock_wrlock(cthrpool_slot_table.rwlock);
    1956            1 : }
    1957              : 
    1958              : // Releases the write side of the table lock that the test took.
    1959            1 : void cthrpool_test_wrunlock_slot_table_for_tests(void) {
    1960            1 :   ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    1961            1 : }
    1962              : #endif
    1963              : 
    1964              : // Tells whether any slot names a pool, so the table is never freed while a pool
    1965              : // or its destroy may still use it; the caller holds the write lock. It reads
    1966              : // ptr, not in_use: A destroy clears in_use first but still uses the table until
    1967              : // its last step, and ptr stays set until then.
    1968          102 : static bool cthrpool_any_slot_live_locked(void) {
    1969          102 :   size_t slot_count = cvector_size(cthrpool_slot_table.slots);
    1970          192 :   for (size_t i = 0; i < slot_count; i++) {
    1971           94 :     cthrpool_slot *slot =
    1972           94 :         (cthrpool_slot *)cvector_at(cthrpool_slot_table.slots, i);
    1973           94 :     if (slot->ptr != NULL) return true;
    1974              :   }
    1975              :   return false;
    1976              : }
    1977              : 
    1978              : // Frees the table when the exit destructor deferred that and no slot is live
    1979              : // any more; the caller holds the write lock. Out of line so the destroy path
    1980              : // keeps its shape.
    1981              : static __attribute__((noinline)) void
    1982         2332 : cthrpool_release_slot_table_if_deferred_locked(void) {
    1983         2333 :   if (cthrpool_slot_table.release_deferred &&
    1984            1 :       !cthrpool_any_slot_live_locked()) {
    1985            1 :     cthrpool_release_slot_table_locked();
    1986              :   }
    1987         2332 : }
    1988              : 
    1989              : // Frees the table vectors and the pin table and deletes the worker key; the
    1990              : // caller holds the write lock and found no live slot. Each vector becomes NULL,
    1991              : // so a later call sees the release. The rwlock isn't destroyed, since the
    1992              : // caller holds it. Any create after this is refused.
    1993           98 : static void cthrpool_release_slot_table_locked(void) {
    1994           98 :   cvector_destroy(cthrpool_slot_table.slots);
    1995           98 :   cvector_destroy(cthrpool_slot_table.free_indices);
    1996           98 :   ccol_pintable_dispose(&cthrpool_pintable);
    1997           98 :   cthrpool_slot_table.release_deferred = false;
    1998           98 :   if (atomic_exchange(&cthrpool_worker_key_bundle.live, false))
    1999           36 :     ccol__thread_ls_key_delete(cthrpool_worker_key_bundle.key);
    2000           98 : }
    2001              : 
    2002              : // Frees the table at process exit or unload so a leak checker doesn't report
    2003              : // it, or sets release_deferred when a pool is still live, so the destroy that
    2004              : // frees the last slot does it (destructor order across files isn't ours to
    2005              : // choose). The call_once is needed because a process may never have created a
    2006              : // pool. The static rwlock is never destroyed.
    2007          101 : __attribute__((destructor)) static void cleanup_cthrpool_slot_table(void) {
    2008          101 :   ccol__call_once(cthrpool_slot_table.once, cthrpool_slot_table_init_globals);
    2009          101 :   if (!cthrpool_slot_table.slots) return;
    2010          101 :   ccol__rw_lock_wrlock(cthrpool_slot_table.rwlock);
    2011          101 :   if (cthrpool_any_slot_live_locked()) {
    2012            4 :     cthrpool_slot_table.release_deferred = true;
    2013            4 :     ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    2014            4 :     return;
    2015              :   }
    2016           97 :   cthrpool_release_slot_table_locked();
    2017           97 :   ccol__rw_lock_unlock(cthrpool_slot_table.rwlock);
    2018              : }
    2019              : 
    2020              : #ifdef RUNNING_UNIT_TESTS
    2021              : // Runs the exit destructor now, so a test can reach the deferred release.
    2022            1 : void cthrpool__run_exit_cleanup_for_tests(void) {
    2023            1 :   cleanup_cthrpool_slot_table();
    2024            1 : }
    2025              : 
    2026              : // Tells whether the worker key exists, so a test can see the release delete
    2027              : // it.
    2028            2 : bool cthrpool__worker_key_live_for_tests(void) {
    2029            2 :   return atomic_load(&cthrpool_worker_key_bundle.live);
    2030              : }
    2031              : #endif
        

Generated by: LCOV version 2.0-1