linkcell 0.5.0

Periodic linked-cell cutoff pairs and k-nearest neighbour search
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
/* One linkcell-owned thread team for a whole k-nearest query.
 *
 * The Rust side owns the points, the bins, and each thread's scratch.
 * This file only schedules: static shares, in thread order, so slot t is
 * the same thread for every phase. The workers are pthreads that this
 * file creates and joins, so no OpenMP runtime holds a thread after
 * shutdown. OpenMP is only read: the team is sized as libgomp sizes a
 * parallel region the caller opens (`omp_get_max_threads()`, then
 * `omp_get_dynamic()` and `omp_get_thread_limit()`), the bind kind and
 * place list place it, and `OMP_STACKSIZE` sizes its stacks. A team of
 * one is the caller itself. Affinity changes only when the caller asks to
 * pin or the runtime binds threads.
 */
#define _GNU_SOURCE

#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <omp.h>
#include <pthread.h>
#include <sched.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

/* Linux sleeps on a futex and places workers with CPU affinity masks.
 * macOS has neither: its barrier sleeps on a condition variable, and a
 * worker runs wherever the scheduler puts it, so `pin` and the OpenMP
 * place list have no effect there. */
#ifdef __linux__
#define LC_AFFINITY 1
#include <linux/futex.h>
#include <sys/syscall.h>
#endif

typedef void (*lc_knn_phase)(void *ctx, int slot, int nthreads, int64_t begin, int64_t end);

static int g_pinned_once;

#ifdef LC_AFFINITY
static int g_cpu[256];
static int g_cpu_n;

static unsigned long long g_prev_busy[256];
static int g_prev_id[256];
static int g_prev_n;

/* Least-loaded CPUs since the previous sample. The first sample uses the
 * counters since boot; later queries see the delta, so a warmup call
 * teaches the ranking before a timed call. */
static void least_loaded(int nt) {
    FILE *fp = fopen("/proc/stat", "r");
    int n = 0;
    int i;
    int take;
    typedef struct {
        int cpu;
        unsigned long long busy;
    } Row;
    Row rows[256];
    Row scored[256];
    int sn = 0;
    char line[384];

    g_cpu_n = 0;
    if (fp == NULL) {
        return;
    }
    while (fgets(line, (int)sizeof line, fp) != NULL && n < 256) {
        int cpu;
        unsigned long long user, nice, sys, idle, iowait, irq, soft, steal;
        if (sscanf(line, "cpu%d %llu %llu %llu %llu %llu %llu %llu %llu", &cpu, &user, &nice, &sys,
                   &idle, &iowait, &irq, &soft, &steal) == 9) {
            rows[n].cpu = cpu;
            rows[n].busy = user + nice + sys + irq + soft + steal;
            n++;
        }
    }
    fclose(fp);
    for (i = 0; i < n; i++) {
        unsigned long long delta = rows[i].busy;
        int p;
        for (p = 0; p < g_prev_n; p++) {
            if (g_prev_id[p] == rows[i].cpu) {
                if (rows[i].busy >= g_prev_busy[p]) {
                    delta = rows[i].busy - g_prev_busy[p];
                }
                break;
            }
        }
        scored[sn].cpu = rows[i].cpu;
        scored[sn].busy = delta;
        sn++;
    }
    for (i = 1; i < sn; i++) {
        Row key = scored[i];
        int j = i;
        while (j > 0 && (scored[j - 1].busy > key.busy ||
                         (scored[j - 1].busy == key.busy && scored[j - 1].cpu > key.cpu))) {
            scored[j] = scored[j - 1];
            j--;
        }
        scored[j] = key;
    }
    take = nt < sn ? nt : sn;
    /* Pin every worker or none. A short set would leave the rest wherever
     * the kernel put them and split the team across two policies. */
    if (take == nt) {
        for (i = 0; i < take; i++) {
            g_cpu[i] = scored[i].cpu;
        }
        g_cpu_n = take;
    }
    g_prev_n = n;
    for (i = 0; i < n; i++) {
        g_prev_id[i] = rows[i].cpu;
        g_prev_busy[i] = rows[i].busy;
    }
}

static __thread cpu_set_t g_orig;
static __thread int g_have_orig;

