-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib1.c
6904 lines (6280 loc) · 177 KB
/
lib1.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 Wu, Xingbo <[email protected]>
*
* All rights reserved. No warranty, explicit or implicit, provided.
*/
#define _GNU_SOURCE
// headers {{{
#include "lib1.h"
#include <assert.h>
#include <math.h>
#include <execinfo.h>
#include <signal.h>
#include <stdatomic.h>
#include <sys/socket.h>
#include <netdb.h>
// }}} headers
// atomic {{{
/* C11 atomic types */
typedef atomic_bool abool;
typedef atomic_uint_least8_t au8;
typedef atomic_uint_least16_t au16;
typedef atomic_uint_least32_t au32;
typedef atomic_uint_least64_t au64;
typedef atomic_int_least8_t as8;
typedef atomic_int_least16_t as16;
typedef atomic_int_least32_t as32;
typedef atomic_int_least64_t as64;
// }}} atomic
// locking {{{
inline void
spinlock_init(spinlock * const lock)
{
pthread_spin_init(&(lock->lock), PTHREAD_PROCESS_SHARED);
}
inline void
spinlock_lock(spinlock * const lock)
{
//lock->padding[7]++;
const int r = pthread_spin_lock(&(lock->lock));
if (r == EDEADLK) exit(0);
}
inline bool
spinlock_trylock(spinlock * const lock)
{
//lock->padding[7]++;
const int r = pthread_spin_trylock(&(lock->lock));
if (r == 0) return true;
else if (r == EBUSY) return false;
else exit(0);
}
inline void
spinlock_unlock(spinlock * const lock)
{
pthread_spin_unlock(&(lock->lock));
}
inline void
mutexlock_init(mutexlock * const lock)
{
pthread_mutex_init(&(lock->lock), NULL);
}
inline void
mutexlock_lock(mutexlock * const lock)
{
do {
const int r = pthread_mutex_lock(&(lock->lock));
if (r == 0) return;
else if (r != EAGAIN) exit(0);
} while (true);
}
inline bool
mutexlock_trylock(mutexlock * const lock)
{
do {
const int r = pthread_mutex_trylock(&(lock->lock));
if (r == 0) return true;
else if (r == EBUSY) return false;
else if (r != EAGAIN) exit(0);
} while (true);
}
inline void
mutexlock_unlock(mutexlock * const lock)
{
do {
const int r = pthread_mutex_unlock(&(lock->lock));
if (r == 0) return;
else if ((r != EAGAIN)) exit(0);
} while (true);
}
#define RWLOCK_WBIT ((UINT64_C(0x8000000000000000)))
inline void
rwlock_init(rwlock * const lock)
{
au64 * const pvar = (typeof(pvar))(&(lock->var));
atomic_store(pvar, 0);
}
inline bool
rwlock_trylock_read(rwlock * const lock)
{
au64 * const pvar = (typeof(pvar))(&(lock->var));
u64 v0 = *pvar;
if ((v0 & RWLOCK_WBIT) == UINT64_C(0)) {
const u64 v1 = v0 + 1;
const bool r = atomic_compare_exchange_strong(pvar, &v0, v1);
return r;
}
return false;
}
inline void
rwlock_lock_read(rwlock * const lock)
{
while (rwlock_trylock_read(lock) == false);
}
inline void
rwlock_unlock_read(rwlock * const lock)
{
au64 * const pvar = (typeof(pvar))(&(lock->var));
bool r = false;
do {
u64 v0 = *pvar;
const u64 v1 = v0 - 1;
r = atomic_compare_exchange_strong(pvar, &v0, v1);
} while (r == false);
}
inline bool
rwlock_trylock_write(rwlock * const lock)
{
au64 * const pvar = (typeof(pvar))(&(lock->var));
u64 v0 = *pvar;
if ((v0 & RWLOCK_WBIT) == UINT64_C(0)) {
const u64 v1 = v0 | RWLOCK_WBIT;
const bool r = atomic_compare_exchange_strong(pvar, &v0, v1);
if (r) {
while (atomic_load(pvar) != RWLOCK_WBIT);
}
return r;
}
return false;
}
inline void
rwlock_lock_write(rwlock * const lock)
{
while (rwlock_trylock_write(lock) == false);
}
inline void
rwlock_unlock_write(rwlock * const lock)
{
au64 * const pvar = (typeof(pvar))(&(lock->var));
atomic_store(pvar, UINT64_C(0));
}
#undef RWLOCK_WBIT
// }}} locking
// timing {{{
inline u64
time_nsec(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
return ts.tv_sec * UINT64_C(1000000000) + ts.tv_nsec;
}
inline double
time_sec(void)
{
const u64 nsec = time_nsec();
return ((double)nsec) / 1000000000.0;
}
inline u64
time_diff_nsec(const u64 last)
{
return time_nsec() - last;
}
inline double
time_diff_sec(const double last)
{
return time_sec() - last;
}
inline u64
timespec_diff(const struct timespec t0, const struct timespec t1)
{
return UINT64_C(1000000000) * (t1.tv_sec - t0.tv_sec) + (t1.tv_nsec - t0.tv_nsec);
}
// }}} timing
// debug {{{
void
debug_backtrace(void)
{
void *array[100];
const int size = backtrace(array, 100);
dprintf(2, "Backtrace (%d):\n", size);
backtrace_symbols_fd(array, size, 2);
}
static u64 * __ptr_watch_u64 = NULL;
static void
__signal_handler_watch_u64(const int sig)
{
(void)sig;
const u64 v = __ptr_watch_u64 ? (*__ptr_watch_u64) : 0;
fprintf(stderr, "[USR1] %" PRIu64 " (0x%" PRIx64 ")\n", v, v);
}
void
watch_u64_usr1(u64 * const ptr)
{
__ptr_watch_u64 = ptr;
struct sigaction sa = {};
sa.sa_handler = __signal_handler_watch_u64;
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());
}
}
void
debug_wait_gdb(void)
{
debug_backtrace();
bool wait = true;
volatile bool * const v = &wait;
*v = true;
time_t now;
time(&now);
struct tm nowtm;
localtime_r(&now, &nowtm);
char timestamp[64] = {};
strftime(timestamp, 64, "%F %T %Z (%z)", &nowtm);
char hostname[256] = {};
gethostname(hostname, 256);
char threadname[256];
pthread_getname_np(pthread_self(), threadname, 256);
const char * const pattern = "[Waiting GDB] %s %s @ %s\n Attach me: sudo -Hi gdb -p %d\n";
fprintf(stderr, pattern, timestamp, threadname, hostname, getpid());
fflush(stderr);
// to continue: gdb> set var *v = 0
while (*v) {
sleep(1);
}
}
#ifndef NDEBUG
inline void
debug_assert(const bool v)
{
if (!v) debug_wait_gdb();
}
#endif
static void
__signal_handler_wait_gdb(const int sig, siginfo_t * const info, void * const context)
{
(void)info;
(void)context;
printf("[SIGNAL] %s\n", strsignal(sig));
debug_wait_gdb();
}
__attribute__((constructor))
static void
debug_catch_fatals(void)
{
struct sigaction sa = {};
sa.sa_sigaction = __signal_handler_wait_gdb;
sigemptyset(&(sa.sa_mask));
sa.sa_flags = SA_SIGINFO;
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);
}
}
}
void
debug_dump_maps(FILE * const out)
{
FILE * const in = fopen("/proc/self/smaps", "r");
char * line0 = malloc(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;
void
debug_perf_start(void)
{
const pid_t self = getpid();
const pid_t perfpid = fork();
if (perfpid < 0) {
fprintf(stderr, "%s fork() failed\n", __func__);
} else if (perfpid == 0) {
// call perf
char buf[10];
sprintf(buf, "%d", self);
char * args[10] = {};
args[0] = "perf";
args[1] = "record";
args[2] = "--call-graph";
args[3] = "lbr";
args[4] = "--switch-output";
args[5] = "-s";
args[6] = "-p";
args[7] = buf;
args[8] = NULL;
execvp(args[0], args);
fprintf(stderr, "%s execvp() failed\n", __func__);
fflush(stderr);
exit(0);
} else {
__perf_pid = perfpid;
}
}
void
debug_perf_switch(void)
{
if (__perf_pid > 0) {
kill(__perf_pid, SIGUSR2);
}
}
void
debug_perf_stop(void)
{
if (__perf_pid > 0) {
kill(__perf_pid, SIGINT);
}
}
// }}} debug
// bits {{{
inline u32
bits_reverse_u32(const u32 v)
{
const u32 v1 = (v >> 16) | (v << 16);
const u32 v2 = ((v1 & UINT32_C(0xff00ff00)) >> 8) | ((v1 & UINT32_C(0x00ff00ff)) << 8);
const u32 v3 = ((v2 & UINT32_C(0xf0f0f0f0)) >> 4) | ((v2 & UINT32_C(0x0f0f0f0f)) << 4);
const u32 v4 = ((v3 & UINT32_C(0xcccccccc)) >> 2) | ((v3 & UINT32_C(0x33333333)) << 2);
const u32 v5 = ((v4 & UINT32_C(0xaaaaaaaa)) >> 1) | ((v4 & UINT32_C(0x55555555)) << 1);
return v5;
}
inline u64
bits_reverse_u64(const u64 v)
{
const u64 v0 = (v >> 32) | (v << 32);
const u64 v1 = ((v0 & UINT64_C(0xffff0000ffff0000)) >> 16) | ((v0 & UINT64_C(0x0000ffff0000ffff)) << 16);
const u64 v2 = ((v1 & UINT64_C(0xff00ff00ff00ff00)) >> 8) | ((v1 & UINT64_C(0x00ff00ff00ff00ff)) << 8);
const u64 v3 = ((v2 & UINT64_C(0xf0f0f0f0f0f0f0f0)) >> 4) | ((v2 & UINT64_C(0x0f0f0f0f0f0f0f0f)) << 4);
const u64 v4 = ((v3 & UINT64_C(0xcccccccccccccccc)) >> 2) | ((v3 & UINT64_C(0x3333333333333333)) << 2);
const u64 v5 = ((v4 & UINT64_C(0xaaaaaaaaaaaaaaaa)) >> 1) | ((v4 & UINT64_C(0x5555555555555555)) << 1);
return v5;
}
inline u64
bits_rotl_u64(const u64 v, const u64 n)
{
const u64 sh = n & 0x3f;
return (v << sh) | (v >> (64 - sh));
}
inline u64
bits_rotr_u64(const u64 v, const u64 n)
{
const u64 sh = n & 0x3f;
return (v >> sh) | (v << (64 - sh));
}
inline u32
bits_rotl_u32(const u32 v, const u64 n)
{
const u64 sh = n & 0x1f;
return (v << sh) | (v >> (32 - sh));
}
inline u32
bits_rotr_u32(const u32 v, const u64 n)
{
const u64 sh = n & 0x1f;
return (v >> sh) | (v << (32 - sh));
}
// }}} bits
// bitmap {{{
struct bitmap {
u64 bits;
au64 ones;
u64 bm[];
};
inline struct bitmap *
bitmap_create(const u64 bits)
{
struct bitmap * const bm = (typeof(bm))calloc(1, sizeof(*bm) + (sizeof(u64) * ((bits + 63) >> 6)));
bm->bits = bits;
atomic_store(&(bm->ones), 0);
return bm;
}
inline bool
bitmap_test(const struct bitmap * const bm, const u64 idx)
{
return ((idx < bm->bits) && (bm->bm[idx >> 6] & (UINT64_C(1) << (idx & UINT64_C(0x3f))))) ? true : false;
}
inline bool
bitmap_test_all1(struct bitmap * const bm)
{
return atomic_load(&(bm->ones)) == bm->bits ? true : false;
}
inline bool
bitmap_test_all0(struct bitmap * const bm)
{
return atomic_load(&(bm->ones)) == 0 ? true : false;
}
inline void
bitmap_set1(struct bitmap * const bm, const u64 idx)
{
if (idx < bm->bits && bitmap_test(bm, idx) == false) {
bm->bm[idx >> 6] |= (UINT64_C(1) << (idx & UINT64_C(0x3f)));
(void)atomic_fetch_add(&(bm->ones), 1);
}
}
inline void
bitmap_set0(struct bitmap * const bm, const u64 idx)
{
if (idx < bm->bits && bitmap_test(bm, idx) == true) {
bm->bm[idx >> 6] &= ~(UINT64_C(1) << (idx & UINT64_C(0x3f)));
(void)atomic_fetch_sub(&(bm->ones), 1);
}
}
inline u64
bitmap_count(struct bitmap * const bm)
{
return atomic_load(&(bm->ones));
}
inline void
bitmap_set_all1(struct bitmap * const bm)
{
memset(bm->bm, 0xff, (sizeof(u64) * ((bm->bits + 63) >> 6)));
atomic_store(&(bm->ones), bm->bits);
}
inline void
bitmap_set_all0(struct bitmap * const bm)
{
memset(bm->bm, 0, (sizeof(u64) * ((bm->bits + 63) >> 6)));
atomic_store(&(bm->ones), 0);
}
inline void
bitmap_static_init(struct bitmap * const bm, const u64 bits)
{
bm->bits = bits;
bitmap_set_all0(bm);
}
// }}} bitmap
// bloom filter {{{
struct bloomfilter {
u64 nr_probe;
struct bitmap * bm;
};
inline struct bloomfilter *
bf_create(const u64 bpk, const u64 capacity)
{
struct bitmap * const bm = bitmap_create(bpk * capacity);
if (bm) {
struct bloomfilter * const bf = malloc(sizeof(*bf));
bf->nr_probe = log(2.0) * (double)bpk;
bf->bm = bm;
return bf;
}
return NULL;
}
inline void
bf_mark(struct bloomfilter * const bf, u64 hash64)
{
u64 t = hash64;
const u64 inc = bits_rotl_u64(hash64, 31);
struct bitmap * const bm = bf->bm;
for (u64 i = 0; i < bf->nr_probe; i++) {
bitmap_set1(bm, t % bm->bits);
t += inc;
}
}
inline bool
bf_test(const struct bloomfilter * const bf, u64 hash64)
{
u64 t = hash64;
const u64 inc = bits_rotl_u64(hash64, 31);
const struct bitmap * const bm = bf->bm;
for (u64 i = 0; i < bf->nr_probe; i++) {
if (bitmap_test(bm, t % bm->bits) == false) return false;
t += inc;
}
return true;
}
inline void
bf_destroy(struct bloomfilter * const bf)
{
free(bf->bm);
free(bf);
}
// }}} bloom filter
// process/thread {{{
u64
process_get_rss(void)
{
u64 size;
u64 rss;
FILE * const fp = fopen("/proc/self/statm", "r");
if (fp == NULL) return 0;
if (fscanf(fp, "%" PRIu64 "%" PRIu64, &size, &rss) != 2) {
fclose(fp);
return 0;
}
fclose(fp);
return rss * (u64)sysconf(_SC_PAGESIZE);
}
static inline cpu_set_t *
__cpu_set_alloc(size_t * const size_out)
{
const int ncpu = sysconf(_SC_NPROCESSORS_CONF);
const size_t s1 = CPU_ALLOC_SIZE(ncpu);
const size_t s2 = sizeof(cpu_set_t);
const size_t size = s1 > s2 ? s1 : s2;
*size_out = size;
cpu_set_t * const set = malloc(size);
return set;
}
u64
process_affinity_core_count(void)
{
size_t xsize = 0;
cpu_set_t * const set = __cpu_set_alloc(&xsize);
if (sched_getaffinity(0, xsize, set) != 0) {
return sysconf(_SC_NPROCESSORS_CONF);
}
const int nr = CPU_COUNT_S(xsize, set);
free(set);
return (nr > 0) ? nr : sysconf(_SC_NPROCESSORS_CONF);
}
u64
process_affinity_core_list(const u64 max, u64 * const cores)
{
memset(cores, 0, max * sizeof(cores[0]));
size_t xsize = 0;
cpu_set_t * const set = __cpu_set_alloc(&xsize);
if (sched_getaffinity(0, xsize, set) != 0) return 0;
const u64 ncpu = sysconf(_SC_NPROCESSORS_CONF);
const u64 nr_affinity = CPU_COUNT_S(xsize, set);
const u64 nr = nr_affinity < max ? nr_affinity : max;
u64 j = 0;
for (u64 i = 0; i < ncpu; i++) {
if (CPU_ISSET_S((int)i, xsize, set)) {
cores[j++] = i;
}
if (j >= nr) break;
}
free(set);
return j;
}
u64
process_cpu_time_usec(void)
{
struct rusage r;
getrusage(RUSAGE_SELF, &r);
const u64 usr = (r.ru_utime.tv_sec * UINT64_C(1000000)) + r.ru_utime.tv_usec;
const u64 sys = (r.ru_stime.tv_sec * UINT64_C(1000000)) + r.ru_stime.tv_usec;
return usr + sys;
}
void
thread_set_affinity(const u64 cpu)
{
const u64 ncpu = sysconf(_SC_NPROCESSORS_CONF);
size_t xsize = 0;
cpu_set_t * const set = __cpu_set_alloc(&xsize);
CPU_ZERO_S(xsize, set);
CPU_SET_S(cpu % ncpu, xsize, set);
sched_setaffinity(0, xsize, set);
free(set);
}
double
thread_fork_join_private(const u64 nr, void *(*func) (void *), void * const * const argv)
{
if (nr == 0) return 0.0;
const u64 ncpu = sysconf(_SC_NPROCESSORS_CONF);
int cores[ncpu];
size_t xsize = 0;
cpu_set_t * const set = __cpu_set_alloc(&xsize);
const bool force_use = (sched_getaffinity(0, xsize, set) != 0) ? true : false;
u64 j = 0;
for (u64 i = 0; i < ncpu; i++) {
if (force_use || CPU_ISSET_S((int)i, xsize, set)) {
cores[j++] = i;
}
}
const u64 ncores = j;
const u64 nr_threads = nr ? nr : ncores;
pthread_t tids[nr_threads];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
char thname[32];
const double t0 = time_sec();
for (u64 i = 0; i < nr_threads; i++) {
CPU_ZERO_S(xsize, set);
CPU_SET_S(cores[i % ncores], xsize, set);
pthread_attr_setaffinity_np(&attr, xsize, set);
const int r = pthread_create(&(tids[i]), &attr, func, argv[i]);
if (r != 0) {
tids[i] = 0;
} else {
sprintf(thname, "fork_join_%"PRIu64, i);
pthread_setname_np(tids[i], thname);
}
}
for (u64 i = 0; i < nr_threads; i++) {
if (tids[i]) pthread_join(tids[i], NULL);
}
const double dt = time_diff_sec(t0);
pthread_attr_destroy(&attr);
free(set);
return dt;
}
inline double
thread_fork_join(const u64 nr, void *(*func) (void *), void * const arg)
{
const u64 nthreads = nr ? nr : process_affinity_core_count();
void * argv[nthreads];
for (u64 i = 0; i < nthreads; i++) {
argv[i] = arg;
}
return thread_fork_join_private(nthreads, func, argv);
}
inline int
thread_create_at(const u64 cpu, pthread_t * const thread, void *(*start_routine) (void *), void * const arg)
{
const u64 ncpu = sysconf(_SC_NPROCESSORS_CONF);
const u64 cpu_id = cpu % ncpu;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
size_t xsize = 0;
cpu_set_t * const set = __cpu_set_alloc(&xsize);
CPU_ZERO_S(xsize, set);
CPU_SET_S(cpu_id, xsize, set);
pthread_attr_setaffinity_np(&attr, xsize, set);
const int r = pthread_create(thread, &attr, start_routine, arg);
pthread_attr_destroy(&attr);
free(set);
return r;
}
// }}} process/thread
// mm {{{
inline void *
xalloc(const u64 align, const u64 size)
{
void * p;
const int r = posix_memalign(&p, align, size);
if (r == 0) return p;
else return NULL;
}
inline void
pages_unmap(void * const ptr, const size_t size)
{
#ifndef HEAPCHECKING
munmap(ptr, size);
#else
(void)size;
free(ptr);
#endif
}
static inline void *
__pages_alloc(const size_t size, const int flags)
{
void * const p = mmap(NULL, size, PROT_READ | PROT_WRITE, flags | MAP_LOCKED, -1, 0);
if (p == MAP_FAILED) {
return NULL;
}
return p;
}
inline void *
pages_alloc_1gb(const size_t nr_1gb)
{
const u64 sz = nr_1gb << 30;
#ifndef HEAPCHECKING
return __pages_alloc(sz, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | (30 << MAP_HUGE_SHIFT));
#else
void * const p = xalloc(UINT64_C(1) << 30, sz);
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_alloc(sz, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | (21 << MAP_HUGE_SHIFT));
#else
void * const p = xalloc(UINT64_C(1) << 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_alloc(sz, MAP_PRIVATE | MAP_ANONYMOUS);
#else
void * const p = xalloc(UINT64_C(1) << 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)
{
if (try_1gb) {
const size_t nr_1gb = (size + ((UINT64_C(1) << 30) - UINT64_C(1))) >> 30;
// 1gb super huge page: waste < 1/16 or 6.25%
if (((nr_1gb << 30) - size) < (size >> 4)) {
void * const p1 = pages_alloc_1gb(nr_1gb);
if (p1) {
*size_out = nr_1gb << 30;
return p1;
}
}
}
// 2mb huge page: at least 1MB
if (size >= (UINT64_C(1) << 20)) {
const size_t nr_2mb = (size + ((UINT64_C(1) << 21) - UINT64_C(1))) >> 21;
void * const p2 = pages_alloc_2mb(nr_2mb);
if (p2) {
*size_out = nr_2mb << 21;
return p2;
}
}
const size_t nr_4kb = (size + ((UINT64_C(1) << 12) - UINT64_C(1))) >> 12;
void * const p3 = pages_alloc_4kb(nr_4kb);
if (p3) {
*size_out = nr_4kb << 12;
}
return p3;
}
// }}} mm
// oalloc {{{
#define OALLOC_UNIT_POWER ((18))
#define OALLOC_UNIT_SIZE ((UINT64_C(1) << OALLOC_UNIT_POWER))
#define OALLOC_PAGE_POWER ((30))
#define OALLOC_PAGE_SIZE ((UINT64_C(1) << OALLOC_PAGE_POWER))
#define OALLOC_NR_UNIT ((OALLOC_PAGE_SIZE / OALLOC_UNIT_SIZE))
#define OALLOC_NR_PAGE ((1000))
#define OALLOC_NR_SHARDS ((1024))
struct oalloc_lp { // large pool
spinlock lock;
u64 page_id;
u64 unit_id;
u8 * pages[OALLOC_NR_PAGE];
};
struct oalloc_sp { // small pool
spinlock lock;
u8 * unit;
u64 offset;
};
struct oalloc {
struct oalloc_lp lp;
struct oalloc_sp sps[OALLOC_NR_SHARDS];
};
struct oalloc *
oalloc_create(void)
{
struct oalloc * const oa = (typeof(oa))calloc(1, sizeof(*oa));
spinlock_init(&(oa->lp.lock));
for (u64 i = 0; i < OALLOC_NR_SHARDS; i++) {
spinlock_init(&(oa->sps[i].lock));
}
return oa;
}
static u8 *
oalloc_lp_alloc(struct oalloc_lp * const lp)
{
spinlock_lock(&(lp->lock));
if ((lp->unit_id) >= OALLOC_NR_UNIT) {
lp->page_id++;
lp->unit_id = 0;
}
if (lp->page_id >= OALLOC_NR_PAGE) {
spinlock_unlock(&(lp->lock));
return NULL;
}
const u64 pid = lp->page_id;
const u64 uid = lp->unit_id;
if (lp->pages[pid] == NULL) {
u64 size = 0;
lp->pages[pid] = pages_alloc_best(OALLOC_PAGE_SIZE, true, &size);
debug_assert(size == OALLOC_PAGE_SIZE);
}
u8 * const ptr = &(lp->pages[pid][uid << OALLOC_UNIT_POWER]);
lp->unit_id++;
spinlock_unlock(&(lp->lock));
return ptr;
}
void *
oalloc_alloc(const u64 size, struct oalloc * const oa)
{
const u64 s = random_u64() % OALLOC_NR_SHARDS;
struct oalloc_sp * const sp = &(oa->sps[s]);
const u64 asize = (size + 7) & (~ UINT64_C(7));
spinlock_lock(&(sp->lock));
if (sp->unit == NULL || ((sp->offset + asize) > OALLOC_UNIT_SIZE)) {
sp->unit = oalloc_lp_alloc(&(oa->lp));
sp->offset = 0;
if (sp->unit == NULL) {
spinlock_unlock(&(sp->lock));
return NULL;
}
}
void * const ptr = &(sp->unit[sp->offset]);
sp->offset += asize;
spinlock_unlock(&(sp->lock));
return ptr;
}
void
oalloc_destroy(struct oalloc * const oa)
{
for (u64 i = 0; i < OALLOC_NR_PAGE; i++) {
if (oa->lp.pages[i]) {
pages_unmap(oa->lp.pages[i], OALLOC_PAGE_SIZE);
}
}
free(oa);
}
// }}} oalloc
// gcache {{{
struct gcache_object {
struct gcache_object * next;
};
#define GALLOC_SHARDS ((32))
struct gcache_class {
struct gcache_object * heads[GALLOC_SHARDS];
};
struct gcache {
spinlock locks[GALLOC_SHARDS];
u64 nr;
u64 inc;
struct gcache_class cs[];
};
struct gcache *
gcache_create(const u64 nr_classes, const u64 inc)
{
struct gcache * const g = (typeof(g))calloc(1, sizeof(*g) + (nr_classes * sizeof(g->cs[0])));
for (u64 i = 0; i < GALLOC_SHARDS; i++) {
spinlock_init(&(g->locks[i]));
}
g->nr = nr_classes;
g->inc = inc;
return g;
}
static void *
gcache_pull_gc(struct gcache * const g, struct gcache_class * const gc)
{
const u64 r = random_u64();
for (u64 i = 0; i < GALLOC_SHARDS; i++) {
const u64 idx = (i + r) % GALLOC_SHARDS;
if (gc->heads[idx]) {
spinlock_lock(&(g->locks[idx]));
if (gc->heads[idx]) {
struct gcache_object * const curr = gc->heads[idx];
gc->heads[idx] = curr->next;
spinlock_unlock(&(g->locks[idx]));
return (void *)curr;
}
spinlock_unlock(&(g->locks[idx]));
}
}
return NULL;
}
void *
gcache_pull(struct gcache * const g, const u64 size)
{
const u64 idx = (size + g->inc - 1) / g->inc;
if (idx >= g->nr || idx == 0) return NULL;
struct gcache_class * const gc = &(g->cs[idx]);
return gcache_pull_gc(g, gc);
}
static void
gcache_push_gc(struct gcache * const g, struct gcache_class * const gc, struct gcache_object * const go)
{
const u64 idx = random_u64() % GALLOC_SHARDS;
spinlock_lock(&(g->locks[idx]));
go->next = gc->heads[idx];
gc->heads[idx] = go;
spinlock_unlock(&(g->locks[idx]));
}
bool
gcache_push(struct gcache * const g, const u64 size, void * ptr)
{
struct gcache_object * const go = (typeof(go))ptr;
const u64 idx = (size + g->inc - 1) / g->inc;
if (idx >= g->nr || idx == 0) return false;
struct gcache_class * const gc = &(g->cs[idx]);
gcache_push_gc(g, gc, go);
return true;
}
void
gcache_clean(struct gcache * const g)
{