-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathforkrun_ring.c
More file actions
5835 lines (5282 loc) · 206 KB
/
forkrun_ring.c
File metadata and controls
5835 lines (5282 loc) · 206 KB
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
// forkrun_ring.c v3.1.3
// ======================================================================================
// ARCHITECTURE OVERVIEW:
//
// 1. Zero-Copy Ingest: Data moved from stdin to memfd via
// splice/copy_file_range.
// 2. Lock-Free Meta Ring: Ingest publishes chunk coordinates to GlobalState.
// 3. Per-Node Indexers: Find physical boundaries instantly in local memory.
// 4. Unified Scanners: A single core hot-loop handles both UMA and NUMA
// execution.
// 5. Min-Heap Orderer: Resolves extreme skew with O(log N) sorting.
// ======================================================================================
// PHYSICS PARADIGM OVERVIEW:
//
// forkrun operates as a frictionless, one-way, born-local river of data:
// 1. Ingest (Born-local): Data pages are physically pinned to specific NUMA
// sockets at birth
// via `set_mempolicy(MPOL_BIND)` driven by backpressure from indexers. This
// minimizes cross-socket migration and enforces conservation of locality.
// 2. Inertial Claiming (Workers): Workers are "inertial particles". They claim
// a large block
// speculatively via lock-free `atomic_fetch_add` (no CAS retry loops). If
// they overshoot (claim > available), they process the available data and
// dump the remainder into an "escrow" side-channel (pipe) for others,
// preventing slow-path blocks.
// 3. Fallow (Entropy Export): As the workflow unspools, a background fallow
// thread
// punches holes in the backing memfd via `fallocate(PUNCH_HOLE)` to prevent
// OOM without breaking the absolute integer offsets.
//
// CRITICAL INVARIANT: The fast path has no locks and no CAS retry loops.
// Batch signs (-N / +N) encode the scanner's advisory vs the worker's finalized
// contract.
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#ifndef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64
#endif
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <poll.h>
#include <sched.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/eventfd.h>
#include <sys/mman.h>
#include <sys/sendfile.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysinfo.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
// ==============================================================================
// AVX2 FAST DELIMITER SCANNER
// ==============================================================================
#if defined(__x86_64__) || defined(__i386__)
#pragma GCC push_options
#pragma GCC target("avx2,popcnt")
#include <immintrin.h>
// High-throughput AVX2 SIMD scanner. Scans 32 bytes at a time for delimiters.
// Uses `_mm256_movemask_epi8` and `__builtin_popcount` on the bitmask of
// matches to instantly skip ahead by multiple records rather than branching per
// character. If the batch 'target' constraint is met inside the 32-byte vector,
// `__builtin_ctz` finds the exact boundary.
__attribute__((target("avx2,popcnt"))) static inline char *
scan_batch_avx2(char *p, char *end, uint64_t target, char delim) {
uint64_t remaining = target;
const __m256i d_vec = _mm256_set1_epi8(delim);
while (p + 32 <= end) {
__m256i v = _mm256_loadu_si256((const __m256i *)p);
__m256i cmp = _mm256_cmpeq_epi8(v, d_vec);
uint32_t mask = (uint32_t)_mm256_movemask_epi8(cmp);
if (!mask) {
p += 32;
continue;
}
uint32_t hits = (uint32_t)__builtin_popcount(mask);
if (hits < remaining) {
remaining -= hits;
p += 32;
continue;
}
uint32_t to_drop = (uint32_t)(remaining - 1);
for (uint32_t i = 0; i < to_drop; i++) {
mask &= mask - 1;
}
int exact_idx = __builtin_ctz(mask);
return p + exact_idx + 1;
}
while (p < end) {
if (*p == delim) {
remaining--;
if (remaining == 0)
return p + 1;
}
p++;
}
return NULL;
}
#pragma GCC pop_options
#endif
#if defined(__aarch64__)
#include <arm_neon.h>
// ARM NEON equivalent of the AVX2 scanner. Scans 16 bytes at a time.
static inline char *scan_batch_neon(char *p, char *end, uint64_t target,
char delim) {
uint64_t remaining = target;
uint8x16_t d_vec = vdupq_n_u8(delim);
while (p + 16 <= end) {
uint8x16_t v = vld1q_u8((const uint8_t *)p);
uint8x16_t cmp = vceqq_u8(v, d_vec);
uint64_t lo = vgetq_lane_u64(vreinterpretq_u64_u8(cmp), 0);
uint64_t hi = vgetq_lane_u64(vreinterpretq_u64_u8(cmp), 1);
if (lo == 0 && hi == 0) {
p += 16;
continue;
}
uint32_t hits_lo = __builtin_popcountll(lo) / 8;
if (hits_lo < remaining) {
remaining -= hits_lo;
} else {
uint32_t to_drop = (uint32_t)(remaining - 1);
for (uint32_t i = 0; i < to_drop; i++) {
int idx = __builtin_ctzll(lo) / 8;
lo &= ~(0xFFULL << (idx * 8));
}
int exact_idx = __builtin_ctzll(lo) / 8;
return p + exact_idx + 1;
}
uint32_t hits_hi = __builtin_popcountll(hi) / 8;
if (hits_hi < remaining) {
remaining -= hits_hi;
} else {
uint32_t to_drop = (uint32_t)(remaining - 1);
for (uint32_t i = 0; i < to_drop; i++) {
int idx = __builtin_ctzll(hi) / 8;
hi &= ~(0xFFULL << (idx * 8));
}
int exact_idx = __builtin_ctzll(hi) / 8;
return p + 8 + exact_idx + 1;
}
p += 16;
}
while (p < end) {
if (*p == delim) {
remaining--;
if (remaining == 0)
return p + 1;
}
p++;
}
return NULL;
}
#endif
static inline char *try_simd_scan(char *p, char *safe_end, uint64_t target,
char delim) {
if (target == 0 || p >= safe_end)
return NULL;
#if defined(__x86_64__) || defined(__i386__)
static int avx2_supported = -1;
if (__builtin_expect(avx2_supported == -1, 0)) {
__builtin_cpu_init();
avx2_supported =
__builtin_cpu_supports("avx2") && __builtin_cpu_supports("popcnt");
}
if (avx2_supported) {
return scan_batch_avx2(p, safe_end, target, delim);
}
#elif defined(__aarch64__)
return scan_batch_neon(p, safe_end, target, delim);
#endif
return NULL;
}
// --- Architecture Specific Pause Logic ---
#if defined(__x86_64__) || defined(__i386__)
#define cpu_relax() __builtin_ia32_pause()
#elif defined(__aarch64__) || defined(__arm__)
#define cpu_relax() __asm__ __volatile__("yield" ::: "memory")
#elif defined(__riscv)
#define cpu_relax() \
__asm__ __volatile__( \
".option push; .option arch, +zihintpause; pause; .option pop" :: \
: "memory")
#elif defined(__powerpc__) || defined(__ppc__) || defined(__PPC__)
#define cpu_relax() __asm__ __volatile__("or 27,27,27" ::: "memory")
#elif defined(__s390__) || defined(__s390x__)
#define cpu_relax() __asm__ __volatile__("diag 0,0,0x44" ::: "memory")
#else
#define cpu_relax() __asm__ __volatile__("" ::: "memory")
#endif
// --- NUMA Syscalls & Constants ---
#ifndef MPOL_DEFAULT
#define MPOL_DEFAULT 0
#endif
#ifndef MPOL_BIND
#define MPOL_BIND 2
#endif
#ifndef __NR_set_mempolicy
#if defined(__x86_64__)
#define __NR_set_mempolicy 238
#elif defined(__aarch64__) || defined(__riscv)
#define __NR_set_mempolicy 237
#elif defined(__powerpc__) || defined(__PPC__)
#define __NR_set_mempolicy 260
#elif defined(__s390x__)
#define __NR_set_mempolicy 276
#else
#define __NR_set_mempolicy -1
#endif
#endif
#ifndef FALLOC_FL_KEEP_SIZE
#define FALLOC_FL_KEEP_SIZE 0x01
#endif
#ifndef FALLOC_FL_PUNCH_HOLE
#define FALLOC_FL_PUNCH_HOLE 0x02
#endif
#ifndef MFD_CLOEXEC
#define MFD_CLOEXEC 0x0001U
#endif
#ifndef MFD_ALLOW_SEALING
#define MFD_ALLOW_SEALING 0x0002U
#endif
#ifndef O_TMPFILE
#define O_TMPFILE 020200000
#endif
#ifndef F_ADD_SEALS
#define F_ADD_SEALS 1033
#endif
#ifndef F_SEAL_SEAL
#define F_SEAL_SEAL 0x0001
#endif
#ifndef F_SEAL_SHRINK
#define F_SEAL_SHRINK 0x0002
#endif
#ifndef F_SEAL_GROW
#define F_SEAL_GROW 0x0004
#endif
#ifndef F_SEAL_WRITE
#define F_SEAL_WRITE 0x0008
#endif
#ifndef F_SETPIPE_SZ
#define F_SETPIPE_SZ 1031
#endif
#define FLAG_PARTIAL_BATCH (1ULL << 63)
#define FLAG_MAJOR_EOF (1U << 31)
#define PACK_KEY(maj, min) (((uint64_t)(maj) << 32) | (min))
#define HUGE_PAGE_SIZE (2 * 1024 * 1024)
#define SCANNER_CHUNK_SIZE (2 * 1024 * 1024)
#define RING_SIZE_LOG2 20
#define RING_SIZE (1ULL << RING_SIZE_LOG2)
#define RING_MASK (RING_SIZE - 1)
#define CACHE_LINE 128 // Safe for all modern architectures
#define ALIGNED(x) __attribute__((aligned(x > CACHE_LINE ? x : CACHE_LINE)))
#define MAX_CHUNK_SIZE (32 * 1024 * 1024)
#define DAMPING_OFFSET 6
#ifndef FORKRUN_RING_VERSION
#define FORKRUN_RING_VERSION "v3.1.3"
#endif
#define atomic_load_acquire(ptr) __atomic_load_n(ptr, __ATOMIC_ACQUIRE)
#define atomic_load_relaxed(ptr) __atomic_load_n(ptr, __ATOMIC_RELAXED)
#define atomic_store_release(ptr, val) \
__atomic_store_n(ptr, val, __ATOMIC_RELEASE)
#define atomic_store_relaxed(ptr, val) \
__atomic_store_n(ptr, val, __ATOMIC_RELAXED)
#define atomic_fetch_add(ptr, val) \
__atomic_fetch_add(ptr, val, __ATOMIC_SEQ_CST)
#define atomic_fetch_sub(ptr, val) \
__atomic_fetch_sub(ptr, val, __ATOMIC_SEQ_CST)
#define atomic_compare_exchange(ptr, exp, des) \
__atomic_compare_exchange_n(ptr, exp, des, 0, __ATOMIC_ACQ_REL, \
__ATOMIC_RELAXED)
#ifndef GIT_HASH
#define GIT_HASH "unknown"
#endif
#ifndef BUILD_OS
#define BUILD_OS "unknown"
#endif
#ifndef BUILD_ARCH
#define BUILD_ARCH "unknown"
#endif
#ifndef COMPILER_FLAGS
#define COMPILER_FLAGS "unknown"
#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
// clang-format off
#include "command.h"
#include "shell.h"
#include "variables.h"
#include "builtins.h"
#include "common.h"
#include "xmalloc.h" // MUST precede undefs so xfree(argv) compiles correctly
// PHYSICS FIX: Bash violently hijacks memory allocators via macros in config.h.
// We MUST undefine them here to ensure our C structures strictly use glibc libc allocators.
// Crossing streams causes `invalid chunk size` and `double free` heap detonations.
#undef malloc
#undef free
#undef realloc
#undef calloc
// clang-format on
extern void dispose_command(COMMAND *);
extern int execute_command(COMMAND *);
extern int add_builtin(struct builtin *bp, int keep);
static int g_debug = 0;
#define SYS_CHK(x) \
do { \
if ((long)(x) == -1) { \
if (g_debug) \
fprintf(stderr, "forkrun[DEBUG] %s:%d: %s failed: %s\n", __FILE__, \
__LINE__, #x, strerror(errno)); \
} \
} while (0)
// ==============================================================================
// PHYSICS FIX: ROBUST IPC IO WRAPPERS
// ==============================================================================
// For IPC Pipes (Order/Fallow/Escrow). Uses poll() to wait for EAGAIN without
// burning CPU.
static inline ssize_t robust_pipe_read(int fd, void *buf, size_t count,
bool exact) {
char *p = (char *)buf;
size_t left = count;
while (left > 0) {
ssize_t r = read(fd, p, left);
if (r < 0) {
if (errno == EINTR)
continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) {
struct pollfd pfd = {.fd = fd, .events = POLLIN};
poll(&pfd, 1, -1);
continue;
}
return (count - left) > 0 ? (ssize_t)(count - left) : -1;
}
if (r == 0)
return count - left; // EOF
p += r;
left -= r;
// CRITICAL FIX: If exact is false, return immediately after ANY successful
// read to prevent Fallow/Order threads from deadlocking on partial queues.
if (!exact)
return count - left;
}
return count;
}
static inline ssize_t robust_pipe_write(int fd, const void *buf, size_t count) {
const char *p = (const char *)buf;
size_t left = count;
while (left > 0) {
ssize_t w = write(fd, p, left);
if (w < 0) {
if (errno == EINTR)
continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) {
struct pollfd pfd = {.fd = fd, .events = POLLOUT};
poll(&pfd, 1, -1);
continue;
}
return -1;
}
p += w;
left -= w;
}
return count;
}
// For EventFDs. Strictly returns -1 EAGAIN if empty so lock-free loops can
// proceed.
static inline ssize_t sys_read(int fd, void *buf, size_t count) {
ssize_t r;
do {
r = read(fd, buf, count);
} while (r < 0 && errno == EINTR);
return r;
}
static inline ssize_t sys_write(int fd, const void *buf, size_t count) {
ssize_t w;
do {
w = write(fd, buf, count);
} while (w < 0 && errno == EINTR);
return w;
}
// RESTORED LOADABLES MACRO
#define FORKRUN_LOADABLES(X) \
X(ring_init, ring_init_main, "ring_init [FLAGS]", \
"Initialize ring with config") \
X(ring_destroy, ring_destroy_main, "ring_destroy", "Destroy ring") \
X(ring_scanner, ring_scanner_main, "ring_scanner <fd> [spawn_fd]", \
"Run unified legacy scanner") \
X(ring_numa_ingest, ring_numa_ingest_main, \
"ring_numa_ingest <infd> <outfd> <nodes> [ordered]", \
"Run NUMA topological ingest") \
X(ring_indexer_numa, ring_indexer_numa_main, \
"ring_indexer_numa <memfd> <node_id>", "Run NUMA chunk indexer") \
X(ring_numa_scanner, ring_numa_scanner_main, \
"ring_numa_scanner <memfd> <node_id> <spawn_fd> <nodes>", \
"Run unified NUMA scanner") \
X(ring_claim, ring_claim_main, "ring_claim [VAR] [FD]", "Claim batch") \
X(ring_worker, ring_worker_main, "ring_worker [inc|dec] [FD]", \
"Worker control") \
X(ring_cleanup_waiter, ring_cleanup_waiter_main, "ring_cleanup_waiter", \
"Cleanup waiter") \
X(ring_ingest, ring_ingest_main, "ring_ingest", "Signal ingest") \
X(ring_fallow, ring_fallow_main, "ring_fallow <PIPE> <FILE> [dry]", \
"Logical fallow") \
X(ring_ack, ring_ack_main, "ring_ack <FD> <FD_OUT>", "Ack batch") \
X(ring_order, ring_order_main, "ring_order <FD> <PFX|memfd> [unordered]", \
"Reorder output") \
X(ring_copy, ring_copy_main, "ring_copy <OUT> <IN>", "Zero-copy ingest") \
X(ring_signal, ring_signal_main, "ring_signal <FD>", "Signal eventfd") \
X(lseek, lseek_main, "lseek <FD> <OFF> [WHENCE] [VAR]", "Seek fd") \
X(ring_indexer, ring_indexer_main, "ring_indexer", "NUMA Indexer") \
X(ring_fetcher, ring_fetcher_main, "ring_fetcher", "NUMA Fetcher") \
X(ring_fallow_phys, ring_fallow_phys_main, "ring_fallow_phys", \
"Physical fallow") \
X(ring_memfd_create, ring_memfd_create_main, "ring_memfd_create <VAR>", \
"Create memfd") \
X(ring_seal, ring_seal_main, "ring_seal <FD>", "Seal memfd") \
X(ring_fcntl, ring_fcntl_main, "ring_fcntl <FD> <cmd>", "File control") \
X(ring_pipe, ring_pipe_main, "ring_pipe <ARR|RD> [WR]", "Create pipe") \
X(ring_splice, ring_splice_main, \
"ring_splice <IN> <OUT> <OFF> <LEN> [close]", "Splice data") \
X(ring_version, ring_version_main, "ring_version [-t|-o|-m|-g|-f|-a]", \
"Show build metadata") \
X(ring_numa_stats, ring_numa_stats_main, "ring_numa_stats", \
"Print NUMA telemetry") \
X(ring_list, ring_list_main, "ring_list [VAR]", "List loadables") \
X(ring_poll, ring_poll_main, "ring_poll <spawn_fd> <scan_arr> <work_arr>", "Poll FDs") \
X(ring_revert_output, ring_revert_output_main, "ring_revert_output <fd>", "Revert partial output") \
X(ring_ack_init, ring_ack_init_main, "ring_ack_init <fd>", "Sync output offset") \
X(ring_escrow_put, ring_escrow_put_main, "ring_escrow_put <node> <idx> <cnt> <kills>", "Deposit to escrow") \
X(ring_dump_resume, ring_dump_resume_main, "ring_dump_resume [bytes]", "Dump checkpoint state") \
X(ring_set_resume, ring_set_resume_main, "ring_set_resume <horizon> [jagged...]", "Set checkpoint state") \
X(ring_abort, ring_abort_main, "ring_abort", "Trigger global emergency abort")
#define X(name, func, usage, doc) static int func(int argc, char **argv);
FORKRUN_LOADABLES(X)
#undef X
static inline int auto_detect_numa_node() {
#ifdef __NR_getcpu
unsigned cpu, node;
if (syscall(__NR_getcpu, &cpu, &node, NULL) == 0)
return (int)node;
#endif
return 0;
}
static int pin_to_numa_node(int node_id) {
char path[256];
snprintf(path, sizeof(path), "/sys/devices/system/node/node%d/cpulist",
node_id);
int fd = open(path, O_RDONLY);
if (fd < 0)
return -1;
char buf[1024] = {0};
ssize_t n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0)
return -1;
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
char *p = buf;
while (*p) {
while (*p && !isdigit(*p))
p++;
if (!*p)
break;
int start = strtol(p, &p, 10);
int end = start;
if (*p == '-') {
p++;
end = strtol(p, &p, 10);
}
for (int i = start; i <= end; i++) {
if (i >= 0 && i < CPU_SETSIZE) {
CPU_SET(i, &cpuset);
}
}
while (*p && *p != ',' && *p != '\n')
p++;
}
return sched_setaffinity(0, sizeof(cpu_set_t), &cpuset);
}
static SHELL_VAR *bind_var_or_array(const char *name, char *value, int flags) {
if (!name)
return NULL;
const char *lb = strchr(name, '[');
if (!lb || name[strlen(name) - 1] != ']')
return bind_variable(name, value, flags);
size_t base_len = (size_t)(lb - name);
char base_tmp[256];
if (base_len >= sizeof(base_tmp))
return NULL;
memcpy(base_tmp, name, base_len);
base_tmp[base_len] = '\0';
size_t idx_len = strlen(lb + 1) - 1;
char idx_tmp[256];
if (idx_len >= sizeof(idx_tmp))
return NULL;
memcpy(idx_tmp, lb + 1, idx_len);
idx_tmp[idx_len] = '\0';
SHELL_VAR *var = find_variable(base_tmp);
if (!var) {
var = make_new_array_variable(base_tmp);
if (!var)
return NULL;
}
SHELL_VAR *ret = NULL;
if (assoc_p(var))
ret = bind_assoc_variable(var, base_tmp, idx_tmp, value, flags);
else if (array_p(var)) {
char *endp = NULL;
errno = 0;
long n = strtol(idx_tmp, &endp, 10);
if (endp == idx_tmp || *endp != '\0' || errno == ERANGE) {
} else
ret = bind_array_variable(base_tmp, (arrayind_t)n, value, flags);
}
return ret;
}
static uint64_t get_cache_bytes() {
long sz = -1;
#ifdef _SC_LEVEL2_CACHE_SIZE
sz = sysconf(_SC_LEVEL2_CACHE_SIZE);
#endif
if (sz <= 0) {
#ifdef _SC_LEVEL3_CACHE_SIZE
sz = sysconf(_SC_LEVEL3_CACHE_SIZE);
#endif
}
if (sz <= 0)
return 512 * 1024;
return (uint64_t)sz;
}
static uint64_t get_llc_size() {
#ifdef _SC_LEVEL3_CACHE_SIZE
long sz = sysconf(_SC_LEVEL3_CACHE_SIZE);
if (sz > 0)
return (uint64_t)sz;
#endif
int fd = open("/sys/devices/system/cpu/cpu0/cache/index3/size", O_RDONLY);
if (fd >= 0) {
char buf[32];
ssize_t n = sys_read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n > 0) {
buf[n] = '\0';
char *end;
uint64_t val = strtoull(buf, &end, 10);
if (*end == 'K' || *end == 'k')
val *= 1024;
else if (*end == 'M' || *end == 'm')
val *= 1024 * 1024;
if (val > 0)
return val;
}
}
return get_cache_bytes() * 8;
}
static uint64_t get_optimal_chunk_size() {
uint64_t llc = get_llc_size();
uint64_t target = llc >> 3;
uint64_t mask = HUGE_PAGE_SIZE - 1;
target = (target + mask) & ~mask;
if (target < HUGE_PAGE_SIZE)
target = HUGE_PAGE_SIZE;
if (target > MAX_CHUNK_SIZE)
target = MAX_CHUNK_SIZE;
return target;
}
static uint64_t get_arg_max_bytes() {
long sys_arg_max = sysconf(_SC_ARG_MAX);
if (sys_arg_max <= 0)
return 2097152;
size_t env_len = 0;
extern char **environ;
for (char **ep = environ; *ep; ++ep)
env_len += strlen(*ep) + 1;
if ((long)env_len < sys_arg_max)
return (uint64_t)((sys_arg_max - (long)env_len) * 15 / 16);
return 32768;
}
static int xcreate_anon_file(const char *name) {
const char *force_fallback = get_string_value("FORKRUN_FORCE_FALLBACK");
bool use_memfd = true;
if (force_fallback && (strcmp(force_fallback, "1") == 0))
use_memfd = false;
if (use_memfd) {
int fd = syscall(__NR_memfd_create, name, MFD_ALLOW_SEALING);
if (fd >= 0)
return fd;
if (errno == EINVAL) {
fd = syscall(__NR_memfd_create, name, 0);
if (fd >= 0)
return fd;
}
}
int fd = open("/dev/shm", O_TMPFILE | O_RDWR | O_EXCL, 0600);
if (fd >= 0)
return fd;
fd = open("/tmp", O_TMPFILE | O_RDWR | O_EXCL, 0600);
if (fd >= 0)
return fd;
char path[64];
snprintf(path, sizeof(path), "/dev/shm/forkrun.XXXXXX");
fd = mkstemp(path);
if (fd < 0) {
snprintf(path, sizeof(path), "/tmp/forkrun.XXXXXX");
fd = mkstemp(path);
}
if (fd >= 0)
unlink(path);
return fd;
}
static inline void u64toa(uint64_t value, char *buffer) {
char temp[24];
char *p = temp;
if (value == 0) {
*buffer++ = '0';
*buffer = '\0';
return;
}
do {
*p++ = (char)(value % 10) + '0';
value /= 10;
} while (value > 0);
int i = 0;
while (p > temp)
buffer[i++] = *--p;
buffer[i] = '\0';
}
static inline uint64_t get_us_time() {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC_COARSE, &ts);
return (uint64_t)ts.tv_sec * 1000000ULL + (uint64_t)ts.tv_nsec / 1000;
}
static inline uint64_t fast_log2(uint64_t v) {
if (v < 2)
return 0;
return 63 - __builtin_clzll(v);
}
// ==============================================================================
// 2. TLS AND SHARED STATE
// ==============================================================================
static __thread int my_numa_node = -1;
static __thread bool is_waiting_on_ring = false;
static __thread int worker_cached_fd = -1;
static __thread off_t last_ack_offset = 0;
static __thread int ack_cached_target_fd = -1;
static __thread int ack_cached_mode = 0;
static __thread uint64_t worker_last_idx = 0;
static __thread uint64_t worker_last_cnt = 0;
static __thread uint32_t worker_last_major = 0;
static __thread uint32_t worker_last_minor = 0;
static __thread uint64_t tl_remainder_idx = 0;
static __thread uint64_t tl_remainder_cnt = 0;
static __thread bool tl_recently_escrowed = false;
static int *evfd_data_arr = NULL;
static int *evfd_eof_arr = NULL;
static int *evfd_indexer_arr = NULL;
static int *evfd_meta_arr = NULL;
static int *fd_escrow_r = NULL;
static int *fd_escrow_w = NULL;
static int evfd_data = -1;
static int evfd_ingest_data = -1;
static int evfd_ingest_eof = -1;
static int evfd_chunk_done = -1;
static int fd_escrow[2] = {-1, -1};
static uint32_t global_num_nodes = 0;
static uint32_t allocated_num_nodes = 0;
static uint32_t *g_logical_to_phys_map = NULL;
static uint8_t g_explicit_pinning = 0; // NEW
// EscrowPacket: Used to solve the "overshoot" problem. When a worker
// speculatively claims more offsets than are currently available from the
// scanner, it processes the available ones and "deposits" the remaining claimed
// count into a side-channel pipe (escrow) for other idle workers to steal.
// NOTE: A given worker can (at any given time) only have a single escrow claim,
// and these claims are inherently rare occurrences (happen only in rare races).
// This means in practice the escrow pipe buffer will NEVER fill up (even if
// its capacity is 64 KB, and especially not at 1 MB).
struct EscrowPacket {
uint64_t idx;
uint64_t cnt;
uint32_t num_kills;
uint32_t _pad;
};
// IndexPacket: Legacy flat-mode packet for passing physical offsets.
struct IndexPacket {
uint64_t idx;
uint64_t cnt;
};
struct PhysPacket {
uint64_t off;
uint64_t len;
};
struct OrderPacket {
uint32_t major_idx;
uint32_t minor_idx;
uint32_t cnt;
int32_t fd;
uint64_t off;
uint64_t len;
uint64_t in_off; // NEW: Absolute input byte start
uint64_t in_len; // NEW: Input byte length
};
#define FLAG_META_READY (1ULL << 63)
#define META_RING_SIZE 4096
#define META_RING_MASK (META_RING_SIZE - 1)
// ChunkMeta: Lock-free metadata describing a slice of physical data added by
// ingest. Workers and the global scanner use this to align physical bounds
// without taking locks.
struct ChunkMeta {
uint64_t raw_offset;
uint64_t raw_length;
uint32_t target_node;
// major_id aligns with chunk boundaries, minor_id will align with individual
// records.
uint32_t major_id;
volatile uint64_t actual_end ALIGNED(CACHE_LINE);
};
struct IntervalNode {
uint64_t s;
uint64_t e;
};
// GlobalState: Contains cross-socket coordination for the pipeline,
struct GlobalState {
uint64_t ingest_publish_idx ALIGNED(CACHE_LINE);
uint64_t ingest_eof_idx ALIGNED(CACHE_LINE);
uint64_t _pad_ingest_waiters[7];
// NEW: Orderer Ledger (The Checkpoint)
uint8_t is_resume_mode ALIGNED(CACHE_LINE);
volatile uint32_t resume_seq; // NEW: Seqlock counter
uint64_t resume_horizon;
uint64_t resume_stdout_bytes;
uint64_t fallow_horizon_bytes; // NEW: Fallback for realtime mode
uint32_t resume_jagged_count;
struct IntervalNode resume_jagged[1024];
struct ChunkMeta meta_ring[META_RING_SIZE];
};
// SharedState: Per-NUMA-socket lock-free ring and state counters.
// This enforces "Conservation of Momentum" - each socket manages its own data
// river. Workers on node i read from state[i]. Variables are CACHE_LINE aligned
// to prevent false-sharing ping-pong between cores on the fast path.
struct SharedState {
uint64_t chunk_queue_head ALIGNED(CACHE_LINE);
uint8_t _pad_cq_head[CACHE_LINE - sizeof(uint64_t)];
uint64_t chunk_ready_head ALIGNED(CACHE_LINE);
uint8_t _pad_cr_head[CACHE_LINE - sizeof(uint64_t)];
uint64_t chunk_queue_tail ALIGNED(CACHE_LINE);
uint8_t _pad_cq_tail[CACHE_LINE - sizeof(uint64_t)];
uint32_t chunk_queue[META_RING_SIZE];
uint64_t read_idx ALIGNED(CACHE_LINE);
uint8_t _pad_read_idx[CACHE_LINE - sizeof(uint64_t)];
uint64_t write_idx ALIGNED(CACHE_LINE);
uint8_t _pad_write_idx[CACHE_LINE - sizeof(uint64_t)];
uint64_t total_lines_consumed ALIGNED(CACHE_LINE);
uint8_t _pad_lines[CACHE_LINE - sizeof(uint64_t)];
uint32_t active_waiters ALIGNED(CACHE_LINE);
uint8_t _pad_waiters[CACHE_LINE - sizeof(uint32_t)];
uint64_t active_workers ALIGNED(CACHE_LINE);
uint64_t global_scanned;
uint64_t tail_idx;
uint8_t scanner_finished;
uint8_t fallow_active;
uint8_t ingest_complete;
uint8_t emergency_abort;
uint32_t indexer_waiters ALIGNED(CACHE_LINE);
uint32_t meta_waiters ALIGNED(CACHE_LINE);
uint64_t min_idx;
int64_t signed_batch_size;
uint64_t batch_change_idx;
uint64_t cfg_w_start ALIGNED(CACHE_LINE);
uint64_t cfg_w_max;
uint64_t cfg_batch_start;
uint64_t cfg_batch_max;
uint64_t cfg_limit;
uint64_t cfg_chunk_bytes;
uint64_t cfg_line_max;
int64_t cfg_timeout_us;
uint8_t mode_byte;
uint8_t fixed_workers;
uint8_t fixed_batch;
uint8_t cfg_return_bytes;
uint8_t numa_enabled;
uint8_t exact_lines;
uint8_t cfg_delim; // Record delimiter character (default '\n')
uint64_t stats_chunks_assigned ALIGNED(CACHE_LINE);
uint64_t stats_chunks_processed;
uint64_t stats_chunks_i_stole;
uint64_t stats_chunks_stolen_from_me;
uint32_t stride_ring[RING_SIZE] ALIGNED(4096);
uint64_t offset_ring[RING_SIZE] ALIGNED(4096);
uint64_t end_ring[RING_SIZE] ALIGNED(4096);
uint32_t major_ring[RING_SIZE] ALIGNED(4096);
uint32_t minor_ring[RING_SIZE] ALIGNED(4096);
// NEW: Dynamic Topology-Aware Steal Thresholds
uint8_t steal_threshold[1024] ALIGNED(CACHE_LINE);
uint32_t chunk_buffer_limit; // Dynamic limit (Ingest -> Scanner)
};
static struct GlobalState *g_state = NULL;
static struct SharedState *state = NULL;
static inline void cleanup_waiter_state() {
if (is_waiting_on_ring) {
int node = (my_numa_node == -1) ? 0 : my_numa_node;
if (state && atomic_load_relaxed(&state[node].active_waiters) > 0) {
atomic_fetch_sub(&state[node].active_waiters, 1);
}
is_waiting_on_ring = false;
}
}
// EMERGENCY SHUTDOWN: Global fire alarm sentry.
// Any thread (Worker or Orderer) can call this to trigger an immediate system-wide
// abort. It atomically flips emergency_abort to 1 (CAS ensures we only blast once),
// then blasts ALL EOF eventfds to wake every sleeping poll across the engine.
// Data eventfds are left untouched to preserve the conservation laws of the ring.
static inline void pull_fire_alarm() {
if (!state) return;
// CAS: Only the first caller blasts the eventfds
uint8_t expected = 0;
if (__atomic_compare_exchange_n(&state[0].emergency_abort, &expected, 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) {
uint64_t blast = 999999;
for (uint32_t n = 0; n < allocated_num_nodes; n++) {
if (evfd_eof_arr && evfd_eof_arr[n] >= 0) sys_write(evfd_eof_arr[n], &blast, 8);
}
if (evfd_ingest_eof >= 0) sys_write(evfd_ingest_eof, &blast, 8);
if (evfd_chunk_done >= 0) sys_write(evfd_chunk_done, &blast, 8); // Wake up Ingest
}
}
#define OOM_WAIT_FOR_MEMORY(free_b_var, threshold, si_var, mu_var) \
do { \
int _oom_sleep_us = 1000; \
int _oom_waited_us = 0; \
while ((free_b_var) < (threshold) && _oom_waited_us < 30000000) { \
usleep(_oom_sleep_us); \
_oom_waited_us += _oom_sleep_us; \
sysinfo(&(si_var)); \
(free_b_var) = (uint64_t)(si_var).freeram * (mu_var); \
_oom_sleep_us += _oom_sleep_us >> 1; \
if (_oom_sleep_us > 100000) \
_oom_sleep_us = 100000; \
} \
} while (0)
static int get_cgroup_free_memory(uint64_t *free_mem) {
char buf[128];
int fd = open("/sys/fs/cgroup/memory.max", O_RDONLY);
if (fd >= 0) {
ssize_t n = sys_read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n > 0) {
buf[n] = '\0';
if (strncmp(buf, "max", 3) == 0)
return -1;
uint64_t max_val = strtoull(buf, NULL, 10);
fd = open("/sys/fs/cgroup/memory.current", O_RDONLY);
if (fd >= 0) {
n = sys_read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n > 0) {
buf[n] = '\0';
uint64_t cur_val = strtoull(buf, NULL, 10);
*free_mem = (max_val > cur_val) ? (max_val - cur_val) : 0;
return 0;
}
}
}
}
fd = open("/sys/fs/cgroup/memory/memory.limit_in_bytes", O_RDONLY);
if (fd >= 0) {
ssize_t n = sys_read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n > 0) {
buf[n] = '\0';
uint64_t max_val = strtoull(buf, NULL, 10);
if (max_val > 9000000000000000000ULL)
return -1;
fd = open("/sys/fs/cgroup/memory/memory.usage_in_bytes", O_RDONLY);
if (fd >= 0) {
n = sys_read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n > 0) {
buf[n] = '\0';
uint64_t cur_val = strtoull(buf, NULL, 10);
*free_mem = (max_val > cur_val) ? (max_val - cur_val) : 0;
return 0;
}
}
}
}
return -1;
}