static void apply_affinity(int pin, int slot) {
    if (!g_have_orig) {
        if (sched_getaffinity(0, sizeof g_orig, &g_orig) == 0) {
            g_have_orig = 1;
        }
    }
    if (pin && slot >= 0 && slot < g_cpu_n) {
        cpu_set_t set;
        CPU_ZERO(&set);
        CPU_SET((unsigned)g_cpu[slot], &set);
        sched_setaffinity(0, sizeof set, &set);
        return;
    }
    if (g_have_orig) {
        sched_setaffinity(0, sizeof g_orig, &g_orig);
    }
}
#endif

static void share(int64_t n, int slot, int nt, int64_t *begin, int64_t *end) {
    *begin = (n * (int64_t)slot) / (int64_t)nt;
    *end = (n * ((int64_t)slot + 1)) / (int64_t)nt;
}

/* A barrier that spins only long enough to cover an idle imbalance, then
 * sleeps. An OpenMP active barrier keeps spinning on a core a burner
 * already owns, which stretches one query from a few milliseconds to
 * tens and splits the samples into two clumps. */
typedef struct {
    unsigned count;
    unsigned phase;
#ifndef LC_AFFINITY
    pthread_mutex_t mu;
    pthread_cond_t cv;
#endif
} LcBar;

#ifdef LC_AFFINITY
static void futex_wait(unsigned *addr, unsigned expect) {
    syscall(SYS_futex, addr, FUTEX_WAIT, expect, NULL, NULL, 0);
}

