forked from facebook/flow
/
hh_shared.c
1528 lines (1309 loc) · 49.6 KB
/
hh_shared.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) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "hh_shared.h"
/*****************************************************************************/
/* File Implementing the shared memory system for Hack.
*
* THIS CODE ONLY WORKS WITH HACK, IT MAY LOOK LIKE A GENERIC ATOMIC
* HASHTABLE FOR OCAML: IT IS NOT!
* BUT ... YOU WERE GOING TO SAY BUT? BUT ...
* THERE IS NO BUT! DONNY YOU'RE OUT OF YOUR ELEMENT!
*
* The lock-free data structures implemented here only work because of how the
* Hack phases are synchronized.
*
* The hashtable maps string keys to string values. (The strings are really
* serialized / marshalled representations of OCaml structures.) Key observation
* of the table is that data with the same key are considered equivalent, and so
* you can arbitrarily get any copy of it; furthermore if data is missing it can
* be recomputed, so incorrectly saying data is missing when it is being written
* is only a potential perf loss. Note that "equivalent" doesn't necessarily
* mean "identical", e.g., two alpha-converted types are "equivalent" though not
* literally byte- identical. (That said, I'm pretty sure the Hack typechecker
* actually does always write identical data, but the hashtable doesn't need
* quite that strong of an invariant.)
*
* The operations implemented, and their limitations:
*
* -) Concurrent writes: SUPPORTED One will win and the other will get
* dropped on the floor. There is no way to tell which happened. Only promise
* is that after a write, the one thread which did the write will see data in
* the table (though it may be slightly different data than what was written,
* see above about equivalent data).
*
* -) Concurrent reads: SUPPORTED If interleaved with a concurrent write, the
* read will arbitrarily say that there is no data at that slot or return the
* entire new data written by the concurrent writer.
*
* -) Concurrent removes: NOT SUPPORTED Only the master can remove, and can
* only do so if there are no other concurrent operations (reads or writes).
*
* Since the values are variably sized and can get quite large, they are
* stored separately from the hashes in a garbage-collected heap.
*
* Hash collisions are resolved via linear probing.
*/
/*****************************************************************************/
/* For printing uint64_t
* http://jhshi.me/2014/07/11/print-uint64-t-properly-in-c/index.html */
#define __STDC_FORMAT_MACROS
/* define CAML_NAME_SPACE to ensure all the caml imports are prefixed with
* 'caml_' */
#define CAML_NAME_SPACE
#include <caml/mlvalues.h>
#include <caml/callback.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/fail.h>
#include <caml/unixsupport.h>
#include <caml/intext.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/errno.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include <inttypes.h>
#include <lz4.h>
#include <sys/time.h>
#include <time.h>
#include "hh_assert.h"
#define UNUSED(x) \
((void)(x))
#define UNUSED1 UNUSED
#define UNUSED2(a, b) \
(UNUSED(a), UNUSED(b))
#define UNUSED3(a, b, c) \
(UNUSED(a), UNUSED(b), UNUSED(c))
#define UNUSED4(a, b, c, d) \
(UNUSED(a), UNUSED(b), UNUSED(c), UNUSED(d))
#define UNUSED5(a, b, c, d, e) \
(UNUSED(a), UNUSED(b), UNUSED(c), UNUSED(d), UNUSED(e))
// Ideally these would live in a handle.h file but our internal build system
// can't support that at the moment. These are shared with handle_stubs.c
#ifdef _WIN32
#define Val_handle(fd) (win_alloc_handle(fd))
#else
#define Handle_val(fd) (Long_val(fd))
#define Val_handle(fd) (Val_long(fd))
#endif
#define HASHTBL_WRITE_IN_PROGRESS (0xfffffffffffffffeull)
/****************************************************************************
* Quoting the linux manpage: memfd_create() creates an anonymous file
* and returns a file descriptor that refers to it. The file behaves
* like a regular file, and so can be modified, truncated,
* memory-mapped, and so on. However, unlike a regular file, it lives
* in RAM and has a volatile backing storage. Once all references to
* the file are dropped, it is automatically released. Anonymous
* memory is used for all backing pages of the file. Therefore, files
* created by memfd_create() have the same semantics as other
* anonymous memory allocations such as those allocated using mmap(2)
* with the MAP_ANONYMOUS flag. The memfd_create() system call first
* appeared in Linux 3.17.
****************************************************************************/
#ifdef __linux__
// Linux version for the architecture must support syscall memfd_create
#ifndef SYS_memfd_create
#if defined(__x86_64__)
#define SYS_memfd_create 319
#elif defined(__powerpc64__)
#define SYS_memfd_create 360
#elif defined(__aarch64__)
#define SYS_memfd_create 385
#else
#error "hh_shared.c requires an architecture that supports memfd_create"
#endif
#endif
#define MEMFD_CREATE 1
#include <asm/unistd.h>
/* Originally this function would call uname(), parse the linux
* kernel release version and make a decision based on whether
* the kernel was >= 3.17 or not. However, syscall will return -1
* with an strerr(errno) of "Function not implemented" if the
* kernel is < 3.17, and that's good enough.
*/
static int memfd_create(const char *name, unsigned int flags) {
return syscall(SYS_memfd_create, name, flags);
}
#endif
#ifndef MAP_NORESERVE
// This flag was unimplemented in FreeBSD and then later removed
#define MAP_NORESERVE 0
#endif
// The following 'typedef' won't be required anymore
// when dropping support for OCaml < 4.03
#ifdef __MINGW64__
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#endif
#ifdef _WIN32
static int win32_getpagesize(void) {
SYSTEM_INFO siSysInfo;
GetSystemInfo(&siSysInfo);
return siSysInfo.dwPageSize;
}
#define getpagesize win32_getpagesize
#endif
/*****************************************************************************/
/* Config settings (essentially constants, so they don't need to live in shared
* memory), initialized in hh_shared_init */
/*****************************************************************************/
/* Convention: .*_b = Size in bytes. */
static size_t heap_size;
/* Used for the shared hashtable */
static uint64_t hashtbl_size;
static size_t hashtbl_size_b;
/* Used for worker-local data */
static size_t locals_size_b;
typedef enum {
KIND_STRING = 1,
KIND_SERIALIZED = !KIND_STRING
} storage_kind;
typedef struct {
// Size of the BLOB in bytes.
size_t size;
// BLOB returned by sqlite3. Its memory is managed by sqlite3.
// It will be automatically freed on the next query of the same
// statement.
void * blob;
} query_result_t;
/* Too lazy to use getconf */
#define CACHE_LINE_SIZE (1 << 6)
#define __ALIGN_MASK(x,mask) (((x)+(mask))&~(mask))
#define ALIGN(x,a) __ALIGN_MASK(x,(typeof(x))(a)-1)
#define CACHE_ALIGN(x) ALIGN(x,CACHE_LINE_SIZE)
/* As a sanity check when loading from a file */
static const uint64_t MAGIC_CONSTANT = 0xfacefacefaceb000ull;
/* The VCS identifier (typically a git hash) of the build */
extern const char* const BuildInfo_kRevision;
/*****************************************************************************/
/* Types */
/*****************************************************************************/
/* Per-worker data which can be quickly updated non-atomically. Will be placed
* in cache-aligned array in the first few pages of shared memory, indexed by
* worker id. */
typedef struct {
uint64_t counter;
} local_t;
// Every heap entry starts with a 64-bit header with the following layout:
//
// 6 3 3 3 0 0
// 3 3 2 1 1 0
// +----------------------------------+-+-----------------------------------+-+
// |11111111 11111111 11111111 1111111|0| 11111111 11111111 11111111 1111111|1|
// +----------------------------------+-+-----------------------------------+-+
// | | | |
// | | | * 0 tag
// | | |
// | | * 31-1 uncompressed size (0 if uncompressed)
// | |
// | * 32 kind (0 = serialized, 1 = string)
// |
// * 63-33 size of heap entry
//
// The tag bit is always 1 and is used to differentiate headers from addresses
// during garbage collection (see hh_collect).
typedef uint64_t hh_header_t;
// Locations in the heap are encoded as byte offsets from the beginning of
// the hash table, shifted left by 1 with the least-significant bit always set
// to 0 to distinguish addresses from headers during garbage collection.
//
// Note that the offsets do not start at the beginning of the heap, but the
// start of the hash table. This has two important implications:
//
// 1. The offset 0 will always point to the hash of the first hash table entry,
// which is never a meaningful offset. Because of this, we can take the
// address 0 to be the "null" address.
//
// 2. During garbage collection, it is necessary to point from the heap to the
// hash table itself, since we temporarily store heap headers in the addr field
// of helt_t. By starting the offsets at the beginning of the hash table, we can
// represent offsets into the hash table itself.
typedef uint64_t addr_t;
#define NULL_ADDR 0
#define Offset_of_addr(addr) ((addr) >> 1)
#define Addr_of_offset(offset) ((offset) << 1)
#define Addr_of_ptr(entry) (Addr_of_offset((char *)(entry) - (char *)hashtbl))
#define Ptr_of_offset(offset) ((char *)hashtbl + (offset))
#define Ptr_of_addr(addr) (Ptr_of_offset(Offset_of_addr(addr)))
#define Entry_of_addr(addr) ((heap_entry_t *)Ptr_of_addr(addr))
#define Entry_of_offset(offset) ((heap_entry_t *)Ptr_of_offset(offset))
#define Header_of_addr(addr) ((hh_header_t *)Ptr_of_addr(addr))
#define Entry_size(x) ((x) >> 33)
#define Entry_kind(x) (((x) >> 32) & 1)
#define Entry_uncompressed_size(x) (((x) >> 1) & 0x7FFFFFFF)
#define Heap_entry_total_size(header) sizeof(heap_entry_t) + Entry_size(header)
/* Shared memory structures. hh_shared.h typedefs this to heap_entry_t. */
typedef struct {
hh_header_t header;
char data[];
} heap_entry_t;
/* Cells of the Hashtable */
typedef struct {
uint64_t hash;
addr_t addr;
} helt_t;
/*****************************************************************************/
/* Globals */
/*****************************************************************************/
/* Total size of allocated shared memory */
static size_t shared_mem_size = 0;
/* Beginning of shared memory */
static char* shared_mem = NULL;
/* A pair of a 31-bit unsigned number and a tag bit. */
typedef struct {
uint32_t num : 31;
uint32_t tag : 1;
} tagged_uint_t;
/* The hashtable containing the shared values. */
static helt_t* hashtbl = NULL;
/* The number of nonempty slots in the hashtable. A nonempty slot has a
* non-zero hash. We never clear hashes so this monotonically increases */
static uint64_t* hcounter = NULL;
/* The number of nonempty filled slots in the hashtable. A nonempty filled slot
* has a non-zero hash AND a non-null addr. It increments when we write data
* into a slot with addr==NULL and decrements when we clear data from a slot */
static uint64_t* hcounter_filled = NULL;
/* A counter increasing globally across all forks. */
static uintptr_t* counter = NULL;
/* Each process reserves a range of values at a time from the shared counter.
* Should be a power of two for more efficient modulo calculation. */
#define COUNTER_RANGE 2048
/* Logging level for shared memory statistics
* 0 = nothing
* 1 = log totals, averages, min, max bytes marshalled and unmarshalled
*/
static size_t* log_level = NULL;
static size_t* workers_should_exit = NULL;
/* Worker-local storage is cache line aligned. */
static char* locals;
#define LOCAL(id) ((local_t *)(locals + id * CACHE_ALIGN(sizeof(local_t))))
/* This should only be used before forking */
static uintptr_t early_counter = 0;
/* The top of the heap, offset from hashtbl pointer */
static size_t* heap = NULL;
/* Useful to add assertions */
static pid_t* master_pid = NULL;
static pid_t my_pid = 0;
static size_t num_workers;
/* This is a process-local value. The master process is 0, workers are numbered
* starting at 1. This is an offset into the worker local values in the heap. */
static size_t worker_id;
static size_t worker_can_exit = 1;
/* Where the heap started (bottom), offset from hashtbl pointer */
static size_t heap_init = 0;
/* Where the heap will end (top), offset from hashtbl pointer */
static size_t heap_max = 0;
static size_t* wasted_heap_size = NULL;
static size_t used_heap_size(void) {
return *heap - heap_init;
}
static long removed_count = 0;
/* Expose so we can display diagnostics */
CAMLprim value hh_used_heap_size(void) {
return Val_long(used_heap_size());
}
/* Part of the heap not reachable from hashtable entries. Can be reclaimed with
* hh_collect. */
CAMLprim value hh_wasted_heap_size(void) {
assert(wasted_heap_size != NULL);
return Val_long(*wasted_heap_size);
}
CAMLprim value hh_log_level(void) {
return Val_long(*log_level);
}
CAMLprim value hh_hash_used_slots(void) {
CAMLparam0();
CAMLlocal1(connector);
connector = caml_alloc_tuple(2);
Store_field(connector, 0, Val_long(*hcounter_filled));
Store_field(connector, 1, Val_long(*hcounter));
CAMLreturn(connector);
}
CAMLprim value hh_hash_slots(void) {
CAMLparam0();
CAMLreturn(Val_long(hashtbl_size));
}
#ifdef _WIN32
struct timeval log_duration(const char *prefix, struct timeval start_t) {
return start_t; // TODO
}
#else
struct timeval log_duration(const char *prefix, struct timeval start_t) {
struct timeval end_t = {0};
gettimeofday(&end_t, NULL);
time_t secs = end_t.tv_sec - start_t.tv_sec;
suseconds_t usecs = end_t.tv_usec - start_t.tv_usec;
double time_taken = secs + ((double)usecs / 1000000);
fprintf(stderr, "%s took %.2lfs\n", prefix, time_taken);
return end_t;
}
#endif
#ifdef _WIN32
static HANDLE memfd;
/**************************************************************************
* We create an anonymous memory file, whose `handle` might be
* inherited by slave processes.
*
* This memory file is tagged "reserved" but not "committed". This
* means that the memory space will be reserved in the virtual memory
* table but the pages will not be bound to any physical memory
* yet. Further calls to 'VirtualAlloc' will "commit" pages, meaning
* they will be bound to physical memory.
*
* This is behavior that should reflect the 'MAP_NORESERVE' flag of
* 'mmap' on Unix. But, on Unix, the "commit" is implicit.
*
* Committing the whole shared heap at once would require the same
* amount of free space in memory (or in swap file).
**************************************************************************/
void memfd_init(char *shm_dir, size_t shared_mem_size, uint64_t minimum_avail) {
memfd = CreateFileMapping(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE | SEC_RESERVE,
shared_mem_size >> 32, shared_mem_size & ((1ll << 32) - 1),
NULL);
if (memfd == NULL) {
win32_maperr(GetLastError());
uerror("CreateFileMapping", Nothing);
}
if (!SetHandleInformation(memfd, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) {
win32_maperr(GetLastError());
uerror("SetHandleInformation", Nothing);
}
}
#else
static int memfd = -1;
static void raise_failed_anonymous_memfd_init(void) {
static value *exn = NULL;
if (!exn) exn = caml_named_value("failed_anonymous_memfd_init");
caml_raise_constant(*exn);
}
static void raise_less_than_minimum_available(uint64_t avail) {
value arg;
static value *exn = NULL;
if (!exn) exn = caml_named_value("less_than_minimum_available");
arg = Val_long(avail);
caml_raise_with_arg(*exn, arg);
}
#include <sys/statvfs.h>
void assert_avail_exceeds_minimum(char *shm_dir, uint64_t minimum_avail) {
struct statvfs stats;
uint64_t avail;
if (statvfs(shm_dir, &stats)) {
uerror("statvfs", caml_copy_string(shm_dir));
}
avail = stats.f_bsize * stats.f_bavail;
if (avail < minimum_avail) {
raise_less_than_minimum_available(avail);
}
}
/**************************************************************************
* The memdfd_init function creates a anonymous memory file that might
* be inherited by `Daemon.spawned` processus (contrary to a simple
* anonymous mmap).
*
* The preferred mechanism is memfd_create(2) (see the upper
* description). Then we try shm_open(2) (on Apple OS X). As a safe fallback,
* we use `mkstemp/unlink`.
*
* mkstemp is preferred over shm_open on Linux as it allows to
* choose another directory that `/dev/shm` on system where this
* partition is too small (e.g. the Travis containers).
*
* The resulting file descriptor should be mmaped with the memfd_map
* function (see below).
****************************************************************************/
void memfd_init(char *shm_dir, size_t shared_mem_size, uint64_t minimum_avail) {
if (shm_dir == NULL) {
// This means that we should try to use the anonymous-y system calls
#if defined(MEMFD_CREATE)
memfd = memfd_create("fb_heap", 0);
#endif
#if defined(__APPLE__)
if (memfd < 0) {
char memname[255];
snprintf(memname, sizeof(memname), "/fb_heap.%d", getpid());
// the ftruncate below will fail with errno EINVAL if you try to
// ftruncate the same sharedmem fd more than once. We're seeing this in
// some tests, which might imply that two flow processes with the same
// pid are starting up. This shm_unlink should prevent that from
// happening. Here's a stackoverflow about it
// http://stackoverflow.com/questions/25502229/ftruncate-not-working-on-posix-shared-memory-in-mac-os-x
shm_unlink(memname);
memfd = shm_open(memname, O_CREAT | O_RDWR, 0666);
if (memfd < 0) {
uerror("shm_open", Nothing);
}
// shm_open sets FD_CLOEXEC automatically. This is undesirable, because
// we want this fd to be open for other processes, so that they can
// reconnect to the shared memory.
int fcntl_flags = fcntl(memfd, F_GETFD);
if (fcntl_flags == -1) {
printf("Error with fcntl(memfd): %s\n", strerror(errno));
uerror("fcntl", Nothing);
}
// Unset close-on-exec
fcntl(memfd, F_SETFD, fcntl_flags & ~FD_CLOEXEC);
}
#endif
if (memfd < 0) {
raise_failed_anonymous_memfd_init();
}
} else {
assert_avail_exceeds_minimum(shm_dir, minimum_avail);
if (memfd < 0) {
char template[1024];
if (!snprintf(template, 1024, "%s/fb_heap-XXXXXX", shm_dir)) {
uerror("snprintf", Nothing);
};
memfd = mkstemp(template);
if (memfd < 0) {
uerror("mkstemp", caml_copy_string(template));
}
unlink(template);
}
}
if(ftruncate(memfd, shared_mem_size) == -1) {
uerror("ftruncate", Nothing);
}
}
#endif
/*****************************************************************************/
/* Given a pointer to the shared memory address space, initializes all
* the globals that live in shared memory.
*/
/*****************************************************************************/
#ifdef _WIN32
static char *memfd_map(size_t shared_mem_size) {
char *mem = NULL;
mem = MapViewOfFile(memfd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (mem == NULL) {
win32_maperr(GetLastError());
uerror("MapViewOfFile", Nothing);
}
return mem;
}
#else
static char *memfd_map(size_t shared_mem_size) {
char *mem = NULL;
/* MAP_NORESERVE is because we want a lot more virtual memory than what
* we are actually going to use.
*/
int flags = MAP_SHARED | MAP_NORESERVE;
int prot = PROT_READ | PROT_WRITE;
mem = (char*)mmap(NULL, shared_mem_size, prot, flags, memfd, 0);
if(mem == MAP_FAILED) {
printf("Error initializing: %s\n", strerror(errno));
exit(2);
}
return mem;
}
#endif
/****************************************************************************
* The function memfd_reserve force allocation of (mem -> mem+sz) in
* the shared heap. This is mandatory on Windows. This is optional on
* Linux but it allows to have explicit "Out of memory" error
* messages. Otherwise, the kernel might terminate the process with
* `SIGBUS`.
****************************************************************************/
static void raise_out_of_shared_memory(void)
{
static value *exn = NULL;
if (!exn) exn = caml_named_value("out_of_shared_memory");
caml_raise_constant(*exn);
}
#ifdef _WIN32
/* Reserves memory. This is required on Windows */
static void win_reserve(char * mem, size_t sz) {
if (!VirtualAlloc(mem, sz, MEM_COMMIT, PAGE_READWRITE)) {
win32_maperr(GetLastError());
raise_out_of_shared_memory();
}
}
/* On Linux, memfd_reserve is only used to reserve memory that is mmap'd to the
* memfd file. Memory outside of that mmap does not need to be reserved, so we
* don't call memfd_reserve on things like the temporary mmap used by
* hh_collect. Instead, they use win_reserve() */
static void memfd_reserve(char * mem, size_t sz) {
win_reserve(mem, sz);
}
#elif defined(__APPLE__)
/* So OSX lacks fallocate, but in general you can do
* fcntl(fd, F_PREALLOCATE, &store)
* however it doesn't seem to work for a shm_open fd, so this function is
* currently a no-op. This means that our OOM handling for OSX is a little
* weaker than the other OS's */
static void memfd_reserve(char * mem, size_t sz) {
(void)mem;
(void)sz;
}
#else
static void memfd_reserve(char *mem, size_t sz) {
off_t offset = (off_t)(mem - shared_mem);
int err;
do {
err = posix_fallocate(memfd, offset, sz);
} while (err == EINTR);
if (err) {
raise_out_of_shared_memory();
}
}
#endif
// DON'T WRITE TO THE SHARED MEMORY IN THIS FUNCTION!!! This function just
// calculates where the memory is and sets local globals. The shared memory
// might not be ready for writing yet! If you want to initialize a bit of
// shared memory, check out init_shared_globals
static void define_globals(char * shared_mem_init) {
size_t page_size = getpagesize();
char *mem = shared_mem_init;
// Beginning of the shared memory
shared_mem = mem;
#ifdef MADV_DONTDUMP
// We are unlikely to get much useful information out of the shared heap in
// a core file. Moreover, it can be HUGE, and the extensive work done dumping
// it once for each CPU can mean that the user will reboot their machine
// before the much more useful stack gets dumped!
madvise(shared_mem, shared_mem_size, MADV_DONTDUMP);
#endif
/* BEGINNING OF THE SMALL OBJECTS PAGE
* We keep all the small objects in this page.
* They are on different cache lines because we modify them atomically.
*/
/* The pointer to the top of the heap.
* We will atomically increment *heap every time we want to allocate.
*/
heap = (size_t*)mem;
// The number of elements in the hashtable
assert(CACHE_LINE_SIZE >= sizeof(uint64_t));
hcounter = (uint64_t*)(mem + CACHE_LINE_SIZE);
assert (CACHE_LINE_SIZE >= sizeof(uintptr_t));
counter = (uintptr_t*)(mem + 2*CACHE_LINE_SIZE);
assert (CACHE_LINE_SIZE >= sizeof(pid_t));
master_pid = (pid_t*)(mem + 3*CACHE_LINE_SIZE);
assert (CACHE_LINE_SIZE >= sizeof(size_t));
log_level = (size_t*)(mem + 4*CACHE_LINE_SIZE);
assert (CACHE_LINE_SIZE >= sizeof(size_t));
workers_should_exit = (size_t*)(mem + 5*CACHE_LINE_SIZE);
assert (CACHE_LINE_SIZE >= sizeof(size_t));
wasted_heap_size = (size_t*)(mem + 6*CACHE_LINE_SIZE);
assert (CACHE_LINE_SIZE >= sizeof(uint64_t));
hcounter_filled = (uint64_t*)(mem + 7*CACHE_LINE_SIZE);
mem += page_size;
// Just checking that the page is large enough.
assert(page_size > 8*CACHE_LINE_SIZE + (int)sizeof(int));
assert (CACHE_LINE_SIZE >= sizeof(local_t));
locals = mem;
mem += locals_size_b;
/* END OF THE SMALL OBJECTS PAGE */
/* Hashtable */
hashtbl = (helt_t*)mem;
mem += hashtbl_size_b;
/* Heap */
heap_init = hashtbl_size_b;
heap_max = heap_init + heap_size;
#ifdef _WIN32
/* Reserve all memory space. This is required for Windows but we don't do this
* for Linux since it lets us run more processes in parallel without running
* out of memory immediately (though we do risk it later on) */
memfd_reserve((char *)heap, page_size + locals_size_b + hashtbl_size_b);
#endif
}
/* The total size of the shared memory. Most of it is going to remain
* virtual. */
static size_t get_shared_mem_size(void) {
size_t page_size = getpagesize();
return (hashtbl_size_b + heap_size + page_size + locals_size_b);
}
static void init_shared_globals(
size_t config_log_level
) {
// Initialize the number of element in the table
*hcounter = 0;
*hcounter_filled = 0;
// Ensure the global counter starts on a COUNTER_RANGE boundary
*counter = ALIGN(early_counter + 1, COUNTER_RANGE);
*log_level = config_log_level;
*workers_should_exit = 0;
*wasted_heap_size = 0;
for (uint64_t i = 0; i <= num_workers; i++) {
LOCAL(i)->counter = 0;
}
// Initialize top heap pointers
*heap = heap_init;
}
static void set_sizes(
uint64_t config_heap_size,
uint64_t config_hash_table_pow,
uint64_t config_num_workers) {
size_t page_size = getpagesize();
heap_size = config_heap_size;
hashtbl_size = 1ul << config_hash_table_pow;
hashtbl_size_b = hashtbl_size * sizeof(hashtbl[0]);
// We will allocate a cache line for the master process and each worker
// process, then pad that out to the nearest page.
num_workers = config_num_workers;
locals_size_b = ALIGN((1 + num_workers) * CACHE_LINE_SIZE, page_size);
shared_mem_size = get_shared_mem_size();
}
/*****************************************************************************/
/* Must be called by the master BEFORE forking the workers! */
/*****************************************************************************/
CAMLprim value hh_shared_init(
value config_val,
value shm_dir_val,
value num_workers_val
) {
CAMLparam3(config_val, shm_dir_val, num_workers_val);
CAMLlocal3(
connector,
config_heap_size_val,
config_hash_table_pow_val
);
config_heap_size_val = Field(config_val, 0);
config_hash_table_pow_val = Field(config_val, 1);
set_sizes(
Long_val(config_heap_size_val),
Long_val(config_hash_table_pow_val),
Long_val(num_workers_val)
);
// None -> NULL
// Some str -> String_val(str)
char *shm_dir = NULL;
if (shm_dir_val != Val_int(0)) {
shm_dir = String_val(Field(shm_dir_val, 0));
}
memfd_init(
shm_dir,
shared_mem_size,
Long_val(Field(config_val, 3))
);
char *shared_mem_init = memfd_map(shared_mem_size);
define_globals(shared_mem_init);
// Keeping the pids around to make asserts.
#ifdef _WIN32
*master_pid = 0;
my_pid = *master_pid;
#else
*master_pid = getpid();
my_pid = *master_pid;
#endif
init_shared_globals(
Long_val(Field(config_val, 4)));
// Checking that we did the maths correctly.
assert(Ptr_of_offset(*heap) + heap_size == shared_mem + shared_mem_size);
#ifndef _WIN32
// Uninstall ocaml's segfault handler. It's supposed to throw an exception on
// stack overflow, but we don't actually handle that exception, so what
// happens in practice is we terminate at toplevel with an unhandled exception
// and a useless ocaml backtrace. A core dump is actually more useful. Sigh.
struct sigaction sigact = { 0 };
sigact.sa_handler = SIG_DFL;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
sigaction(SIGSEGV, &sigact, NULL);
#endif
connector = caml_alloc_tuple(5);
Store_field(connector, 0, Val_handle(memfd));
Store_field(connector, 1, config_heap_size_val);
Store_field(connector, 2, config_hash_table_pow_val);
Store_field(connector, 3, num_workers_val);
CAMLreturn(connector);
}
/* Must be called by every worker before any operation is performed */
value hh_connect(value connector, value worker_id_val) {
CAMLparam2(connector, worker_id_val);
memfd = Handle_val(Field(connector, 0));
set_sizes(
Long_val(Field(connector, 1)),
Long_val(Field(connector, 2)),
Long_val(Field(connector, 3))
);
worker_id = Long_val(worker_id_val);
#ifdef _WIN32
my_pid = 1; // Trick
#else
my_pid = getpid();
#endif
char *shared_mem_init = memfd_map(shared_mem_size);
define_globals(shared_mem_init);
CAMLreturn(Val_unit);
}
/*****************************************************************************/
/* Counter
*
* Provides a counter intended to be increasing over the lifetime of the program
* including all forks. Uses a global variable until hh_shared_init is called,
* so it's safe to use in the early init stages of the program (as long as you
* fork after hh_shared_init of course). Wraps around at the maximum value of an
* ocaml int, which is something like 30 or 62 bits on 32 and 64-bit
* architectures respectively.
*/
/*****************************************************************************/
CAMLprim value hh_counter_next(void) {
CAMLparam0();
CAMLlocal1(result);
uintptr_t v = 0;
if (counter) {
v = LOCAL(worker_id)->counter;
if (v % COUNTER_RANGE == 0) {
v = __atomic_fetch_add(counter, COUNTER_RANGE, __ATOMIC_RELAXED);
}
++v;
LOCAL(worker_id)->counter = v;
} else {
v = ++early_counter;
}
result = Val_long(v % Max_long); // Wrap around.
CAMLreturn(result);
}
/*****************************************************************************/
/* There are a bunch of operations that only the designated master thread is
* allowed to do. This assert will fail if the current process is not the master
* process
*/
/*****************************************************************************/
void assert_master(void) {
assert(my_pid == *master_pid);
}
void assert_not_master(void) {
assert(my_pid != *master_pid);
}
/*****************************************************************************/
CAMLprim value hh_stop_workers(void) {
CAMLparam0();
assert_master();
*workers_should_exit = 1;
CAMLreturn(Val_unit);
}
CAMLprim value hh_resume_workers(void) {
CAMLparam0();
assert_master();
*workers_should_exit = 0;
CAMLreturn(Val_unit);
}
CAMLprim value hh_set_can_worker_stop(value val) {
CAMLparam1(val);
worker_can_exit = Bool_val(val);
CAMLreturn(Val_unit);
}
void check_should_exit(void) {
assert(workers_should_exit != NULL);
if(worker_can_exit && *workers_should_exit) {
static value *exn = NULL;
if (!exn) exn = caml_named_value("worker_should_exit");
caml_raise_constant(*exn);
}
}
CAMLprim value hh_check_should_exit (void) {
CAMLparam0();
check_should_exit();
CAMLreturn(Val_unit);
}
/*****************************************************************************/
/* Hashes an integer such that the low bits are a good starting hash slot. */
/*****************************************************************************/
static uint64_t hash_uint64(uint64_t n) {
// Multiplying produces a well-mixed value in the high bits of the result.
// The bswap moves those "good" high bits into the low bits, to serve as the
// initial hash table slot number.
const uint64_t golden_ratio = 0x9e3779b97f4a7c15ull;
return __builtin_bswap64(n * golden_ratio);
}
// TODO - DEAD CODE
value hh_check_heap_overflow(void) {
if (*heap >= heap_max) {
return Val_bool(1);
}
return Val_bool(0);
}
/*****************************************************************************/
/* We compact the heap when it gets twice as large as its initial size.
* Step one, copy the live values in a new heap.
* Step two, memcopy the values back into the shared heap.
* We could probably use something smarter, but this is fast enough.
*
* The collector should only be called by the master.
*/
/*****************************************************************************/