-
Notifications
You must be signed in to change notification settings - Fork 24
/
lib.c
3373 lines (3010 loc) · 76.2 KB
/
lib.c
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
/*
* Copyright (c) 2016--2021 Wu, Xingbo <[email protected]>
*
* All rights reserved. No warranty, explicit or implicit, provided.
*/
#define _GNU_SOURCE
// headers {{{
#include "lib.h"
#include "ctypes.h"
#include <assert.h>
#include <execinfo.h>
#include <math.h>
#include <netdb.h>
#include <sched.h>
#include <signal.h>
#include <sys/socket.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <time.h>
#include <stdarg.h> // va_start
#if defined(__linux__)
#include <linux/fs.h>
#include <malloc.h> // malloc_usable_size
#elif defined(__APPLE__) && defined(__MACH__)
#include <sys/disk.h>
#include <malloc/malloc.h>
#elif defined(__FreeBSD__)
#include <sys/disk.h>
#include <malloc_np.h>
#endif // OS
#if defined(__FreeBSD__)
#include <pthread_np.h>
#endif
// }}} headers
// math {{{
inline u64
mhash64(const u64 v)
{
return v * 11400714819323198485lu;
}
inline u32
mhash32(const u32 v)
{
return v * 2654435761u;
}
// From Daniel Lemire's blog (2013, lemire.me)
u64
gcd64(u64 a, u64 b)
{
if (a == 0)
return b;
if (b == 0)
return a;
const u32 shift = (u32)__builtin_ctzl(a | b);
a >>= __builtin_ctzl(a);
do {
b >>= __builtin_ctzl(b);
if (a > b) {
const u64 t = b;
b = a;
a = t;
}
b = b - a;
} while (b);
return a << shift;
}
// }}} math
// random {{{
// Lehmer's generator is 2x faster than xorshift
/**
* D. H. Lehmer, Mathematical methods in large-scale computing units.
* Proceedings of a Second Symposium on Large Scale Digital Calculating
* Machinery;
* Annals of the Computation Laboratory, Harvard Univ. 26 (1951), pp. 141-146.
*
* P L'Ecuyer, Tables of linear congruential generators of different sizes and
* good lattice structure. Mathematics of Computation of the American
* Mathematical
* Society 68.225 (1999): 249-260.
*/
struct lehmer_u64 {
union {
u128 v128;
u64 v64[2];
};
};
static __thread struct lehmer_u64 rseed_u128 = {.v64 = {4294967291, 1549556881}};
static inline u64
lehmer_u64_next(struct lehmer_u64 * const s)
{
const u64 r = s->v64[1];
s->v128 *= 0xda942042e4dd58b5lu;
return r;
}
static inline void
lehmer_u64_seed(struct lehmer_u64 * const s, const u64 seed)
{
s->v128 = (((u128)(~seed)) << 64) | (seed | 1);
(void)lehmer_u64_next(s);
}
inline u64
random_u64(void)
{
return lehmer_u64_next(&rseed_u128);
}
inline void
srandom_u64(const u64 seed)
{
lehmer_u64_seed(&rseed_u128, seed);
}
inline double
random_double(void)
{
// random between [0.0 - 1.0]
const u64 r = random_u64();
return ((double)r) * (1.0 / ((double)(~0lu)));
}
// }}} random
// timing {{{
inline u64
time_nsec(void)
{
struct timespec ts;
// MONO_RAW is 5x to 10x slower than MONO
clock_gettime(CLOCK_MONOTONIC, &ts);
return ((u64)ts.tv_sec) * 1000000000lu + ((u64)ts.tv_nsec);
}
inline double
time_sec(void)
{
const u64 nsec = time_nsec();
return ((double)nsec) * 1.0e-9;
}
inline u64
time_diff_nsec(const u64 last)
{
return time_nsec() - last;
}
inline double
time_diff_sec(const double last)
{
return time_sec() - last;
}
// need char str[64]
void
time_stamp(char * str, const size_t size)
{
time_t now;
struct tm nowtm;
time(&now);
localtime_r(&now, &nowtm);
strftime(str, size, "%F %T %z", &nowtm);
}
void
time_stamp2(char * str, const size_t size)
{
time_t now;
struct tm nowtm;
time(&now);
localtime_r(&now, &nowtm);
strftime(str, size, "%F-%H-%M-%S%z", &nowtm);
}
// }}} timing
// cpucache {{{
inline void
cpu_pause(void)
{
#if defined(__x86_64__)
_mm_pause();
#elif defined(__aarch64__)
// nop
#endif
}
inline void
cpu_mfence(void)
{
atomic_thread_fence(MO_SEQ_CST);
}
// compiler fence
inline void
cpu_cfence(void)
{
atomic_thread_fence(MO_ACQ_REL);
}
inline void
cpu_prefetch0(const void * const ptr)
{
__builtin_prefetch(ptr, 0, 0);
}
inline void
cpu_prefetch1(const void * const ptr)
{
__builtin_prefetch(ptr, 0, 1);
}
inline void
cpu_prefetch2(const void * const ptr)
{
__builtin_prefetch(ptr, 0, 2);
}
inline void
cpu_prefetch3(const void * const ptr)
{
__builtin_prefetch(ptr, 0, 3);
}
inline void
cpu_prefetchw(const void * const ptr)
{
__builtin_prefetch(ptr, 1, 0);
}
// }}} cpucache
// crc32c {{{
inline u32
crc32c_u8(const u32 crc, const u8 v)
{
#if defined(__x86_64__)
return _mm_crc32_u8(crc, v);
#elif defined(__aarch64__)
return __crc32cb(crc, v);
#endif
}
inline u32
crc32c_u16(const u32 crc, const u16 v)
{
#if defined(__x86_64__)
return _mm_crc32_u16(crc, v);
#elif defined(__aarch64__)
return __crc32ch(crc, v);
#endif
}
inline u32
crc32c_u32(const u32 crc, const u32 v)
{
#if defined(__x86_64__)
return _mm_crc32_u32(crc, v);
#elif defined(__aarch64__)
return __crc32cw(crc, v);
#endif
}
inline u32
crc32c_u64(const u32 crc, const u64 v)
{
#if defined(__x86_64__)
return (u32)_mm_crc32_u64(crc, v);
#elif defined(__aarch64__)
return (u32)__crc32cd(crc, v);
#endif
}
inline u32
crc32c_inc_123(const u8 * buf, u32 nr, u32 crc)
{
if (nr == 1)
return crc32c_u8(crc, buf[0]);
crc = crc32c_u16(crc, *(u16 *)buf);
return (nr == 2) ? crc : crc32c_u8(crc, buf[2]);
}
inline u32
crc32c_inc_x4(const u8 * buf, u32 nr, u32 crc)
{
//debug_assert((nr & 3) == 0);
const u32 nr8 = nr >> 3;
#pragma nounroll
for (u32 i = 0; i < nr8; i++)
crc = crc32c_u64(crc, ((u64*)buf)[i]);
if (nr & 4u)
crc = crc32c_u32(crc, ((u32*)buf)[nr8<<1]);
return crc;
}
u32
crc32c_inc(const u8 * buf, u32 nr, u32 crc)
{
crc = crc32c_inc_x4(buf, nr, crc);
const u32 nr123 = nr & 3u;
return nr123 ? crc32c_inc_123(buf + nr - nr123, nr123, crc) : crc;
}
// }}} crc32c
// debug {{{
void
debug_break(void)
{
usleep(100);
}
static u64 * debug_watch_u64 = NULL;
static void
watch_u64_handler(const int sig)
{
(void)sig;
const u64 v = debug_watch_u64 ? (*debug_watch_u64) : 0;
fprintf(stderr, "[USR1] %lu (0x%lx)\n", v, v);
}
void
watch_u64_usr1(u64 * const ptr)
{
debug_watch_u64 = ptr;
struct sigaction sa = {};
sa.sa_handler = watch_u64_handler;
sigemptyset(&(sa.sa_mask));
sa.sa_flags = SA_RESTART;
if (sigaction(SIGUSR1, &sa, NULL) == -1) {
fprintf(stderr, "Failed to set signal handler for SIGUSR1\n");
} else {
fprintf(stderr, "to watch> kill -s SIGUSR1 %d\n", getpid());
}
}
static void * debug_bt_state = NULL;
#if defined(BACKTRACE) && defined(__linux__)
// TODO: get exec path on MacOS and FreeBSD
#include <backtrace.h>
static char debug_filepath[1024] = {};
static void
debug_bt_error_cb(void * const data, const char * const msg, const int errnum)
{
(void)data;
if (msg)
dprintf(2, "libbacktrace: %s %s\n", msg, strerror(errnum));
}
static int
debug_bt_print_cb(void * const data, const uintptr_t pc,
const char * const file, const int lineno, const char * const func)
{
u32 * const plevel = (typeof(plevel))data;
if (file || func || lineno) {
dprintf(2, "[%u]0x%012lx " TERMCLR(35) "%s" TERMCLR(31) ":" TERMCLR(34) "%d" TERMCLR(0)" %s\n",
*plevel, pc, file ? file : "???", lineno, func ? func : "???");
} else if (pc) {
dprintf(2, "[%u]0x%012lx ??\n", *plevel, pc);
}
(*plevel)++;
return 0;
}
__attribute__((constructor))
static void
debug_backtrace_init(void)
{
const ssize_t len = readlink("/proc/self/exe", debug_filepath, 1023);
// disable backtrace
if (len < 0 || len >= 1023)
return;
debug_filepath[len] = '\0';
debug_bt_state = backtrace_create_state(debug_filepath, 1, debug_bt_error_cb, NULL);
}
#endif // BACKTRACE
static void
debug_wait_gdb(void * const bt_state)
{
if (bt_state) {
#if defined(BACKTRACE)
dprintf(2, "Backtrace :\n");
u32 level = 0;
backtrace_full(debug_bt_state, 1, debug_bt_print_cb, debug_bt_error_cb, &level);
#endif // BACKTRACE
} else { // fallback to execinfo if no backtrace or initialization failed
void *array[64];
const int size = backtrace(array, 64);
dprintf(2, "Backtrace (%d):\n", size - 1);
backtrace_symbols_fd(array + 1, size - 1, 2);
}
abool v = true;
char timestamp[32];
time_stamp(timestamp, 32);
char threadname[32] = {};
thread_get_name(pthread_self(), threadname, 32);
strcat(threadname, "(!!)");
thread_set_name(pthread_self(), threadname);
char hostname[32];
gethostname(hostname, 32);
const char * const pattern = "[Waiting GDB] %1$s %2$s @ %3$s\n"
" Attach me: " TERMCLR(31) "sudo -Hi gdb -p %4$d" TERMCLR(0) "\n";
char buf[256];
sprintf(buf, pattern, timestamp, threadname, hostname, getpid());
write(2, buf, strlen(buf));
// to continue: gdb> set var v = 0
// to kill from shell: $ kill %pid; kill -CONT %pid
// uncomment this line to surrender the shell on error
// kill(getpid(), SIGSTOP); // stop burning cpu, once
static au32 nr_waiting = 0;
const u32 seq = atomic_fetch_add_explicit(&nr_waiting, 1, MO_RELAXED);
if (seq == 0) {
sprintf(buf, "/run/user/%u/.debug_wait_gdb_pid", getuid());
const int pidfd = open(buf, O_CREAT|O_TRUNC|O_WRONLY, 00644);
if (pidfd >= 0) {
dprintf(pidfd, "%u", getpid());
close(pidfd);
}
}
#pragma nounroll
while (atomic_load_explicit(&v, MO_CONSUME))
sleep(1);
}
#ifndef NDEBUG
void
debug_assert(const bool v)
{
if (!v)
debug_wait_gdb(debug_bt_state);
}
#endif
__attribute__((noreturn))
void
debug_die(void)
{
debug_wait_gdb(debug_bt_state);
exit(0);
}
__attribute__((noreturn))
void
debug_die_perror(void)
{
perror(NULL);
debug_die();
}
#if !defined(NOSIGNAL)
// signal handler for wait_gdb on fatal errors
static void
wait_gdb_handler(const int sig, siginfo_t * const info, void * const context)
{
(void)info;
(void)context;
char buf[64] = "[SIGNAL] ";
strcat(buf, strsignal(sig));
write(2, buf, strlen(buf));
debug_wait_gdb(NULL);
}
// setup hooks for catching fatal errors
__attribute__((constructor))
static void
debug_init(void)
{
void * stack = pages_alloc_4kb(16);
//fprintf(stderr, "altstack %p\n", stack);
stack_t ss = {.ss_sp = stack, .ss_flags = 0, .ss_size = PGSZ*16};
if (sigaltstack(&ss, NULL))
fprintf(stderr, "sigaltstack failed\n");
struct sigaction sa = {.sa_sigaction = wait_gdb_handler, .sa_flags = SA_SIGINFO | SA_ONSTACK};
sigemptyset(&(sa.sa_mask));
const int fatals[] = {SIGSEGV, SIGFPE, SIGILL, SIGBUS, 0};
for (int i = 0; fatals[i]; i++) {
if (sigaction(fatals[i], &sa, NULL) == -1) {
fprintf(stderr, "Failed to set signal handler for %s\n", strsignal(fatals[i]));
fflush(stderr);
}
}
}
__attribute__((destructor))
static void
debug_exit(void)
{
// to get rid of valgrind warnings
stack_t ss = {.ss_flags = SS_DISABLE};
stack_t oss = {};
sigaltstack(&ss, &oss);
if (oss.ss_sp)
pages_unmap(oss.ss_sp, PGSZ * 16);
}
#endif // !defined(NOSIGNAL)
void
debug_dump_maps(FILE * const out)
{
FILE * const in = fopen("/proc/self/smaps", "r");
char * line0 = yalloc(1024);
size_t size0 = 1024;
while (!feof(in)) {
const ssize_t r1 = getline(&line0, &size0, in);
if (r1 < 0) break;
fprintf(out, "%s", line0);
}
fflush(out);
fclose(in);
}
static pid_t perf_pid = 0;
#if defined(__linux__)
__attribute__((constructor))
static void
debug_perf_init(void)
{
const pid_t ppid = getppid();
char tmp[256] = {};
sprintf(tmp, "/proc/%d/cmdline", ppid);
FILE * const fc = fopen(tmp, "r");
const size_t nr = fread(tmp, 1, sizeof(tmp) - 1, fc);
fclose(fc);
// look for "perf record"
if (nr < 12)
return;
tmp[nr] = '\0';
for (u64 i = 0; i < nr; i++)
if (tmp[i] == 0)
tmp[i] = ' ';
char * const perf = strstr(tmp, "perf record");
if (perf) {
fprintf(stderr, "%s: perf detected\n", __func__);
perf_pid = ppid;
}
}
#endif // __linux__
bool
debug_perf_switch(void)
{
if (perf_pid > 0) {
kill(perf_pid, SIGUSR2);
return true;
} else {
return false;
}
}
// }}} debug
// mm {{{
#ifdef ALLOCFAIL
bool
alloc_fail(void)
{
#define ALLOCFAIL_RECP ((64lu))
#define ALLOCFAIL_MAGIC ((ALLOCFAIL_RECP / 3lu))
return ((random_u64() % ALLOCFAIL_RECP) == ALLOCFAIL_MAGIC);
}
#ifdef MALLOCFAIL
extern void * __libc_malloc(size_t size);
void *
malloc(size_t size)
{
if (alloc_fail())
return NULL;
return __libc_malloc(size);
}
extern void * __libc_calloc(size_t nmemb, size_t size);
void *
calloc(size_t nmemb, size_t size)
{
if (alloc_fail())
return NULL;
return __libc_calloc(nmemb, size);
}
extern void *__libc_realloc(void *ptr, size_t size);
void *
realloc(void *ptr, size_t size)
{
if (alloc_fail())
return NULL;
return __libc_realloc(ptr, size);
}
#endif // MALLOC_FAIL
#endif // ALLOC_FAIL
void *
xalloc(const size_t align, const size_t size)
{
#ifdef ALLOCFAIL
if (alloc_fail())
return NULL;
#endif
void * p;
return (posix_memalign(&p, align, size) == 0) ? p : NULL;
}
// alloc cache-line aligned address
void *
yalloc(const size_t size)
{
#ifdef ALLOCFAIL
if (alloc_fail())
return NULL;
#endif
void * p;
return (posix_memalign(&p, 64, size) == 0) ? p : NULL;
}
void **
malloc_2d(const size_t nr, const size_t size)
{
const size_t size1 = nr * sizeof(void *);
const size_t size2 = nr * size;
void ** const mem = malloc(size1 + size2);
u8 * const mem2 = ((u8 *)mem) + size1;
for (size_t i = 0; i < nr; i++)
mem[i] = mem2 + (i * size);
return mem;
}
inline void **
calloc_2d(const size_t nr, const size_t size)
{
void ** const ret = malloc_2d(nr, size);
memset(ret[0], 0, nr * size);
return ret;
}
inline void
pages_unmap(void * const ptr, const size_t size)
{
#ifndef HEAPCHECKING
munmap(ptr, size);
#else
(void)size;
free(ptr);
#endif
}
void
pages_lock(void * const ptr, const size_t size)
{
static bool use_mlock = true;
if (use_mlock) {
const int ret = mlock(ptr, size);
if (ret != 0) {
use_mlock = false;
fprintf(stderr, "%s: mlock disabled\n", __func__);
}
}
}
#ifndef HEAPCHECKING
static void *
pages_do_alloc(const size_t size, const int flags)
{
// vi /etc/security/limits.conf
// * - memlock unlimited
void * const p = mmap(NULL, size, PROT_READ | PROT_WRITE, flags, -1, 0);
if (p == MAP_FAILED)
return NULL;
pages_lock(p, size);
return p;
}
#if defined(__linux__) && defined(MAP_HUGETLB)
#if defined(MAP_HUGE_SHIFT)
#define PAGES_FLAGS_1G ((MAP_HUGETLB | (30 << MAP_HUGE_SHIFT)))
#define PAGES_FLAGS_2M ((MAP_HUGETLB | (21 << MAP_HUGE_SHIFT)))
#else // MAP_HUGE_SHIFT
#define PAGES_FLAGS_1G ((MAP_HUGETLB))
#define PAGES_FLAGS_2M ((MAP_HUGETLB))
#endif // MAP_HUGE_SHIFT
#else
#define PAGES_FLAGS_1G ((0))
#define PAGES_FLAGS_2M ((0))
#endif // __linux__
#endif // HEAPCHECKING
inline void *
pages_alloc_1gb(const size_t nr_1gb)
{
const u64 sz = nr_1gb << 30;
#ifndef HEAPCHECKING
return pages_do_alloc(sz, MAP_PRIVATE | MAP_ANONYMOUS | PAGES_FLAGS_1G);
#else
void * const p = xalloc(1lu << 21, sz); // Warning: valgrind fails with 30
if (p)
memset(p, 0, sz);
return p;
#endif
}
inline void *
pages_alloc_2mb(const size_t nr_2mb)
{
const u64 sz = nr_2mb << 21;
#ifndef HEAPCHECKING
return pages_do_alloc(sz, MAP_PRIVATE | MAP_ANONYMOUS | PAGES_FLAGS_2M);
#else
void * const p = xalloc(1lu << 21, sz);
if (p)
memset(p, 0, sz);
return p;
#endif
}
inline void *
pages_alloc_4kb(const size_t nr_4kb)
{
const size_t sz = nr_4kb << 12;
#ifndef HEAPCHECKING
return pages_do_alloc(sz, MAP_PRIVATE | MAP_ANONYMOUS);
#else
void * const p = xalloc(1lu << 12, sz);
if (p)
memset(p, 0, sz);
return p;
#endif
}
void *
pages_alloc_best(const size_t size, const bool try_1gb, u64 * const size_out)
{
#ifdef ALLOCFAIL
if (alloc_fail())
return NULL;
#endif
// 1gb huge page: at least 0.25GB
if (try_1gb) {
if (size >= (1lu << 28)) {
const size_t nr_1gb = bits_round_up(size, 30) >> 30;
void * const p1 = pages_alloc_1gb(nr_1gb);
if (p1) {
*size_out = nr_1gb << 30;
return p1;
}
}
}
// 2mb huge page: at least 0.5MB
if (size >= (1lu << 19)) {
const size_t nr_2mb = bits_round_up(size, 21) >> 21;
void * const p2 = pages_alloc_2mb(nr_2mb);
if (p2) {
*size_out = nr_2mb << 21;
return p2;
}
}
const size_t nr_4kb = bits_round_up(size, 12) >> 12;
void * const p3 = pages_alloc_4kb(nr_4kb);
if (p3)
*size_out = nr_4kb << 12;
return p3;
}
// }}} mm
// process/thread {{{
static u32 process_ncpu;
#if defined(__FreeBSD__)
typedef cpuset_t cpu_set_t;
#elif defined(__APPLE__) && defined(__MACH__)
typedef u64 cpu_set_t;
#define CPU_SETSIZE ((64))
#define CPU_COUNT(__cpu_ptr__) (__builtin_popcountl(*__cpu_ptr__))
#define CPU_ISSET(__cpu_idx__, __cpu_ptr__) (((*__cpu_ptr__) >> __cpu_idx__) & 1lu)
#define CPU_ZERO(__cpu_ptr__) ((*__cpu_ptr__) = 0)
#define CPU_SET(__cpu_idx__, __cpu_ptr__) ((*__cpu_ptr__) |= (1lu << __cpu_idx__))
#define CPU_CLR(__cpu_idx__, __cpu_ptr__) ((*__cpu_ptr__) &= ~(1lu << __cpu_idx__))
#define pthread_attr_setaffinity_np(...) ((void)0)
#endif
__attribute__((constructor))
static void
process_init(void)
{
// Linux's default is 1024 cpus
process_ncpu = (u32)sysconf(_SC_NPROCESSORS_CONF);
if (process_ncpu > CPU_SETSIZE) {
fprintf(stderr, "%s: can use only %zu cores\n",
__func__, (size_t)CPU_SETSIZE);
process_ncpu = CPU_SETSIZE;
}
thread_set_name(pthread_self(), "main");
}
static inline int
thread_getaffinity_set(cpu_set_t * const cpuset)
{
#if defined(__linux__)
return sched_getaffinity(0, sizeof(*cpuset), cpuset);
#elif defined(__FreeBSD__)
return cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(*cpuset), cpuset);
#elif defined(__APPLE__) && defined(__MACH__)
*cpuset = (1lu << process_ncpu) - 1;
return (int)process_ncpu; // TODO
#endif // OS
}
static inline int
thread_setaffinity_set(const cpu_set_t * const cpuset)
{
#if defined(__linux__)
return sched_setaffinity(0, sizeof(*cpuset), cpuset);
#elif defined(__FreeBSD__)
return cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(*cpuset), cpuset);
#elif defined(__APPLE__) && defined(__MACH__)
(void)cpuset; // TODO
return 0;
#endif // OS
}
void
thread_get_name(const pthread_t pt, char * const name, const size_t len)
{
#if defined(__linux__)
pthread_getname_np(pt, name, len);
#elif defined(__FreeBSD__)
pthread_get_name_np(pt, name, len);
#elif defined(__APPLE__) && defined(__MACH__)
(void)pt;
(void)len;
strcpy(name, "unknown"); // TODO
#endif // OS
}
void
thread_set_name(const pthread_t pt, const char * const name)
{
#if defined(__linux__)
pthread_setname_np(pt, name);
#elif defined(__FreeBSD__)
pthread_set_name_np(pt, name);
#elif defined(__APPLE__) && defined(__MACH__)
(void)pt;
(void)name; // TODO
#endif // OS
}
// kB
long
process_get_rss(void)
{
struct rusage rs;
getrusage(RUSAGE_SELF, &rs);
return rs.ru_maxrss;
}
u32
process_affinity_count(void)
{
cpu_set_t set;
if (thread_getaffinity_set(&set) != 0)
return process_ncpu;
const u32 nr = (u32)CPU_COUNT(&set);
return nr ? nr : process_ncpu;
}
u32
process_getaffinity_list(const u32 max, u32 * const cores)
{
memset(cores, 0, max * sizeof(cores[0]));
cpu_set_t set;
if (thread_getaffinity_set(&set) != 0)
return 0;
const u32 nr_affinity = (u32)CPU_COUNT(&set);
const u32 nr = nr_affinity < max ? nr_affinity : max;
u32 j = 0;
for (u32 i = 0; i < process_ncpu; i++) {
if (CPU_ISSET(i, &set))
cores[j++] = i;
if (j >= nr)
break;
}
return j;
}
void
thread_setaffinity_list(const u32 nr, const u32 * const list)
{
cpu_set_t set;
CPU_ZERO(&set);
for (u32 i = 0; i < nr; i++)
if (list[i] < process_ncpu)
CPU_SET(list[i], &set);
thread_setaffinity_set(&set);
}
void
thread_pin(const u32 cpu)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cpu % process_ncpu, &set);
thread_setaffinity_set(&set);
}
u64
process_cpu_time_usec(void)
{
struct rusage rs;
getrusage(RUSAGE_SELF, &rs);
const u64 usr = (((u64)rs.ru_utime.tv_sec) * 1000000lu) + ((u64)rs.ru_utime.tv_usec);
const u64 sys = (((u64)rs.ru_stime.tv_sec) * 1000000lu) + ((u64)rs.ru_stime.tv_usec);
return usr + sys;
}
struct fork_join_info {
u32 total;
u32 ncores;
u32 * cores;
void *(*func)(void *);
bool args;
union {
void * arg1;
void ** argn;
};
union {
struct { volatile au32 ferr, jerr; };
volatile au64 xerr;
};
};
// DON'T CHANGE!
#define FORK_JOIN_RANK_BITS ((16)) // 16
#define FORK_JOIN_MAX ((1u << FORK_JOIN_RANK_BITS))
/*
* fj(6): T0
* / \
* T0 T4
* / \ /
* T0 T2 T4
* / \ / \ / \
* t0 t1 t2 t3 t4 t5
*/
// recursive tree fork-join
static void *
thread_do_fork_join_worker(void * const ptr)
{
struct entry13 fjp = {.ptr = ptr};
// GCC: Without explicitly casting from fjp.fji (a 45-bit u64 value),
// the high bits will get truncated, which is always CORRECT in gcc.
// Don't use gcc.
struct fork_join_info * const fji = u64_to_ptr(fjp.e3);
const u32 rank = (u32)fjp.e1;
const u32 nchild = (u32)__builtin_ctz(rank ? rank : bits_p2_up_u32(fji->total));
debug_assert(nchild <= FORK_JOIN_RANK_BITS);
pthread_t tids[FORK_JOIN_RANK_BITS];
if (nchild) {
cpu_set_t set;
CPU_ZERO(&set);
pthread_attr_t attr;
pthread_attr_init(&attr);
//pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); // Joinable by default
// fork top-down
for (u32 i = nchild - 1; i < nchild; i--) {
const u32 cr = rank + (1u << i); // child's rank
if (cr >= fji->total)
continue; // should not break
const u32 core = fji->cores[(cr < fji->ncores) ? cr : (cr % fji->ncores)];
CPU_SET(core, &set);