static void futex_wake(unsigned *addr) {
    syscall(SYS_futex, addr, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
}
#endif

/* Open the next phase and wake every sleeper. */
static void bar_open(LcBar *bar, unsigned next) {
#ifdef LC_AFFINITY
    __atomic_store_n(&bar->phase, next, __ATOMIC_RELEASE);
    futex_wake(&bar->phase);
#else
    pthread_mutex_lock(&bar->mu);
    __atomic_store_n(&bar->phase, next, __ATOMIC_RELEASE);
    pthread_cond_broadcast(&bar->cv);
    pthread_mutex_unlock(&bar->mu);
#endif
}

/* Sleep until the phase moves off `phase`. May return early. */
static void bar_sleep(LcBar *bar, unsigned phase) {
#ifdef LC_AFFINITY
    futex_wait(&bar->phase, phase);
#else
    pthread_mutex_lock(&bar->mu);
    while (__atomic_load_n(&bar->phase, __ATOMIC_ACQUIRE) == phase) {
        pthread_cond_wait(&bar->cv, &bar->mu);
    }
    pthread_mutex_unlock(&bar->mu);
#endif
}

static void cpu_relax(void) {
#if defined(__x86_64__)
    __asm__ __volatile__("pause");
#else
    __asm__ __volatile__("yield");
#endif
}

static void passive_barrier(LcBar *bar, int nt) {
    unsigned phase;
    unsigned got;
    int spin;
    if (nt <= 1) {
        return;
    }
    phase = __atomic_load_n(&bar->phase, __ATOMIC_ACQUIRE);
    got = __atomic_add_fetch(&bar->count, 1, __ATOMIC_ACQ_REL);
    if (got == (unsigned)nt) {
        __atomic_store_n(&bar->count, 0, __ATOMIC_RELAXED);
        bar_open(bar, phase + 1);
        return;
    }
    for (spin = 0; spin < 4000; spin++) {
        if (__atomic_load_n(&bar->phase, __ATOMIC_ACQUIRE) != phase) {
            return;
        }
        cpu_relax();
    }
    while (__atomic_load_n(&bar->phase, __ATOMIC_ACQUIRE) == phase) {
        bar_sleep(bar, phase);
    }
}

int lc_omp_max_threads(void) { return omp_get_max_threads(); }

typedef struct {
    void *ctx;
    int pin;
    int restore;
    int64_t n_points;
    int64_t n_bins;
    int64_t n_blocks;
    lc_knn_phase bin;
    lc_knn_phase count;
    lc_knn_phase scan_base;
    lc_knn_phase scan;
    lc_knn_phase fill;
    lc_knn_phase select;
    int *team;
} LcJob;

/* One standing team between queries. Workers sleep on `cv`. Phase edges
 * use LcBar. The team is joined from `lc_knn_shutdown`, including the
 * image destructor, so a dlclose does not leave threads in unmapped code.
 * Team size comes from `team_size`, kept for as long as the caller's
 * nthreads-var and dyn-var stay the same and the team is not joined. */
#define LC_EMPTY 0
#define LC_START 1
#define LC_UP 2
#define LC_STOP 3

static struct {
    pthread_mutex_t mu;
    pthread_cond_t cv;
    pthread_t *workers;
    int started;
    int state;
    int nt;
    int parked;
    int epoch;
    int done;
    int busy;
    int quit;
    int sized_want;
    int sized_dyn;
    int sized_nt;
    LcJob job;
    LcBar bar;
} g_team = {
    .mu = PTHREAD_MUTEX_INITIALIZER,
    .cv = PTHREAD_COND_INITIALIZER,
#ifndef LC_AFFINITY
    .bar = {.mu = PTHREAD_MUTEX_INITIALIZER, .cv = PTHREAD_COND_INITIALIZER},
#endif
};

/* Slot t takes share t of every phase, as `schedule(static)` over nt
 * iterations on nt threads does. Slot 0 runs the singles. */
static void run_phases(const LcJob *job, int slot, int nt) {
    void *ctx = job->ctx;
    int pin = job->pin;
    int restore = job->restore;
    LcBar *bar = &g_team.bar;
    int64_t begin, end;

#ifdef LC_AFFINITY
    if (pin || restore) {
        if (slot == 0 && pin) {
            least_loaded(nt);
        }
        passive_barrier(bar, nt);
        apply_affinity(pin, slot);
    }
#else
    (void)pin;
    (void)restore;
#endif

    share(job->n_points, slot, nt, &begin, &end);
    job->bin(ctx, slot, nt, begin, end);
    passive_barrier(bar, nt);
    share(job->n_bins, slot, nt, &begin, &end);
    job->count(ctx, slot, nt, begin, end);
    passive_barrier(bar, nt);
    if (slot == 0) {
        job->scan_base(ctx, 0, nt, 0, job->n_bins);
    }
    passive_barrier(bar, nt);
    share(job->n_bins, slot, nt, &begin, &end);
    job->scan(ctx, slot, nt, begin, end);
    passive_barrier(bar, nt);
    share(job->n_points, slot, nt, &begin, &end);
    job->fill(ctx, slot, nt, begin, end);
    passive_barrier(bar, nt);
    share(job->n_blocks, slot, nt, &begin, &end);
    job->select(ctx, slot, nt, begin, end);
    passive_barrier(bar, nt);
    if (slot == 0 && job->team != NULL) {
        *job->team = nt;
    }
}

/* Every worker carries this name, so `top -H` and
 * `/proc/<pid>/task/<tid>/comm` tell linkcell's team apart from the
 * caller's threads and from any the OpenMP runtime keeps. */
#define LC_TEAM_NAME "linkcell-knn"

static void *team_worker(void *arg) {
    int slot = (int)(intptr_t)arg;
    int seen = 0;
    int nt;
#ifdef __APPLE__
    pthread_setname_np(LC_TEAM_NAME);
#else
    pthread_setname_np(pthread_self(), LC_TEAM_NAME);
#endif
    pthread_mutex_lock(&g_team.mu);
    nt = g_team.nt;
    g_team.parked++;
    if (g_team.parked == nt) {
        g_team.state = LC_UP;
        pthread_cond_broadcast(&g_team.cv);
    }
    for (;;) {
        while (g_team.epoch == seen && !g_team.quit) {
            pthread_cond_wait(&g_team.cv, &g_team.mu);
        }
        if (g_team.quit) {
            pthread_mutex_unlock(&g_team.mu);
            break;
        }
        seen = g_team.epoch;
        LcJob job = g_team.job;
        pthread_mutex_unlock(&g_team.mu);
        run_phases(&job, slot, nt);
        pthread_mutex_lock(&g_team.mu);
        g_team.done++;
        if (g_team.done == nt) {
            pthread_cond_broadcast(&g_team.cv);
        }
    }
    return NULL;
}

#ifdef LC_AFFINITY
/* The place of slot `slot` in a team of `nt` over `np` places, as libgomp
 * binds a team that a new thread starts: from place 0 of the whole list.
 * `close` and `true` put consecutive slots on consecutive places. `spread`
 * starts each slot on its own subpartition, the first `np % nt` one place
 * longer. With more slots than places both give each place a run of
 * `nt / np` consecutive slots, and the `nt % np` left over wrap round from
 * place 0. `primary` keeps every slot on place 0. */
static int place_of(int bind, int slot, int nt, int np) {
    int each, rest;
    if (bind != omp_proc_bind_true && bind != omp_proc_bind_close && bind != omp_proc_bind_spread) {
        return 0;
    }
    if (nt > np) {
        each = nt / np;
        if (slot < each * np) {
            return slot / each;
        }
        return slot - each * np;
    }
    if (bind == omp_proc_bind_spread) {
        each = np / nt;
        rest = np % nt;
        if (slot < rest) {
            return slot * (each + 1);
        }
        return rest * (each + 1) + (slot - rest) * each;
    }
    return slot;
}

static int place_mask(int place, cpu_set_t *set) {
    int n = omp_get_place_num_procs(place);
    int *ids;
    int i;
    CPU_ZERO(set);
    if (n <= 0) {
        return 0;
    }
    ids = malloc(sizeof *ids * (size_t)n);
    if (ids == NULL) {
        return 0;
    }
    omp_get_place_proc_ids(place, ids);
    for (i = 0; i < n; i++) {
        if (ids[i] >= 0 && ids[i] < CPU_SETSIZE) {
            CPU_SET((unsigned)ids[i], set);
        }
    }
    free(ids);
    return CPU_COUNT(set) > 0;
}
#endif

/* libgomp's reading of OMP_STACKSIZE: a decimal size with an optional
 * B, K, M, or G suffix (K when absent), spaces allowed around both. The
 * OpenMP API has no getter for stacksize-var, so the variable is read
 * here, once. An invalid value leaves the default, as libgomp does after
 * it has reported the value itself. */
static int parse_stacksize(const char *name, size_t *out) {
    const char *env = getenv(name);
    char *end;
    unsigned long value;
    unsigned shift = 10;
    if (env == NULL) {
        return 0;
    }
    while (isspace((unsigned char)*env)) {
        env++;
    }
    if (*env == '\0') {
        return 0;
    }
    errno = 0;
    value = strtoul(env, &end, 10);
    if (errno != 0 || end == env) {
        return 0;
    }
    while (isspace((unsigned char)*end)) {
        end++;
    }
    if (*end != '\0') {
        switch (tolower((unsigned char)*end)) {
        case 'b':
            shift = 0;
            break;
        case 'k':
            break;
        case 'm':
            shift = 20;
            break;
        case 'g':
            shift = 30;
            break;
        default:
            return 0;
        }
        end++;
        while (isspace((unsigned char)*end)) {
            end++;
        }
        if (*end != '\0') {
            return 0;
        }
    }
    if (((value << shift) >> shift) != value) {
        return 0;
    }
    *out = (size_t)(value << shift);
    return 1;
}

static pthread_once_t g_stack_once = PTHREAD_ONCE_INIT;
static size_t g_stacksize;
/* `pthread_attr_setstacksize` returned EINVAL. Later queries do not try
 * that size again. Read and written only with `mu` held. */
static int g_stack_refused;
#ifndef LC_AFFINITY
/* The guard size every worker is created with. Only Linux can read it
 * back from a running thread. Written with `mu` held. */
static size_t g_guard;
#endif
/* `pthread_create` failed for an explicit size. The warning is once.
 * The next query tries again. Read and written only with `mu` held. */
static int g_stack_create_warned;
/* Times `start_team` got as far as creating workers. */
static unsigned g_stack_starts;

/* `pthread_attr_setstacksize` rejects a size below `PTHREAD_STACK_MIN`.
 * The wide fold frame does not fit in that minimum: on this toolchain
 * `fold8_regs` asks for about 8 KiB after its callers have already used
 * most of a 16 KiB stack, and the worker dies on the guard. 32 KiB
 * completes the query. The floor is 64 KiB, or `PTHREAD_STACK_MIN` when
 * that is larger. Any request below the floor is raised to it, so a size
 * that pthread accepts but the frame does not fit is raised too. */
static size_t stack_floor(void) {
    size_t floor = (size_t)PTHREAD_STACK_MIN;
    if (floor < (size_t)64 * 1024) {
        floor = (size_t)64 * 1024;
    }
    return floor;
}

/* Runs once, from read_stacksize under g_stack_once. */
static void note_stack_raised(void) {
    static int noted;
    if (noted) {
        return;
    }
    noted = 1;
    fprintf(stderr, "linkcell: OMP_STACKSIZE is below the worker stack floor; using %zu bytes\n",
            g_stacksize);
}

static void note_stack_refused(void) {
    if (g_stack_refused) {
        return;
    }
    g_stack_refused = 1;
    fprintf(stderr,
            "linkcell: OMP_STACKSIZE was refused; k-nearest queries stay on the calling thread\n");
}

static void note_stack_create_failed(void) {
    if (g_stack_create_warned) {
        return;
    }
    g_stack_create_warned = 1;
    fprintf(stderr, "linkcell: OMP_STACKSIZE could not start a worker; this query stays on the "
                    "calling thread\n");
}

static void read_stacksize(void) {
    if (!parse_stacksize("OMP_STACKSIZE", &g_stacksize) &&
        !parse_stacksize("GOMP_STACKSIZE", &g_stacksize)) {
        g_stacksize = 0;
        return;
    }
    if (g_stacksize < stack_floor()) {
        g_stacksize = stack_floor();
        note_stack_raised();
    }
#ifdef __APPLE__
    /* `pthread_attr_setstacksize` refuses a size that is not a whole
     * number of pages. */
    {
        long page = sysconf(_SC_PAGESIZE);
        if (page > 0 && g_stacksize % (size_t)page != 0) {
            size_t add = (size_t)page - g_stacksize % (size_t)page;
            if (g_stacksize <= SIZE_MAX - add) {
                g_stacksize += add;
            }
        }
    }
#endif
}

/* 1 started, 0 the place could not be applied, -1
 * `pthread_attr_setstacksize` returned EINVAL, -2 some other start
 * failure. A `pthread_create` failure is -2, including EAGAIN. */
static int create_worker(pthread_t *th, void *arg, const void *place) {
    pthread_attr_t attr;
    int set;
    if (pthread_attr_init(&attr) != 0) {
        return -2;
    }
    if (g_stacksize != 0) {
        set = pthread_attr_setstacksize(&attr, g_stacksize);
        if (set != 0) {
            pthread_attr_destroy(&attr);
            return set == EINVAL ? -1 : -2;
        }
    }
#ifdef LC_AFFINITY
    if (place != NULL &&
        pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), (const cpu_set_t *)place) != 0) {
        pthread_attr_destroy(&attr);
        return 0;
    }
