forked from ocaml-flambda/flambda-backend
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdomain.c
2198 lines (1834 loc) · 70.3 KB
/
domain.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
/**************************************************************************/
/* */
/* OCaml */
/* */
/* KC Sivaramakrishnan, Indian Institute of Technology, Madras */
/* Stephen Dolan, University of Cambridge */
/* Tom Kelly, OCaml Labs Consultancy */
/* */
/* Copyright 2021 OCaml Labs Consultancy Ltd */
/* Copyright 2019 Indian Institute of Technology, Madras */
/* Copyright 2019 University of Cambridge */
/* */
/* All rights reserved. This file is distributed under the terms of */
/* the GNU Lesser General Public License version 2.1, with the */
/* special exception on linking described in the file LICENSE. */
/* */
/**************************************************************************/
#define CAML_INTERNALS
#define _GNU_SOURCE /* For sched.h CPU_ZERO(3) and CPU_COUNT(3) */
#include "caml/config.h"
#include <stdbool.h>
#include <stdio.h>
#ifdef HAS_UNISTD
#include <unistd.h>
#endif
#include <pthread.h>
#include <string.h>
#include <assert.h>
#ifdef HAS_GNU_GETAFFINITY_NP
#include <sched.h>
#ifdef HAS_PTHREAD_NP_H
#include <pthread_np.h>
#endif
#endif
#ifdef HAS_BSD_GETAFFINITY_NP
#include <pthread_np.h>
#include <sys/cpuset.h>
typedef cpuset_t cpu_set_t;
#endif
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <sysinfoapi.h>
#endif
#include "caml/alloc.h"
#include "caml/backtrace.h"
#include "caml/backtrace_prim.h"
#include "caml/callback.h"
#include "caml/debugger.h"
#include "caml/domain.h"
#include "caml/domain_state.h"
#include "caml/runtime_events.h"
#include "caml/fail.h"
#include "caml/fiber.h"
#include "caml/finalise.h"
#include "caml/gc_ctrl.h"
#include "caml/globroots.h"
#include "caml/intext.h"
#include "caml/major_gc.h"
#include "caml/minor_gc.h"
#include "caml/memprof.h"
#include "caml/misc.h"
#include "caml/memory.h"
#include "caml/osdeps.h"
#include "caml/platform.h"
#include "caml/shared_heap.h"
#include "caml/signals.h"
#include "caml/startup.h"
#include "caml/sync.h"
#include "caml/weak.h"
/* Check that the domain_state structure was laid out without padding,
since the runtime assumes this in computing offsets */
static_assert(
offsetof(caml_domain_state, LAST_DOMAIN_STATE_MEMBER) ==
(Domain_state_num_fields - 1) * 8,
"");
/* The runtime can run stop-the-world (STW) sections, during which all
active domains run the same callback in parallel (with a barrier
mechanism to synchronize within the callback).
Stop-the-world sections are used to handle duties such as:
- minor GC
- major GC phase changes
Code within the STW callback can have the guarantee that no mutator
code runs in parallel -- precisely, the guarantee holds only for
code that is followed by a barrier. Furthermore, new domains being
spawned are blocked from running any mutator code while a STW
section is in progress, and terminating domains cannot stop until
they have participated to all STW sections currently in progress.
To provide these guarantees:
- Domains must register as STW participants before running any
mutator code.
- STW sections must not trigger other callbacks into mutator code
(eg. finalisers or signal handlers).
See the comments on [caml_try_run_on_all_domains_with_spin_work]
below for more details on the synchronization mechanisms involved.
*/
/* For timely handling of STW requests, domains registered as STW
participants must be careful to service STW interrupt requests. The
compiler inserts "poll points" in mutator code, and the runtime
uses a "backup thread" mechanism during blocking sections.
When the main C-stack for a domain enters a blocking call,
a 'backup thread' becomes responsible for servicing the STW
sections on behalf of the domain. Care is needed to hand off duties
for servicing STW sections between the main pthread and the backup
pthread when caml_enter_blocking_section and
caml_leave_blocking_section are called.
When the state for the backup thread is BT_IN_BLOCKING_SECTION
the backup thread will service the STW section.
The state machine for the backup thread (and its transitions)
are:
BT_INIT <---------------------------------------+
| |
(install_backup_thread) |
[main pthread] |
| |
v |
BT_ENTERING_OCAML <-----------------+ |
| | |
(caml_enter_blocking_section) | |
[main pthread] | |
| | |
| | |
| (caml_leave_blocking_section) |
| [main pthread] |
v | |
BT_IN_BLOCKING_SECTION ----------------+ |
| |
(domain_terminate) |
[main pthread] |
| |
v |
BT_TERMINATE (backup_thread_func)
| [backup pthread]
| |
+---------------------------------------------+
*/
#define BT_IN_BLOCKING_SECTION 0
#define BT_ENTERING_OCAML 1
#define BT_TERMINATE 2
#define BT_INIT 3
/* control of STW interrupts */
struct interruptor {
/* The outermost atomic is for synchronization with
caml_interrupt_all_signal_safe. The innermost atomic is also for
cross-domain communication.*/
_Atomic(atomic_uintnat *) interrupt_word;
caml_plat_mutex lock;
caml_plat_cond cond;
int running;
int terminating;
/* unlike the domain ID, this ID number is not reused */
uintnat unique_id;
/* indicates whether there is an interrupt pending */
atomic_uintnat interrupt_pending;
};
Caml_inline int interruptor_has_pending(struct interruptor *s)
{ return atomic_load_acquire(&s->interrupt_pending) != 0; }
Caml_inline void interruptor_set_handled(struct interruptor *s)
{ atomic_store_release(&s->interrupt_pending, 0); }
Caml_inline void interruptor_set_pending(struct interruptor *s)
{ atomic_store_release(&s->interrupt_pending, 1); }
struct dom_internal {
/* readonly fields, initialised and never modified */
int id;
caml_domain_state* state;
struct interruptor interruptor;
/* backup thread */
int backup_thread_running;
pthread_t backup_thread;
atomic_uintnat backup_thread_msg;
caml_plat_mutex domain_lock;
caml_plat_cond domain_cond;
/* modified only during STW sections */
uintnat minor_heap_area_start;
uintnat minor_heap_area_end;
};
typedef struct dom_internal dom_internal;
static struct {
/* enter barrier for STW sections, participating domains arrive into
the barrier before executing the STW callback */
caml_plat_barrier domains_still_running;
/* the number of domains that have yet to return from the callback */
atomic_uintnat num_domains_still_processing;
void (*callback)(caml_domain_state*,
void*,
int participating_count,
caml_domain_state** others_participating);
void* data;
int (*enter_spin_callback)(caml_domain_state*, void*);
void* enter_spin_data;
/* global_barrier state */
int num_domains;
caml_plat_barrier barrier;
caml_domain_state* participating[Max_domains];
} stw_request = {
CAML_PLAT_BARRIER_INITIALIZER,
0,
NULL,
NULL,
NULL,
NULL,
0,
CAML_PLAT_BARRIER_INITIALIZER,
{ 0 },
};
static caml_plat_mutex all_domains_lock = CAML_PLAT_MUTEX_INITIALIZER;
static caml_plat_cond all_domains_cond = CAML_PLAT_COND_INITIALIZER;
static atomic_uintnat /* dom_internal* */ stw_leader = 0;
static uintnat stw_requests_suspended = 0; /* protected by all_domains_lock */
static caml_plat_cond requests_suspended_cond = CAML_PLAT_COND_INITIALIZER;
static dom_internal all_domains[Max_domains];
CAMLexport atomic_uintnat caml_num_domains_running;
/* size of the virtual memory reservation for the minor heap, per domain */
uintnat caml_minor_heap_max_wsz;
/*
The amount of memory reserved for all minor heaps of all domains is
Max_domains * caml_minor_heap_max_wsz. Individual domains can allocate
smaller minor heaps, but when a domain calls Gc.set to allocate a bigger minor
heap than this reservation, we perform a new virtual memory reservation based
on the increased minor heap size.
New domains are created with a minor heap of size
caml_params->init_minor_heap_wsz.
To perform a new virtual memory reservation for the heaps, we stop the world
and do a minor collection on all domains.
See [stw_resize_minor_heap_reservation].
*/
CAMLexport uintnat caml_minor_heaps_start;
CAMLexport uintnat caml_minor_heaps_end;
static CAMLthread_local dom_internal* domain_self;
/*
* This structure is protected by all_domains_lock
* [0, participating_domains) are all the domains taking part in STW sections
* [participating_domains, Max_domains) are all those domains free to be used
*/
static struct {
int participating_domains;
dom_internal* domains[Max_domains];
} stw_domains = {
0,
{ 0 }
};
static void add_next_to_stw_domains(void)
{
CAMLassert(stw_domains.participating_domains < Max_domains);
stw_domains.participating_domains++;
#ifdef DEBUG
/* Enforce here the invariant for early-exit in
[caml_interrupt_all_signal_safe], because the latter must be
async-signal-safe and one cannot CAMLassert inside it. */
bool prev_has_interrupt_word = true;
for (int i = 0; i < Max_domains; i++) {
bool has_interrupt_word = all_domains[i].interruptor.interrupt_word != NULL;
if (i < stw_domains.participating_domains) CAMLassert(has_interrupt_word);
if (!prev_has_interrupt_word) CAMLassert(!has_interrupt_word);
prev_has_interrupt_word = has_interrupt_word;
}
#endif
}
static void remove_from_stw_domains(dom_internal* dom) {
int i;
for(i=0; stw_domains.domains[i]!=dom; ++i) {
CAMLassert(i<Max_domains);
}
CAMLassert(i < stw_domains.participating_domains);
/* swap passed domain to first free domain */
stw_domains.participating_domains--;
stw_domains.domains[i] =
stw_domains.domains[stw_domains.participating_domains];
stw_domains.domains[stw_domains.participating_domains] = dom;
}
static dom_internal* next_free_domain(void) {
if (stw_domains.participating_domains == Max_domains)
return NULL;
CAMLassert(stw_domains.participating_domains < Max_domains);
return stw_domains.domains[stw_domains.participating_domains];
}
CAMLexport CAMLthread_local caml_domain_state* caml_state;
#ifndef HAS_FULL_THREAD_VARIABLES
/* Export a getter for caml_state, to be used in DLLs */
CAMLexport caml_domain_state* caml_get_domain_state(void)
{
return caml_state;
}
#endif
Caml_inline void interrupt_domain(struct interruptor* s)
{
atomic_uintnat * interrupt_word = atomic_load_relaxed(&s->interrupt_word);
atomic_store_release(interrupt_word, UINTNAT_MAX);
}
Caml_inline void interrupt_domain_local(caml_domain_state* dom_st)
{
atomic_store_relaxed(&dom_st->young_limit, UINTNAT_MAX);
}
int caml_incoming_interrupts_queued(void)
{
return interruptor_has_pending(&domain_self->interruptor);
}
/* must NOT be called with s->lock held */
static void stw_handler(caml_domain_state* domain);
static int handle_incoming(struct interruptor* s)
{
int handled = interruptor_has_pending(s);
CAMLassert (s->running);
if (handled) {
interruptor_set_handled(s);
stw_handler(domain_self->state);
}
return handled;
}
static void handle_incoming_otherwise_relax (struct interruptor* self)
{
if (!handle_incoming(self))
cpu_relax();
}
void caml_handle_incoming_interrupts(void)
{
handle_incoming(&domain_self->interruptor);
}
int caml_send_interrupt(struct interruptor* target)
{
/* signal that there is an interrupt pending */
interruptor_set_pending(target);
/* Signal the condition variable, in case the target is
itself waiting for an interrupt to be processed elsewhere */
caml_plat_lock_blocking(&target->lock);
caml_plat_broadcast(&target->cond); // OPT before/after unlock? elide?
caml_plat_unlock(&target->lock);
interrupt_domain(target);
return 1;
}
asize_t caml_norm_minor_heap_size (intnat wsize)
{
asize_t bs;
if (wsize < Minor_heap_min) wsize = Minor_heap_min;
bs = caml_mem_round_up_mapping_size(Bsize_wsize (wsize));
return Wsize_bsize(bs);
}
/* The current minor heap layout is as follows:
- A contiguous memory block of size
[caml_minor_heap_max_wsz * Max_domains]
is reserved by [caml_init_domains]. The boundaries
of this reserved area are stored in the globals
[caml_minor_heaps_start]
and
[caml_minor_heaps_end].
- Each domain gets a reserved section of this block
of size [caml_minor_heap_max_wsz], whose boundaries are stored as
[domain_self->minor_heap_area_start]
and
[domain_self->minor_heap_area_end]
These variables accessed in [stw_resize_minor_heap_reservation],
synchronized by a global barrier.
- Each domain then commits a segment of size
[domain_state->minor_heap_wsz]
starting at
[domain_state->minor_heap_area_start]
that it actually uses.
This is done below in
[caml_reallocate_minor_heap]
which is called both at domain-initialization (by [domain_create])
and if a request comes to change the minor heap size.
The boundaries of this committed memory area are
[domain_state->young_start]
and
[domain_state->young_end].
Those [young_{start,end}] variables are never accessed by another
domain, so they need no synchronization.
*/
Caml_inline void check_minor_heap(void) {
caml_domain_state* domain_state = Caml_state;
CAMLassert(domain_state->young_ptr == domain_state->young_end);
caml_gc_log("young_start: %p, young_end: %p, minor_heap_area_start: %p,"
" minor_heap_area_end: %p, minor_heap_wsz: %"
ARCH_SIZET_PRINTF_FORMAT "u words",
domain_state->young_start,
domain_state->young_end,
(value*)domain_self->minor_heap_area_start,
(value*)domain_self->minor_heap_area_end,
domain_state->minor_heap_wsz);
CAMLassert(
(/* uninitialized minor heap */
domain_state->young_start == NULL
&& domain_state->young_end == NULL)
||
(/* initialized minor heap */
domain_state->young_start == (value*)domain_self->minor_heap_area_start
&& domain_state->young_end <= (value*)domain_self->minor_heap_area_end));
}
static void free_minor_heap(void) {
caml_domain_state* domain_state = Caml_state;
caml_gc_log ("trying to free old minor heap: %"
ARCH_SIZET_PRINTF_FORMAT "uk words",
domain_state->minor_heap_wsz / 1024);
check_minor_heap();
/* free old minor heap.
instead of unmapping the heap, we decommit it, so there's
no race whereby other code could attempt to reuse the memory. */
caml_mem_decommit(
(void*)domain_self->minor_heap_area_start,
Bsize_wsize(domain_state->minor_heap_wsz),
"minor reservation");
domain_state->young_start = NULL;
domain_state->young_end = NULL;
domain_state->young_ptr = NULL;
domain_state->young_trigger = NULL;
domain_state->memprof_young_trigger = NULL;
atomic_store_release(&domain_state->young_limit,
(uintnat) domain_state->young_start);
}
static int allocate_minor_heap(asize_t wsize) {
caml_domain_state* domain_state = Caml_state;
check_minor_heap();
wsize = caml_norm_minor_heap_size(wsize);
CAMLassert (wsize <= caml_minor_heap_max_wsz);
caml_gc_log ("trying to allocate minor heap: %"
ARCH_SIZET_PRINTF_FORMAT "uk words", wsize / 1024);
char name[32];
snprintf(name, sizeof name, "minor heap %d", domain_self->id);
if (!caml_mem_commit(
(void*)domain_self->minor_heap_area_start, Bsize_wsize(wsize), name)) {
return -1;
}
#ifdef DEBUG
{
uintnat* p = (uintnat*)domain_self->minor_heap_area_start;
for (;
p < (uintnat*)(domain_self->minor_heap_area_start + Bsize_wsize(wsize));
p++) {
*p = Debug_free_minor;
}
}
#endif
domain_state->minor_heap_wsz = wsize;
domain_state->young_start = (value*)domain_self->minor_heap_area_start;
domain_state->young_end =
(value*)(domain_self->minor_heap_area_start + Bsize_wsize(wsize));
domain_state->young_ptr = domain_state->young_end;
/* Trigger a GC poll when half of the minor heap is filled. At that point, a
* major slice is scheduled. */
domain_state->young_trigger = domain_state->young_start
+ (domain_state->young_end - domain_state->young_start) / 2;
caml_memprof_set_trigger(domain_state);
caml_reset_young_limit(domain_state);
check_minor_heap();
return 0;
}
int caml_reallocate_minor_heap(asize_t wsize)
{
free_minor_heap();
return allocate_minor_heap(wsize);
}
/* This variable is owned by [all_domains_lock]. */
static uintnat next_domain_unique_id = 0;
/* Precondition: you must own [all_domains_lock].
Specification:
- returns 0 on the first call
(we want the main domain to have unique_id 0)
- returns distinct ids unless there is an overflow
- never returns 0 again, even in presence of overflow.
*/
static uintnat fresh_domain_unique_id(void) {
uintnat next = next_domain_unique_id++;
/* On 32-bit systems, there is a risk of wraparound of the unique
id counter. We have decided to let that happen and live with
it, but we still ensure that id 0 is not reused, to avoid
having new domains believe that they are the main domain. */
if (next_domain_unique_id == 0)
next_domain_unique_id++;
return next;
}
/* must be run on the domain's thread */
static void domain_create(uintnat initial_minor_heap_wsize,
caml_domain_state *parent)
{
dom_internal* d = 0;
caml_domain_state* domain_state;
struct interruptor* s;
uintnat stack_wsize = caml_get_init_stack_wsize(-1 /* main thread */);
CAMLassert (domain_self == 0);
/* take the all_domains_lock so that we can alter the STW participant
set atomically */
caml_plat_lock_blocking(&all_domains_lock);
/* How many STW sections we are willing to wait for, any more are
prevented from happening */
#define Max_stws_before_suspend 2
int stws_waited = 1;
/* Wait until any in-progress STW sections end. */
while (atomic_load_acquire(&stw_leader)) {
if (stws_waited++ < Max_stws_before_suspend) {
/* [caml_plat_wait] releases [all_domains_lock] until the current
STW section ends, and then takes the lock again. */
caml_plat_wait(&all_domains_cond, &all_domains_lock);
} else {
/* Prevent new STW requests to avoid our own starvation */
stw_requests_suspended++;
/* Wait for the current STW to end */
do {
caml_plat_wait(&all_domains_cond, &all_domains_lock);
} while (atomic_load_acquire(&stw_leader));
if (--stw_requests_suspended == 0) {
/* Notify threads that were trying to run an STW section.
We still hold the lock, so they won't wake up yet. */
caml_plat_broadcast(&requests_suspended_cond);
}
break;
}
}
d = next_free_domain();
if (d == NULL)
goto domain_init_complete;
s = &d->interruptor;
CAMLassert(!s->running);
CAMLassert(!interruptor_has_pending(s));
/* If the chosen domain slot has not been previously used, allocate a fresh
domain state. Otherwise, reuse it.
Reusing the slot ensures that the GC stats are not lost:
- Heap stats are moved to the free list on domain termination,
so we don't reuse those stats (caml_init_shared_heap will reset them)
- But currently there is no orphaning process for allocation stats,
we just reuse the previous stats from the previous domain
with the same index.
*/
if (d->state == NULL) {
/* FIXME: Never freed. Not clear when to. */
domain_state = (caml_domain_state*)
caml_stat_calloc_noexc(1, sizeof(caml_domain_state));
if (domain_state == NULL)
goto domain_init_complete;
d->state = domain_state;
} else {
domain_state = d->state;
}
/* Note: until we take d->domain_lock, the domain_state may still be
* shared with a domain which is terminating (see
* domain_terminate). */
caml_plat_lock_blocking(&d->domain_lock);
/* Set domain_self if we have successfully allocated the
* caml_domain_state. Otherwise domain_self will be NULL and it's up
* to the caller to deal with that. */
domain_self = d;
caml_state = domain_state;
domain_state->young_limit = 0;
domain_state->id = d->id;
domain_state->unique_id = s->unique_id;
/* Synchronized with [caml_interrupt_all_signal_safe], so that the
initializing write of young_limit happens before any
interrupt. */
atomic_store_explicit(&s->interrupt_word, &domain_state->young_limit,
memory_order_release);
/* Tell memprof system about the new domain before either (a) new
* domain can allocate anything or (b) parent domain can go away. */
CAMLassert(domain_state->memprof == NULL);
caml_memprof_new_domain(parent, domain_state);
if (!domain_state->memprof) {
goto init_memprof_failure;
}
CAMLassert(!interruptor_has_pending(s));
domain_state->extra_heap_resources = 0.0;
domain_state->extra_heap_resources_minor = 0.0;
domain_state->dependent_size = 0;
domain_state->dependent_allocated = 0;
domain_state->major_work_done_between_slices = 0;
/* the minor heap will be initialized by
[caml_reallocate_minor_heap] below. */
domain_state->young_start = NULL;
domain_state->young_end = NULL;
domain_state->young_ptr = NULL;
domain_state->young_trigger = NULL;
domain_state->minor_tables = caml_alloc_minor_tables();
if(domain_state->minor_tables == NULL) {
goto alloc_minor_tables_failure;
}
d->state->shared_heap = caml_init_shared_heap();
if(d->state->shared_heap == NULL) {
goto init_shared_heap_failure;
}
if (caml_init_major_gc(domain_state) < 0) {
goto init_major_gc_failure;
}
if(caml_reallocate_minor_heap(initial_minor_heap_wsize) < 0) {
goto reallocate_minor_heap_failure;
}
domain_state->in_minor_collection = 0;
domain_state->dls_root = Val_unit;
caml_register_generational_global_root(&domain_state->dls_root);
domain_state->stack_cache = caml_alloc_stack_cache();
if(domain_state->stack_cache == NULL) {
goto create_stack_cache_failure;
}
domain_state->extern_state = NULL;
domain_state->intern_state = NULL;
domain_state->current_stack =
caml_alloc_main_stack(stack_wsize);
if(domain_state->current_stack == NULL) {
goto alloc_main_stack_failure;
}
/* No remaining failure cases: domain creation is going to succeed,
* so we can update globally-visible state without needing to unwind
* it. */
s->unique_id = fresh_domain_unique_id();
domain_state->unique_id = s->unique_id;
s->running = 1;
atomic_fetch_add(&caml_num_domains_running, 1);
domain_state->c_stack = NULL;
domain_state->exn_handler = NULL;
domain_state->async_exn_handler = NULL;
domain_state->action_pending = 0;
domain_state->gc_regs_buckets = NULL;
domain_state->gc_regs = NULL;
domain_state->allocated_words = 0;
domain_state->allocated_words_direct = 0;
domain_state->swept_words = 0;
domain_state->local_roots = NULL;
domain_state->backtrace_buffer = NULL;
domain_state->backtrace_last_exn = Val_unit;
domain_state->backtrace_active = 0;
caml_register_generational_global_root(&domain_state->backtrace_last_exn);
domain_state->local_arenas = NULL;
domain_state->local_sp = 0;
domain_state->local_top = NULL;
domain_state->local_limit = 0;
domain_state->compare_unordered = 0;
domain_state->oo_next_id_local = 0;
domain_state->requested_major_slice = 0;
domain_state->requested_minor_gc = 0;
domain_state->major_slice_epoch = 0;
domain_state->requested_external_interrupt = 0;
domain_state->parser_trace = 0;
if (caml_params->backtrace_enabled) {
caml_record_backtraces(1);
}
domain_state->raising_async_exn = 0;
#ifndef NATIVE_CODE
domain_state->external_raise = NULL;
domain_state->external_raise_async = NULL;
domain_state->trap_sp_off = 1;
domain_state->trap_barrier_off = 0;
domain_state->trap_barrier_block = -1;
#endif
add_next_to_stw_domains();
goto domain_init_complete;
alloc_main_stack_failure:
create_stack_cache_failure:
caml_remove_generational_global_root(&domain_state->dls_root);
reallocate_minor_heap_failure:
caml_teardown_major_gc();
init_major_gc_failure:
caml_teardown_shared_heap(d->state->shared_heap);
init_shared_heap_failure:
caml_free_minor_tables(domain_state->minor_tables);
domain_state->minor_tables = NULL;
alloc_minor_tables_failure:
caml_memprof_delete_domain(domain_state);
init_memprof_failure:
domain_self = NULL;
domain_init_complete:
caml_gc_log("domain init complete");
caml_plat_unlock(&all_domains_lock);
}
CAMLexport void caml_reset_domain_lock(void)
{
dom_internal* self = domain_self;
// This is only used to reset the domain_lock state on fork.
/* FIXME: initializing an already-initialized mutex and cond
variable is UB (especially mutexes that are locked).
* On systhreads, this is best-effort but at least the error
conditions should be checked and reported.
* If there is only one thread, it is sensible to fork but the
mutex should still not be initialized while locked. On Linux it
seems that the mutex remains valid and locked
(https://man7.org/linux/man-pages/man2/fork.2.html). For
portability on POSIX the lock should be released and destroyed
prior to calling fork and then init afterwards in both parent
and child. */
caml_plat_mutex_init(&self->domain_lock);
caml_plat_cond_init(&self->domain_cond);
return;
}
/* minor heap initialization and resizing */
static void reserve_minor_heaps_from_stw_single(void) {
void* heaps_base;
uintnat minor_heap_reservation_bsize;
uintnat minor_heap_max_bsz;
CAMLassert (
caml_mem_round_up_mapping_size(Bsize_wsize(caml_minor_heap_max_wsz))
== Bsize_wsize(caml_minor_heap_max_wsz));
minor_heap_max_bsz = (uintnat)Bsize_wsize(caml_minor_heap_max_wsz);
minor_heap_reservation_bsize = minor_heap_max_bsz * Max_domains;
/* reserve memory space for minor heaps */
heaps_base = caml_mem_map(minor_heap_reservation_bsize, 1 /* reserve_only */, "minor reservation");
if (heaps_base == NULL)
caml_fatal_error("Not enough heap memory to reserve minor heaps");
caml_minor_heaps_start = (uintnat) heaps_base;
caml_minor_heaps_end = (uintnat) heaps_base + minor_heap_reservation_bsize;
caml_gc_log("new minor heap reserved from %p to %p",
(value*)caml_minor_heaps_start, (value*)caml_minor_heaps_end);
for (int i = 0; i < Max_domains; i++) {
struct dom_internal* dom = &all_domains[i];
uintnat domain_minor_heap_area = caml_minor_heaps_start +
minor_heap_max_bsz * (uintnat)i;
dom->minor_heap_area_start = domain_minor_heap_area;
dom->minor_heap_area_end =
domain_minor_heap_area + minor_heap_max_bsz;
CAMLassert(dom->minor_heap_area_end <= caml_minor_heaps_end);
}
}
static void unreserve_minor_heaps_from_stw_single(void) {
uintnat size;
caml_gc_log("unreserve_minor_heaps");
for (int i = 0; i < Max_domains; i++) {
struct dom_internal* dom = &all_domains[i];
CAMLassert(
/* this domain is not running */
!dom->interruptor.running
|| (
/* or its minor heap must already be uninitialized */
dom->state != NULL
&& dom->state->young_start == NULL
&& dom->state->young_end == NULL
));
/* Note: interruptor.running does not guarantee that dom->state is
correctly initialized, but domain initialization cannot run
concurrently with STW sections so we cannot observe partial
initialization states. */
/* uninitialize the minor heap area */
dom->minor_heap_area_start = dom->minor_heap_area_end = 0;
}
size = caml_minor_heaps_end - caml_minor_heaps_start;
CAMLassert (Bsize_wsize(caml_minor_heap_max_wsz) * Max_domains == size);
caml_mem_unmap((void *) caml_minor_heaps_start, size);
}
static
void domain_resize_heap_reservation_from_stw_single(uintnat new_minor_wsz)
{
CAML_EV_BEGIN(EV_DOMAIN_RESIZE_HEAP_RESERVATION);
caml_gc_log("stw_resize_minor_heap_reservation: "
"unreserve_minor_heaps");
unreserve_minor_heaps_from_stw_single();
/* new_minor_wsz is (huge)page-aligned because caml_norm_minor_heap_size has
been called to normalize it earlier. (An assertion checks this in
[reserve_minor_heaps_from_stw_single].)
*/
caml_minor_heap_max_wsz = new_minor_wsz;
caml_gc_log("stw_resize_minor_heap_reservation: reserve_minor_heaps");
reserve_minor_heaps_from_stw_single();
/* The call to [reserve_minor_heaps_from_stw_single] makes a new
reservation, and it also updates the reservation boundaries of each
domain by mutating its [minor_heap_area_start{,_end}] variables.
These variables are synchronized by the fact that we are inside
a STW section: no other domains are running in parallel, and
the participating domains will synchronize with this write by
exiting the barrier, before they read those variables in
[allocate_minor_heap] below. */
CAML_EV_END(EV_DOMAIN_RESIZE_HEAP_RESERVATION);
}
static void
stw_resize_minor_heap_reservation(caml_domain_state* domain,
void* minor_wsz_data,
int participating_count,
caml_domain_state** participating) {
caml_gc_log("stw_resize_minor_heap_reservation: "
"caml_empty_minor_heap_no_major_slice_from_stw");
caml_empty_minor_heap_no_major_slice_from_stw(
domain, NULL, participating_count, participating);
caml_gc_log("stw_resize_minor_heap_reservation: free_minor_heap");
free_minor_heap();
Caml_global_barrier_if_final(participating_count) {
uintnat new_minor_wsz = (uintnat) minor_wsz_data;
domain_resize_heap_reservation_from_stw_single(new_minor_wsz);
}
caml_gc_log("stw_resize_minor_heap_reservation: "
"allocate_minor_heap");
/* Note: each domain allocates its own minor heap. This seems
important to get good NUMA behavior. We don't want a single
domain to allocate all minor heaps, which could create locality
issues we don't understand very well. */
if (allocate_minor_heap(Caml_state->minor_heap_wsz) < 0) {
caml_fatal_error("Fatal error: No memory for minor heap");
}
}
void caml_update_minor_heap_max(uintnat requested_wsz) {
caml_gc_log("Changing heap_max_wsz from %" ARCH_INTNAT_PRINTF_FORMAT
"u to %" ARCH_INTNAT_PRINTF_FORMAT "u.",
caml_minor_heap_max_wsz, requested_wsz);
while (requested_wsz > caml_minor_heap_max_wsz) {
caml_try_run_on_all_domains(
&stw_resize_minor_heap_reservation, (void*)requested_wsz, 0);
}
check_minor_heap();
}
void caml_init_domains(uintnat minor_heap_wsz) {
int i;
reserve_minor_heaps_from_stw_single();
/* stw_single: mutators and domains have not started yet. */
for (i = 0; i < Max_domains; i++) {
struct dom_internal* dom = &all_domains[i];
stw_domains.domains[i] = dom;
dom->id = i;
dom->interruptor.interrupt_word = NULL;
caml_plat_mutex_init(&dom->interruptor.lock);
caml_plat_cond_init(&dom->interruptor.cond);
dom->interruptor.running = 0;
dom->interruptor.terminating = 0;
dom->interruptor.unique_id = 0;
dom->interruptor.interrupt_pending = 0;
caml_plat_mutex_init(&dom->domain_lock);
caml_plat_cond_init(&dom->domain_cond);
dom->backup_thread_running = 0;
dom->backup_thread_msg = BT_INIT;
}
domain_create(minor_heap_wsz, NULL);
if (!domain_self) caml_fatal_error("Failed to create main domain");
CAMLassert (domain_self->state->unique_id == 0);
caml_init_signal_handling();
}
void caml_init_domain_self(int domain_id) {
CAMLassert (domain_id >= 0 && domain_id < Max_domains);
domain_self = &all_domains[domain_id];
caml_state = domain_self->state;
}
enum domain_status { Dom_starting, Dom_started, Dom_failed };
struct domain_ml_values {
value callback;
value term_sync;
};