#else
    (void)place;
    pthread_attr_getguardsize(&attr, &g_guard);
#endif
    if (pthread_create(th, &attr, team_worker, arg) != 0) {
        pthread_attr_destroy(&attr);
        return -2;
    }
    pthread_attr_destroy(&attr);
    return 1;
}

/* A bound slot starts on its place, as an OpenMP worker does. When that
 * place cannot be applied, a second start keeps the stack size and
 * inherits the caller's mask. A size below the stack floor was already
 * raised to it. EINVAL from `pthread_attr_setstacksize` is remembered,
 * and a later query does not try the size. A `pthread_create` failure
 * warns once and leaves the size to be tried on the next query. */
static int start_worker(int slot, int nt, int bind, int np) {
    pthread_t *th = &g_team.workers[slot];
    void *arg = (void *)(intptr_t)slot;
    int rc;
#ifdef LC_AFFINITY
    cpu_set_t set;
#endif
    pthread_once(&g_stack_once, read_stacksize);
    if (g_stack_refused) {
        return 0;
    }
#ifdef LC_AFFINITY
    if (np > 0 && place_mask(place_of(bind, slot, nt, np), &set)) {
        rc = create_worker(th, arg, &set);
        if (rc == 1) {
            return 1;
        }
        if (rc == -1) {
            note_stack_refused();
            return 0;
        }
    }
#else
    (void)nt;
    (void)bind;
    (void)np;
#endif
    rc = create_worker(th, arg, NULL);
    if (rc == 1) {
        return 1;
    }
    if (rc == -1) {
        note_stack_refused();
        return 0;
    }
    if (g_stacksize != 0) {
        note_stack_create_failed();
        return 0;
    }
    fprintf(stderr, "linkcell: k-nearest worker %d failed to start\n", slot);
    return 0;
}

/* Called with `mu` held and the team empty. Returns with `mu` held. A
 * short team cannot run the static shares, so a failed start joins the
 * workers it made and leaves the team empty. */
static int start_team(int want) {
#ifdef LC_AFFINITY
    int bind = (int)omp_get_proc_bind();
    int np = bind == omp_proc_bind_false ? 0 : omp_get_num_places();
#else
    int bind = 0;
    int np = 0;
#endif
    int slot;
    pthread_once(&g_stack_once, read_stacksize);
    if (g_stack_refused) {
        return 0;
    }
    g_stack_starts++;
    g_team.workers = malloc(sizeof *g_team.workers * (size_t)want);
    if (g_team.workers == NULL) {
        return 0;
    }
    g_team.state = LC_START;
    g_team.nt = want;
    g_team.parked = 0;
    g_team.quit = 0;
    g_team.started = 0;
    for (slot = 0; slot < want; slot++) {
        if (!start_worker(slot, want, bind, np)) {
            break;
        }
        g_team.started++;
    }
    if (g_team.started == want) {
        return 1;
    }
    g_team.quit = 1;
    pthread_cond_broadcast(&g_team.cv);
    pthread_mutex_unlock(&g_team.mu);
    for (slot = 0; slot < g_team.started; slot++) {
        pthread_join(g_team.workers[slot], NULL);
    }
    pthread_mutex_lock(&g_team.mu);
    free(g_team.workers);
    g_team.workers = NULL;
    g_team.started = 0;
    g_team.quit = 0;
    g_team.nt = 0;
    g_team.parked = 0;
    g_team.state = LC_EMPTY;
    pthread_cond_broadcast(&g_team.cv);
    return 0;
}

static void ensure_team(int want) {
    if (want < 1) {
        want = 1;
    }
    pthread_mutex_lock(&g_team.mu);
    for (;;) {
        if (g_team.state == LC_STOP) {
            pthread_cond_wait(&g_team.cv, &g_team.mu);
            continue;
        }
        if (g_team.state == LC_UP && g_team.parked == g_team.nt && g_team.nt > 0) {
            break;
        }
        if (g_team.state == LC_EMPTY && !start_team(want)) {
            pthread_mutex_unlock(&g_team.mu);
            return;
        }
        pthread_cond_wait(&g_team.cv, &g_team.mu);
    }
    pthread_mutex_unlock(&g_team.mu);
}

/* Join every worker. Safe to call twice, from a query, and from the
 * image destructor (process exit, or dlclose after the workers have been
 * asked to leave). */
void lc_knn_shutdown_impl(void) {
    pthread_t *workers;
    int started;
    int slot;
    pthread_mutex_lock(&g_team.mu);
    g_team.sized_want = 0;
    if (g_team.state == LC_EMPTY) {
        pthread_mutex_unlock(&g_team.mu);
        return;
    }
    if (g_team.state == LC_STOP) {
        while (g_team.state != LC_EMPTY) {
            pthread_cond_wait(&g_team.cv, &g_team.mu);
        }
        pthread_mutex_unlock(&g_team.mu);
        return;
    }
    while (g_team.busy || g_team.state == LC_START) {
        pthread_cond_wait(&g_team.cv, &g_team.mu);
    }
    if (g_team.state == LC_EMPTY) {
        pthread_mutex_unlock(&g_team.mu);
        return;
    }
    g_team.state = LC_STOP;
    g_team.quit = 1;
    g_team.epoch++;
    workers = g_team.workers;
    started = g_team.started;
    pthread_cond_broadcast(&g_team.cv);
    pthread_mutex_unlock(&g_team.mu);
    for (slot = 0; slot < started; slot++) {
        pthread_join(workers[slot], NULL);
    }
    pthread_mutex_lock(&g_team.mu);
    free(workers);
    g_team.workers = NULL;
    g_team.started = 0;
    g_team.quit = 0;
    g_team.nt = 0;
    g_team.parked = 0;
    g_team.epoch = 0;
    g_team.done = 0;
    g_team.busy = 0;
    g_team.state = LC_EMPTY;
    g_pinned_once = 0;
    pthread_cond_broadcast(&g_team.cv);
    pthread_mutex_unlock(&g_team.mu);
}

__attribute__((destructor)) static void lc_knn_at_unload(void) { lc_knn_shutdown_impl(); }

#ifdef LC_AFFINITY
/* Called with `mu` held. */
static int team_attr(int slot, pthread_attr_t *attr) {
    if (g_team.state != LC_UP || slot < 0 || slot >= g_team.started) {
        return 0;
    }
    return pthread_getattr_np(g_team.workers[slot], attr) == 0;
}
#endif

/* The stack size of worker `slot` as the C library reports it, or 0 when
 * the standing team has no such worker. This is the stack the thread was
 * given, whatever the memory map looks like: a recent glibc on a recent
 * kernel keeps the guard inside the stack mapping, and a reused stack
 * makes no new mapping at all. */
size_t lc_knn_team_stack(int slot) {
    size_t size = 0;
    pthread_mutex_lock(&g_team.mu);
#ifdef LC_AFFINITY
    {
        pthread_attr_t attr;
        if (team_attr(slot, &attr)) {
            if (pthread_attr_getstacksize(&attr, &size) != 0) {
                size = 0;
            }
            pthread_attr_destroy(&attr);
        }
    }
#else
    if (g_team.state == LC_UP && slot >= 0 && slot < g_team.started) {
        size = pthread_get_stacksize_np(g_team.workers[slot]);
#if defined(__APPLE__) && (defined(__arm64__) || defined(__aarch64__))
        /* Darwin places pthread_t 12 KiB into the top 16 KiB stack page
         * and includes that PTHREAD_T_OFFSET in pthread_get_stacksize_np.
         * pthread_attr_setstacksize does not include it, so remove the
         * implementation offset to report the requested usable stack. */
        if (size >= (size_t)12 * 1024) {
            size -= (size_t)12 * 1024;
        }
#endif
    }
#endif
    pthread_mutex_unlock(&g_team.mu);
    return size;
}

size_t lc_knn_pthread_stack_min(void) { return (size_t)PTHREAD_STACK_MIN; }

size_t lc_knn_stack_floor(void) { return stack_floor(); }

size_t lc_knn_stack_starts(void) {
    size_t n;
    pthread_mutex_lock(&g_team.mu);
    n = g_stack_starts;
    pthread_mutex_unlock(&g_team.mu);
    return n;
}

/* The guard size beside that stack, or 0 when the standing team has no
 * such worker. `pthread_attr_setstacksize` keeps a guard, so a live
 * worker reports a size above zero. */
size_t lc_knn_team_guard(int slot) {
    size_t size = 0;
    pthread_mutex_lock(&g_team.mu);
#ifdef LC_AFFINITY
    {
        pthread_attr_t attr;
        if (team_attr(slot, &attr)) {
            if (pthread_attr_getguardsize(&attr, &size) != 0) {
                size = 0;
            }
            pthread_attr_destroy(&attr);
        }
    }
#else
    if (g_team.state == LC_UP && slot >= 0 && slot < g_team.started) {
        size = g_guard;
    }
#endif
    pthread_mutex_unlock(&g_team.mu);
    return size;
}

/* libgomp's size for a parallel region the caller opens with no
 * num_threads clause. With dyn-var set the team is the processors
 * available, at most nthreads-var, less the 15-minute load average
 * rounded as libgomp rounds it, and at least one. thread-limit-var caps
 * the result. Called with `mu` held. */
static int team_size(int want, int dyn) {
    int nt = want;
    int limit;
    if (g_team.sized_want == want && g_team.sized_dyn == dyn) {
        return g_team.sized_nt;
    }
    if (dyn) {
        int procs = omp_get_num_procs();
        double load[3];
        int busy = 0;
        if (procs > want) {
            procs = want;
        }
        if (getloadavg(load, 3) == 3) {
            busy = (int)(load[2] + 0.1);
        }
        procs = busy >= procs ? 1 : procs - busy;
        if (procs < nt) {
            nt = procs;
        }
    }
    limit = omp_get_thread_limit();
    if (limit > 0 && limit < nt) {
        nt = limit;
    }
    if (nt < 1) {
        nt = 1;
    }
    g_team.sized_want = want;
    g_team.sized_dyn = dyn;
    g_team.sized_nt = nt;
    return nt;
}

/* A team of one is the caller: no worker and no handoff. For the query
 * the caller takes the CPU or the place slot 0 would have had, then gets
 * its own mask back. */
static void run_on_caller(const LcJob *job) {
#ifdef LC_AFFINITY
    cpu_set_t mine;
    cpu_set_t set;
    int moved = 0;
    if (job->pin) {
        pthread_mutex_lock(&g_team.mu);
        while (g_team.busy) {
            pthread_cond_wait(&g_team.cv, &g_team.mu);
        }
        least_loaded(1);
        if (g_cpu_n == 1) {
            CPU_ZERO(&set);
            CPU_SET((unsigned)g_cpu[0], &set);
            moved = 1;
        }
        pthread_mutex_unlock(&g_team.mu);
    } else {
        int bind = (int)omp_get_proc_bind();
        int np = bind == omp_proc_bind_false ? 0 : omp_get_num_places();
        moved = np > 0 && place_mask(place_of(bind, 0, 1, np), &set);
    }
    moved = moved && sched_getaffinity(0, sizeof mine, &mine) == 0 &&
            sched_setaffinity(0, sizeof set, &set) == 0;
#endif
    job->bin(job->ctx, 0, 1, 0, job->n_points);
    job->count(job->ctx, 0, 1, 0, job->n_bins);
    job->scan_base(job->ctx, 0, 1, 0, job->n_bins);
    job->scan(job->ctx, 0, 1, 0, job->n_bins);
    job->fill(job->ctx, 0, 1, 0, job->n_points);
    job->select(job->ctx, 0, 1, 0, job->n_blocks);
#ifdef LC_AFFINITY
    if (moved) {
        sched_setaffinity(0, sizeof mine, &mine);
    }
#endif
    if (job->team != NULL) {
        *job->team = 1;
    }
}

/* `bin`, `count`, `scan`, `fill`, and `select` run on the standing team.
 * `scan_base` is the single that publishes each slot's prefix. The
 * caller waits on the condition variable for every slot to finish. A
 * change of team size joins the old team first. `width` above zero
 * stands in for `omp_get_max_threads()`, as a num_threads clause does,
 * and is trimmed and capped the same way. */
void lc_knn_one_region(void *ctx, int pin, int64_t n_points, int64_t n_bins, int64_t n_blocks,
                       lc_knn_phase bin, lc_knn_phase count, lc_knn_phase scan_base,
                       lc_knn_phase scan, lc_knn_phase fill, lc_knn_phase select, int *team,
                       int width) {
    int want = width > 0 ? width : omp_get_max_threads();
    int dyn = omp_get_dynamic() != 0;
    int nt;
    int up;
    LcJob job = {
        .ctx = ctx,
        .pin = pin,
        .n_points = n_points,
        .n_bins = n_bins,
        .n_blocks = n_blocks,
        .bin = bin,
        .count = count,
        .scan_base = scan_base,
        .scan = scan,
        .fill = fill,
        .select = select,
        .team = team,
    };
    if (want < 1) {
        want = 1;
    }
    pthread_mutex_lock(&g_team.mu);
    nt = team_size(want, dyn);
    up = g_team.state == LC_UP && g_team.nt != nt;
    pthread_mutex_unlock(&g_team.mu);
    if (up) {
        lc_knn_shutdown_impl();
        pthread_mutex_lock(&g_team.mu);
        nt = team_size(want, dyn);
        pthread_mutex_unlock(&g_team.mu);
    }
    if (nt <= 1) {
        run_on_caller(&job);
        return;
    }
    ensure_team(nt);
    pthread_mutex_lock(&g_team.mu);
    while (g_team.busy) {
        pthread_cond_wait(&g_team.cv, &g_team.mu);
    }
    if (g_team.state != LC_UP) {
        pthread_mutex_unlock(&g_team.mu);
        run_on_caller(&job);
        return;
    }
    g_team.busy = 1;
    g_team.bar.count = 0;
    g_team.bar.phase = 0;
    g_team.done = 0;
    job.restore = g_pinned_once;
    g_team.job = job;
    g_team.epoch++;
    pthread_cond_broadcast(&g_team.cv);
    while (g_team.done < g_team.nt) {
        pthread_cond_wait(&g_team.cv, &g_team.mu);
    }
    g_team.busy = 0;
    g_pinned_once = pin;
    pthread_cond_broadcast(&g_team.cv);
    pthread_mutex_unlock(&g_team.mu);
}